feat: add folder uploads and archives with simpler account and plan forms
This commit is contained in:
1 parent
9afd7d0067
commit
fa391b3e3d
41 files changed
+1027
-71
No files matched your search
@@ -1,5 +1,6 @@
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/dist-demo/
|
||||
frontend/*.tsbuildinfo
|
||||
frontend/vite.config.js
|
||||
frontend/vite.config.d.ts
|
||||
|
||||
@@ -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 安全配置。
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// Stable internal IDs keep batch previews and retries consistent without exposing an extra form field.
|
||||
func accountSlug(login string) string {
|
||||
digest := sha256.Sum256([]byte(login))
|
||||
return "u-" + hex.EncodeToString(digest[:10])
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sea-vhost/internal/auth"
|
||||
"sea-vhost/internal/config"
|
||||
"sea-vhost/internal/isolation"
|
||||
"sea-vhost/internal/panel"
|
||||
"sea-vhost/internal/service"
|
||||
"sea-vhost/internal/store"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNamedAccountMySQL(t *testing.T) {
|
||||
dsn := os.Getenv("SEA_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("disposable MySQL schema not supplied")
|
||||
}
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") {
|
||||
t.Fatal("refusing a non-test schema")
|
||||
}
|
||||
db, err := store.Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
ctx := context.Background()
|
||||
must := func(err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
must(db.Migrate(ctx))
|
||||
must(db.BootstrapAdmin(ctx, "identity-admin@example.invalid", "测试管理员", "identity-admin-password-123"))
|
||||
admin, err := db.UserByLogin(ctx, "identity-admin@example.invalid")
|
||||
must(err)
|
||||
root := t.TempDir()
|
||||
must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"))
|
||||
secret := "named-account-test-session-secret-at-least-thirty-two-characters"
|
||||
projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid")
|
||||
server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects)
|
||||
token, err := auth.NewSessionToken(secret)
|
||||
must(err)
|
||||
must(db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)))
|
||||
call := func(method, path string, body any, session string) *httptest.ResponseRecorder {
|
||||
var buffer bytes.Buffer
|
||||
must(json.NewEncoder(&buffer).Encode(body))
|
||||
r := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer)
|
||||
r.Header.Set("Origin", "https://control.example.invalid")
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
if session != "" {
|
||||
r.AddCookie(&http.Cookie{Name: "sea_session", Value: session})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
expect := func(w *httptest.ResponseRecorder, status int) {
|
||||
t.Helper()
|
||||
if w.Code != status {
|
||||
t.Fatalf("HTTP %d want %d: %s", w.Code, status, w.Body.String())
|
||||
}
|
||||
}
|
||||
input := map[string]any{"loginName": "customer01", "displayName": "测试用户", "email": "customer01@example.invalid", "password": "identity-user-password-123", "planId": 1}
|
||||
created := call("POST", "/api/v1/admin/tenants", input, token)
|
||||
expect(created, 201)
|
||||
var value struct {
|
||||
ID uint64 `json:"id"`
|
||||
}
|
||||
must(json.Unmarshal(created.Body.Bytes(), &value))
|
||||
profile, err := db.AccountProfile(ctx, value.ID)
|
||||
must(err)
|
||||
if profile.LoginName != "customer01" || profile.Name != "测试用户" || profile.DisplayName != "测试用户" || profile.Slug != accountSlug("customer01") {
|
||||
t.Fatalf("unexpected profile: %+v", profile)
|
||||
}
|
||||
for _, login := range []string{"customer01", "customer01@example.invalid"} {
|
||||
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": login, "password": "identity-user-password-123"}, ""), 200)
|
||||
}
|
||||
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": "customer01", "password": "incorrect-password"}, ""), 401)
|
||||
duplicate := map[string]any{"loginName": "customer01", "displayName": "重复用户", "email": "different@example.invalid", "password": "identity-user-password-123", "planId": 1}
|
||||
expect(call("POST", "/api/v1/admin/tenants", duplicate, token), 422)
|
||||
input["loginName"] = "another-user"
|
||||
expect(call("POST", "/api/v1/admin/tenants", input, token), 422)
|
||||
input["loginName"] = "bad@name"
|
||||
expect(call("POST", "/api/v1/admin/tenants", input, token), 422)
|
||||
list, err := db.ListTenants(ctx)
|
||||
must(err)
|
||||
if len(list) != 1 || list[0].LoginName != "customer01" {
|
||||
t.Fatalf("unexpected user list: %+v", list)
|
||||
}
|
||||
profile.Email = "updated@example.invalid"
|
||||
profile.Name = "修改名称"
|
||||
profile.DisplayName = profile.Name
|
||||
must(db.UpdateAccount(ctx, value.ID, profile))
|
||||
updated, err := db.UserByLogin(ctx, "customer01")
|
||||
must(err)
|
||||
if updated.Email != profile.Email {
|
||||
t.Fatal("email update failed")
|
||||
}
|
||||
_, err = db.UserByLogin(ctx, "customer01@example.invalid")
|
||||
if err == nil {
|
||||
t.Fatal("old email still usable")
|
||||
}
|
||||
batch := batchRequest{Operation: "create_users", Rows: []batchRow{{LoginName: "batch-account", DisplayName: "批量用户", Email: "batch-account@example.invalid"}}}
|
||||
preview, err := server.normalizeBatch(ctx, &batch)
|
||||
must(err)
|
||||
if len(preview) != 1 || !preview[0].Valid {
|
||||
t.Fatalf("batch preview rejected: %+v", preview)
|
||||
}
|
||||
stable := batch.Rows[0].Slug
|
||||
preview, err = server.normalizeBatch(ctx, &batch)
|
||||
must(err)
|
||||
if !preview[0].Valid || stable != batch.Rows[0].Slug {
|
||||
t.Fatal("batch identity changed on retry")
|
||||
}
|
||||
result, err := server.performBatchRow(ctx, "create_users", batch.Rows[0])
|
||||
must(err)
|
||||
if result.Login != "batch-account" || result.Password == "" {
|
||||
t.Fatal("batch credentials missing login account")
|
||||
}
|
||||
expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": result.Login, "password": result.Password}, ""), 200)
|
||||
preview, err = server.normalizeBatch(ctx, &batch)
|
||||
must(err)
|
||||
if preview[0].Valid {
|
||||
t.Fatal("duplicate batch account accepted")
|
||||
}
|
||||
t.Log("single creation, account/email login, password rejection, duplicate/invalid account rejection, stable batch identity, user listing and email update passed")
|
||||
}
|
||||
@@ -85,6 +85,7 @@ func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var input struct {
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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, "缺少上传文件")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sea-vhost/internal/nodefiles"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const batchUploadLimit int64 = 30 << 20
|
||||
|
||||
type uploadItem struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Success bool `json:"success"`
|
||||
Status int `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Validate the whole selection before any file is committed.
|
||||
var errUploadPath = errors.New("文件夹相对路径无效、重复或包含系统保留目录")
|
||||
|
||||
func batchUploadNames(headers []*multipart.FileHeader, limit int64) ([]string, error) {
|
||||
return batchUploadPaths(headers, limit, nil)
|
||||
}
|
||||
func batchUploadPaths(headers []*multipart.FileHeader, limit int64, relative []string) ([]string, error) {
|
||||
if relative != nil && len(relative) != len(headers) {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
if len(headers) == 0 || len(headers) > 100 {
|
||||
return nil, errors.New("每批请选择 1–100 个文件")
|
||||
}
|
||||
names := make([]string, len(headers))
|
||||
seen := map[string]bool{}
|
||||
var total int64
|
||||
for i, h := range headers {
|
||||
if h.Size < 0 || h.Size > limit {
|
||||
return nil, errors.New(uploadLimitMessage(limit))
|
||||
}
|
||||
if h.Size > batchUploadLimit-total {
|
||||
return nil, errors.New("单批上传总大小不能超过 30 MB")
|
||||
}
|
||||
total += h.Size
|
||||
name := filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/"))
|
||||
if relative != nil {
|
||||
name = relative[i]
|
||||
if !utf8.ValidString(name) || len(name) > 1024 || strings.ContainsAny(name, "\\:\x00\r\n") || strings.HasPrefix(name, "/") || path.Clean(name) != name || nodefiles.IsProtectedPath(name) || path.Base(name) != filepath.Base(strings.ReplaceAll(h.Filename, "\\", "/")) {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
parts := strings.Split(name, "/")
|
||||
if len(parts) > 32 {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
for _, part := range parts {
|
||||
if part == "" || part == "." || part == ".." || len(part) > 255 {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
}
|
||||
}
|
||||
if name == "." || name == ".." || name == "" || seen[name] {
|
||||
return nil, errors.New("文件名无效或本批存在同名文件")
|
||||
}
|
||||
names[i] = name
|
||||
seen[name] = true
|
||||
}
|
||||
for _, name := range names {
|
||||
for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) {
|
||||
if seen[parent] {
|
||||
return nil, errUploadPath
|
||||
}
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (s *Server) uploadBatchFiles(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) {
|
||||
headers := r.MultipartForm.File["file"]
|
||||
limit := min(s.cfg.UploadLimitBytes, int64(20<<20))
|
||||
var relative []string
|
||||
if raw := r.FormValue("relativePaths"); raw != "" {
|
||||
if len(raw) > 128<<10 || json.Unmarshal([]byte(raw), &relative) != nil || relative == nil {
|
||||
writeError(w, 400, "文件夹路径列表无效")
|
||||
return
|
||||
}
|
||||
}
|
||||
names, err := batchUploadPaths(headers, limit, relative)
|
||||
if err != nil {
|
||||
status := 413
|
||||
if errors.Is(err, errUploadPath) {
|
||||
status = 400
|
||||
}
|
||||
writeError(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
dir, err := safeProjectName(root, r.FormValue("path"))
|
||||
if err != nil {
|
||||
writeError(w, 400, "路径无效")
|
||||
return
|
||||
}
|
||||
projectRoot, err := s.projects.OpenFiles(r.Context(), root)
|
||||
if err != nil {
|
||||
writeError(w, 404, "项目目录不存在")
|
||||
return
|
||||
}
|
||||
defer projectRoot.Close()
|
||||
targets := make([]string, len(names))
|
||||
overwrite := r.FormValue("overwrite") == "true"
|
||||
var additional uint64
|
||||
for i, name := range names {
|
||||
targets[i], err = safeProjectName(root, path.Join(dir, name))
|
||||
if err != nil {
|
||||
writeError(w, 400, "路径无效或包含系统保留文件")
|
||||
return
|
||||
}
|
||||
growth := uint64(headers[i].Size)
|
||||
if old, e := projectRoot.Lstat(targets[i]); e == nil && old.Mode().IsRegular() {
|
||||
if !overwrite {
|
||||
growth = 0
|
||||
} else if uint64(old.Size()) >= growth {
|
||||
growth = 0
|
||||
} else {
|
||||
growth -= uint64(old.Size())
|
||||
}
|
||||
}
|
||||
additional += growth
|
||||
}
|
||||
if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additional); err != nil {
|
||||
writeFileQuotaError(w, err)
|
||||
return
|
||||
}
|
||||
results := make([]uploadItem, 0, len(names))
|
||||
for i, name := range names {
|
||||
result := uploadItem{Name: name, Status: 422, Error: "上传失败,请刷新目录核对"}
|
||||
flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
|
||||
if overwrite {
|
||||
flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
|
||||
}
|
||||
source, e := headers[i].Open()
|
||||
if e == nil {
|
||||
if parent := path.Dir(filepath.ToSlash(targets[i])); parent != "." {
|
||||
if mkdirErr := projectRoot.MkdirAll(parent, 0770); mkdirErr != nil {
|
||||
source.Close()
|
||||
s.logFile(r, tenantID, "file_operation", "文件夹上传创建子目录失败:"+name)
|
||||
results = append(results, result)
|
||||
continue
|
||||
}
|
||||
}
|
||||
destination, openErr := projectRoot.OpenFile(targets[i], flag, 0660)
|
||||
if openErr == nil {
|
||||
written, copyErr := io.Copy(destination, io.LimitReader(source, limit+1))
|
||||
if copyErr == nil && written == headers[i].Size && written <= limit {
|
||||
e = destination.Close()
|
||||
} else {
|
||||
e = errors.New("upload truncated")
|
||||
}
|
||||
destination.Abort()
|
||||
if e == nil {
|
||||
result = uploadItem{Name: name, Size: written, Success: true, Status: 201}
|
||||
s.logFile(r, tenantID, "upload", "批量上传文件:"+filepath.ToSlash(targets[i]))
|
||||
}
|
||||
} else {
|
||||
e = openErr
|
||||
}
|
||||
source.Close()
|
||||
}
|
||||
if !result.Success {
|
||||
if errors.Is(e, os.ErrExist) {
|
||||
result.Status = 409
|
||||
result.Error = "同名文件已存在,未覆盖"
|
||||
}
|
||||
s.logFile(r, tenantID, "file_operation", "批量上传失败:"+name)
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
writeJSON(w, 207, map[string]any{"files": results})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"mime/multipart"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBatchUploadLimitsBeforeWriting(t *testing.T) {
|
||||
const mb = 1 << 20
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
files []*multipart.FileHeader
|
||||
ok bool
|
||||
}{
|
||||
{"exact total", []*multipart.FileHeader{{Filename: "a", Size: 20 * mb}, {Filename: "b", Size: 10 * mb}}, true},
|
||||
{"over total", []*multipart.FileHeader{{Filename: "a", Size: 20 * mb}, {Filename: "b", Size: 10*mb + 1}}, false},
|
||||
{"over single", []*multipart.FileHeader{{Filename: "a", Size: 20*mb + 1}}, false},
|
||||
{"duplicate normalized name", []*multipart.FileHeader{{Filename: "a"}, {Filename: "folder/a"}}, false},
|
||||
{"empty", nil, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := batchUploadNames(test.files, 20*mb)
|
||||
if (err == nil) != test.ok {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
files := make([]*multipart.FileHeader, 101)
|
||||
for i := range files {
|
||||
files[i] = &multipart.FileHeader{Filename: "x"}
|
||||
}
|
||||
if _, err := batchUploadNames(files, 20*mb); err == nil {
|
||||
t.Fatal("unbounded file count accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFolderUploadPathsAreRootedAndUnambiguous(t *testing.T) {
|
||||
headers := []*multipart.FileHeader{{Filename: "index.php", Size: 5}, {Filename: "index.php", Size: 4}}
|
||||
paths := []string{"site/a/index.php", "site/b/index.php"}
|
||||
names, err := batchUploadPaths(headers, 20<<20, paths)
|
||||
if err != nil || names[0] != paths[0] || names[1] != paths[1] {
|
||||
t.Fatalf("folder paths lost: %v %v", names, err)
|
||||
}
|
||||
for _, name := range []string{"../index.php", "/index.php", "site/../index.php", "site//index.php", "site/./index.php", `site\index.php`, "C:/index.php", "site/.sea-runtime/index.php", "site/.sea-trash/index.php", "site/.user.ini/index.php", "site/other.php"} {
|
||||
if _, err = batchUploadPaths(headers[:1], 20<<20, []string{name}); err == nil {
|
||||
t.Errorf("unsafe path accepted: %q", name)
|
||||
}
|
||||
}
|
||||
if _, err = batchUploadPaths(headers, 20<<20, paths[:1]); err == nil {
|
||||
t.Fatal("path count mismatch accepted")
|
||||
}
|
||||
conflicting := []*multipart.FileHeader{{Filename: "site"}, {Filename: "index.php"}}
|
||||
if _, err = batchUploadPaths(conflicting, 20<<20, []string{"site", "site/index.php"}); err == nil {
|
||||
t.Fatal("file/directory collision accepted")
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package nodefiles
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+3
-2
@@ -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 批量管理、网站、文件、计划任务、财务站对接 |
|
||||
|
||||
@@ -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`,尚无数据表或管理员;安装令牌及数据库密码由单独的私密交付信息提供,不进入源码包。重装前已验证完整备份,宝塔其他资源、控制台证书和已安装运行环境保留。
|
||||
|
||||
|
||||
@@ -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 策略依证书配置确定。
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Sea vHost v0.1.0-rc.5
|
||||
|
||||
整理日期:2026-11-15。本版汇总 rc.4 后的账户、套餐与文件管理改动,继续作为 Debian Linux amd64 单机实机测试版交付。
|
||||
|
||||
## 本版变化
|
||||
|
||||
- 用户创建统一填写登录账号、显示名称、邮箱和密码,内部标识自动生成;支持登录账号或邮箱登录,保留旧账号的登录方式。JSON 批量导入、预览和凭据导出同步支持登录账号。
|
||||
- 创建主机和网站时预填可修改的随机名称。输入名称仍是显示名称,实际主机登录名、目录及服务账号由后端独立分配;本版没有合并这两套命名。
|
||||
- 套餐的存储空间、数据库空间使用 MB,月流量使用 GB;按 1024 进制换算并取整后以 Bytes 提交,修复小数容量导致接口拒绝的问题。复制套餐保留实际容量。
|
||||
- 普通生产构建始终连接后端并要求认证;演示站必须通过 `npm run build:demo` 显式构建,演示内容不进入正式控制台。
|
||||
- 文件管理支持多文件及整文件夹上传:单批最多 100 个文件、合计 30 MiB,单文件仍为 20 MiB。文件夹保留相对目录,浏览器未提供的空目录不上传;不同目录下的同名文件可同时上传。
|
||||
- 上传前检查大小、路径及套餐空间,逐文件返回结果;已有文件不自动覆盖,用户确认后仅重试冲突文件。管理站点 Nginx 请求体上限调整为 31 MiB,容纳 multipart 开销。
|
||||
- 增加 TAR、TAR.GZ、TGZ 解压并保留 ZIP。解压至不存在的目标目录,限制条目数、解压总量和剩余空间,拒绝路径穿越、保留目录、软硬链接及特殊文件;失败不发布部分解压结果。
|
||||
|
||||
## 验证与边界
|
||||
|
||||
本次提交的本地验证:`go test ./...` 通过,前端 22 个测试文件共 105 项通过,安装向导 19 项通过,正式前端及六个 Linux amd64 服务程序构建通过(Go 1.27.3)。依赖临时 MySQL 的集成测试在未提供专用测试 DSN 时跳过,不能据此声称本轮重新完成了实机联调。
|
||||
|
||||
本版相关改动此前已部署到 36 环境:隔离 MySQL 测试库中的账户登录和资源 CRUD、批量/嵌套目录上传、容量边界和 TAR 解压已通过;已核对正式站及独立演示站静态资源、演示站 API 禁止访问和文件管理界面。浏览器文件夹选择器的完整上传交互未单独执行,以前端交互测试及真实后端 multipart 集成测试覆盖。
|
||||
|
||||
此前按要求开通的课堂账户和主机是服务器业务数据,不包含在仓库、源码包或部署包内。密钥、密码、会话、服务器配置及私有测试材料同样不随版本交付。历史实测记录代表当时结果,不作为本次重新安装或全功能复测的结论。
|
||||
|
||||
## 安装与升级
|
||||
|
||||
部署包为 `sea-vhost-linux-amd64.tar.gz`,配套 SHA-256 文件和 `runtime-manifest.json`;源码以仓库标签及单独的源码归档交付。部署包包含正式控制台,不包含演示站构建产物。
|
||||
|
||||
全新安装解压后运行 `bash deploy/install.sh`,通过交互安装及 Web 向导填写本机配置。已有环境按 [部署说明](deployment.md) 备份数据库、配置与程序后更新,保留现有业务数据;不要用清理重装代替更新。本版未新增数据库迁移。
|
||||
|
||||
日常文件操作和限制见 [操作说明](hosting-operations.md),账户与回收规则见 [资源管理](resource-management.md)。
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
## 用户
|
||||
|
||||
可以创建、查询、编辑用户名称、联系人和登录邮箱,以及启停、删除用户。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。
|
||||
创建用户填写登录账号、显示名称、邮箱和密码,内部用户标识自动生成。新用户可用登录账号或邮箱登录,原有用户仍保留原登录方式。可以查询、编辑显示名称和登录邮箱,以及启停、删除用户;登录账号在资料编辑页只读。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。
|
||||
|
||||
## 节点
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"scripts": {
|
||||
"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"
|
||||
},
|
||||
|
||||
@@ -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(<HostProvisioning users={[]} plans={[demoPlan]} onClose={vi.fn()} onComplete={vi.fn()}/>);
|
||||
const name=(screen.getByLabelText('主机名称') as HTMLInputElement).value;
|
||||
expect(name).toMatch(/^sv[0-9a-f]{10}$/);
|
||||
fireEvent.change(screen.getByLabelText('主机名称'),{target:{value:'my-site'}});
|
||||
expect(screen.getByLabelText('主机名称')).toHaveValue('my-site');first.unmount();
|
||||
render(<HostProvisioning users={[]} plans={[demoPlan]} onClose={vi.fn()} onComplete={vi.fn()}/>);
|
||||
expect(screen.getByLabelText('主机名称')).not.toHaveValue(name);
|
||||
});
|
||||
it('creates users with four visible fields and sends a real login account',async()=>{
|
||||
const create=vi.fn().mockRejectedValue(new Error('账号已存在'));
|
||||
render(<UserForm plans={[demoPlan]} onClose={vi.fn()} onCreate={create}/>);
|
||||
expect(screen.queryByLabelText('用户标识')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('联系人姓名')).not.toBeInTheDocument();
|
||||
for(const [label,value] of [['登录账号','customer01'],['显示名称','测试用户'],['登录邮箱','customer01@example.invalid'],['初始密码','test-password-123']])fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'创建用户'}));
|
||||
await waitFor(()=>expect(create).toHaveBeenCalledWith({loginName:'customer01',name:'测试用户',displayName:'测试用户',email:'customer01@example.invalid',password:'test-password-123',planId:demoPlan.id}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('账号已存在');
|
||||
});
|
||||
it('creates small plans using MB capacities and GB traffic with integer byte payloads',async()=>{
|
||||
const create=vi.fn().mockResolvedValue(undefined);
|
||||
render(<PlanForm onCreate={create} onClose={vi.fn()}/>);
|
||||
fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'ClassHost'}});
|
||||
fireEvent.change(screen.getByLabelText('存储空间(MB)'),{target:{value:'800'}});
|
||||
fireEvent.change(screen.getByLabelText('数据库空间(MB)'),{target:{value:'100'}});
|
||||
fireEvent.change(screen.getByLabelText('月流量(GB)'),{target:{value:'30'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
||||
await waitFor(()=>expect(create).toHaveBeenCalledWith(expect.objectContaining({storageBytes:838860800,databaseBytes:104857600,bandwidthBytes:32212254720})));
|
||||
fireEvent.change(screen.getByLabelText('存储空间(MB)'),{target:{value:'800.1'}});
|
||||
fireEvent.change(screen.getByLabelText('数据库空间(MB)'),{target:{value:'100.1'}});
|
||||
fireEvent.change(screen.getByLabelText('月流量(GB)'),{target:{value:'0.1'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
||||
await waitFor(()=>expect(create).toHaveBeenCalledTimes(2));
|
||||
expect(create.mock.calls[1][0]).toEqual(expect.objectContaining({storageBytes:838965658,databaseBytes:104962458,bandwidthBytes:107374182}));
|
||||
});
|
||||
it('keeps copied capacities exact and displays plan capacities in their configured units',async()=>{
|
||||
const save=vi.fn().mockResolvedValue(undefined);
|
||||
const plan={...demoPlan,storageBytes:838965658,databaseBytes:104962458,bandwidthBytes:107374182};
|
||||
render(<Plans plans={[plan]} create={vi.fn()} save={save}/>);
|
||||
expect(screen.getByText('800.1 MB')).toBeInTheDocument();
|
||||
expect(screen.getByText('100.1 MB')).toBeInTheDocument();
|
||||
expect(screen.getByText('0.1 GB')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'复制套餐 '+plan.name}));
|
||||
expect(screen.getByLabelText('存储空间(MB)')).toHaveValue(plan.storageBytes/1024**2);
|
||||
expect(screen.getByLabelText('数据库空间(MB)')).toHaveValue(plan.databaseBytes/1024**2);
|
||||
fireEvent.click(screen.getByRole('button',{name:'保存为新套餐'}));
|
||||
await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({storageBytes:plan.storageBytes,databaseBytes:plan.databaseBytes,bandwidthBytes:plan.bandwidthBytes})));
|
||||
});
|
||||
it('retains a rejected plan form and explains the failure',async()=>{
|
||||
const create=vi.fn().mockRejectedValue(new Error('套餐名称重复'));
|
||||
render(<PlanForm onCreate={create} onClose={vi.fn()}/>);fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'重复套餐'}});fireEvent.click(screen.getByRole('button',{name:'创建套餐'}));
|
||||
|
||||
@@ -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(<BatchComposer operation="create_users" users={[]} projects={[]} plans={[demoPlan]} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
|
||||
expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-batch'}});
|
||||
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');
|
||||
|
||||
@@ -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: '',
|
||||
|
||||
@@ -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(<FileManager projects={initialProjects}/>);await screen.findByText('index.txt');
|
||||
const input=screen.getByLabelText('上传文件夹');expect(input).toHaveAttribute('webkitdirectory');expect(input).toHaveAttribute('multiple');
|
||||
fireEvent.change(input,{target:{files:[a,b]}});
|
||||
const dialog=await screen.findByRole('alertdialog',{name:'覆盖文件'});expect(dialog).toHaveTextContent('site/b/index.php');
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'覆盖同名文件'}));
|
||||
await waitFor(()=>expect(upload).toHaveBeenLastCalledWith(1,'',[b],true));
|
||||
expect(await screen.findByText('上传完成:成功 2 个,失败或跳过 0 个')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('validates the whole batch before uploading and preserves the 20 MB single-file cap',async()=>{
|
||||
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));const upload=vi.spyOn(api,'uploadFiles').mockResolvedValue({files:[]});
|
||||
render(<FileManager projects={initialProjects}/>);await screen.findByText('index.txt');
|
||||
const input=screen.getByLabelText('批量上传文件');expect(input).toHaveAttribute('multiple');
|
||||
const file=(name:string,size:number)=>{const out=new window.File(['x'],name);Object.defineProperty(out,'size',{value:size});return out};
|
||||
fireEvent.change(input,{target:{files:[file('a',20*1024**2),file('b',10*1024**2+1)]}});
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('单批上传总大小不能超过 30 MB');expect(upload).not.toHaveBeenCalled();
|
||||
fireEvent.change(input,{target:{files:[file('a',20*1024**2+1)]}});expect(screen.getByRole('alert')).toHaveTextContent('单文件不能超过 20 MB');expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
it('reports partial results and retries only conflicting files after explicit confirmation',async()=>{
|
||||
vi.spyOn(api,'files').mockResolvedValue(listing('index.txt'));
|
||||
const a=new window.File(['a'],'a.txt'),b=new window.File(['b'],'b.txt');
|
||||
const upload=vi.spyOn(api,'uploadFiles').mockResolvedValueOnce({files:[{name:'a.txt',size:1,success:true,status:201},{name:'b.txt',size:0,success:false,status:409,error:'同名文件已存在'}]}).mockResolvedValueOnce({files:[{name:'b.txt',size:1,success:true,status:201}]});
|
||||
render(<FileManager projects={initialProjects}/>);await screen.findByText('index.txt');
|
||||
fireEvent.change(screen.getByLabelText('批量上传文件'),{target:{files:[a,b]}});
|
||||
const dialog=await screen.findByRole('alertdialog',{name:'覆盖文件'});expect(upload).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'覆盖同名文件'}));
|
||||
await waitFor(()=>expect(upload).toHaveBeenLastCalledWith(1,'',[b],true));
|
||||
expect(await screen.findByText('上传完成:成功 2 个,失败或跳过 0 个')).toBeInTheDocument();
|
||||
});
|
||||
it('offers an explicit TAR.GZ extraction action with a correctly derived destination',async()=>{
|
||||
vi.spyOn(api,'files').mockResolvedValue(listing('site.tar.gz'));const action=vi.spyOn(api,'fileAction').mockResolvedValue(undefined);
|
||||
render(<FileManager projects={initialProjects}/>);fireEvent.click(await screen.findByRole('button',{name:'解压 site.tar.gz'}));
|
||||
expect(screen.getByLabelText('目标路径')).toHaveValue('site-extracted');
|
||||
fireEvent.click(screen.getByRole('button',{name:'执行操作'}));await waitFor(()=>expect(action).toHaveBeenCalledWith(1,'extract','site.tar.gz','site-extracted'));
|
||||
});
|
||||
|
||||
it('does not present binary filenames as buttons that cannot do anything',async()=>{
|
||||
vi.spyOn(api,'files').mockResolvedValue(listing('program.bin'));
|
||||
render(<FileManager projects={initialProjects}/>);
|
||||
|
||||
@@ -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(<App/>);
|
||||
expect(screen.getByText('示例科技有限公司')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading',{name:'总览'})).toBeInTheDocument();
|
||||
expect(setup).not.toHaveBeenCalled();expect(me).not.toHaveBeenCalled();
|
||||
});
|
||||
it('requires backend authentication in production even when the API build flag is missing',async()=>{
|
||||
vi.stubEnv('DEV',false);vi.stubEnv('VITE_API_MODE',undefined);
|
||||
const setup=vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});
|
||||
vi.spyOn(api,'me').mockRejectedValue(Object.assign(new Error('unauthorized'),{status:401}));
|
||||
vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:false,userPasswordLogin:true,adminPasswordLogin:true});
|
||||
render(<App/>);
|
||||
expect(await screen.findByRole('heading',{name:'登录控制台'})).toBeInTheDocument();
|
||||
expect(setup).toHaveBeenCalled();
|
||||
expect(screen.queryByText('示例科技有限公司')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button',{name:'创建虚拟主机'})).not.toBeInTheDocument();
|
||||
});
|
||||
it('submits one state change during rapid clicks and shows the requested final state',async()=>{
|
||||
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);
|
||||
|
||||
@@ -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(<AccountEditor account={{id:4,slug:'customer'} as Tenant} onClose={vi.fn()} onChanged={vi.fn().mockResolvedValue(undefined)}/>);
|
||||
await screen.findByLabelText('用户名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled();
|
||||
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(<NodeEditor node={{id:1,name:'本机节点',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true} as ControlNode} onClose={vi.fn()} onChanged={vi.fn()}/>);
|
||||
|
||||
+10
-3
@@ -12,12 +12,12 @@ export interface DomainResource { id: number; projectId: number; siteId: number;
|
||||
export interface FTPResource { enabled?:boolean; id: number; projectId: number; hostName: string; projectName: string; username: string; rootPath: string; createdAt: string; }
|
||||
export interface 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 });
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,
|
||||
<fieldset className="batch-composer-fields" disabled={busy}><div className="batch-controls">
|
||||
<label>输入方式<select value={mode} onChange={event=>{invalidate();setMode(event.target.value as typeof mode)}}>{creating?<option value="quantity">数量与名称前缀</option>:null}{selection.length?<option value="selection">已勾选的 {selection.length} 项</option>:null}<option value="json">JSON 模板导入</option></select></label>
|
||||
{mode==='quantity'?<><label>创建数量<input type="number" min="1" max={operation==='create_users'?100:50} value={count} onChange={e=>{invalidate();setCount(Number(e.target.value))}}/></label><label>名称前缀<input value={prefix} maxLength={37} onChange={e=>{invalidate();setPrefix(e.target.value)}}/></label><label>起始编号<input type="number" min="1" max="999999" value={start} onChange={e=>{invalidate();setStart(Number(e.target.value))}}/></label></>:null}
|
||||
{operation==='create_users'&&mode==='quantity'?<><label>用户名称前缀<input value={displayPrefix} onChange={e=>{invalidate();setDisplayPrefix(e.target.value)}}/></label><label>登录邮箱后缀<input placeholder="vhost.ser888.cn" value={emailDomain} onChange={e=>{invalidate();setEmailDomain(e.target.value)}}/></label></>:null}
|
||||
{operation==='create_users'&&mode==='quantity'?<><label>显示名称前缀<input value={displayPrefix} onChange={e=>{invalidate();setDisplayPrefix(e.target.value)}}/></label><label>登录邮箱后缀<input placeholder="vhost.ser888.cn" value={emailDomain} onChange={e=>{invalidate();setEmailDomain(e.target.value)}}/></label></>:null}
|
||||
{operation==='create_hosts'||operation==='assign_hosts'?<label>{operation==='assign_hosts'?'目标用户':'绑定用户(可选)'}<select value={owner} onChange={e=>{invalidate();setOwner(Number(e.target.value))}}><option value="0">{operation==='assign_hosts'?'解绑用户,仅保留独立主机登录':'不绑定用户,独立主机账号登录'}</option>{users.filter(user=>user.status==='active').map(user=><option key={user.id} value={user.id}>{user.name} · {user.slug}</option>)}</select></label>:null}
|
||||
{operation==='assign_hosts'?<><label>凭据处理<select value={credentialMode} onChange={e=>{invalidate();setCredentialMode(e.target.value as 'preserve'|'reset')}}><option value="preserve">保留主机、FTP、数据库密码</option><option value="reset">随机重置三类密码</option></select></label><label className="batch-check"><input type="checkbox" checked={stopServices} onChange={e=>{invalidate();setStopServices(e.target.checked)}}/>变更前停止全部网站(默认)</label><label className="batch-check"><input type="checkbox" checked={resumeOwnership} onChange={e=>{invalidate();setResumeOwnership(e.target.checked)}}/>按原策略恢复未完成的归属变更</label></>:null}
|
||||
{operation==='create_hosts'?<><label>所属节点<select value={node} onChange={e=>{invalidate();setNode(Number(e.target.value))}}><option value="0" disabled>请选择节点</option>{nodes.map(item=><option value={item.id} key={item.id}>{item.name} · {item.rootDomain}</option>)}</select></label><label>运行环境<select value={runtime} onChange={e=>{invalidate();setRuntime(e.target.value as Runtime)}}>{Object.keys(catalog).map(name=><option key={name}>{name}</option>)}</select></label><label>运行版本<select aria-label="批量运行版本" value={version} onChange={e=>{invalidate();setVersion(e.target.value)}}>{(catalog[runtime]||[]).map(value=><option key={value}>{value}</option>)}</select></label><label>运行目录<input value={runPath} onChange={e=>{invalidate();setRunPath(e.target.value)}}/></label></>:null}
|
||||
|
||||
@@ -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<void>;users:Tenant[];query:string;setQuery:(value:string)=>void;create:()=>void;expiry:(id:number,value?:string)=>Promise<void>;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void}){
|
||||
const [editing,setEditing]=useState<Tenant>(),[deleting,setDeleting]=useState<Tenant>();
|
||||
const [selected,setSelected]=useState<number[]>([]);const list=users.filter(item=>`${item.name} ${item.slug}`.toLowerCase().includes(query.toLowerCase()));const ids=selected.filter(id=>users.some(item=>item.id===id));
|
||||
const [selected,setSelected]=useState<number[]>([]);const list=users.filter(item=>`${item.name} ${item.slug} ${item.loginName||''}`.toLowerCase().includes(query.toLowerCase()));const ids=selected.filter(id=>users.some(item=>item.id===id));
|
||||
const change=(id:number,checked:boolean)=>setSelected(current=>checked?[...new Set([...current,id])]:current.filter(value=>value!==id));
|
||||
const run=(operation:'user_enable'|'user_disable',targets=ids)=>bulk({operation,rows:targets.map(accountId=>({accountId}))});
|
||||
return <><section className="admin-page"><Heading title="用户管理" description="用户可管理名下多台主机;每台主机可独立绑定或解绑用户。" action={<div className="row-actions"><button className="secondary" onClick={()=>bulk({operation:'create_users'})}>批量创建用户</button><button className="primary" onClick={create}><Plus size={16}/>新建用户</button></div>}/><div className="admin-toolbar"><SearchBox value={query} change={setQuery} placeholder="搜索用户名称或标识"/><span>共 {list.length} 个用户 · 已选 {ids.length} 个</span><button className="secondary" disabled={!ids.length} onClick={()=>run('user_enable')}>批量启用</button><button className="secondary" disabled={!ids.length} onClick={()=>run('user_disable')}>批量停用</button></div><Table><thead><tr><th><input type="checkbox" aria-label="选择全部用户" checked={list.length>0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/></th><th>用户</th><th>虚拟主机</th><th>状态</th><th>操作</th></tr></thead><tbody>{list.map(item=><tr key={item.id}><td><input type="checkbox" aria-label={'选择用户 '+item.slug} checked={ids.includes(item.id)} onChange={event=>change(item.id,event.target.checked)}/></td><td><b>{item.name}</b><small>{item.slug}</small></td><td>{item.projectCount}</td><td>{item.status==='active'?'正常':'已停用'}</td><td><div className="row-actions"><button className="table-link" aria-label={'编辑用户 '+item.slug} onClick={()=>setEditing(item)}>详情 / 编辑</button><button className="table-link" aria-label={'进入用户 '+item.slug} disabled={item.status!=='active'||!enter} onClick={()=>enter?.(item.id)}>进入用户</button><button className="table-link" aria-label={(item.status==='active'?'停用用户 ':'启用用户 ')+item.slug} onClick={()=>run(item.status==='active'?'user_disable':'user_enable',[item.id])}>{item.status==='active'?'停用':'启用'}</button><button className="table-link danger-text" aria-label={'删除用户 '+item.slug} disabled={item.projectCount>0} title={item.projectCount>0?'请先逐一解绑或转移全部主机,包括回收中的主机':undefined} onClick={()=>setDeleting(item)}>删除</button></div></td></tr>)}</tbody></Table></section>{deleting?<AccountEditor intent="delete" account={deleting} onClose={()=>setDeleting(undefined)} onChanged={refresh}/>:null}{editing?<AccountEditor account={editing} onClose={()=>setEditing(undefined)} onChanged={refresh}/>:null}</>;
|
||||
return <><section className="admin-page"><Heading title="用户管理" description="用户可管理名下多台主机;每台主机可独立绑定或解绑用户。" action={<div className="row-actions"><button className="secondary" onClick={()=>bulk({operation:'create_users'})}>批量创建用户</button><button className="primary" onClick={create}><Plus size={16}/>新建用户</button></div>}/><div className="admin-toolbar"><SearchBox value={query} change={setQuery} placeholder="搜索用户名称或标识"/><span>共 {list.length} 个用户 · 已选 {ids.length} 个</span><button className="secondary" disabled={!ids.length} onClick={()=>run('user_enable')}>批量启用</button><button className="secondary" disabled={!ids.length} onClick={()=>run('user_disable')}>批量停用</button></div><Table><thead><tr><th><input type="checkbox" aria-label="选择全部用户" checked={list.length>0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/></th><th>用户</th><th>虚拟主机</th><th>状态</th><th>操作</th></tr></thead><tbody>{list.map(item=><tr key={item.id}><td><input type="checkbox" aria-label={'选择用户 '+item.slug} checked={ids.includes(item.id)} onChange={event=>change(item.id,event.target.checked)}/></td><td><b>{item.name}</b><small>{item.loginName||item.slug}</small></td><td>{item.projectCount}</td><td>{item.status==='active'?'正常':'已停用'}</td><td><div className="row-actions"><button className="table-link" aria-label={'编辑用户 '+item.slug} onClick={()=>setEditing(item)}>详情 / 编辑</button><button className="table-link" aria-label={'进入用户 '+item.slug} disabled={item.status!=='active'||!enter} onClick={()=>enter?.(item.id)}>进入用户</button><button className="table-link" aria-label={(item.status==='active'?'停用用户 ':'启用用户 ')+item.slug} onClick={()=>run(item.status==='active'?'user_disable':'user_enable',[item.id])}>{item.status==='active'?'停用':'启用'}</button><button className="table-link danger-text" aria-label={'删除用户 '+item.slug} disabled={item.projectCount>0} title={item.projectCount>0?'请先逐一解绑或转移全部主机,包括回收中的主机':undefined} onClick={()=>setDeleting(item)}>删除</button></div></td></tr>)}</tbody></Table></section>{deleting?<AccountEditor intent="delete" account={deleting} onClose={()=>setDeleting(undefined)} onChanged={refresh}/>:null}{editing?<AccountEditor account={editing} onClose={()=>setEditing(undefined)} onChanged={refresh}/>:null}</>;
|
||||
}
|
||||
|
||||
|
||||
export function Plans({ plans, create,save,changed }: { plans: Plan[]; create: () => void;save:(input:PlanInput)=>Promise<void>;changed?:()=>Promise<void> }) {
|
||||
const [copy,setCopy]=useState<Plan>(),[removing,setRemoving]=useState<Plan>(),[confirmation,setConfirmation]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[hidden,setHidden]=useState<number[]>([]);
|
||||
return <section className="admin-page"><Heading title="套餐管理" description="套餐按版本保存,已创建套餐配额只读;可复制套餐后调整额度,再为主机更换套餐,避免影响其他主机。" action={<button className="primary" onClick={create}><Plus size={16} />创建套餐</button>} /><div className="plan-cards">{plans.filter(p=>!hidden.includes(p.id)).map((plan) => <article key={plan.id}><header><span><Boxes size={19} /></span><h2>{plan.name}</h2></header><dl><div><dt>存储空间</dt><dd>{formatBytes(plan.storageBytes)}</dd></div><div><dt>数据库空间</dt><dd>{formatBytes(plan.databaseBytes)}</dd></div><div><dt>月流量</dt><dd>{formatBytes(plan.bandwidthBytes)}</dd></div><div><dt>HTTP / FTP 限速</dt><dd>{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}</dd></div><div><dt>进程上限</dt><dd>{plan.processLimit}</dd></div><div><dt>每主机网站数</dt><dd>{plan.projectLimit}</dd></div><div><dt>FTP 账号</dt><dd>{plan.ftpLimit}</dd></div><div><dt>数据库</dt><dd>{plan.databaseLimit}</dd></div></dl><div className="row-actions"><button aria-label={'复制套餐 '+plan.name} onClick={()=>setCopy(plan)}>复制套餐</button><button aria-label={'删除套餐 '+plan.name} disabled={!!plan.deleteBlockedReason||plan.id===1} title={plan.deleteBlockedReason||(plan.id===1?'系统默认套餐不能删除':'删除未使用套餐')} onClick={()=>{setRemoving(plan);setConfirmation('');setError('')}}>删除</button></div>{plan.deleteBlockedReason||plan.id===1?<p className="field-hint">{plan.deleteBlockedReason||'系统默认套餐不能删除'}</p>:null}</article>)}</div>{copy?<PlanForm initial={copy} onClose={()=>setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?<ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy||confirmation!==removing.name)return;setBusy(true);setError('');try{await api.deletePlan(removing.id,confirmation);setHidden(v=>[...v,removing.id]);setRemoving(undefined);await changed?.()}catch(e){setError(e instanceof Error?e.message:'删除套餐失败')}finally{setBusy(false)}}}><h2>删除未使用套餐</h2><p>仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。</p><label>输入套餐名称确认删除<input value={confirmation} onChange={e=>setConfirmation(e.target.value)} disabled={busy} placeholder={removing.name}/></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>setRemoving(undefined)}>取消</button><button className="primary danger-confirm" disabled={busy||confirmation!==removing.name}>{busy?'正在删除…':'确认删除套餐'}</button></div></form></ModalBackdrop>:null}</section>; }
|
||||
return <section className="admin-page"><Heading title="套餐管理" description="套餐按版本保存,已创建套餐配额只读;可复制套餐后调整额度,再为主机更换套餐,避免影响其他主机。" action={<button className="primary" onClick={create}><Plus size={16} />创建套餐</button>} /><div className="plan-cards">{plans.filter(p=>!hidden.includes(p.id)).map((plan) => <article key={plan.id}><header><span><Boxes size={19} /></span><h2>{plan.name}</h2></header><dl><div><dt>存储空间</dt><dd>{`${(plan.storageBytes / planMB).toLocaleString('zh-CN', { maximumFractionDigits: 3 })} MB`}</dd></div><div><dt>数据库空间</dt><dd>{`${(plan.databaseBytes / planMB).toLocaleString('zh-CN', { maximumFractionDigits: 3 })} MB`}</dd></div><div><dt>月流量</dt><dd>{`${(plan.bandwidthBytes / planGB).toLocaleString('zh-CN', { maximumFractionDigits: 6 })} GB`}</dd></div><div><dt>HTTP / FTP 限速</dt><dd>{plan.bandwidthMbps ? `${plan.bandwidthMbps} Mbps` : '不限速'}</dd></div><div><dt>进程上限</dt><dd>{plan.processLimit}</dd></div><div><dt>每主机网站数</dt><dd>{plan.projectLimit}</dd></div><div><dt>FTP 账号</dt><dd>{plan.ftpLimit}</dd></div><div><dt>数据库</dt><dd>{plan.databaseLimit}</dd></div></dl><div className="row-actions"><button aria-label={'复制套餐 '+plan.name} onClick={()=>setCopy(plan)}>复制套餐</button><button aria-label={'删除套餐 '+plan.name} disabled={!!plan.deleteBlockedReason||plan.id===1} title={plan.deleteBlockedReason||(plan.id===1?'系统默认套餐不能删除':'删除未使用套餐')} onClick={()=>{setRemoving(plan);setConfirmation('');setError('')}}>删除</button></div>{plan.deleteBlockedReason||plan.id===1?<p className="field-hint">{plan.deleteBlockedReason||'系统默认套餐不能删除'}</p>:null}</article>)}</div>{copy?<PlanForm initial={copy} onClose={()=>setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?<ModalBackdrop><form className="tenant-modal" onSubmit={async e=>{e.preventDefault();if(busy||confirmation!==removing.name)return;setBusy(true);setError('');try{await api.deletePlan(removing.id,confirmation);setHidden(v=>[...v,removing.id]);setRemoving(undefined);await changed?.()}catch(e){setError(e instanceof Error?e.message:'删除套餐失败')}finally{setBusy(false)}}}><h2>删除未使用套餐</h2><p>仅允许删除未被主机或历史账号引用的套餐,此操作不能恢复。</p><label>输入套餐名称确认删除<input value={confirmation} onChange={e=>setConfirmation(e.target.value)} disabled={busy} placeholder={removing.name}/></label>{error?<p role="alert" className="form-error">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>setRemoving(undefined)}>取消</button><button className="primary danger-confirm" disabled={busy||confirmation!==removing.name}>{busy?'正在删除…':'确认删除套餐'}</button></div></form></ModalBackdrop>:null}</section>; }
|
||||
|
||||
function Lifecycle({projects,onManage}:{projects:AdminProject[];onManage:()=>void}){return <section className="admin-page"><Heading title="到期与回收" description="调度器自动处理到期和清理;恢复主机、修改套餐或到期时间请进入虚拟主机管理。宽限 3 天,回收 7 天,清理后的备份保留 14 天。" action={<button className="secondary" onClick={onManage}>管理主机 / 恢复</button>}/><Table><thead><tr><th>虚拟主机</th><th>用户 / 节点</th><th>当前阶段</th><th>到期时间</th></tr></thead><tbody>{projects.map(p=><tr key={p.id}><td>{p.hostName}</td><td>{p.tenantName} / #{p.nodeId}</td><td><LifecycleBadge state={p.lifecycleState as Tenant['lifecycleState']}/></td><td>{p.expiresAt?dateText(p.expiresAt):"长期使用"}</td></tr>)}</tbody></Table></section>}
|
||||
|
||||
function Table({ children }: { children: ReactNode }) { return <div className="admin-table-v2"><table>{children}</table></div>; }
|
||||
|
||||
function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record<string, unknown>) => Promise<void> }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true); const form = new FormData(event.currentTarget); try { await onCreate({ slug: form.get('slug'), name: form.get('name'), email: form.get('email'), displayName: form.get('displayName'), password: form.get('password'), planId: plans[0]?.id }); } catch (reason) { setError(reason instanceof Error ? reason.message : '创建失败'); setBusy(false); } }}><h2>创建用户</h2><p>创建登录账号后,可继续为该用户新增多个虚拟主机。</p><label>用户名称<input name="name" maxLength={120} required /></label><label>用户标识<input name="slug" pattern="[a-z0-9\-]{3,48}" required /></label><label>联系人姓名<input name="displayName" minLength={2} maxLength={80} required /></label><label>登录邮箱<input name="email" type="email" required /></label><label>初始密码<input name="password" type="password" minLength={12} required /></label>{error ? <p className="form-error">{error}</p> : null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy || !plans.length}>{busy ? '创建中…' : '创建用户'}</button></div></form></ModalBackdrop>; }
|
||||
export function PlanForm({ onClose, onCreate,initial }: { initial?:Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise<void> }) { const [busy, setBusy] = useState(false);const [error,setError]=useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal plan-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true);setError(''); const form = new FormData(event.currentTarget); const gib = 1024 ** 3; try { await onCreate({ name: String(form.get('name')), storageBytes: Number(form.get('storageGB')) * gib, databaseBytes: Number(form.get('databaseGB')) * gib, bandwidthBytes: Number(form.get('bandwidthGB')) * gib, bandwidthMbps: Number(form.get('bandwidthMbps')), processLimit: Number(form.get('processLimit')), projectLimit: Number(form.get('projectLimit')), ftpLimit: Number(form.get('ftpLimit')), databaseLimit: Number(form.get('databaseLimit')) }); } catch(e){setError(e instanceof Error?e.message:'套餐保存失败')} finally { setBusy(false); } }}><h2>{initial?'复制资源套餐':'创建资源套餐'}</h2><label>套餐名称<input name="name" defaultValue={initial?initial.name+' 副本':''} maxLength={80} required /></label><div className="plan-form-grid">{[['storageGB', '存储空间(GB)', initial?initial.storageBytes/1024**3:50], ['databaseGB', '数据库空间(GB)', initial?initial.databaseBytes/1024**3:20], ['bandwidthGB', '月流量(GB)', initial?initial.bandwidthBytes/1024**3:500], ['bandwidthMbps', 'HTTP 每请求 / FTP 每会话限速(Mbps,0 不限)', initial?.bandwidthMbps??0], ['processLimit', '进程数', initial?.processLimit??100], ['projectLimit', '每主机网站数', initial?.projectLimit??10], ['ftpLimit', 'FTP 账号数', initial?.ftpLimit??10], ['databaseLimit', '数据库数', initial?.databaseLimit??10]].map(([name, label, value]) => <label key={String(name)}>{label}<input name={String(name)} type="number" step={String(name).endsWith('GB')?'any':1} min={name === 'bandwidthMbps' ? 0 : String(name).endsWith('GB')?1/1024:1} max={name === 'bandwidthMbps' ? 10000 : undefined} defaultValue={value} required /></label>)}</div>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy ? '创建中…' : initial?'保存为新套餐':'创建套餐'}</button></div></form></ModalBackdrop>; }
|
||||
export function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record<string, unknown>) => Promise<void> }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal" onSubmit={async (event) => { event.preventDefault(); setBusy(true); const form = new FormData(event.currentTarget); try { await onCreate({ loginName: form.get('loginName'), name: form.get('displayName'), email: form.get('email'), displayName: form.get('displayName'), password: form.get('password'), planId: plans[0]?.id }); } catch (reason) { setError(reason instanceof Error ? reason.message : '创建失败'); setBusy(false); } }}><h2>创建用户</h2><p>创建登录账号后,可继续为该用户新增多个虚拟主机。</p><label>登录账号<input name="loginName" pattern="[a-z0-9][a-z0-9\-]{1,46}[a-z0-9]" minLength={3} maxLength={48} autoComplete="off" required /></label><label>显示名称<input name="displayName" minLength={2} maxLength={80} required /></label><label>登录邮箱<input name="email" type="email" required /></label><label>初始密码<input name="password" type="password" minLength={12} maxLength={72} required /></label>{error ? <p className="form-error" role="alert">{error}</p> : null}<div className="form-actions"><button type="button" className="secondary" onClick={onClose}>取消</button><button className="primary" disabled={busy || !plans.length}>{busy ? '创建中…' : '创建用户'}</button></div></form></ModalBackdrop>; }
|
||||
const planMB = 1024 ** 2;
|
||||
const planGB = 1024 ** 3;
|
||||
|
||||
export function PlanForm({ onClose, onCreate, initial }: { initial?: Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise<void> }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const fields = [
|
||||
{ name: 'storageMB', label: '存储空间(MB)', value: initial ? initial.storageBytes / planMB : 50 * 1024, min: 1, max: 1024 ** 3, capacity: true },
|
||||
{ name: 'databaseMB', label: '数据库空间(MB)', value: initial ? initial.databaseBytes / planMB : 20 * 1024, min: 1, max: 1024 ** 3, capacity: true },
|
||||
{ name: 'bandwidthGB', label: '月流量(GB)', value: initial ? initial.bandwidthBytes / planGB : 500, min: 1 / 1024, max: 1024 ** 2, capacity: true },
|
||||
{ name: 'bandwidthMbps', label: 'HTTP 每请求 / FTP 每会话限速(Mbps,0 不限)', value: initial?.bandwidthMbps ?? 0, min: 0, max: 10000 },
|
||||
{ name: 'processLimit', label: '进程数', value: initial?.processLimit ?? 100, min: 1, max: 100000 },
|
||||
{ name: 'projectLimit', label: '每主机网站数', value: initial?.projectLimit ?? 10, min: 1, max: 10000 },
|
||||
{ name: 'ftpLimit', label: 'FTP 账号数', value: initial?.ftpLimit ?? 10, min: 1, max: 10000 },
|
||||
{ name: 'databaseLimit', label: '数据库数', value: initial?.databaseLimit ?? 10, min: 1, max: 10000 },
|
||||
];
|
||||
return <ModalBackdrop className="modal-backdrop"><form className="tenant-modal plan-modal" onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
if (busy || !event.currentTarget.reportValidity()) return;
|
||||
const form = new FormData(event.currentTarget);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const capacity = (name: string, unit: number) => {
|
||||
const bytes = Math.round(Number(form.get(name)) * unit);
|
||||
if (!Number.isSafeInteger(bytes) || bytes < planMB || bytes > 1024 ** 5) throw new Error('资源容量必须在 1 MB 至 1 PB 之间');
|
||||
return bytes;
|
||||
};
|
||||
await onCreate({
|
||||
name: String(form.get('name')),
|
||||
storageBytes: capacity('storageMB', planMB),
|
||||
databaseBytes: capacity('databaseMB', planMB),
|
||||
bandwidthBytes: capacity('bandwidthGB', planGB),
|
||||
bandwidthMbps: Number(form.get('bandwidthMbps')),
|
||||
processLimit: Number(form.get('processLimit')),
|
||||
projectLimit: Number(form.get('projectLimit')),
|
||||
ftpLimit: Number(form.get('ftpLimit')),
|
||||
databaseLimit: Number(form.get('databaseLimit')),
|
||||
});
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '套餐保存失败');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}><h2>{initial ? '复制资源套餐' : '创建资源套餐'}</h2><label>套餐名称<input name="name" defaultValue={initial ? initial.name + ' 副本' : ''} maxLength={80} required /></label>
|
||||
<div className="plan-form-grid">{fields.map(field => <label key={field.name}>{field.label}<input name={field.name} type="number" step={field.capacity ? 'any' : 1} min={field.min} max={field.max} defaultValue={field.value} required disabled={busy} /></label>)}</div>
|
||||
{error ? <p className="form-error" role="alert">{error}</p> : null}
|
||||
<div className="form-actions"><button type="button" className="secondary" disabled={busy} onClick={onClose}>取消</button><button className="primary" disabled={busy}>{busy ? '创建中…' : initial ? '保存为新套餐' : '创建套餐'}</button></div>
|
||||
</form></ModalBackdrop>;
|
||||
}
|
||||
|
||||
function AdoptionForm({users,plans,onClose,onComplete}:{users:Tenant[];plans:Plan[];onClose:()=>void;onComplete:()=>Promise<void>}){return <HostProvisioning adopt users={users} plans={plans} onClose={onClose} onComplete={onComplete}/>}
|
||||
|
||||
|
||||
@@ -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<ProjectDraft>({ name: 'blog-demo', runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/', customDomain: '', autoSSL: true });
|
||||
const [draft, setDraft] = useState<ProjectDraft>(() => ({ name: randomHostName(), runtime: initialRuntime, version: runtimeVersions[initialRuntime]?.[0] ?? '', runPath: '/', customDomain: '', autoSSL: true }));
|
||||
const safeName = useMemo(() => draft.name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, ''), [draft.name]);
|
||||
const assignedDomain = `<随机主机名>.${rootDomain}`;
|
||||
const root = `${projectRoot.replace(/\/+$/, '')}/<随机主机名>`;
|
||||
|
||||
@@ -13,6 +13,7 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
||||
const previousInitialProject = useRef(initialProjectID);
|
||||
const [entries, setEntries] = useState<FileEntry[]>([]);
|
||||
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<HTMLInputElement>(null);
|
||||
const folderRef = useRef<HTMLInputElement>(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 <div className="page file-page">{confirmation}
|
||||
<div className="page-heading"><h1>文件管理</h1></div>
|
||||
<section className="file-panel">
|
||||
<div className="file-toolbar"><select aria-label="选择虚拟主机" value={projectID} onChange={(event) => { setProjectID(Number(event.target.value)); setPath(''); setError(''); }} disabled={loading}>{projects.map((project) => <option key={project.id} value={project.id}>{project.name} · {project.domain}</option>)}</select><div className="file-actions"><button className="secondary" disabled={loading} onClick={()=>setOperation({action:"mkdir",path:joinPath(path,"new-directory"),to:""})}>新建目录</button><button className="secondary" disabled={loading} onClick={()=>void showTrash()}>回收站</button><button className="secondary" disabled={loading} onClick={() => {setError('');setEditor({ path: joinPath(path, 'new-file.txt'), content: '', isNew: true })}}><Plus size={15} />新建文本</button><button className="secondary" onClick={() => uploadRef.current?.click()} disabled={loading}><Upload size={15} />上传文件</button><button className="secondary" onClick={() => void emptyTrash()} disabled={loading}><Trash2 size={15} />清空回收站</button><input ref={uploadRef} type="file" hidden onChange={(event) => { const file = event.target.files?.[0]; if (file) void upload(file); }} /><button className="icon-button" onClick={() => void load()} disabled={loading} aria-label="刷新文件"><RefreshCw size={16} /></button></div></div>
|
||||
<div className="file-toolbar"><select aria-label="选择虚拟主机" value={projectID} onChange={(event) => { setProjectID(Number(event.target.value)); setPath(''); setError(''); }} disabled={loading}>{projects.map((project) => <option key={project.id} value={project.id}>{project.name} · {project.domain}</option>)}</select><div className="file-actions"><button className="secondary" disabled={loading} onClick={()=>setOperation({action:"mkdir",path:joinPath(path,"new-directory"),to:""})}>新建目录</button><button className="secondary" disabled={loading} onClick={()=>void showTrash()}>回收站</button><button className="secondary" disabled={loading} onClick={() => {setError('');setEditor({ path: joinPath(path, 'new-file.txt'), content: '', isNew: true })}}><Plus size={15} />新建文本</button><button className="secondary" onClick={() => uploadRef.current?.click()} disabled={loading}><Upload size={15} />批量上传</button><button className="secondary" disabled={loading||!folderSupported} title={folderSupported?"保留所选文件夹及子目录结构":"当前浏览器不支持文件夹选择,请压缩后上传"} onClick={()=>folderRef.current?.click()}><Folder size={15}/>上传文件夹</button><button className="secondary" onClick={() => void emptyTrash()} disabled={loading}><Trash2 size={15} />清空回收站</button><input ref={uploadRef} aria-label="批量上传文件" type="file" multiple hidden onChange={(event) => {void upload(Array.from(event.target.files||[]))}} /><input ref={folderRef} aria-label="上传文件夹" type="file" multiple {...{webkitdirectory:''}} hidden onChange={event=>{const selected=Array.from(event.target.files||[]);if(!selected.length){setError('所选文件夹没有可上传文件;空目录不会被上传');return}void upload(selected)}} /><button className="icon-button" onClick={() => void load()} disabled={loading} aria-label="刷新文件"><RefreshCw size={16} /></button></div></div>
|
||||
<p className="file-transfer-hint">单批最多 100 个文件、总大小 30 MB,单文件上限 {formatBytes(uploadLimit)};文件夹上传保留目录结构(不含空目录);支持解压 ZIP、TAR、TAR.GZ、TGZ。</p>
|
||||
{uploadStatus?<p className="file-upload-status" role="status">{uploadStatus}</p>:null}
|
||||
<div className="file-breadcrumb"><button disabled={loading} onClick={() => setPath('')}>根目录</button>{segments.map((segment, index) => <span key={`${segment}-${index}`}>/ <button disabled={loading} onClick={() => setPath(segments.slice(0, index + 1).join('/'))}>{segment}</button></span>)}</div>
|
||||
{error && !editor && !operation ? <p className="file-error" role="alert">{error}</p> : null}
|
||||
<div className="file-table" aria-busy={loading}><div className="file-row file-head"><span>名称</span><span>大小</span><span>修改时间</span><span>操作</span></div>{path ? <button disabled={loading} className="file-row file-parent" onClick={() => setPath(parentPath(path))}><span><ArrowLeft size={17} />返回上级</span><span>—</span><span>—</span><span /></button> : null}{visibleEntries.map((entry) => <div className="file-row" key={entry.path}>{entry.directory||isTextFile(entry)&&entry.size<=1024**2?<button className="file-name" onClick={()=>entry.directory?setPath(entry.path):void edit(entry)}>{entry.directory?<Folder size={18}/>:<File size={18}/>}<span>{entry.name}</span></button>:<span className="file-name" title={isTextFile(entry)?'超过 1 MB,请下载后编辑并重新上传':'此类型不支持在线编辑,请下载或使用 FTP 处理'}><File size={18}/><span>{entry.name}</span></span>}<span>{entry.directory ? '—' : formatBytes(entry.size)}</span><span>{formatDate(entry.modified)}</span><span className="file-row-actions">{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? <button onClick={() => void edit(entry)} aria-label={`编辑 ${entry.name}`}><Edit3 size={15} /></button> : null}{!entry.directory ? <a href={api.fileDownloadURL(projectID, entry.path)} aria-label={`下载 ${entry.name}`}><Download size={15} /></a> : null}<select aria-label={'更多操作 '+entry.name} value="" disabled={loading} onChange={e=>{const action=e.target.value;if(action)setOperation({action,path:entry.path,to:operationTarget(action,entry)})}}><option value="">更多</option><option value="move">重命名 / 移动</option><option value="copy">复制</option><option value="zip">压缩为 ZIP</option>{entry.name.toLowerCase().endsWith('.zip')?<option value="extract">解压 ZIP</option>:null}</select><button onClick={() => void trash(entry)} aria-label={`删除 ${entry.name}`}><Trash2 size={15} /></button></span></div>)}{!loading && !error && entries.length === 0 ? <div className="file-empty">目录为空</div> : null}{loading ? <div className="file-empty" role="status">正在读取…</div> : null}</div>
|
||||
<div className="file-table" aria-busy={loading}><div className="file-row file-head"><span>名称</span><span>大小</span><span>修改时间</span><span>操作</span></div>{path ? <button disabled={loading} className="file-row file-parent" onClick={() => setPath(parentPath(path))}><span><ArrowLeft size={17} />返回上级</span><span>—</span><span>—</span><span /></button> : null}{visibleEntries.map((entry) => <div className="file-row" key={entry.path}>{entry.directory||isTextFile(entry)&&entry.size<=1024**2?<button className="file-name" onClick={()=>entry.directory?setPath(entry.path):void edit(entry)}>{entry.directory?<Folder size={18}/>:<File size={18}/>}<span>{entry.name}</span></button>:<span className="file-name" title={isTextFile(entry)?'超过 1 MB,请下载后编辑并重新上传':'此类型不支持在线编辑,请下载或使用 FTP 处理'}><File size={18}/><span>{entry.name}</span></span>}<span>{entry.directory ? '—' : formatBytes(entry.size)}</span><span>{formatDate(entry.modified)}</span><span className="file-row-actions">{!entry.directory && isTextFile(entry) && entry.size <= 1024 ** 2 ? <button onClick={() => void edit(entry)} aria-label={`编辑 ${entry.name}`}><Edit3 size={15} /></button> : null}{!entry.directory ? <a href={api.fileDownloadURL(projectID, entry.path)} aria-label={`下载 ${entry.name}`}><Download size={15} /></a> : null}{!entry.directory&&isArchive(entry)?<button onClick={()=>setOperation({action:'extract',path:entry.path,to:operationTarget('extract',entry)})} aria-label={'解压 '+entry.name}>解压</button>:null}<select aria-label={'更多操作 '+entry.name} value="" disabled={loading} onChange={e=>{const action=e.target.value;if(action)setOperation({action,path:entry.path,to:operationTarget(action,entry)})}}><option value="">更多</option><option value="move">重命名 / 移动</option><option value="copy">复制</option><option value="zip">压缩为 ZIP</option>{isArchive(entry)?<option value="extract">解压压缩包</option>:null}</select><button onClick={() => void trash(entry)} aria-label={`删除 ${entry.name}`}><Trash2 size={15} /></button></span></div>)}{!loading && !error && entries.length === 0 ? <div className="file-empty">目录为空</div> : null}{loading ? <div className="file-empty" role="status">正在读取…</div> : null}</div>
|
||||
</section>
|
||||
{trashEntries?<section className="file-panel"><h2>主机回收站</h2><button className="secondary" onClick={closeTrash}>关闭回收站</button>{!trashEntries.length?<p>回收站为空</p>:trashEntries.map(entry=><div className="file-row" key={entry.id}><span>{entry.originalPath}</span><span>{formatBytes(entry.size)}</span><span>{formatDate(entry.deletedAt)}</span><button onClick={()=>setOperation({action:'restore',path:entry.id,to:entry.originalPath})}>恢复 {entry.name}</button></div>)}</section>:null}
|
||||
{operation?<ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={e=>{e.preventDefault();void perform()}}><h2>{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压 ZIP',restore:'恢复文件'}[operation.action]}</h2><p>路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。</p>{operation.action!=='restore'?<label>{operation.action==='mkdir'?'目录路径':'源路径'}<input disabled={busy} value={operation.path} readOnly={operation.action!=='mkdir'} required onChange={e=>setOperation({...operation,path:e.target.value})}/></label>:null}{operation.action!=='mkdir'?<label>目标路径<input disabled={busy} value={operation.to} required onChange={e=>setOperation({...operation,to:e.target.value})}/></label>:null}{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>{setOperation(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy?'正在处理…':'执行操作'}</button></div></form></ModalBackdrop>:null}
|
||||
{operation?<ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={e=>{e.preventDefault();void perform()}}><h2>{{mkdir:'新建目录',move:'重命名 / 移动',copy:'复制',zip:'压缩 ZIP',extract:'解压压缩包',restore:'恢复文件'}[operation.action]}</h2><p>路径均相对于当前主机根目录。目标必须不存在;复制、压缩和解压最多处理 256 MiB,并受套餐剩余空间限制。</p>{operation.action!=='restore'?<label>{operation.action==='mkdir'?'目录路径':'源路径'}<input disabled={busy} value={operation.path} readOnly={operation.action!=='mkdir'} required onChange={e=>setOperation({...operation,path:e.target.value})}/></label>:null}{operation.action!=='mkdir'?<label>目标路径<input disabled={busy} value={operation.to} required onChange={e=>setOperation({...operation,to:e.target.value})}/></label>:null}{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" disabled={busy} onClick={()=>{setOperation(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy?'正在处理…':'执行操作'}</button></div></form></ModalBackdrop>:null}
|
||||
{editor ? <ModalBackdrop className="modal-backdrop"><form className="file-editor" onSubmit={async (event) => { event.preventDefault(); if(busy)return; setBusy(true); setError(''); if (!live) { setEditor(null); setBusy(false); return; } try { await api.writeFile(projectID, editor.path, editor.content, !editor.isNew); setEditor(null); await load(); } catch (reason) { setError(message(reason, '保存失败')); } finally { setBusy(false); } }}><button type="button" className="modal-close" disabled={busy} onClick={() => {setEditor(null);setError('')}} aria-label="关闭编辑器"><X size={17} /></button><h2>{editor.isNew ? '新建文本文件' : '编辑文本文件'}</h2><label>主机内路径<input disabled={busy} required value={editor.path} readOnly={!editor.isNew} onChange={(event) => setEditor({ ...editor, path: event.target.value })} /></label><label>内容<textarea disabled={busy} spellCheck={false} value={editor.content} onChange={(event) => setEditor({ ...editor, content: event.target.value })} /></label>{error?<p className="form-error" role="alert">{error}</p>:null}<div className="form-actions"><button type="button" className="secondary" disabled={busy} onClick={() => {setEditor(null);setError('')}}>取消</button><button className="primary" disabled={loading}>{busy ? '保存中…' : '保存'}</button></div></form></ModalBackdrop> : null}
|
||||
</div>;
|
||||
}
|
||||
@@ -125,7 +145,7 @@ export function FileManager({ projects, initialProjectID, live = true }: { proje
|
||||
function operationTarget(action:string,entry:FileEntry){
|
||||
if(action==='move')return entry.path;
|
||||
if(action==='zip')return entry.path+'.zip';
|
||||
if(action==='extract')return entry.path.replace(/\.zip$/i,'')+'-extracted';
|
||||
if(action==='extract')return entry.path.replace(/\.(?:tar\.gz|tgz|tar|zip)$/i,'')+'-extracted';
|
||||
const extension=entry.directory?-1:entry.name.lastIndexOf('.');
|
||||
return extension>0?entry.path.slice(0,-(entry.name.length-extension))+'-copy'+entry.name.slice(extension):entry.path+'-copy';
|
||||
}
|
||||
@@ -140,3 +160,7 @@ function demoEntries(path: string): FileEntry[] {
|
||||
if (path) return [];
|
||||
return [{ name: 'assets', path: 'assets', directory: true, size: 0, modified }, { name: 'index.php', path: 'index.php', directory: false, size: 1260, modified }, { name: 'README.md', path: 'README.md', directory: false, size: 860, modified }];
|
||||
}
|
||||
|
||||
function isArchive(entry:FileEntry){return !entry.directory&&/\.(?:zip|tar|tar\.gz|tgz)$/i.test(entry.name)}
|
||||
|
||||
function uploadFilePath(file:File){return file.webkitRelativePath||file.name}
|
||||
@@ -1,3 +1,4 @@
|
||||
import {randomHostName} from '../hostName';
|
||||
import {ModalBackdrop} from './ModalBackdrop';
|
||||
import {useEffect,useState} from 'react';
|
||||
import {api,type AdminProject,type ControlNode,type Credentials,type PanelSite,type Tenant} from '../api';
|
||||
@@ -5,6 +6,7 @@ import type {Plan,RuntimeCatalog,Runtime} from '../types';
|
||||
import {CredentialsModal} from './CredentialsModal';
|
||||
|
||||
export function HostProvisioning({users,plans,adopt=false,onClose,onComplete}:{users:Tenant[];plans:Plan[];adopt?:boolean;onClose:()=>void;onComplete:()=>Promise<void>}){
|
||||
const [defaultName]=useState(randomHostName);
|
||||
const [nodes,setNodes]=useState<ControlNode[]>([]);const [nodeId,setNodeId]=useState(0);const [versions,setVersions]=useState<RuntimeCatalog>({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});const [sites,setSites]=useState<PanelSite[]>([]);const [siteId,setSiteId]=useState(0);const [runtime,setRuntime]=useState<Runtime>('PHP');const [version,setVersion]=useState('');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [credentials,setCredentials]=useState<Credentials>();
|
||||
useEffect(()=>{let active=true;api.nodes().then(r=>{if(active){setNodes(r.nodes);setNodeId(r.nodes.find(n=>n.enabled)?.id||0)}}).catch(e=>{if(active)setError(e.message)});return()=>{active=false}},[]);
|
||||
useEffect(()=>{let active=true;setVersions({PHP:[],"Node.js":[],Python:[],Go:[],Java:[]});setSites([]);setSiteId(0);setVersion('');if(!nodeId)return;setBusy(true);setError('');api.panelSites(nodeId).then(r=>{if(active){const catalog=Object.fromEntries((["PHP","Node.js","Python","Go","Java"] as Runtime[]).map(name=>[name,Array.isArray(r.versions?.[name])?r.versions[name]:[]])) as RuntimeCatalog;setVersions(catalog);setSites(Array.isArray(r.sites)?r.sites:[]);setRuntime('PHP');setVersion(catalog.PHP?.[0]||'')}}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setBusy(false)});return()=>{active=false}},[nodeId]);
|
||||
@@ -15,7 +17,7 @@ export function HostProvisioning({users,plans,adopt=false,onClose,onComplete}:{u
|
||||
<label>所属节点<select aria-label="所属节点" value={nodeId} required onChange={e=>setNodeId(Number(e.target.value))}><option value="0" disabled>请选择节点</option>{nodes.filter(n=>n.enabled).map(n=><option key={n.id} value={n.id}>{n.name} · {n.rootDomain}</option>)}</select></label>
|
||||
<div className="plan-form-grid"><label>{adopt?'分配用户':'绑定用户(可选)'}<select name="tenantId" required={adopt}><option value={adopt?'':'0'}>{adopt?'请选择':'不绑定用户,独立主机账号登录'}</option>{users.filter(u=>u.status==='active').map(u=><option key={u.id} value={u.id}>{u.name}</option>)}</select></label><label>主机套餐<select name="planId" required><option value="">请选择</option>{plans.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></label></div>
|
||||
{adopt?<label>待迁移站点<select value={siteId||''} required onChange={e=>setSiteId(Number(e.target.value))}><option value="">请选择</option>{sites.map(s=><option key={s.id} value={s.id}>{s.domain} · {s.path}</option>)}</select><small>原目录复制至主机根目录,接管成功前保留原文件。</small></label>:null}
|
||||
<label>主机名称<input name="name" minLength={3} maxLength={50} pattern="[a-z0-9](?:[a-z0-9]|-){1,48}[a-z0-9]" required/></label>
|
||||
<label>主机名称<input name="name" defaultValue={defaultName} minLength={3} maxLength={50} pattern="[a-z0-9](?:[a-z0-9]|-){1,48}[a-z0-9]" required/></label>
|
||||
<div className="plan-form-grid"><label>运行环境<select value={runtime} onChange={e=>{setRuntime(e.target.value as Runtime);setVersion(versions[e.target.value as Runtime]?.[0]||'')}}>{Object.keys(versions).map(v=><option key={v}>{v}</option>)}</select></label><label>版本<select value={version} required onChange={e=>setVersion(e.target.value)}>{(versions[runtime]||[]).map(v=><option key={v}>{v}</option>)}</select></label></div>
|
||||
<label>运行目录<input name="runPath" defaultValue="/" required/><small>目录位于 {node?.tenantRoot}/随机主机名,默认域名为 随机主机名.{node?.rootDomain}</small></label>
|
||||
{!adopt?<label>到期时间<input name="expiresAt" type="datetime-local"/><small>留空表示长期使用;到期停用,宽限 3 天,回收保留 7 天,备份保留 14 天。</small></label>:null}
|
||||
|
||||
@@ -12,7 +12,7 @@ export function AccountEditor({account,onClose,onChanged,intent='edit'}:{intent?
|
||||
useEffect(()=>{let active=true;setProfile(undefined);setError('');api.accountProfile(account.id).then(p=>{if(active)setProfile(p)}).catch(e=>{if(active)setError(message(e))});return()=>{active=false}},[account.id,retry]);
|
||||
async function save(){if(!profile)return;setBusy(true);setError('');try{await api.updateAccount(account.id,profile);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||
async function remove(){if(!profile||!await confirm(`删除用户「${profile.name}」?登录权限将被撤销,用户标识和历史审计保留。名下主机必须先解绑或转移。`,{title:'删除用户',confirmLabel:'确认删除用户',danger:true}))return;setBusy(true);setError('');try{await api.deleteAccount(account.id,account.slug);await onChanged();onClose()}catch(e){setError(message(e))}finally{setBusy(false)}}
|
||||
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>{intent==='delete'?'删除用户':'用户详情与编辑'}</h2><p>用户标识:<code>{account.slug}</code> · #{account.id}</p>{error?<p className="form-error" role="alert">{error}</p>:null}{profile?<>{intent==='edit'?<form onSubmit={e=>{e.preventDefault();void save()}}><fieldset disabled={busy}><label>用户名称<input required maxLength={120} value={profile.name} onChange={e=>setProfile({...profile,name:e.target.value})}/></label><label>联系人姓名<input required minLength={2} maxLength={80} value={profile.displayName} onChange={e=>setProfile({...profile,displayName:e.target.value})}/></label><label>登录邮箱<input type="email" required maxLength={190} value={profile.email} onChange={e=>setProfile({...profile,email:e.target.value})}/></label><p>关联主机:{profile.projectCount} 台</p><div className="form-actions"><button type="button" className="secondary" onClick={onClose}>关闭</button><button className="primary">{busy?'保存中…':'保存用户资料'}</button></div></fieldset></form>:null}<div className="resource-danger-zone"><p>删除前需逐一解绑或转移全部主机,包括回收中的主机。用户标识与日志保留。</p><button type="button" className="secondary danger-text" title={profile.projectCount>0?'需先逐一解绑或转移全部主机,包括回收中的主机':undefined} disabled={busy||profile.projectCount>0} onClick={()=>void remove()}>删除用户</button>{intent==='delete'?<button type="button" className="secondary" onClick={onClose}>取消</button>:null}</div></>:<><p>{error?'用户资料读取失败':'正在读取用户资料…'}</p><div className="form-actions"><button onClick={onClose}>关闭</button>{error?<button onClick={()=>setRetry(v=>v+1)}>重新读取</button>:null}</div></>}</section></ModalBackdrop>{confirmation}</>;
|
||||
return <><ModalBackdrop><section className="tenant-modal resource-editor"><h2>{intent==='delete'?'删除用户':'用户详情与编辑'}</h2><p>用户标识:<code>{account.slug}</code> · #{account.id}</p>{error?<p className="form-error" role="alert">{error}</p>:null}{profile?<>{intent==='edit'?<form onSubmit={e=>{e.preventDefault();void save()}}><fieldset disabled={busy}><label>登录账号<input readOnly value={profile.loginName||profile.email}/></label><label>显示名称<input required minLength={2} maxLength={80} value={profile.displayName} onChange={e=>setProfile({...profile,name:e.target.value,displayName:e.target.value})}/></label><label>登录邮箱<input type="email" required maxLength={190} value={profile.email} onChange={e=>setProfile({...profile,email:e.target.value})}/></label><p>关联主机:{profile.projectCount} 台</p><div className="form-actions"><button type="button" className="secondary" onClick={onClose}>关闭</button><button className="primary">{busy?'保存中…':'保存用户资料'}</button></div></fieldset></form>:null}<div className="resource-danger-zone"><p>删除前需逐一解绑或转移全部主机,包括回收中的主机。用户标识与日志保留。</p><button type="button" className="secondary danger-text" title={profile.projectCount>0?'需先逐一解绑或转移全部主机,包括回收中的主机':undefined} disabled={busy||profile.projectCount>0} onClick={()=>void remove()}>删除用户</button>{intent==='delete'?<button type="button" className="secondary" onClick={onClose}>取消</button>:null}</div></>:<><p>{error?'用户资料读取失败':'正在读取用户资料…'}</p><div className="form-actions"><button onClick={onClose}>关闭</button>{error?<button onClick={()=>setRetry(v=>v+1)}>重新读取</button>:null}</div></>}</section></ModalBackdrop>{confirmation}</>;
|
||||
}
|
||||
|
||||
export function HostEditor({host,onClose,onChanged,intent='edit'}:{intent?:'edit'|'recycle';host:AdminProject;onClose:()=>void;onChanged:()=>Promise<void>}){
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export function randomHostName() {
|
||||
return 'sv' + Array.from(crypto.getRandomValues(new Uint8Array(5)), value => value.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
@@ -5320,3 +5320,5 @@ to {
|
||||
.sites-head > span:last-child {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.file-transfer-hint, .file-upload-status { margin: 12px 16px; color: var(--text-muted, #7b899c); font-size: 12px; line-height: 1.6; }
|
||||
Reference in new issue
Block a user