commit 248badd33ec21650def2b5776062d1ae9747ef5d Author: canglan Date: Fri Oct 30 08:39:10 2026 +0800 feat: import Sea vHost single-server testing release diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1bbd695 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.sh text eol=lf +*.py text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d246cb1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +frontend/node_modules/ +frontend/dist/ +frontend/*.tsbuildinfo +frontend/vite.config.js +frontend/vite.config.d.ts +backend/sea-vhost +backend/coverage.out +.env +*.log +.idea/ +.vscode/ +data/ +.cache/ +__pycache__/ +*.pyc +build/bin/ +build/web/ +build/smoke/ +build/tools/ +build/*.tar.gz +build/*.sha256 +build/ +releases/ +backend/.cache/ +backend/.tmp*/ +frontend/.npm-cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..50c5d85 --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# Sea vHost + +36 单机实机测试从 [交付说明](docs/handover-2026-10-30.md) 开始。现有服务已启动,直接访问控制台;无需重新安装。标准安装包与干净源码包分别交付,文件清单及用途见 [安装工具说明](deploy/README.md)。 + +Sea vHost 是面向 Debian + 宝塔 Linux 面板的多租户虚拟主机控制面,支持本机托管或主控主动连接多台被控。主控集中保存平台 MySQL 数据与调度状态,通过双向 TLS 调用被控的受限执行入口;被控使用本机宝塔 API 管理 Nginx 站点、FTP、MySQL、SSL、反向代理和运行环境,并用隔离代理管理固定根目录、目录权限和自有 Nginx 安全配置。 + +多被控的安装入口、主机级套餐、节点域名与验证边界见 [多被控安装说明](docs/multi-node-installation.md)。当前按用户要求,以 `36.140.39.34` 的 `host.ser888.cn` 作为单机生产测试环境;平台使用本机节点,后续开发测试以此机为准。真实 MySQL 与两个 mTLS 执行端的集成测试已通过,两台独立宝塔服务器的跨机安装与运行验收尚未完成。 + +当前功能、正常使用流程及剩余验收边界见 [2026-10-29 项目状态整理](docs/project-status-2026-10-29.md)。环境切换与真实 HTTP-01 实测见 [2026-10-29 验收报告](docs/ui-acceptance-2026-10-29.md)。后续页面美化、SSO 首次绑定/可选建号与分类密码策略见 [SSO 与界面验收](docs/sso-ui-acceptance.md)。 + +单机 Web 创建、五类语言部署、账号安全、主机回收与权限实测见 [2026-10-26 Web 验收报告](docs/web-acceptance-2026-10-26.md)。管理员已可从用户/主机列表临时代入,业务接口按目标身份鉴权,代入操作仅进入管理员审计;客户日志只显示对应用户/主机的普通操作。 + +解压安装包后,以 root 在终端运行 `bash deploy/install.sh`,进入中文交互向导并选择主控或被控。被控只需配对文件和隐藏输入的宝塔 API 密钥,无需手写凭据 JSON。原脚本参数方式保留给自动化部署。 + +主机、用户与节点的增删改查、回收恢复及权限规则见 [资源管理说明](docs/resource-management.md)。 + +完整文档分类与阅读顺序见 [文档索引](docs/README.md)。 + +## 已实现 + +- 节点管理与配对、按节点配置环境和 IP 池、按用户/节点/套餐开通主机;每台主机独立额度与到期时间。远程执行的不确定结果进入主控待核验记录,不自动重发破坏性请求。 +- 管理员、租户与主机三级账户,不开放公开密码注册;管理员可额外允许通过已验证的 SSO 身份创建普通用户,默认关闭。每台虚拟主机拥有独立随机登录名和密码,主机账号只能访问自身资源且不支持 SSO。租户可重置主机登录密码,重置后该主机的旧会话立即全部失效。 +- 一台虚拟主机可在固定根目录下新增多个网站;每站独立选择 PHP、Node.js、Python、Go 或 Java 版本、运行目录和域名,并可独立启停。删除附加网站只撤销宝塔/Nginx 配置,不删除主机目录中的源码;系统不接入 Docker。 +- 自动三级域名、自定义域名审核开关,以及 Let’s Encrypt HTTP-01 与 DNS-01 两套签发流程。创建时与后续绑定统一拒绝平台根域、控制台域名和独立配置的 FTP 证书来源域名;每站最多保留 100 个域名(含默认域名),计数在站点行锁内完成。DNS-01 由管理员为平台根域、租户为自有域名分别配置 Cloudflare、阿里云 DNS、腾讯云 DNSPod、西部数码或彩虹聚合 DNS 凭据,系统按最长域名后缀路由、创建并精确删除 TXT 记录、部署证书并提前 30 天续期;凭据经 AES-256-GCM 加密,不进入宝塔全局 DNS 配置、主机目录或租户进程环境。凭据可单独执行“随机 TXT 创建并精确删除”的连通性测试,不接触 ACME 签发限额。租户也可关闭 SSL,或上传经完整校验的自有 PEM 证书。 +- 租户资源中心可查看全部网站域名、FTP、MySQL 与操作日志;自定义域名可精确提交到某个附加网站,管理员具有待审核队列和批准/拒绝操作。 +- 项目创建的原子化编排与逆序回滚;宝塔 API 模拟器便于无实机开发。 +- 非 PHP 网站提供上传后部署:按运行环境校验入口文件、运行目录和普通文件类型,拒绝越界与软链接;通过宝塔免费语言项目接口创建、验证、启停及删除真实进程,再由 Nginx 反代分配的回环端口。适配器不会把接口返回成功等同于进程已运行。 +- 每主机默认一个 FTP 与同名 MySQL 账号,密码随机生成、经认证加密保存并可在授权界面重新查看;FTP 客户端直接连接该主机自己的默认域名,服务器级 Pure-FTPd 可复用覆盖租户泛域名的证书并强制显式 FTPS;Web 文件管理器默认单文件上限 20 MiB,带路径与符号链接防越界。 +- 套餐包含磁盘容量、数据库容量、月流量、带宽限速、进程数、FTP 账号数、数据库数和网站数八项额度;分钟级统一巡检实际扫描目录、读取宝塔数据库大小、按 Nginx 日志游标累计月流量并按独立 UID 统计进程。任一容量超额都会停站、停 FTP、终止租户进程并撤销主机 Linux 身份的目录写权限,但保留 Web 文件服务的删除/清理能力;控制面同时冻结新增、启动、部署、绑域名及证书变更。恢复后只恢复受管目录权限并保持网站停止,须租户手动启动。 +- 数据库超额会撤销同名原生 MySQL 账号的写权限并断开旧连接,保留查询与删除/删表清理能力,额度恢复后恢复写入。回收前生成网站+客户 SQL+SHA-256 清单的完整归档并验证,失败保留源资源,备份自创建起保留 14 天。 +- 套餐单独配置 Mbps 限速:HTTP 每请求、FTP 每会话,0 为不限速;月流量合并 HTTP 响应正文与 FTP 文件上传/下载。多个连接不共享一份主机总速率。 +- 独立 root 隔离代理与最小权限 Unix Socket;每台虚拟主机使用 home 为 `/nonexistent`、密码锁定、`nologin` 的独立 Linux 身份,Node/Python/Go/Java 进程、PHP-FPM master/worker 和 FTP UID/GID 都映射到该身份,PHP 进程不继承 agent capabilities,Nginx `www` 仅通过 ACL 获得只读权限。磁盘仍采用可恢复的软配额,不依赖文件系统 quota。 +- 宝塔密钥隔离:专用非 root panel broker 独占密钥,Web API 只调用固定 RPC,并以资源登记表保护面板既有资源。 +- 免费能力硬白名单:底层客户端只允许网站、FTP、数据库、ACME、反代和基础语言项目接口,未登记路由会在发送前拒绝;不调用宝塔专业版或企业版插件。 +- 管理员“环境配置”支持持久化安装/更新任务、PHP 同分支补丁更新、逐站点切换已安装版本,以及配置版本与实际进程版本核验。PHP 更新前保存分支环境并检查扩展,失败回退;Node.js、Python、Java 保留旧版本逐站点迁移,Python 新建虚拟环境并恢复依赖,Go 必须上传由目标 SDK 编译的新程序。跨分支切换必须明确确认,不自动升级业务。 +- 自有 Nginx 基础防护:每站点启用限频、单 IP 连接限制、请求体/超时约束、危险方法与敏感文件拦截;写入后必须通过 `nginx -t`,失败自动恢复旧配置。 +- 中文蓝色响应式控制台,按管理员、用户和独立主机身份提供对应的主机、网站、域名、数据库、FTP、文件、资源图表与操作日志入口;独立主机视图不显示总览,并提供可用的移动端抽屉导航。 +- 一次性 Web 安装向导:现场填写并测试 MySQL、宝塔 API、租户根域、控制台域名、FTP 证书来源域名与首个管理员,成功后原子落盘并自动切换运行模式。证书来源可与控制台域名相同,但证书必须覆盖租户默认主机名。 + +## 目录 + +- `frontend/`:React + TypeScript + Vite 控制台。 +- `backend/`:Go API、MySQL 迁移、宝塔适配器与隔离代理。 +- `deploy/`:Nginx、systemd、构建与安装脚本。 +- `docs/`:架构、安全、宝塔兼容性和部署说明。 + +## 本地开发 + +```bash +cd frontend +npm install +npm run dev + +cd ../backend +copy .env.example .env +go test ./... +``` + +后端需要 MySQL。新部署由 `deploy/install.sh` 生成安装令牌,再通过 Web 向导完成配置。旧版纯环境变量模式仅保留给升级与本地开发;生产安装向导会强制关闭面板和隔离代理 mock,并通过 `docs/security.md` 的上线安全门。 + +## 验证 + +```bash +cd frontend && npm run build && npm test +cd backend && go test ./... +``` + +部署步骤见 `docs/deployment.md`。 + +组件补丁与站点迁移的行为、共享 PHP 影响范围和中断恢复规则见 `docs/deployment.md` 的“运行环境维护”。下述 2026-10-20 验收结论属于当日历史快照,不替代后续版本的实机验证。 + +早期测试机的安装与资源验收见 [2026-10-25 安装与测试报告](docs/installation-test-2026-10-25.md):三种安装角色、升级、主控主动 mTLS、五类语言应用、FTPS/MySQL、软配额与权限边界均已测试。后续已实测数据库写保护与恢复、SQL 回收备份及两次还原、HTTP/FTP 限速与流量计量。三条根域+端口公网入口通过,仅供本轮测试;外部 DNS/SSO/SMTP、跨服务器 mTLS 和子域白名单仍按实际覆盖范围列出。 + +日常开通、JSON 批量管理、网站配置、计划任务、phpMyAdmin 与管理端 API 的操作流程见 [主机系统操作说明](docs/hosting-operations.md)。 diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..a16d5b0 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,18 @@ +SEA_ADDR=127.0.0.1:8080 +SEA_CONFIG_FILE=/var/lib/sea-vhost/config.json + +# deploy/install.sh 会生成至少 32 字节的随机值。首次安装写接口必须携带该令牌。 +SEA_SETUP_TOKEN=replace-with-at-least-24-random-characters +SEA_COOKIE_SECURE=true + +# 下列路径由管理员固定,不允许通过 Web 安装页改写。 +SEA_TENANT_ROOT=/www/wwwroot/seavHost/vHost +SEA_UPLOAD_LIMIT=20971520 +SEA_AGENT_SOCKET=/run/sea-vhost/agent.sock +SEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock +SEA_PANEL_BROKER_STATE=/var/lib/sea-vhost-panel +SEA_QUOTA_MOUNT=/www +SEA_AGENT_GROUP=sea-vhost-files + +# 兼容旧版纯环境变量部署:仅当 SEA_CONFIG_FILE 不存在且设置了 +# SEA_SESSION_SECRET 时生效。新安装请使用 Web 安装向导。 diff --git a/backend/cmd/agent/main.go b/backend/cmd/agent/main.go new file mode 100644 index 0000000..5064ceb --- /dev/null +++ b/backend/cmd/agent/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + "sea-vhost/internal/isolation" +) + +func main() { + socket := env("SEA_AGENT_SOCKET", "/run/sea-vhost/agent.sock") + root := env("SEA_TENANT_ROOT", "/www/wwwroot/seavHost/vHost") + backupRoot := env("SEA_BACKUP_ROOT", "/www/backup/sea-vhost") + legacyRoot := env("SEA_LEGACY_SITE_ROOT", "/www/wwwroot") + fileOwner := env("SEA_FILE_OWNER", "sea-vhost") + nodePIDRoot := env("SEA_NODE_PID_ROOT", "/www/server/nodejs/vhost/pids") + nginxVhostRoot := env("SEA_NGINX_VHOST_ROOT", "/www/server/panel/vhost/nginx") + nginxBinary := env("SEA_NGINX_BINARY", "/www/server/nginx/sbin/nginx") + purePWBinary := env("SEA_PURE_PW_BINARY", "/www/server/pure-ftpd/bin/pure-pw") + phpStateRoot := env("SEA_PHP_IDENTITY_STATE", "/var/lib/sea-vhost-agent/php") + phpRunRoot := env("SEA_PHP_IDENTITY_RUN", "/run/sea-vhost-php") + usageStatePath := env("SEA_USAGE_STATE", "/var/lib/sea-vhost-agent/traffic.json") + nginxLogRoot := env("SEA_NGINX_LOG_ROOT", "/www/wwwlogs") + certificateRoot := env("SEA_CERT_ROOT", "/www/server/panel/vhost/cert") + pureFTPConfig := env("SEA_PURE_FTP_CONFIG", "/www/server/pure-ftpd/etc/pure-ftpd.conf") + pureFTPPem := env("SEA_PURE_FTP_PEM", "/www/server/pure-ftpd/etc/pure-ftpd.pem") + if err := os.MkdirAll(filepath.Dir(socket), 0750); err != nil { + slog.Error("cannot create socket directory", "error", err) + os.Exit(1) + } + _ = os.Remove(socket) + listener, err := net.Listen("unix", socket) + if err != nil { + slog.Error("cannot listen", "error", err) + os.Exit(1) + } + defer listener.Close() + if err = os.Chmod(socket, 0660); err != nil { + slog.Error("cannot secure socket", "error", err) + os.Exit(1) + } + agent := isolation.Agent{Root: root, BackupRoot: backupRoot, LegacyRoot: legacyRoot, FileOwner: fileOwner, NodePIDRoot: nodePIDRoot, NginxVhostRoot: nginxVhostRoot, NginxBinary: nginxBinary, PurePWBinary: purePWBinary, PHPStateRoot: phpStateRoot, PHPRunRoot: phpRunRoot, UsageStatePath: usageStatePath, NginxLogRoot: nginxLogRoot, CertificateRoot: certificateRoot, PureFTPConfig: pureFTPConfig, PureFTPPem: pureFTPPem, InternalToken: os.Getenv("SEA_INTERNAL_AUTH_TOKEN")} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if os.Getenv("SEA_NODE_STATELESS") != "true" { + go agent.RunRuntimeBackupExpiry(ctx) + } + server := &http.Server{Handler: agent.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 2 * time.Hour, IdleTimeout: 30 * time.Second} + go func() { + if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + slog.Error("agent failed", "error", err) + os.Exit(1) + } + }() + stop := make(chan os.Signal, 1) + signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) + <-stop + _ = server.Close() +} +func env(name, fallback string) string { + if value := os.Getenv(name); value != "" { + return value + } + return fallback +} diff --git a/backend/cmd/node/main.go b/backend/cmd/node/main.go new file mode 100644 index 0000000..7dd6128 --- /dev/null +++ b/backend/cmd/node/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + "sea-vhost/internal/controlwire" + "sea-vhost/internal/executor" +) + +type configuration struct { + Identity controlwire.ServerIdentity `json:"identity"` + Address string `json:"address"` + TenantRoot string `json:"tenantRoot"` + BrokerSocket string `json:"brokerSocket"` + AgentSocket string `json:"agentSocket"` +} + +func main() { + path := os.Getenv("SEA_NODE_CONFIG") + if path == "" { + path = "/etc/sea-vhost-node/config.json" + } + data, err := os.ReadFile(path) + if err != nil { + slog.Error("cannot read node configuration") + os.Exit(1) + } + var cfg configuration + if json.Unmarshal(data, &cfg) != nil || cfg.Identity.NodeID == 0 || cfg.Address == "" || cfg.TenantRoot == "" { + slog.Error("invalid node configuration") + os.Exit(1) + } + if !filepath.IsAbs(cfg.TenantRoot) || filepath.Clean(cfg.TenantRoot) != cfg.TenantRoot { + slog.Error("invalid node root") + os.Exit(1) + } + tlsConfig, err := controlwire.ServerTLS(cfg.Identity) + if err != nil { + slog.Error("invalid node TLS identity") + os.Exit(1) + } + token := os.Getenv("SEA_INTERNAL_AUTH_TOKEN") + if len(token) < 32 { + slog.Error("node local execution token is missing") + os.Exit(1) + } + gateway := &executor.Gateway{NodeID: cfg.Identity.NodeID, TenantRoot: cfg.TenantRoot, BrokerSocket: cfg.BrokerSocket, AgentSocket: cfg.AgentSocket, InternalToken: token} + server := &http.Server{Addr: cfg.Address, Handler: gateway.Handler(), TLSConfig: tlsConfig, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 2 * time.Hour, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10} + failed := make(chan error, 1) + go func() { failed <- server.ListenAndServeTLS("", "") }() + stop, done := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer done() + select { + case <-stop.Done(): + case err := <-failed: + if !errors.Is(err, http.ErrServerClosed) { + slog.Error("node service stopped", "error", err) + os.Exit(1) + } + } + shutdown, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) +} diff --git a/backend/cmd/panel-broker/main.go b/backend/cmd/panel-broker/main.go new file mode 100644 index 0000000..a889af3 --- /dev/null +++ b/backend/cmd/panel-broker/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "errors" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + "sea-vhost/internal/panel" +) + +func main() { + socket := env("SEA_PANEL_BROKER_SOCKET", "/run/sea-vhost-panel/broker.sock") + stateDir := env("SEA_PANEL_BROKER_STATE", "/var/lib/sea-vhost-panel") + tenantRoot := env("SEA_TENANT_ROOT", "/www/wwwroot/seavHost/vHost") + serverHandler, err := panel.NewBrokerServer(stateDir, tenantRoot, os.Getenv("SEA_SETUP_TOKEN"), os.Getenv("SEA_INTERNAL_AUTH_TOKEN")) + if err != nil { + slog.Error("cannot initialize panel broker", "error", err) + os.Exit(1) + } + if os.Getenv("SEA_NODE_STATELESS") == "true" { + if err = serverHandler.EnableStateless(); err != nil { + slog.Error("cannot start stateless node broker", "error", err) + os.Exit(1) + } + } + if err := os.MkdirAll(filepath.Dir(socket), 0750); err != nil { + slog.Error("cannot create broker socket directory", "error", err) + os.Exit(1) + } + _ = os.Remove(socket) + listener, err := net.Listen("unix", socket) + if err != nil { + slog.Error("cannot listen on panel broker socket", "error", err) + os.Exit(1) + } + defer listener.Close() + if err = os.Chmod(socket, 0660); err != nil { + slog.Error("cannot secure panel broker socket", "error", err) + os.Exit(1) + } + server := &http.Server{ + Handler: serverHandler.Handler(), ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 30 * time.Second, WriteTimeout: 5 * time.Minute, IdleTimeout: 30 * time.Second, + } + go func() { + if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + slog.Error("panel broker failed", "error", err) + os.Exit(1) + } + }() + slog.Info("Sea vHost panel broker listening", "socket", socket) + stop := make(chan os.Signal, 1) + signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) + <-stop + _ = server.Close() +} + +func env(name, fallback string) string { + if value := os.Getenv(name); value != "" { + return value + } + return fallback +} diff --git a/backend/cmd/runner/main.go b/backend/cmd/runner/main.go new file mode 100644 index 0000000..3e54d02 --- /dev/null +++ b/backend/cmd/runner/main.go @@ -0,0 +1,116 @@ +//go:build linux + +package main + +import ( + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "os/signal" + "path/filepath" + "regexp" + "sea-vhost/internal/hosting" + "sync" + "syscall" +) + +func main() { + if e := run(); e != nil { + fmt.Fprintln(os.Stderr, "Sea vHost: application launch failed") + os.Exit(1) + } +} +func run() error { + if (len(os.Args) != 2 && len(os.Args) != 5) || !regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`).MatchString(os.Args[1]) { + return fmt.Errorf("invalid site") + } + f, e := os.Open("/var/lib/sea-vhost-agent/startup/" + os.Args[1] + ".json") + if e != nil { + return e + } + defer f.Close() + i, e := f.Stat() + if e != nil { + return e + } + stat, ok := i.Sys().(*syscall.Stat_t) + if !ok || stat.Uid != 0 || i.Mode().Perm()&0022 != 0 { + return fmt.Errorf("unsafe launcher state") + } + var v hosting.RunnerConfig + if e = json.NewDecoder(io.LimitReader(f, 128<<10)).Decode(&v); e != nil { + return e + } + if v.UID == 0 || uint32(os.Getuid()) != v.UID || v.SiteName != os.Args[1] { + return fmt.Errorf("wrong identity") + } + if !validInvocation(os.Args, v) { + return fmt.Errorf("launcher arguments do not match protected state") + } + cmd := exec.Command(v.Binary, v.Arguments...) + cmd.Dir = v.WorkDir + cmd.Env = []string{"PATH=" + filepath.Dir(v.Binary) + ":/usr/bin:/bin", "HOME=/nonexistent", "LANG=C.UTF-8"} + for k, value := range v.Environment { + cmd.Env = append(cmd.Env, k+"="+value) + } + root, e := os.OpenRoot(v.LogDir) + if e != nil { + return e + } + defer root.Close() + logger := &rollingLog{root: root, name: v.SiteName + ".log"} + cmd.Stdout = logger + cmd.Stderr = logger + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL} + if e = cmd.Start(); e != nil { + return e + } + signals := make(chan os.Signal, 2) + signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT) + defer signal.Stop(signals) + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case e = <-done: + return e + case <-signals: + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + return <-done + } +} + +func validInvocation(args []string, v hosting.RunnerConfig) bool { + if len(args) == 2 { + return true + } + return len(args) == 5 && args[2] == "--java" && args[3] == v.Binary && filepath.Base(v.Binary) == "java" && len(v.Arguments) >= 2 && v.Arguments[0] == "-jar" && args[4] == v.Arguments[1] +} + +type rollingLog struct { + root *os.Root + name string + mu sync.Mutex +} + +func (l *rollingLog) Write(v []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + if i, e := l.root.Lstat(l.name); e == nil { + if !i.Mode().IsRegular() { + return len(v), nil + } + if i.Size() > 8<<20 { + _ = l.root.Remove(l.name + ".1") + _ = l.root.Rename(l.name, l.name+".1") + } + } + f, e := l.root.OpenFile(l.name, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0660) + if e != nil { + return len(v), nil + } + defer f.Close() + _, _ = f.Write(v) + return len(v), nil +} diff --git a/backend/cmd/runner/main_test.go b/backend/cmd/runner/main_test.go new file mode 100644 index 0000000..db9718c --- /dev/null +++ b/backend/cmd/runner/main_test.go @@ -0,0 +1,21 @@ +//go:build linux + +package main + +import ( + "sea-vhost/internal/hosting" + "testing" +) + +func TestJavaInvocationOnlyUsesProtectedState(t *testing.T) { + v := hosting.RunnerConfig{Binary: "/www/server/java/jdk-25/bin/java", Arguments: []string{"-jar", "/www/wwwroot/host/app.jar"}} + good := []string{"runner", "sv0123456789", "--java", v.Binary, v.Arguments[1]} + if !validInvocation(good, v) { + t.Fatal("expected matching Java invocation") + } + for _, args := range [][]string{{"runner", "sv0123456789", "--java", "/bin/sh", v.Arguments[1]}, {"runner", "sv0123456789", "--java", v.Binary, "/tmp/foreign.jar"}, {"runner", "sv0123456789", "--command", v.Binary, v.Arguments[1]}} { + if validInvocation(args, v) { + t.Fatal("accepted foreign launcher command") + } + } +} diff --git a/backend/cmd/scheduler/main.go b/backend/cmd/scheduler/main.go new file mode 100644 index 0000000..7092dc4 --- /dev/null +++ b/backend/cmd/scheduler/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "os" + "sea-vhost/internal/schedulerbridge" + "strconv" + "strings" + "time" +) + +func main() { + if e := tick(); e != nil { + fmt.Fprintln(os.Stderr, "Sea vHost 调度触发失败") + os.Exit(1) + } +} +func tick() error { + if len(os.Args) != 2 || os.Args[1] != "tick" { + return fmt.Errorf("usage: sea-vhost-scheduler tick") + } + raw, e := os.ReadFile(schedulerbridge.ConfigPath) + if e != nil { + return e + } + var cfg schedulerbridge.Config + if json.Unmarshal(raw, &cfg) != nil || cfg.Validate() != nil { + return fmt.Errorf("invalid configuration") + } + nonce := make([]byte, 16) + if _, e = rand.Read(nonce); e != nil { + return e + } + node := strconv.FormatUint(cfg.NodeID, 10) + stamp := strconv.FormatInt(time.Now().Unix(), 10) + n := hex.EncodeToString(nonce) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + r, e := http.NewRequestWithContext(ctx, "POST", strings.TrimRight(cfg.Controller, "/")+schedulerbridge.TickPath, nil) + if e != nil { + return e + } + r.Header.Set("X-Sea-Node", node) + r.Header.Set("X-Sea-Time", stamp) + r.Header.Set("X-Sea-Nonce", n) + r.Header.Set("X-Sea-Signature", schedulerbridge.Signature(cfg.Key, node, stamp, n)) + client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + res, e := client.Do(r) + if e != nil { + return e + } + res.Body.Close() + if res.StatusCode != 202 && res.StatusCode != 204 { + return fmt.Errorf("trigger rejected") + } + return nil +} diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go new file mode 100644 index 0000000..88deb2b --- /dev/null +++ b/backend/cmd/server/main.go @@ -0,0 +1,194 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "sea-vhost/internal/cluster" + "sea-vhost/internal/config" + "sea-vhost/internal/httpapi" + "sea-vhost/internal/isolation" + "sea-vhost/internal/notify" + "sea-vhost/internal/panel" + "sea-vhost/internal/secrets" + "sea-vhost/internal/service" + setupserver "sea-vhost/internal/setup" + "sea-vhost/internal/store" +) + +func main() { + for { + cfg, err := config.Load() + if errors.Is(err, config.ErrSetupRequired) { + installed, setupErr := runSetupServer() + if setupErr != nil { + slog.Error("setup server failed", "error", setupErr) + os.Exit(1) + } + if installed { + continue + } + return + } + if err != nil { + slog.Error("configuration error", "error", err) + os.Exit(1) + } + if err := runApplication(cfg); err != nil { + slog.Error("application failed", "error", err) + os.Exit(1) + } + return + } +} + +func runSetupServer() (bool, error) { + setup, err := setupserver.New(os.Getenv("SEA_SETUP_TOKEN")) + if err != nil { + return false, err + } + server := newHTTPServer(config.SetupAddr(), setup.Handler()) + serverErrors := make(chan error, 1) + go func() { + slog.Warn("Sea vHost requires installation", "address", config.SetupAddr(), "config", config.Path()) + if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + serverErrors <- err + } + }() + stop := make(chan os.Signal, 1) + signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(stop) + installed := false + select { + case <-setup.Done(): + installed = true + case <-stop: + case err := <-serverErrors: + return false, err + } + shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if err := server.Shutdown(shutdownCtx); err != nil { + return false, err + } + return installed, nil +} + +func runApplication(cfg config.Config) error { + database, err := store.Open(cfg.DatabaseDSN) + if err != nil { + return err + } + defer database.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + if err = database.Migrate(ctx); err == nil { + err = database.BootstrapAdmin(ctx, os.Getenv("SEA_BOOTSTRAP_ADMIN_EMAIL"), os.Getenv("SEA_BOOTSTRAP_ADMIN_NAME"), os.Getenv("SEA_BOOTSTRAP_ADMIN_PASSWORD")) + } + cancel() + if err != nil { + return err + } + var panelClient panel.Interface + if err = database.RecoverControlTasks(context.Background()); err != nil { + return err + } + manager := &cluster.Manager{Store: database, Box: secrets.New(cfg.SessionSecret), PanelSocket: cfg.PanelBrokerSocket, AgentSocket: cfg.AgentSocket, LocalToken: cfg.InternalAuthToken} + if err = database.InitializeLocalNode(context.Background(), cfg.RootDomain, cfg.TenantRoot, cfg.FTPDomain); err != nil { + return err + } + if cfg.ControllerOnly { + if err = database.SetNodeEnabled(context.Background(), 1, false); err != nil { + return err + } + } + if cfg.PanelMock { + panelClient = panel.NewMock() + slog.Warn("panel mock mode is active; do not use in production") + } else { + panelClient = manager.Panel() + } + var isolator isolation.Interface + if cfg.AgentMock { + isolator = isolation.Mock{Root: cfg.TenantRoot} + slog.Warn("isolation agent mock mode is active; do not use in production") + } else { + isolator = manager.Isolation() + } + reservedDomains := append([]string{cfg.ManagementDomain, cfg.FTPDomain}, cfg.ReservedDomains...) + projectService := service.NewProjects(database, panelClient, isolator, cfg.RootDomain, cfg.TenantRoot, cfg.DomainApproval, cfg.SessionSecret, cfg.FTPDomain, reservedDomains...) + if !cfg.AgentMock { + projectService.WithFileOpener(manager.OpenFiles) + } + reconcileContext, stopReconcile := context.WithTimeout(context.Background(), 5*time.Minute) + err = projectService.ReconcileIdentities(reconcileContext) + stopReconcile() + if err != nil { + slog.Error("host identity reconciliation needs attention", "error", err) + _ = database.EnqueueAdminNotification(context.Background(), "critical", "node", "主机身份核验未完成", err.Error()) + } + quotaContext, stopQuotaMonitor := context.WithCancel(context.Background()) + defer stopQuotaMonitor() + go projectService.RunStorageQuotaMonitor(quotaContext, time.Minute) + go projectService.RunCertificateRenewalMonitor(quotaContext, 12*time.Hour) + go runSessionCleanup(quotaContext, database) + go projectService.RunLifecycleMonitor(quotaContext, time.Minute) + go projectService.RunRuntimeMaintenance(quotaContext) + go projectService.RunRuntimeUpdateChecks(quotaContext) + go notify.New(database, cfg.SessionSecret).Run(quotaContext, time.Minute) + apiServer := httpapi.New(cfg, database, projectService).WithCluster(manager) + go apiServer.RunAdminBatches(quotaContext) + server := newHTTPServer(cfg.Addr, apiServer.Handler()) + serverErrors := make(chan error, 1) + go func() { + slog.Info("Sea vHost API listening", "address", cfg.Addr) + if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + serverErrors <- err + } + }() + stop := make(chan os.Signal, 1) + signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(stop) + select { + case <-stop: + case err := <-serverErrors: + return err + } + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) + defer shutdownCancel() + return server.Shutdown(shutdownCtx) +} + +func runSessionCleanup(ctx context.Context, database *store.Store) { + cleanup := func() { + cleanupCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + if err := database.DeleteExpiredSessions(cleanupCtx); err != nil && !errors.Is(err, context.Canceled) { + slog.Error("expired session cleanup failed", "error", err) + } + } + cleanup() + ticker := time.NewTicker(time.Hour) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + cleanup() + } + } +} + +func newHTTPServer(address string, handler http.Handler) *http.Server { + return &http.Server{ + Addr: address, Handler: handler, ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, WriteTimeout: 5 * time.Minute, + IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 1 << 20, + } +} diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..9f44fb9 --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,15 @@ +module sea-vhost + +go 1.27.3 + +require ( + github.com/go-sql-driver/mysql v1.10.1 + golang.org/x/crypto v0.58.0 +) + +require ( + filippo.io/edwards25519 v1.2.0 // indirect + github.com/coreos/go-oidc/v3 v3.21.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect + golang.org/x/oauth2 v0.37.0 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..9fc36ec --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,12 @@ +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM= +github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= +github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= diff --git a/backend/internal/auth/auth.go b/backend/internal/auth/auth.go new file mode 100644 index 0000000..9a7451d --- /dev/null +++ b/backend/internal/auth/auth.go @@ -0,0 +1,56 @@ +package auth + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + + "golang.org/x/crypto/bcrypt" +) + +func VerifyPassword(hash, password string) bool { + return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil +} + +var dummyPasswordHash = func() string { + hash, _ := bcrypt.GenerateFromPassword([]byte("sea-vhost-dummy-credential"), bcrypt.DefaultCost) + return string(hash) +}() + +func VerifyPasswordConstantWork(hash, password string) bool { + if hash == "" { + _ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password)) + return false + } + return VerifyPassword(hash, password) +} + +func HashPassword(password string) (string, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + return string(hash), err +} + +func NewSessionToken(secret string) (string, error) { + random := make([]byte, 32) + if _, err := rand.Read(random); err != nil { + return "", err + } + mac := hmac.New(sha256.New, []byte(secret)) + _, _ = mac.Write(random) + payload := append(random, mac.Sum(nil)...) + return base64.RawURLEncoding.EncodeToString(payload), nil +} + +func ValidateSessionToken(secret, token string) bool { + payload, err := base64.RawURLEncoding.DecodeString(token) + if err != nil || len(payload) != 64 { + return false + } + mac := hmac.New(sha256.New, []byte(secret)) + _, _ = mac.Write(payload[:32]) + return hmac.Equal(payload[32:], mac.Sum(nil)) +} + +var ErrInvalidCredentials = errors.New("invalid credentials") diff --git a/backend/internal/auth/totp.go b/backend/internal/auth/totp.go new file mode 100644 index 0000000..462d11a --- /dev/null +++ b/backend/internal/auth/totp.go @@ -0,0 +1,86 @@ +package auth + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha1" + "crypto/sha256" + "encoding/base32" + "encoding/binary" + "fmt" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + totpPeriod = int64(30) + totpDigits = 6 +) + +func NewTOTPSecret() (string, error) { + random := make([]byte, 20) + if _, err := rand.Read(random); err != nil { + return "", err + } + return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(random), nil +} + +func TOTPURI(secret, account string) string { + label := url.PathEscape("Sea vHost:" + account) + query := url.Values{"secret": {secret}, "issuer": {"Sea vHost"}, "algorithm": {"SHA1"}, "digits": {strconv.Itoa(totpDigits)}, "period": {strconv.FormatInt(totpPeriod, 10)}} + return "otpauth://totp/" + label + "?" + query.Encode() +} + +func VerifyTOTP(secret, code string, now time.Time) bool { + code = strings.TrimSpace(code) + if len(code) != totpDigits { + return false + } + for _, character := range code { + if character < '0' || character > '9' { + return false + } + } + for offset := int64(-1); offset <= 1; offset++ { + if hmac.Equal([]byte(code), []byte(totpAt(secret, now.Unix()/totpPeriod+offset))) { + return true + } + } + return false +} + +func totpAt(secret string, counter int64) string { + key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(secret)) + if err != nil { + return "" + } + message := make([]byte, 8) + binary.BigEndian.PutUint64(message, uint64(counter)) + mac := hmac.New(sha1.New, key) + _, _ = mac.Write(message) + digest := mac.Sum(nil) + offset := digest[len(digest)-1] & 0x0f + value := binary.BigEndian.Uint32(digest[offset:offset+4]) & 0x7fffffff + return fmt.Sprintf("%0*d", totpDigits, value%1000000) +} + +func NewRecoveryCodes(count int) ([]string, error) { + codes := make([]string, 0, count) + for len(codes) < count { + random := make([]byte, 8) + if _, err := rand.Read(random); err != nil { + return nil, err + } + encoded := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(random)) + codes = append(codes, encoded[:4]+"-"+encoded[4:8]+"-"+encoded[8:12]) + } + return codes, nil +} + +func RecoveryCodeHash(code string) []byte { + normalized := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(code), "-", "")) + hash := sha256.Sum256([]byte("sea-vhost/mfa-recovery/v1\x00" + normalized)) + return hash[:] +} diff --git a/backend/internal/auth/totp_test.go b/backend/internal/auth/totp_test.go new file mode 100644 index 0000000..3cbb139 --- /dev/null +++ b/backend/internal/auth/totp_test.go @@ -0,0 +1,25 @@ +package auth + +import ( + "bytes" + "testing" + "time" +) + +func TestTOTPVerificationWindow(t *testing.T) { + secret := "JBSWY3DPEHPK3PXP" + now := time.Unix(1_700_000_000, 0) + code := totpAt(secret, now.Unix()/totpPeriod) + if !VerifyTOTP(secret, code, now) { + t.Fatal("current TOTP code was rejected") + } + if VerifyTOTP(secret, "0000000", now) || VerifyTOTP(secret, "abcdef", now) { + t.Fatal("malformed TOTP code was accepted") + } +} + +func TestRecoveryCodeHashNormalizesFormatting(t *testing.T) { + if !bytes.Equal(RecoveryCodeHash("abcd-efgh-ijkl"), RecoveryCodeHash(" ABCDEFGHIJKL ")) { + t.Fatal("equivalent recovery codes produced different hashes") + } +} diff --git a/backend/internal/cluster/files.go b/backend/internal/cluster/files.go new file mode 100644 index 0000000..7bc598d --- /dev/null +++ b/backend/internal/cluster/files.go @@ -0,0 +1,59 @@ +package cluster + +import ( + "context" + "encoding/json" + "errors" + "io" + "path" + "sea-vhost/internal/controlwire" + "sea-vhost/internal/nodefiles" +) + +func (m *Manager) OpenFiles(ctx context.Context, root string) (*nodefiles.Root, error) { + host := path.Base(root) + node, err := m.Resolve(ctx, []byte(`{"hostName":"`+host+`"}`)) + if err != nil { + return nil, err + } + if !hostPrefix.MatchString(host) || len(host) != 12 || path.Clean(root) != path.Join(node.TenantRoot, host) { + return nil, errors.New("文件目录与节点不符") + } + return nodefiles.New(ctx, host, func(ctx context.Context, q nodefiles.Request) (nodefiles.Response, error) { + if node.Transport == "local" { + return nodefiles.Execute(root, q), nil + } + raw, err := json.Marshal(q) + if err != nil { + return nodefiles.Response{}, err + } + id, err := requestID() + if err != nil { + return nodefiles.Response{}, err + } + req, err := controlwire.NewRequest("POST", node.Endpoint, "/v1/files", node.ID, id, raw) + if err != nil { + return nodefiles.Response{}, err + } + client, err := m.client(node) + if err != nil { + return nodefiles.Response{}, err + } + defer client.CloseIdleConnections() + response, err := client.Do(req.WithContext(ctx)) + if err != nil { + return nodefiles.Response{}, ErrUncertain + } + defer response.Body.Close() + if response.StatusCode != 200 { + return nodefiles.Response{}, errors.New("节点文件操作未完成,请核对后再操作") + } + var result nodefiles.Response + decoder := json.NewDecoder(io.LimitReader(response.Body, nodefiles.MaxMessageBytes+1)) + decoder.DisallowUnknownFields() + if decoder.Decode(&result) != nil || decoder.Decode(&struct{}{}) != io.EOF { + return result, ErrUncertain + } + return result, nil + }), nil +} diff --git a/backend/internal/cluster/manager.go b/backend/internal/cluster/manager.go new file mode 100644 index 0000000..d2c5a69 --- /dev/null +++ b/backend/internal/cluster/manager.go @@ -0,0 +1,358 @@ +// Package cluster is controller-only: node selection, credentials, resource +// snapshots and operation history stay in the controller MySQL database. +package cluster + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "regexp" + "strings" + "time" + + "sea-vhost/internal/controlwire" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/secrets" + "sea-vhost/internal/store" +) + +var ErrUncertain = errors.New("节点操作结果待核验,未自动重试") + +type Manager struct { + Store *store.Store + Box *secrets.Box + PanelSocket, AgentSocket, LocalToken string +} +type transport struct { + manager *Manager + kind string +} + +func (m *Manager) Panel() *panel.BrokerClient { + return panel.NewTransportClient(&transport{manager: m, kind: "panel"}, 2*time.Hour) +} +func (m *Manager) Isolation() *isolation.Client { + return isolation.NewTransportClient(&transport{manager: m, kind: "isolation"}) +} +func (m *Manager) CredentialLabel(id uint64) string { return fmt.Sprintf("node/%d/transport/v1", id) } +func (m *Manager) Pair(ctx context.Context, id uint64) (controlwire.ServerIdentity, error) { + node, err := m.Store.Node(ctx, id) + if err != nil { + return controlwire.ServerIdentity{}, err + } + credentials, identity, err := controlwire.Pair(id, node.Endpoint) + if err != nil { + return identity, err + } + raw, err := json.Marshal(credentials) + if err != nil { + return identity, err + } + cipher, err := m.Box.Seal(m.CredentialLabel(id), string(raw)) + if err != nil { + return identity, err + } + return identity, m.Store.SetNodeCredentials(ctx, id, cipher) +} +func (m *Manager) client(node store.Node) (*http.Client, error) { + raw, err := m.Box.Open(m.CredentialLabel(node.ID), node.Credentials) + if err != nil { + return nil, errors.New("node transport credentials are unavailable") + } + var credentials controlwire.Credentials + if json.Unmarshal([]byte(raw), &credentials) != nil { + return nil, errors.New("node transport credentials are invalid") + } + tls, err := controlwire.ClientTLS(credentials) + if err != nil { + return nil, err + } + return &http.Client{Transport: &http.Transport{TLSClientConfig: tls, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 10 * time.Second, MaxIdleConnsPerHost: 4, ResponseHeaderTimeout: 2 * time.Hour}, Timeout: 2 * time.Hour, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("node redirect denied") }}, nil +} +func requestID() (string, error) { + raw := make([]byte, 16) + _, err := rand.Read(raw) + return hex.EncodeToString(raw), err +} +func (m *Manager) Probe(ctx context.Context, id uint64) error { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + node, err := m.Store.Node(ctx, id) + if err != nil { + return err + } + if node.Transport == "local" { + return errors.New("local node is verified through its local services") + } + client, err := m.client(node) + if err != nil { + return err + } + defer client.CloseIdleConnections() + requestID, err := requestID() + if err != nil { + return err + } + req, err := controlwire.NewRequest("GET", node.Endpoint, "/v1/status", id, requestID, nil) + if err != nil { + return err + } + response, err := client.Do(req.WithContext(ctx)) + if err != nil { + _ = m.Store.RecordNodeProbe(context.WithoutCancel(ctx), id, "节点连接或双向 TLS 校验失败") + return errors.New("节点连接或双向 TLS 校验失败") + } + defer response.Body.Close() + var status struct { + NodeID uint64 `json:"nodeId"` + Protocol string `json:"protocol"` + } + if response.StatusCode != 200 || json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&status) != nil || status.NodeID != id || status.Protocol != controlwire.Version { + return errors.New("node identity or protocol mismatch") + } + return m.Store.RecordNodeProbe(ctx, id, "") +} + +var hostPrefix = regexp.MustCompile(`^sv[a-f0-9]{10}(?:$|[._-])`) + +func hostFromValue(value any) string { + switch v := value.(type) { + case map[string]any: + for _, key := range []string{"hostName", "HostName", "ProjectName", "projectName", "Name", "name", "Username", "username"} { + if text, ok := v[key].(string); ok && hostPrefix.MatchString(text) && (len(text) == 12 || (strings.EqualFold(key, "projectName") && strings.HasPrefix(text[12:], "_"))) { + return text[:12] + } + } + for _, key := range []string{"project", "Project", "site", "Site", "runtime", "Runtime", "spec"} { + if child, ok := v[key]; ok { + if host := hostFromValue(child); host != "" { + return host + } + } + } + } + return "" +} +func (m *Manager) Resolve(ctx context.Context, body []byte) (store.Node, error) { + id, explicit := scope.ExplicitNode(ctx) + if id == 0 { + id = 1 + } + var value any + if len(body) > 0 && json.Unmarshal(body, &value) != nil { + return store.Node{}, errors.New("invalid execution request") + } + if host := hostFromValue(value); host != "" { + resolved, err := m.Store.NodeForHost(ctx, host) + if err != nil { + return store.Node{}, err + } + if explicit && id != resolved { + return store.Node{}, errors.New("resource belongs to another node") + } + id = resolved + } + node, err := m.Store.Node(ctx, id) + if err != nil { + return node, err + } + if !node.Enabled { + return node, errors.New("节点已停用") + } + return node, nil +} +func executionOperation(kind, route string, body []byte) (string, bool) { + if kind == "panel" { + var q struct { + Operation string `json:"operation"` + } + _ = json.Unmarshal(body, &q) + read := map[string]bool{"ping": true, "runtime_catalog": true, "runtime_capabilities": true, "runtime_environments": true, "list_unmanaged_sites": true, "managed_runtime": true, "php_update_pending": true, "database_size": true} + return "panel/" + q.Operation, read[q.Operation] + } + read := route == "/v1/database/phpmyadmin" || route == "/v1/site/log" || route == "/healthz" || route == "/v1/resources/usage" || route == "/v1/runtime/probe" || route == "/v1/runtime/backups/prune" || route == "/v1/lifecycle/backup/verify" + return "agent" + route, read +} +func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) { + var body []byte + var err error + if r.Body != nil { + body, err = io.ReadAll(io.LimitReader(r.Body, controlwire.MaxEnvelopeBytes+1)) + } + if r.Body != nil { + _ = r.Body.Close() + } + if err != nil || len(body) > controlwire.MaxEnvelopeBytes { + return nil, errors.New("execution request exceeds limit") + } + node, err := t.manager.Resolve(r.Context(), body) + if t.kind == "isolation" && r.URL.Path == "/v1/lifecycle/backup/delete" { + if id, explicit := scope.ExplicitNode(r.Context()); explicit { + node, err = t.manager.Store.Node(r.Context(), id) + if err == nil && !node.Enabled { + err = errors.New("节点已停用") + } + } + } + if err != nil { + return nil, err + } + if node.Transport == "local" { + socket := t.manager.PanelSocket + if t.kind == "isolation" { + socket = t.manager.AgentSocket + } + if socket == "" || t.manager.LocalToken == "" { + return nil, errors.New("local node is not configured") + } + local := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket) + }} + defer local.CloseIdleConnections() + req := r.Clone(r.Context()) + req.Body = io.NopCloser(bytes.NewReader(body)) + req.ContentLength = int64(len(body)) + req.Header.Set("Authorization", "Bearer "+t.manager.LocalToken) + return local.RoundTrip(req) + } + if t.kind == "panel" && r.URL.Path != "/v1/operations" { + return nil, errors.New("remote node does not expose panel setup endpoints") + } + operation, readOnly := executionOperation(t.kind, r.URL.Path, body) + if operation == "agent/v1/ftp/tls" || operation == "agent/v1/runtime/python/install" || operation == "agent/v1/runtime/php/maintenance" || operation == "panel/install_runtime_component" || operation == "panel/install_runtime_environment" || operation == "panel/update_php_runtime" { + r = r.WithContext(scope.WithProject(r.Context(), 0, node.ID)) + } + if !readOnly { + blocked, e := t.manager.Store.NodeHasUnresolvedTask(r.Context(), node.ID) + if e != nil { + return nil, e + } + if blocked { + return nil, ErrUncertain + } + } + route := "/v1/isolation" + r.URL.Path + if t.kind == "isolation" && r.Method == http.MethodGet && r.URL.Path == "/healthz" { + route = "/v1/status" + } + var lease *store.NodeRegistryLease + if t.kind == "panel" { + lease, err = t.manager.Store.LockNodeRegistry(r.Context(), node.ID) + if err != nil { + return nil, err + } + defer lease.Close() + if !readOnly { + blocked, e := t.manager.Store.NodeHasUnresolvedTask(r.Context(), node.ID) + if e != nil { + return nil, e + } + if blocked { + return nil, ErrUncertain + } + } + snapshot, e := lease.Read(r.Context()) + if e != nil { + return nil, e + } + body, e = json.Marshal(panel.ScopedExecution{Request: body, Registry: snapshot}) + if e != nil { + return nil, e + } + route = "/v1/panel" + } + id, err := requestID() + if err != nil { + return nil, err + } + var task uint64 + if !readOnly { + task, err = t.manager.Store.StartControlTask(r.Context(), node.ID, scope.Project(r.Context()), operation, id) + if err != nil { + return nil, err + } + } + finish := func(state, detail string) { + if task == 0 { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = t.manager.Store.FinishControlTask(ctx, task, state, detail) + } + client, err := t.manager.client(node) + if err != nil { + finish("failed", "节点身份配置无效") + return nil, err + } + defer client.CloseIdleConnections() + req, err := controlwire.NewRequest(r.Method, node.Endpoint, route, node.ID, id, body) + if err != nil { + finish("failed", "节点请求配置无效") + return nil, err + } + response, err := client.Do(req.WithContext(r.Context())) + if err != nil { + finish("uncertain", "连接中断,需要核对被控实际状态") + return nil, ErrUncertain + } + defer response.Body.Close() + result, err := io.ReadAll(io.LimitReader(response.Body, controlwire.MaxEnvelopeBytes+1)) + if err != nil || len(result) > controlwire.MaxEnvelopeBytes { + finish("uncertain", "节点响应不完整") + return nil, ErrUncertain + } + if response.StatusCode != 200 { + detail := []rune(strings.TrimSpace(string(result))) + if len(detail) > 300 { + detail = detail[:300] + } + if !readOnly { + finish("uncertain", fmt.Sprintf("节点返回 HTTP %d:%s;请核对实际状态", response.StatusCode, string(detail))) + return nil, ErrUncertain + } + finish("uncertain", fmt.Sprintf("节点返回 HTTP %d,需要核对实际状态", response.StatusCode)) + return &http.Response{StatusCode: response.StatusCode, Header: response.Header.Clone(), Body: io.NopCloser(bytes.NewReader(result)), Request: r}, nil + } + if lease != nil { + var out panel.ScopedResult + if json.Unmarshal(result, &out) != nil || len(out.Registry) == 0 || !json.Valid(out.Registry) { + finish("uncertain", "节点资源响应待核验") + return nil, ErrUncertain + } + if err = lease.Save(r.Context(), out.Registry); err != nil { + finish("uncertain", "资源登记回写失败") + return nil, ErrUncertain + } + result = out.Response + } + finish("succeeded", "") + _ = t.manager.Store.RecordNodeProbe(r.Context(), node.ID, "") + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(bytes.NewReader(result)), Request: r}, nil +} + +func (m *Manager) NodeDomains(ctx context.Context) ([]string, error) { + nodes, err := m.Store.Nodes(ctx) + if err != nil { + return nil, err + } + domains := []string{} + for _, node := range nodes { + if strings.TrimSpace(node.RootDomain) != "" { + domains = append(domains, node.RootDomain) + } + if node.FTPCertificateDomain != "" { + domains = append(domains, node.FTPCertificateDomain) + } + } + return domains, nil +} diff --git a/backend/internal/cluster/manager_integration_test.go b/backend/internal/cluster/manager_integration_test.go new file mode 100644 index 0000000..553f621 --- /dev/null +++ b/backend/internal/cluster/manager_integration_test.go @@ -0,0 +1,210 @@ +package cluster + +import ( + "context" + "encoding/json" + "errors" + "github.com/go-sql-driver/mysql" + "io" + "log" + "net/http/httptest" + "os" + "path/filepath" + "sea-vhost/internal/controlwire" + "sea-vhost/internal/executor" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/secrets" + "sea-vhost/internal/store" + "strings" + "testing" + "time" +) + +func TestControllerTwoNodesMySQL(t *testing.T) { + dsn := os.Getenv("SEA_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("dedicated MySQL schema not supplied") + } + cfg, err := mysql.ParseDSN(dsn) + if err != nil || !strings.HasPrefix(cfg.DBName, "svh_cluster_test_") { + t.Fatal("non-test schema denied") + } + database, err := store.Open(dsn) + if err != nil { + t.Fatal(err) + } + defer database.Close() + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + if err = database.Migrate(ctx); err != nil { + t.Fatal(err) + } + plans, err := database.ListPlans(ctx) + if err != nil || len(plans) == 0 { + t.Fatal("plans unavailable") + } + tenant, err := database.CreateTenant(ctx, store.NewTenant{Slug: "rpc-test", Name: "RPC 测试用户", Email: "rpc@example.invalid", DisplayName: "RPC 测试", Password: "RPC-test-only-123456", PlanID: plans[0].ID}) + if err != nil { + t.Fatal(err) + } + manager := &Manager{Store: database, Box: secrets.New(strings.Repeat("test-only-secret", 4))} + client := manager.Panel() + type host struct { + node, project uint64 + name, root, domain string + site, ftp, db int64 + } + hosts := []host{} + for _, name := range []string{"sv1111111111", "sv2222222222"} { + root := filepath.ToSlash(t.TempDir()) + if err = os.Mkdir(filepath.Join(root, name), 0750); err != nil { + t.Fatal(err) + } + server := httptest.NewUnstartedServer(nil) + server.Config.ErrorLog = log.New(io.Discard, "", 0) + endpoint := "https://" + server.Listener.Addr().String() + node, err := database.CreateNode(ctx, store.Node{Name: name, Endpoint: endpoint, RootDomain: name + ".example.invalid", TenantRoot: root, FTPCertificateDomain: "ftp.example.invalid"}) + if err != nil { + t.Fatal(err) + } + identity, err := manager.Pair(ctx, node) + if err != nil { + t.Fatal(err) + } + server.TLS, err = controlwire.ServerTLS(identity) + if err != nil { + t.Fatal(err) + } + server.Config.Handler = (&executor.Gateway{NodeID: node, TenantRoot: root, Direct: panel.NewMock()}).Handler() + server.StartTLS() + t.Cleanup(server.Close) + if err = manager.Probe(ctx, node); err != nil { + t.Fatal(err) + } + if err = database.SetNodeEnabled(ctx, node, true); err != nil { + t.Fatal(err) + } + project, err := database.InsertProject(ctx, store.NewProject{TenantID: tenant, NodeID: node, PlanID: plans[0].ID, HostName: name, Slug: name, Path: root + "/" + name, RunPath: "/public", Runtime: "PHP", Version: "8.4", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-only"}) + if err != nil { + t.Fatal(err) + } + h := host{node: node, project: project, name: name, root: root + "/" + name, domain: name + ".example.invalid"} + op := scope.WithProject(ctx, project, node) + h.site, err = client.CreateSite(op, panel.SiteSpec{Name: name, Domain: h.domain, Path: h.root, RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: name, Port: 20000, ProcessLimit: 10}) + if err != nil { + t.Fatal(err) + } + h.ftp, err = client.CreateFTP(op, name, "TestPassword123456789", h.root, 1<<20) + if err != nil { + t.Fatal(err) + } + h.db, err = client.CreateDatabase(op, name, name, "TestPassword123456789", h.site) + if err != nil { + t.Fatal(err) + } + if err = database.CompleteProject(op, project, h.site, h.ftp, h.db, name, name, name, []byte("cipher"), []byte("cipher"), "running", "", "", false); err != nil { + t.Fatal(err) + } + rootFiles, err := manager.OpenFiles(op, h.root) + if err != nil { + t.Fatal(err) + } + file, err := rootFiles.OpenFile("marker.txt", os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0660) + if err != nil { + t.Fatal(err) + } + if _, err = file.Write([]byte(name)); err != nil { + t.Fatal(err) + } + if err = file.Close(); err != nil { + t.Fatal(err) + } + if err = manager.Isolation().Ping(op); err != nil { + t.Fatalf("remote GET health routing: %v", err) + } + hosts = append(hosts, h) + } + if hosts[0].site != hosts[1].site || hosts[0].ftp != hosts[1].ftp || hosts[0].db != hosts[1].db { + t.Fatal("native ID collision was not exercised") + } + for _, h := range hosts { + op := scope.WithProject(ctx, h.project, h.node) + lease, err := database.LockNodeRegistry(op, h.node) + if err != nil { + t.Fatal(err) + } + raw, err := lease.Read(op) + lease.Close() + if err != nil { + t.Fatal(err) + } + var registry struct { + Sites map[string]json.RawMessage `json:"sites"` + } + if json.Unmarshal(raw, ®istry) != nil || len(registry.Sites) != 1 || !strings.Contains(string(raw), h.domain) { + t.Fatalf("controller registry mismatch: %s", raw) + } + targets, err := database.RuntimeTargets(op) + if err != nil || len(targets) != 1 || targets[0].Project.NodeID != h.node { + t.Fatalf("runtime target placement: %+v %v", targets, err) + } + if err = client.SetSiteState(op, h.site, h.domain, false); err != nil { + t.Fatal(err) + } + } + a := hosts[0] + b := hosts[1] + opA := scope.WithProject(ctx, a.project, a.node) + opB := scope.WithProject(ctx, b.project, b.node) + if _, err = client.CreateSite(opA, panel.SiteSpec{Name: a.name, Domain: "invalid.example.invalid", Path: "/outside/namespace", RunPath: "/", Runtime: "PHP", Version: "8.4", RunUser: a.name, Port: 20001, ProcessLimit: 10}); !errors.Is(err, ErrUncertain) { + t.Fatalf("write rejection should preserve an uncertain task: %v", err) + } + if err = client.SetSiteState(opA, a.site, a.domain, true); !errors.Is(err, ErrUncertain) { + t.Fatalf("unresolved node mutation was allowed: %v", err) + } + if _, err = database.CreateRuntimeJob(opA, store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}); err == nil { + t.Fatal("node-wide maintenance ignored unresolved host state") + } + // A tenant-triggered failure must not freeze another host on the same node. + peerName := "sv4444444444" + peerRoot := filepath.Join(filepath.Dir(a.root), peerName) + if err = os.Mkdir(peerRoot, 0750); err != nil { + t.Fatal(err) + } + peer, err := database.InsertProject(ctx, store.NewProject{TenantID: tenant, NodeID: a.node, PlanID: plans[0].ID, HostName: peerName, Slug: peerName, Path: peerRoot, RunPath: "/public", Runtime: "PHP", Version: "8.4", Domain: peerName + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-only"}) + if err != nil { + t.Fatal(err) + } + peerCtx := scope.WithProject(ctx, peer, a.node) + peerSite, err := client.CreateSite(peerCtx, panel.SiteSpec{Name: peerName, Domain: peerName + ".example.invalid", Path: peerRoot, RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: peerName, Port: 20020, ProcessLimit: 10}) + if err != nil { + t.Fatalf("host A failure blocked another host on the same node: %v", err) + } + if err = client.SetSiteState(peerCtx, peerSite, peerName+".example.invalid", true); err != nil { + t.Fatal(err) + } + if err = client.SetSiteState(opB, b.site, b.domain, true); err != nil { + t.Fatalf("node A failure blocked node B: %v", err) + } + tasks, err := database.ControlTasks(ctx, a.node) + if err != nil { + t.Fatal(err) + } + resolved := false + for _, task := range tasks { + if task.State == "uncertain" { + if err = database.ResolveControlTask(ctx, a.node, task.ID, "测试已核对拒绝发生在变更之前"); err != nil { + t.Fatal(err) + } + resolved = true + } + } + if !resolved { + t.Fatal("uncertain operation was not recorded centrally") + } + if err = client.SetSiteState(opA, a.site, a.domain, true); err != nil { + t.Fatal(err) + } + t.Log("controller MySQL + two mTLS gateways: native ID collision, central snapshots, site/FTP/database operations, file routing, health routing, maintenance placement and independent failure recovery passed") +} diff --git a/backend/internal/cluster/manager_test.go b/backend/internal/cluster/manager_test.go new file mode 100644 index 0000000..d481c91 --- /dev/null +++ b/backend/internal/cluster/manager_test.go @@ -0,0 +1,20 @@ +package cluster + +import "testing" + +func TestRoutingIgnoresCustomerDomainPrefixes(t *testing.T) { + cases := []struct { + body map[string]any + host string + }{ + {map[string]any{"name": "sv0123456789.customer.example", "domain": "svabcdef0123.example"}, ""}, + {map[string]any{"hostName": "sv0123456789"}, "sv0123456789"}, + {map[string]any{"site": map[string]any{"Name": "svabcdef0123", "Domain": "sv0123456789.customer.example"}}, "svabcdef0123"}, + {map[string]any{"runtime": map[string]any{"ProjectName": "svabcdef0123_42"}}, "svabcdef0123"}, + } + for _, tc := range cases { + if got := hostFromValue(tc.body); got != tc.host { + t.Fatalf("route identity = %q, want %q", got, tc.host) + } + } +} diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..b1e375b --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,267 @@ +package config + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +var ErrSetupRequired = errors.New("Sea vHost has not been installed") + +type Config struct { + ControllerOnly bool + Addr string + DatabaseDSN string + SessionSecret string + CookieSecure bool + PanelBrokerSocket string + PanelMock bool + RootDomain string + TenantRoot string + UploadLimitBytes int64 + DomainApproval bool + SessionTTL time.Duration + ProvisionTimeout time.Duration + AgentSocket string + AgentMock bool + InternalAuthToken string + ManagementDomain string + FTPDomain string + ReservedDomains []string +} + +type persistedConfig struct { + ControllerOnly bool `json:"controller_only,omitempty"` + Version int `json:"version"` + DatabaseDSN string `json:"database_dsn"` + SessionSecret string `json:"session_secret"` + CookieSecure bool `json:"cookie_secure"` + PanelBrokerSocket string `json:"panel_broker_socket"` + PanelMock bool `json:"panel_mock"` + RootDomain string `json:"root_domain"` + TenantRoot string `json:"tenant_root"` + UploadLimitBytes int64 `json:"upload_limit_bytes"` + DomainApproval bool `json:"domain_approval"` + AgentSocket string `json:"agent_socket"` + AgentMock bool `json:"agent_mock"` + ManagementDomain string `json:"management_domain,omitempty"` + FTPDomain string `json:"ftp_domain,omitempty"` + ReservedDomains []string `json:"reserved_domains,omitempty"` +} + +func Path() string { return env("SEA_CONFIG_FILE", "/var/lib/sea-vhost/config.json") } + +func SetupAddr() string { return env("SEA_ADDR", "127.0.0.1:8080") } + +func AgentSocketPath() string { return env("SEA_AGENT_SOCKET", "/run/sea-vhost/agent.sock") } + +func PanelBrokerSocketPath() string { + return env("SEA_PANEL_BROKER_SOCKET", "/run/sea-vhost-panel/broker.sock") +} + +func Load() (Config, error) { + data, err := os.ReadFile(Path()) + if err == nil { + var stored persistedConfig + if err := json.Unmarshal(data, &stored); err != nil { + return Config{}, fmt.Errorf("read installed configuration: %w", err) + } + cfg := defaults() + cfg.ControllerOnly = stored.ControllerOnly || envBool("SEA_CONTROLLER_ONLY", false) + cfg.DatabaseDSN = stored.DatabaseDSN + cfg.SessionSecret = stored.SessionSecret + cfg.CookieSecure = stored.CookieSecure + cfg.PanelBrokerSocket = stored.PanelBrokerSocket + if strings.TrimSpace(cfg.PanelBrokerSocket) == "" { + cfg.PanelBrokerSocket = PanelBrokerSocketPath() + } + cfg.PanelMock = stored.PanelMock + cfg.RootDomain = strings.ToLower(stored.RootDomain) + cfg.TenantRoot = stored.TenantRoot + cfg.UploadLimitBytes = stored.UploadLimitBytes + cfg.DomainApproval = stored.DomainApproval + cfg.AgentSocket = stored.AgentSocket + cfg.AgentMock = stored.AgentMock + cfg.ManagementDomain = strings.ToLower(strings.TrimSuffix(stored.ManagementDomain, ".")) + cfg.FTPDomain = strings.ToLower(strings.TrimSuffix(stored.FTPDomain, ".")) + cfg.ReservedDomains = normalizeDomains(stored.ReservedDomains) + cfg.InternalAuthToken = InternalAuthToken() + // Operational values may be changed without rewriting stored secrets. + cfg.Addr = SetupAddr() + return cfg, Validate(cfg) + } + if !errors.Is(err, os.ErrNotExist) { + return Config{}, fmt.Errorf("read configuration: %w", err) + } + // Keep the legacy environment-only path for development and upgrades. + if strings.TrimSpace(os.Getenv("SEA_SESSION_SECRET")) == "" { + return Config{}, ErrSetupRequired + } + cfg := fromEnvironment() + return cfg, Validate(cfg) +} + +func NewInstalled(databaseDSN, sessionSecret, rootDomain, managementDomain, ftpDomain string, reservedDomains []string, domainApproval bool) Config { + cfg := defaults() + cfg.DatabaseDSN = databaseDSN + cfg.SessionSecret = sessionSecret + cfg.PanelMock = false + cfg.RootDomain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(rootDomain)), ".") + cfg.AgentMock = false + cfg.DomainApproval = domainApproval + cfg.ManagementDomain = normalizeDomain(managementDomain) + cfg.FTPDomain = normalizeDomain(ftpDomain) + cfg.ReservedDomains = normalizeDomains(reservedDomains) + return cfg +} + +func Save(cfg Config) error { + if err := Validate(cfg); err != nil { + return err + } + stored := persistedConfig{ + ControllerOnly: cfg.ControllerOnly, + Version: 1, DatabaseDSN: cfg.DatabaseDSN, SessionSecret: cfg.SessionSecret, + CookieSecure: cfg.CookieSecure, PanelBrokerSocket: cfg.PanelBrokerSocket, + PanelMock: cfg.PanelMock, RootDomain: cfg.RootDomain, + TenantRoot: cfg.TenantRoot, UploadLimitBytes: cfg.UploadLimitBytes, DomainApproval: cfg.DomainApproval, + AgentSocket: cfg.AgentSocket, AgentMock: cfg.AgentMock, + ManagementDomain: cfg.ManagementDomain, FTPDomain: cfg.FTPDomain, + ReservedDomains: cfg.ReservedDomains, + } + data, err := json.MarshalIndent(stored, "", " ") + if err != nil { + return err + } + path := Path() + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return err + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".config-*.tmp") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err = temporary.Chmod(0600); err == nil { + _, err = temporary.Write(append(data, '\n')) + } + if err == nil { + err = temporary.Sync() + } + closeErr := temporary.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + // Hard-linking is atomic and fails if another installer already won the race. + if err := os.Link(temporaryPath, path); err != nil { + if errors.Is(err, os.ErrExist) { + return fmt.Errorf("configuration already exists") + } + return err + } + return nil +} + +func Validate(cfg Config) error { + if len(cfg.SessionSecret) < 32 { + return fmt.Errorf("session secret must contain at least 32 characters") + } + if strings.TrimSpace(cfg.DatabaseDSN) == "" { + return fmt.Errorf("database DSN is required") + } + if !cfg.ControllerOnly && !cfg.PanelMock && strings.TrimSpace(cfg.PanelBrokerSocket) == "" { + return fmt.Errorf("panel broker socket is required") + } + if cfg.UploadLimitBytes <= 0 { + return fmt.Errorf("upload limit must be positive") + } + if !cfg.ControllerOnly && (!cfg.PanelMock || !cfg.AgentMock) && len(strings.TrimSpace(cfg.InternalAuthToken)) < 32 { + return fmt.Errorf("internal authentication token must contain at least 32 characters") + } + return nil +} + +func defaults() Config { + return Config{ + ControllerOnly: envBool("SEA_CONTROLLER_ONLY", false), + Addr: SetupAddr(), CookieSecure: envBool("SEA_COOKIE_SECURE", true), + PanelBrokerSocket: PanelBrokerSocketPath(), RootDomain: "vhost.ser888.cn", + TenantRoot: env("SEA_TENANT_ROOT", "/www/wwwroot/seavHost/vHost"), UploadLimitBytes: envInt64("SEA_UPLOAD_LIMIT", 20*1024*1024), + DomainApproval: true, SessionTTL: 12 * time.Hour, ProvisionTimeout: 4 * time.Minute, + AgentSocket: AgentSocketPath(), + InternalAuthToken: InternalAuthToken(), + } +} + +func fromEnvironment() Config { + cfg := defaults() + cfg.DatabaseDSN = env("SEA_DATABASE_DSN", "sea_vhost:change-me@tcp(127.0.0.1:3306)/sea_vhost?parseTime=true&charset=utf8mb4&collation=utf8mb4_unicode_ci") + cfg.SessionSecret = os.Getenv("SEA_SESSION_SECRET") + cfg.PanelMock = envBool("SEA_PANEL_MOCK", true) + cfg.RootDomain = strings.ToLower(env("SEA_ROOT_DOMAIN", cfg.RootDomain)) + cfg.DomainApproval = envBool("SEA_DOMAIN_APPROVAL", true) + cfg.AgentMock = envBool("SEA_AGENT_MOCK", true) + cfg.ManagementDomain = normalizeDomain(os.Getenv("SEA_MANAGEMENT_DOMAIN")) + cfg.FTPDomain = normalizeDomain(os.Getenv("SEA_FTP_DOMAIN")) + cfg.ReservedDomains = normalizeDomains(strings.Split(os.Getenv("SEA_RESERVED_DOMAINS"), ",")) + return cfg +} + +func InternalAuthToken() string { return strings.TrimSpace(os.Getenv("SEA_INTERNAL_AUTH_TOKEN")) } + +func normalizeDomain(value string) string { + return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), ".")) +} + +func normalizeDomains(values []string) []string { + result := make([]string, 0, len(values)) + seen := make(map[string]bool, len(values)) + for _, value := range values { + value = normalizeDomain(value) + if value != "" && !seen[value] { + seen[value] = true + result = append(result, value) + } + } + return result +} + +func env(name, fallback string) string { + if value := strings.TrimSpace(os.Getenv(name)); value != "" { + return value + } + return fallback +} + +func envBool(name string, fallback bool) bool { + value := strings.TrimSpace(os.Getenv(name)) + if value == "" { + return fallback + } + parsed, err := strconv.ParseBool(value) + if err != nil { + return fallback + } + return parsed +} + +func envInt64(name string, fallback int64) int64 { + value := strings.TrimSpace(os.Getenv(name)) + if value == "" { + return fallback + } + parsed, err := strconv.ParseInt(value, 10, 64) + if err != nil || parsed <= 0 { + return fallback + } + return parsed +} diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go new file mode 100644 index 0000000..19d8bec --- /dev/null +++ b/backend/internal/config/config_test.go @@ -0,0 +1,53 @@ +package config + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSaveAndLoadInstalledConfiguration(t *testing.T) { + path := filepath.Join(t.TempDir(), "state", "config.json") + t.Setenv("SEA_CONFIG_FILE", path) + t.Setenv("SEA_SESSION_SECRET", "") + t.Setenv("SEA_INTERNAL_AUTH_TOKEN", strings.Repeat("i", 48)) + cfg := NewInstalled( + "sea_vhost:secret@tcp(127.0.0.1:3306)/sea_vhost?parseTime=true", + "012345678901234567890123456789012345678901234567", + "hosts.example.com", "console.example.com", "ftp.example.com", []string{"panel.example.com"}, false, + ) + if err := Save(cfg); err != nil { + t.Fatalf("Save() error = %v", err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), "panel_api_key") { + t.Fatal("Web API configuration contains a panel API key") + } + loaded, err := Load() + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if loaded.DatabaseDSN != cfg.DatabaseDSN || loaded.PanelBrokerSocket != cfg.PanelBrokerSocket || loaded.RootDomain != cfg.RootDomain || loaded.ManagementDomain != cfg.ManagementDomain || loaded.FTPDomain != cfg.FTPDomain { + t.Fatalf("Load() did not preserve installed configuration") + } + if loaded.PanelMock || loaded.AgentMock || loaded.DomainApproval { + t.Fatalf("production flags were not preserved") + } + if err := Save(cfg); err == nil { + t.Fatal("Save() unexpectedly overwrote an installed configuration") + } +} + +func TestLoadRequiresSetupWithoutConfigOrLegacySecret(t *testing.T) { + t.Setenv("SEA_CONFIG_FILE", filepath.Join(t.TempDir(), "missing.json")) + t.Setenv("SEA_SESSION_SECRET", "") + _, err := Load() + if !errors.Is(err, ErrSetupRequired) { + t.Fatalf("Load() error = %v, want ErrSetupRequired", err) + } +} diff --git a/backend/internal/controlwire/pairing.go b/backend/internal/controlwire/pairing.go new file mode 100644 index 0000000..3d31a78 --- /dev/null +++ b/backend/internal/controlwire/pairing.go @@ -0,0 +1,86 @@ +package controlwire + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/pem" + "errors" + "math/big" + "net" + "time" +) + +func Pair(nodeID uint64, endpoint string) (Credentials, ServerIdentity, error) { + if nodeID == 0 { + return Credentials{}, ServerIdentity{}, errors.New("node identity required") + } + u, err := ValidateEndpoint(endpoint) + if err != nil { + return Credentials{}, ServerIdentity{}, err + } + serial := func() (*big.Int, error) { return rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120)) } + caSerial, err := serial() + if err != nil { + return Credentials{}, ServerIdentity{}, err + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return Credentials{}, ServerIdentity{}, err + } + now := time.Now() + ca := &x509.Certificate{SerialNumber: caSerial, Subject: pkix.Name{CommonName: "Sea vHost node trust"}, NotBefore: now.Add(-5 * time.Minute), NotAfter: now.AddDate(2, 0, 0), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign} + caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key) + if err != nil { + return Credentials{}, ServerIdentity{}, err + } + caPEM := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER})) + issue := func(client bool) (string, string, *ecdsa.PrivateKey, error) { + k, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if e != nil { + return "", "", nil, e + } + certSerial, e := serial() + if e != nil { + return "", "", nil, e + } + cert := &x509.Certificate{SerialNumber: certSerial, Subject: pkix.Name{CommonName: "Sea vHost paired identity"}, NotBefore: now.Add(-5 * time.Minute), NotAfter: now.AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature} + if client { + cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} + } else { + cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + if ip := net.ParseIP(u.Hostname()); ip != nil { + cert.IPAddresses = []net.IP{ip} + } else { + cert.DNSNames = []string{u.Hostname()} + } + } + der, e := x509.CreateCertificate(rand.Reader, cert, ca, &k.PublicKey, key) + if e != nil { + return "", "", nil, e + } + private, e := x509.MarshalPKCS8PrivateKey(k) + if e != nil { + return "", "", nil, e + } + return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})), string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: private})), k, nil + } + clientCert, clientKey, client, e := issue(true) + if e != nil { + return Credentials{}, ServerIdentity{}, e + } + serverCert, serverKey, _, e := issue(false) + if e != nil { + return Credentials{}, ServerIdentity{}, e + } + spki, e := x509.MarshalPKIXPublicKey(&client.PublicKey) + if e != nil { + return Credentials{}, ServerIdentity{}, e + } + digest := sha256.Sum256(spki) + return Credentials{CAPEM: caPEM, ClientCertificate: clientCert, ClientPrivateKey: clientKey}, ServerIdentity{NodeID: nodeID, CAPEM: caPEM, Certificate: serverCert, PrivateKey: serverKey, ClientSPKI: hex.EncodeToString(digest[:])}, nil +} diff --git a/backend/internal/controlwire/protocol.go b/backend/internal/controlwire/protocol.go new file mode 100644 index 0000000..acaaaa3 --- /dev/null +++ b/backend/internal/controlwire/protocol.go @@ -0,0 +1,176 @@ +// Package controlwire defines the versioned controller-initiated node wire +// protocol. It has no store, scheduler or business database dependency. +package controlwire + +import ( + "bytes" + "crypto/sha256" + "crypto/subtle" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" +) + +const Version = "sea-vhost-node/1" +const MaxEnvelopeBytes = 4 << 20 + +type Credentials struct { + CAPEM string `json:"caPem"` + ClientCertificate string `json:"clientCertificate"` + ClientPrivateKey string `json:"clientPrivateKey"` +} +type ServerIdentity struct { + NodeID uint64 `json:"nodeId"` + CAPEM string `json:"caPem"` + Certificate string `json:"certificate"` + PrivateKey string `json:"privateKey"` + ClientSPKI string `json:"clientSpki"` +} + +func ValidateEndpoint(endpoint string) (*url.URL, error) { + u, err := url.Parse(endpoint) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return nil, errors.New("node endpoint must be an HTTPS origin without credentials, path, query or fragment") + } + return u, nil +} +func ClientTLS(credentials Credentials) (*tls.Config, error) { + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM([]byte(credentials.CAPEM)) { + return nil, errors.New("invalid node CA") + } + certificate, err := tls.X509KeyPair([]byte(credentials.ClientCertificate), []byte(credentials.ClientPrivateKey)) + if err != nil { + return nil, errors.New("invalid controller client identity") + } + return &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{certificate}}, nil +} +func ServerTLS(identity ServerIdentity) (*tls.Config, error) { + if identity.NodeID == 0 || len(identity.ClientSPKI) != 64 { + return nil, errors.New("invalid node identity") + } + expected, err := hex.DecodeString(identity.ClientSPKI) + if err != nil { + return nil, err + } + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM([]byte(identity.CAPEM)) { + return nil, errors.New("invalid controller trust CA") + } + certificate, err := tls.X509KeyPair([]byte(identity.Certificate), []byte(identity.PrivateKey)) + if err != nil { + return nil, errors.New("invalid node TLS keypair") + } + return &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{certificate}, ClientCAs: roots, ClientAuth: tls.RequireAndVerifyClientCert, VerifyConnection: func(state tls.ConnectionState) error { + if len(state.PeerCertificates) == 0 { + return errors.New("controller identity missing") + } + actual := sha256.Sum256(state.PeerCertificates[0].RawSubjectPublicKeyInfo) + if subtle.ConstantTimeCompare(actual[:], expected) != 1 { + return errors.New("controller identity is not paired to this node") + } + return nil + }}, nil +} +func Decode(w http.ResponseWriter, r *http.Request, out any) error { + r.Body = http.MaxBytesReader(w, r.Body, MaxEnvelopeBytes) + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(out); err != nil { + return errors.New("invalid node request") + } + if decoder.Decode(&struct{}{}) != io.EOF { + return errors.New("trailing node request data") + } + return nil +} +func Encode(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +// Authenticated also binds the destination node and protocol. Credentials for +// one node cannot be silently reused against a different node endpoint. +func Authenticated(nodeID uint64, next http.Handler) http.Handler { + var mu sync.Mutex + seen := map[string]int64{} + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.TLS == nil || len(r.TLS.VerifiedChains) == 0 { + http.Error(w, "mutual TLS required", 401) + return + } + if r.Header.Get("X-Sea-Protocol") != Version || r.Header.Get("X-Sea-Node") != strconv.FormatUint(nodeID, 10) { + http.Error(w, "wrong node or protocol", 403) + return + } + expiry, err := strconv.ParseInt(r.Header.Get("X-Sea-Expires"), 10, 64) + now := time.Now().Unix() + if err != nil || expiry < now || expiry > now+300 { + http.Error(w, "expired node request", 403) + return + } + requestID := r.Header.Get("X-Sea-Request") + if len(requestID) != 32 { + http.Error(w, "invalid request identity", 400) + return + } + if _, err := hex.DecodeString(requestID); err != nil { + http.Error(w, "invalid request identity", 400) + return + } + if r.Method != http.MethodGet { + mu.Lock() + for id, until := range seen { + if until < now { + delete(seen, id) + } + } + _, duplicate := seen[requestID] + full := len(seen) >= 20000 + if !duplicate && !full { + seen[requestID] = expiry + } + mu.Unlock() + if duplicate { + http.Error(w, "request already received; reconcile actual state", 409) + return + } + if full { + http.Error(w, "node request capacity reached", 503) + return + } + } + next.ServeHTTP(w, r) + }) +} +func NewRequest(method, endpoint, route string, nodeID uint64, requestID string, body []byte) (*http.Request, error) { + base, err := ValidateEndpoint(endpoint) + if err != nil { + return nil, err + } + if !strings.HasPrefix(route, "/v1/") || strings.Contains(route, "..") || strings.ContainsAny(route, "?#") { + return nil, errors.New("invalid node route") + } + base.Path = route + request, err := http.NewRequest(method, base.String(), bytes.NewReader(body)) + if err != nil { + return nil, err + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-Sea-Protocol", Version) + request.Header.Set("X-Sea-Node", strconv.FormatUint(nodeID, 10)) + request.Header.Set("X-Sea-Request", requestID) + request.Header.Set("X-Sea-Expires", strconv.FormatInt(time.Now().Add(2*time.Minute).Unix(), 10)) + return request, nil +} diff --git a/backend/internal/dnsprovider/dnsmgr.go b/backend/internal/dnsprovider/dnsmgr.go new file mode 100644 index 0000000..48379a7 --- /dev/null +++ b/backend/internal/dnsprovider/dnsmgr.go @@ -0,0 +1,184 @@ +package dnsprovider + +import ( + "context" + "crypto/md5" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type dnsmgr struct { + client *http.Client + zone string + credential Credential + now func() time.Time +} + +func positiveID(s string) bool { + id, e := strconv.ParseUint(s, 10, 64) + return e == nil && id > 0 && strconv.FormatUint(id, 10) == s +} +func md5Hex(v string) string { sum := md5.Sum([]byte(v)); return hex.EncodeToString(sum[:]) } +func (p *dnsmgr) call(ctx context.Context, path string, values url.Values, output any) error { + stamp := strconv.FormatInt(p.now().Unix(), 10) + values.Set("uid", p.credential.UserID) + values.Set("timestamp", stamp) + values.Set("sign", md5Hex(p.credential.UserID+stamp+p.credential.APIKey)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(p.credential.Endpoint, "/")+"/api/"+path, strings.NewReader(values.Encode())) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + // List APIs use {total,rows}; mutation/info APIs require an explicit successful code. + var raw json.RawMessage + if err = doJSON(p.client, req, &raw); err != nil { + return err + } + var status struct { + Code *int `json:"code"` + } + if json.Unmarshal(raw, &status) != nil { + return errors.New("彩虹 DNS 响应无效") + } + if status.Code != nil && *status.Code != 0 { + return errors.New("彩虹 DNS 拒绝请求,请检查 API 权限与票据") + } + if !strings.HasSuffix(path, "domain") && !strings.HasPrefix(path, "record/data/") && status.Code == nil { + return errors.New("彩虹 DNS 未确认操作结果") + } + return json.Unmarshal(raw, output) +} +func (p *dnsmgr) Present(ctx context.Context, fqdn, value string) (string, error) { + return p.CreateRecord(ctx, fqdn, "TXT", value) +} + +type mgrRecord struct { + ID json.RawMessage `json:"RecordId"` + Name string `json:"Name"` + Type string `json:"Type"` + Value json.RawMessage `json:"Value"` +} + +func rawID(raw json.RawMessage) string { + var s string + if json.Unmarshal(raw, &s) == nil { + return s + } + var n json.Number + if json.Unmarshal(raw, &n) == nil { + return n.String() + } + return "" +} +func rawValueContains(raw json.RawMessage, value string) bool { + var s string + if json.Unmarshal(raw, &s) == nil { + return s == value + } + var all []string + if json.Unmarshal(raw, &all) == nil { + for _, s := range all { + if s == value { + return true + } + } + } + return false +} +func (p *dnsmgr) records(ctx context.Context, rr, kind, value string) ([]mgrRecord, error) { + var out struct { + Total *int `json:"total"` + Rows []mgrRecord `json:"rows"` + } + if err := p.call(ctx, "record/data/"+p.credential.ZoneID, url.Values{"subdomain": {rr}, "type": {kind}, "value": {value}, "offset": {"0"}, "limit": {"100"}}, &out); err != nil { + return nil, err + } + if out.Total == nil || *out.Total > 100 { + return nil, errors.New("彩虹 DNS 记录响应不完整") + } + return out.Rows, nil +} +func (p *dnsmgr) CreateRecord(ctx context.Context, fqdn, kind, value string) (string, error) { + if err := validateRecord(kind, value); err != nil { + return "", err + } + rr, err := relativeRecordName(fqdn, p.zone) + if err != nil { + return "", err + } + if !positiveID(p.credential.ZoneID) { + return "", errors.New("彩虹 DNS 域名编号无效") + } + before, err := p.records(ctx, rr, kind, value) + if err != nil { + return "", err + } + old := map[string]bool{} + for _, r := range before { + old[rawID(r.ID)] = true + } + var info struct { + Code int `json:"code"` + Data struct { + RecordLine []struct { + ID string `json:"id"` + Name string `json:"name"` + } `json:"recordLine"` + MinTTL json.Number `json:"minTTL"` + } `json:"data"` + } + if err = p.call(ctx, "domain/"+p.credential.ZoneID, url.Values{}, &info); err != nil { + return "", err + } + minTTL := int64(0) + if info.Data.MinTTL != "" { + minTTL, err = info.Data.MinTTL.Int64() + if err != nil || minTTL < 0 || minTTL > 2147483647 { + return "", errors.New("彩虹 DNS 返回了无效的最小 TTL") + } + } + line := "" + found := false + for _, l := range info.Data.RecordLine { + if l.Name == "默认" || strings.EqualFold(l.Name, "default") { + line = l.ID + found = true + break + } + } + if !found { + return "", errors.New("彩虹 DNS 未提供默认解析线路") + } + var response struct { + Code int `json:"code"` + } + if err = p.call(ctx, "record/add/"+p.credential.ZoneID, url.Values{"name": {rr}, "type": {kind}, "value": {value}, "line": {line}, "ttl": {strconv.FormatInt(max(int64(600), minTTL), 10)}}, &response); err != nil { + return "", err + } + after, err := p.records(ctx, rr, kind, value) + if err != nil { + return "", err + } + for _, r := range after { + id := rawID(r.ID) + if validIdentifier(id, 1, 128) && !old[id] && (r.Name == rr || r.Name == fqdn) && r.Type == kind && rawValueContains(r.Value, value) { + return id, nil + } + } + return "", errors.New("彩虹 DNS 已接受创建,但未能核对新增记录编号,请管理员核验") +} +func (p *dnsmgr) Cleanup(ctx context.Context, id string) error { + if !positiveID(p.credential.ZoneID) || !validIdentifier(id, 1, 128) { + return errors.New("彩虹 DNS 记录编号无效") + } + var out struct { + Code int `json:"code"` + } + return p.call(ctx, "record/delete/"+p.credential.ZoneID, url.Values{"recordid": {id}}, &out) +} diff --git a/backend/internal/dnsprovider/dnsmgr_ttl_test.go b/backend/internal/dnsprovider/dnsmgr_ttl_test.go new file mode 100644 index 0000000..bac1250 --- /dev/null +++ b/backend/internal/dnsprovider/dnsmgr_ttl_test.go @@ -0,0 +1,36 @@ +package dnsprovider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestDNSManagerRejectsInvalidTTLBeforeCreatingRecord(t *testing.T) { + for _, ttl := range []any{"-1", "1.5", "invalid", "2147483648", false} { + t.Run(stringJSON(ttl), func(t *testing.T) { + writes := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/record/data/7": + _, _ = w.Write([]byte(`{"total":0,"rows":[]}`)) + case "/api/domain/7": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"minTTL": ttl, "recordLine": []map[string]any{{"id": "default", "name": "默认"}}}}) + default: + writes++ + _, _ = w.Write([]byte(`{"code":0}`)) + } + })) + defer server.Close() + provider := &dnsmgr{client: server.Client(), zone: "example.com", credential: Credential{Endpoint: server.URL, UserID: "12", APIKey: "fixture-api-key", ZoneID: "7"}, now: time.Now} + if _, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof"); err == nil || writes != 0 { + t.Fatal("invalid TTL reached mutation", err, writes) + } + }) + } +} + +func stringJSON(v any) string { raw, _ := json.Marshal(v); return string(raw) } diff --git a/backend/internal/dnsprovider/extended_test.go b/backend/internal/dnsprovider/extended_test.go new file mode 100644 index 0000000..0896d0e --- /dev/null +++ b/backend/internal/dnsprovider/extended_test.go @@ -0,0 +1,128 @@ +package dnsprovider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/netip" + "strconv" + "testing" + "time" +) + +func TestDNSManagerPreservesExistingRecordsAndSignsRequests(t *testing.T) { + for _, tc := range []struct { + name string + ttl any + want string + }{{"numeric", 600, "600"}, {"string-low", "60", "600"}, {"string-high", "1800", "1800"}} { + t.Run(tc.name, func(t *testing.T) { + created := false + deleted := "" + stamp := time.Unix(1780000000, 0) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + t.Error("wrong method") + } + _ = r.ParseForm() + if r.Form.Get("uid") != "12" || r.Form.Get("timestamp") != strconv.FormatInt(stamp.Unix(), 10) || r.Form.Get("sign") != md5Hex("12"+strconv.FormatInt(stamp.Unix(), 10)+"fixture-api-key") { + t.Error("invalid API signature") + } + if r.Form.Get("key") != "" { + t.Error("plaintext key transmitted") + } + switch r.URL.Path { + case "/api/domain/7": + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"recordLine": []map[string]any{{"id": "default", "name": "默认"}}, "minTTL": tc.ttl}}) + case "/api/record/data/7": + rows := []map[string]any{{"RecordId": "9", "Name": "_acme-challenge", "Type": "TXT", "Value": "proof"}} + if created { + rows = append(rows, map[string]any{"RecordId": "10", "Name": "_acme-challenge", "Type": "TXT", "Value": "proof"}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"total": len(rows), "rows": rows}) + case "/api/record/add/7": + if r.Form.Get("line") != "default" || r.Form.Get("name") != "_acme-challenge" || r.Form.Get("ttl") != tc.want { + t.Error("wrong record target") + } + created = true + _, _ = w.Write([]byte(`{"code":0}`)) + case "/api/record/delete/7": + deleted = r.Form.Get("recordid") + _, _ = w.Write([]byte(`{"code":0}`)) + default: + t.Error("unexpected endpoint", r.URL.Path) + w.WriteHeader(404) + } + })) + defer srv.Close() + p := &dnsmgr{client: srv.Client(), zone: "example.com", credential: Credential{Endpoint: srv.URL, UserID: "12", APIKey: "fixture-api-key", ZoneID: "7"}, now: func() time.Time { return stamp }} + id, e := p.Present(context.Background(), "_acme-challenge.example.com", "proof") + if e != nil || id != "10" { + t.Fatal(id, e) + } + if e = p.Cleanup(context.Background(), id); e != nil { + t.Fatal(e) + } + if deleted != "10" { + t.Fatal("deleted pre-existing record", deleted) + } + if _, e = p.Present(context.Background(), "outside.example.net", "proof"); e == nil { + t.Fatal("zone escape accepted") + } + }) + } +} +func TestWestAccountUsesReadOnlyDiscoveryAndExactRecordDeletion(t *testing.T) { + deleted := "" + stamp := time.Unix(1780000000, 0) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + if r.Form.Get("token") != md5Hex("fixture-user"+"fixture-api-key"+strconv.FormatInt(stamp.UnixMilli(), 10)) { + t.Error("bad account signature") + } + switch r.Form.Get("act") { + case "adddnsrecord": + if r.Form.Get("domain") != "example.com" || r.Form.Get("host") != "_acme-challenge" { + t.Error("wrong zone") + } + _, _ = w.Write([]byte(`{"result":200,"data":{"id":55}}`)) + case "deldnsrecord": + deleted = r.Form.Get("id") + _, _ = w.Write([]byte(`{"result":200,"data":{}}`)) + default: + t.Error("unexpected operation") + w.WriteHeader(404) + } + })) + defer srv.Close() + p := &west{client: srv.Client(), baseURL: srv.URL, zone: "example.com", credential: Credential{Username: "fixture-user", APIKey: "fixture-api-key"}, now: func() time.Time { return stamp }} + id, e := p.Present(context.Background(), "_acme-challenge.example.com", "proof") + if e != nil || id != "55" { + t.Fatal(id, e) + } + if e = p.Cleanup(context.Background(), id); e != nil { + t.Fatal(e) + } + if deleted != "55" { + t.Fatal(deleted) + } +} +func TestDNSCustomEndpointCannotReachPrivateNetworks(t *testing.T) { + for _, s := range []string{"http://dns.example.com", "https://127.0.0.1", "https://[::1]", "https://10.0.0.1", "https://dns.example.com:9443", "https://user:key@dns.example.com", "https://dns.example.com?a=b", "https://100.64.0.1", "https://[64:ff9b::7f00:1]"} { + if _, e := publicEndpoint(s); e == nil { + t.Error("unsafe endpoint", s) + } + } + if _, e := publicEndpoint("https://dns.example.com/subdir"); e != nil { + t.Fatal(e) + } + for _, s := range []string{"127.0.0.1", "::1", "::ffff:127.0.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "64:ff9b::7f00:1", "2002:7f00:1::"} { + if publicIP(netip.MustParseAddr(s)) { + t.Error("restricted IP accepted", s) + } + } + if !publicIP(netip.MustParseAddr("1.1.1.1")) { + t.Fatal("public DNS address rejected") + } +} diff --git a/backend/internal/dnsprovider/provider.go b/backend/internal/dnsprovider/provider.go new file mode 100644 index 0000000..a80e960 --- /dev/null +++ b/backend/internal/dnsprovider/provider.go @@ -0,0 +1,472 @@ +package dnsprovider + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const maxResponseBytes = 64 << 10 + +type Provider interface { + Present(context.Context, string, string) (string, error) + CreateRecord(context.Context, string, string, string) (string, error) + Cleanup(context.Context, string) error +} + +type Credential struct { + Endpoint string `json:"endpoint,omitempty"` + UserID string `json:"userId,omitempty"` + APIKey string `json:"apiKey,omitempty"` + Username string `json:"username,omitempty"` + DomainKey string `json:"domainKey,omitempty"` + + APIToken string `json:"apiToken,omitempty"` + ZoneID string `json:"zoneId,omitempty"` + AccessKeyID string `json:"accessKeyId,omitempty"` + AccessKeySecret string `json:"accessKeySecret,omitempty"` + SecretID string `json:"secretId,omitempty"` + SecretKey string `json:"secretKey,omitempty"` +} + +func Validate(provider string, credential Credential) error { + provider = strings.ToLower(strings.TrimSpace(provider)) + switch provider { + case "cloudflare": + if !validSecret(credential.APIToken, 20, 512) || !validIdentifier(credential.ZoneID, 8, 128) { + return errors.New("Cloudflare API Token 或 Zone ID 格式无效") + } + case "aliyun": + if !validIdentifier(credential.AccessKeyID, 8, 128) || !validSecret(credential.AccessKeySecret, 16, 512) { + return errors.New("阿里云 AccessKey ID 或 Secret 格式无效") + } + case "tencent": + if !validIdentifier(credential.SecretID, 8, 128) || !validSecret(credential.SecretKey, 16, 512) { + return errors.New("腾讯云 SecretId 或 SecretKey 格式无效") + } + case "west": + if credential.DomainKey != "" { + if !validSecret(credential.DomainKey, 8, 512) { + return errors.New("西部数码单域名密钥格式无效") + } + } else if !validSecret(credential.Username, 1, 128) || !validSecret(credential.APIKey, 8, 512) { + return errors.New("西部数码 API 用户名或 API 密码无效") + } + case "dnsmgr": + if !positiveID(credential.UserID) || !validSecret(credential.APIKey, 8, 512) { + return errors.New("彩虹 DNS 用户 ID 或密钥无效") + } + if _, err := publicEndpoint(credential.Endpoint); err != nil { + return err + } + default: + return errors.New("不支持的 DNS 服务商") + } + return nil +} + +func New(provider, zone string, credential Credential) (Provider, error) { + if err := Validate(provider, credential); err != nil { + return nil, err + } + client := &http.Client{ + Timeout: 20 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + switch strings.ToLower(strings.TrimSpace(provider)) { + case "cloudflare": + return &cloudflare{client: client, token: credential.APIToken, zoneID: credential.ZoneID}, nil + case "aliyun": + return &aliyun{client: client, accessKeyID: credential.AccessKeyID, accessKeySecret: credential.AccessKeySecret, zone: zone, now: time.Now}, nil + case "tencent": + return &tencent{client: client, secretID: credential.SecretID, secretKey: credential.SecretKey, zone: zone, now: time.Now}, nil + case "west": + return &west{client: client, zone: zone, credential: credential, now: time.Now}, nil + case "dnsmgr": + return &dnsmgr{client: publicClient(), zone: zone, credential: credential, now: time.Now}, nil + default: + return nil, errors.New("不支持的 DNS 服务商") + } +} + +func validSecret(value string, min, max int) bool { + if value != strings.TrimSpace(value) || strings.ContainsAny(value, "\r\n\x00") { + return false + } + return len(value) >= min && len(value) <= max && !strings.ContainsAny(value, "\r\n\x00") +} + +func validIdentifier(value string, min, max int) bool { + if value != strings.TrimSpace(value) { + return false + } + if len(value) < min || len(value) > max { + return false + } + for _, char := range value { + if !(char >= 'a' && char <= 'z') && !(char >= 'A' && char <= 'Z') && !(char >= '0' && char <= '9') && char != '-' && char != '_' { + return false + } + } + return true +} + +func relativeRecordName(fqdn, zone string) (string, error) { + fqdn = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(fqdn), ".")) + zone = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(zone), ".")) + if fqdn == zone { + return "@", nil + } + suffix := "." + zone + if !strings.HasSuffix(fqdn, suffix) { + return "", errors.New("DNS 记录不属于凭据区域") + } + return strings.TrimSuffix(fqdn, suffix), nil +} + +type cloudflare struct { + client *http.Client + token string + zoneID string + baseURL string +} + +func (p *cloudflare) endpoint(path string) string { + base := p.baseURL + if base == "" { + base = "https://api.cloudflare.com/client/v4" + } + return strings.TrimSuffix(base, "/") + "/zones/" + url.PathEscape(p.zoneID) + "/dns_records" + path +} + +func (p *cloudflare) Present(ctx context.Context, fqdn, value string) (string, error) { + return p.CreateRecord(ctx, fqdn, "TXT", value) +} + +func (p *cloudflare) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) { + if err := validateRecord(recordType, value); err != nil { + return "", err + } + payload, _ := json.Marshal(map[string]any{"type": recordType, "name": fqdn, "content": value, "ttl": 120, "proxied": false}) + request, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint(""), bytes.NewReader(payload)) + if err != nil { + return "", err + } + request.Header.Set("Authorization", "Bearer "+p.token) + request.Header.Set("Content-Type", "application/json") + var response struct { + Success bool `json:"success"` + Result struct { + ID string `json:"id"` + } `json:"result"` + } + if err = doJSON(p.client, request, &response); err != nil || !response.Success || response.Result.ID == "" { + if err == nil { + err = errors.New("Cloudflare 未返回记录编号") + } + return "", err + } + return response.Result.ID, nil +} + +func (p *cloudflare) Cleanup(ctx context.Context, recordID string) error { + if !validIdentifier(recordID, 1, 128) { + return errors.New("Cloudflare 记录编号无效") + } + request, err := http.NewRequestWithContext(ctx, http.MethodDelete, p.endpoint("/"+url.PathEscape(recordID)), nil) + if err != nil { + return err + } + request.Header.Set("Authorization", "Bearer "+p.token) + request.Header.Set("Content-Type", "application/json") + var response struct { + Success bool `json:"success"` + } + if err = doJSON(p.client, request, &response); err != nil { + return err + } + if !response.Success { + return errors.New("Cloudflare 删除 DNS 记录失败") + } + return nil +} + +type aliyun struct { + client *http.Client + accessKeyID, accessKeySecret string + zone, baseURL string + now func() time.Time +} + +func (p *aliyun) Present(ctx context.Context, fqdn, value string) (string, error) { + return p.CreateRecord(ctx, fqdn, "TXT", value) +} + +func (p *aliyun) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) { + if err := validateRecord(recordType, value); err != nil { + return "", err + } + rr, err := relativeRecordName(fqdn, p.zone) + if err != nil { + return "", err + } + var response struct { + RecordID string `json:"RecordId"` + } + err = p.call(ctx, "AddDomainRecord", url.Values{"DomainName": {p.zone}, "RR": {rr}, "Type": {recordType}, "Value": {value}, "TTL": {"600"}}, &response) + if err != nil { + return "", err + } + if response.RecordID == "" { + return "", errors.New("阿里云未返回记录编号") + } + return response.RecordID, nil +} + +func (p *aliyun) Cleanup(ctx context.Context, recordID string) error { + if !validIdentifier(recordID, 1, 128) { + return errors.New("阿里云记录编号无效") + } + var response struct { + Code string `json:"Code"` + Message string `json:"Message"` + } + if err := p.call(ctx, "DeleteDomainRecord", url.Values{"RecordId": {recordID}}, &response); err != nil { + return err + } + if response.Code != "" { + return &providerError{Code: response.Code, Message: response.Message} + } + return nil +} + +func (p *aliyun) call(ctx context.Context, action string, query url.Values, output any) error { + host := "dns.aliyuncs.com" + base := p.baseURL + if base == "" { + base = "https://" + host + } + parsed, err := url.Parse(base) + if err != nil { + return err + } + if parsed.Host != "" { + host = parsed.Host + } + now := p.now().UTC() + nonceBytes := make([]byte, 16) + if _, err = rand.Read(nonceBytes); err != nil { + return err + } + payloadHash := sha256Hex(nil) + headers := map[string]string{ + "host": host, + "x-acs-action": action, + "x-acs-content-sha256": payloadHash, + "x-acs-date": now.Format("2006-01-02T15:04:05Z"), + "x-acs-signature-nonce": hex.EncodeToString(nonceBytes), + "x-acs-version": "2015-01-09", + } + signed := "host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version" + canonicalHeaders := "host:" + headers["host"] + "\n" + "x-acs-action:" + headers["x-acs-action"] + "\n" + "x-acs-content-sha256:" + headers["x-acs-content-sha256"] + "\n" + "x-acs-date:" + headers["x-acs-date"] + "\n" + "x-acs-signature-nonce:" + headers["x-acs-signature-nonce"] + "\n" + "x-acs-version:" + headers["x-acs-version"] + "\n" + canonical := "POST\n/\n" + query.Encode() + "\n" + canonicalHeaders + "\n" + signed + "\n" + payloadHash + stringToSign := "ACS3-HMAC-SHA256\n" + sha256Hex([]byte(canonical)) + signature := hmacHex([]byte(p.accessKeySecret), stringToSign) + parsed.RawQuery = query.Encode() + request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), http.NoBody) + if err != nil { + return err + } + for name, value := range headers { + request.Header.Set(name, value) + } + request.Header.Set("Authorization", "ACS3-HMAC-SHA256 Credential="+p.accessKeyID+",SignedHeaders="+signed+",Signature="+signature) + return doJSON(p.client, request, output) +} + +type tencent struct { + client *http.Client + secretID, secretKey string + zone, baseURL string + now func() time.Time +} + +func (p *tencent) Present(ctx context.Context, fqdn, value string) (string, error) { + return p.CreateRecord(ctx, fqdn, "TXT", value) +} + +func (p *tencent) CreateRecord(ctx context.Context, fqdn, recordType, value string) (string, error) { + if err := validateRecord(recordType, value); err != nil { + return "", err + } + rr, err := relativeRecordName(fqdn, p.zone) + if err != nil { + return "", err + } + var response struct { + Response struct { + RecordID uint64 `json:"RecordId"` + Error *providerError `json:"Error"` + } `json:"Response"` + } + err = p.call(ctx, "CreateRecord", map[string]any{"Domain": p.zone, "SubDomain": rr, "RecordType": recordType, "RecordLine": "默认", "Value": value, "TTL": 600}, &response) + if err != nil { + return "", err + } + if response.Response.Error != nil { + return "", response.Response.Error + } + if response.Response.RecordID == 0 { + return "", errors.New("腾讯云未返回记录编号") + } + return strconv.FormatUint(response.Response.RecordID, 10), nil +} + +func (p *tencent) Cleanup(ctx context.Context, recordID string) error { + id, err := strconv.ParseUint(recordID, 10, 64) + if err != nil || id == 0 { + return errors.New("腾讯云记录编号无效") + } + var response struct { + Response struct { + Error *providerError `json:"Error"` + } `json:"Response"` + } + if err = p.call(ctx, "DeleteRecord", map[string]any{"Domain": p.zone, "RecordId": id}, &response); err != nil { + return err + } + if response.Response.Error != nil { + return response.Response.Error + } + return nil +} + +func (p *tencent) call(ctx context.Context, action string, input any, output any) error { + payload, err := json.Marshal(input) + if err != nil { + return err + } + host := "dnspod.tencentcloudapi.com" + endpoint := p.baseURL + if endpoint == "" { + endpoint = "https://" + host + } + parsed, err := url.Parse(endpoint) + if err != nil { + return err + } + if parsed.Host != "" { + host = parsed.Host + } + now := p.now().UTC() + timestamp := strconv.FormatInt(now.Unix(), 10) + contentType := "application/json; charset=utf-8" + canonicalHeaders := "content-type:" + contentType + "\n" + "host:" + host + "\n" + "x-tc-action:" + strings.ToLower(action) + "\n" + signedHeaders := "content-type;host;x-tc-action" + canonical := "POST\n/\n\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + sha256Hex(payload) + date := now.Format("2006-01-02") + scope := date + "/dnspod/tc3_request" + stringToSign := "TC3-HMAC-SHA256\n" + timestamp + "\n" + scope + "\n" + sha256Hex([]byte(canonical)) + secretDate := hmacBytes([]byte("TC3"+p.secretKey), date) + secretService := hmacBytes(secretDate, "dnspod") + secretSigning := hmacBytes(secretService, "tc3_request") + signature := hmacHex(secretSigning, stringToSign) + authorization := "TC3-HMAC-SHA256 Credential=" + p.secretID + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + signature + request, err := http.NewRequestWithContext(ctx, http.MethodPost, parsed.String(), bytes.NewReader(payload)) + if err != nil { + return err + } + request.Header.Set("Authorization", authorization) + request.Header.Set("Content-Type", contentType) + request.Header.Set("X-TC-Action", action) + request.Header.Set("X-TC-Timestamp", timestamp) + request.Header.Set("X-TC-Version", "2021-03-23") + return doJSON(p.client, request, output) +} + +type providerError struct{ Code, Message string } + +func (e *providerError) Error() string { + if e == nil { + return "" + } + if e.Code == "" { + return "DNS 服务商拒绝请求" + } + return "DNS 服务商返回错误 " + e.Code +} + +func doJSON(client *http.Client, request *http.Request, output any) error { + response, err := client.Do(request) + if err != nil { + return errors.New("无法连接 DNS 服务商") + } + defer response.Body.Close() + body, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1)) + if err != nil { + return errors.New("读取 DNS 服务商响应失败") + } + if len(body) > maxResponseBytes { + return errors.New("DNS 服务商响应过大") + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + return fmt.Errorf("DNS 服务商返回 HTTP %d", response.StatusCode) + } + if err = json.Unmarshal(body, output); err != nil { + return errors.New("DNS 服务商响应格式无效") + } + return nil +} + +func sha256Hex(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) } +func hmacBytes(key []byte, value string) []byte { + mac := hmac.New(sha256.New, key) + _, _ = mac.Write([]byte(value)) + return mac.Sum(nil) +} +func hmacHex(key []byte, value string) string { return hex.EncodeToString(hmacBytes(key, value)) } + +func validateRecord(recordType, value string) error { + recordType = strings.ToUpper(strings.TrimSpace(recordType)) + value = strings.TrimSpace(value) + if recordType != "TXT" && recordType != "A" && recordType != "AAAA" && recordType != "CNAME" { + return errors.New("DNS record type is not supported") + } + if value == "" || len(value) > 1024 || strings.ContainsAny(value, "\r\n\x00") { + return errors.New("DNS record value is invalid") + } + if recordType == "A" && net.ParseIP(value).To4() == nil { + return errors.New("DNS A record requires IPv4") + } + if recordType == "AAAA" { + ip := net.ParseIP(value) + if ip == nil || ip.To4() != nil { + return errors.New("DNS AAAA record requires IPv6") + } + } + if recordType == "CNAME" && !brokerCompatibleDomainValue(value) { + return errors.New("DNS CNAME value is invalid") + } + return nil +} + +func brokerCompatibleDomainValue(value string) bool { + value = strings.ToLower(strings.TrimSuffix(value, ".")) + if len(value) < 3 || len(value) > 253 || strings.ContainsAny(value, " /\\:\t") { + return false + } + return strings.Contains(value, ".") +} diff --git a/backend/internal/dnsprovider/provider_test.go b/backend/internal/dnsprovider/provider_test.go new file mode 100644 index 0000000..d19b7b2 --- /dev/null +++ b/backend/internal/dnsprovider/provider_test.go @@ -0,0 +1,155 @@ +package dnsprovider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestRelativeRecordName(t *testing.T) { + name, err := relativeRecordName("_acme-challenge.app.example.com", "example.com") + if err != nil || name != "_acme-challenge.app" { + t.Fatalf("name=%q err=%v", name, err) + } + if _, err = relativeRecordName("_acme-challenge.evil.example", "example.com"); err == nil { + t.Fatal("expected zone boundary error") + } +} + +func TestAliyunCleanupDoesNotTreatProviderRejectionAsSuccess(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"Code":"Forbidden","Message":"denied"}`)) + })) + defer server.Close() + provider := &aliyun{client: server.Client(), accessKeyID: "test", accessKeySecret: "test", zone: "example.com", baseURL: server.URL, now: time.Now} + if err := provider.Cleanup(context.Background(), "record_123"); err == nil { + t.Fatal("provider rejection treated as successful deletion") + } +} + +func TestCloudflarePresentAndCleanup(t *testing.T) { + var created bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 24) { + t.Error("missing bearer token") + } + switch r.Method { + case http.MethodPost: + created = true + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + if body["name"] != "_acme-challenge.example.com" || body["type"] != "TXT" { + t.Errorf("unexpected body: %#v", body) + } + _, _ = w.Write([]byte(`{"success":true,"result":{"id":"record_123"}}`)) + case http.MethodDelete: + if !created || !strings.HasSuffix(r.URL.Path, "/record_123") { + t.Errorf("unexpected cleanup path: %s", r.URL.Path) + } + _, _ = w.Write([]byte(`{"success":true}`)) + } + })) + defer server.Close() + provider := &cloudflare{client: server.Client(), token: strings.Repeat("t", 24), zoneID: "zone_123456", baseURL: server.URL} + recordID, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof") + if err != nil || recordID != "record_123" { + t.Fatalf("record=%q err=%v", recordID, err) + } + if err = provider.Cleanup(context.Background(), recordID); err != nil { + t.Fatal(err) + } +} + +func TestCloudflareCreatesCNAMEWithoutProxying(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + if body["name"] != "app.example.com" || body["type"] != "CNAME" || body["content"] != "target.vhost.example" || body["proxied"] != false { + t.Errorf("unexpected body: %#v", body) + } + _, _ = w.Write([]byte(`{"success":true,"result":{"id":"cname_123"}}`)) + })) + defer server.Close() + provider := &cloudflare{client: server.Client(), token: strings.Repeat("t", 24), zoneID: "zone_123456", baseURL: server.URL} + recordID, err := provider.CreateRecord(context.Background(), "app.example.com", "CNAME", "target.vhost.example") + if err != nil || recordID != "cname_123" { + t.Fatalf("record=%q err=%v", recordID, err) + } +} + +func TestValidateRecordRejectsInvalidAddressAndCNAME(t *testing.T) { + for _, input := range []struct{ recordType, value string }{{"A", "2001:db8::1"}, {"AAAA", "192.0.2.1"}, {"CNAME", "not-a-domain"}, {"MX", "mail.example.com"}} { + if err := validateRecord(input.recordType, input.value); err == nil { + t.Fatalf("accepted invalid %s value %q", input.recordType, input.value) + } + } +} + +func TestAliyunSignedRequests(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.Header.Get("Authorization"), "ACS3-HMAC-SHA256 Credential=accessKey123") { + t.Error("missing Aliyun V3 signature") + } + switch r.Header.Get("x-acs-action") { + case "AddDomainRecord": + if r.URL.Query().Get("RR") != "_acme-challenge.app" || r.URL.Query().Get("DomainName") != "example.com" { + t.Errorf("unexpected query: %s", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"RecordId":"9988"}`)) + case "DeleteDomainRecord": + if r.URL.Query().Get("RecordId") != "9988" { + t.Errorf("unexpected record id") + } + _, _ = w.Write([]byte(`{"RequestId":"ok"}`)) + default: + t.Errorf("unexpected action") + } + })) + defer server.Close() + provider := &aliyun{client: server.Client(), accessKeyID: "accessKey123", accessKeySecret: strings.Repeat("s", 20), zone: "example.com", baseURL: server.URL, now: func() time.Time { return time.Unix(1700000000, 0) }} + recordID, err := provider.Present(context.Background(), "_acme-challenge.app.example.com", "proof") + if err != nil || recordID != "9988" { + t.Fatalf("record=%q err=%v", recordID, err) + } + if err = provider.Cleanup(context.Background(), recordID); err != nil { + t.Fatal(err) + } +} + +func TestTencentSignedRequests(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.Header.Get("Authorization"), "TC3-HMAC-SHA256 Credential=secretId123/") { + t.Error("missing Tencent V3 signature") + } + switch r.Header.Get("X-Tc-Action") { + case "CreateRecord": + _, _ = w.Write([]byte(`{"Response":{"RecordId":7788,"RequestId":"ok"}}`)) + case "DeleteRecord": + _, _ = w.Write([]byte(`{"Response":{"RequestId":"ok"}}`)) + default: + t.Errorf("unexpected action %q", r.Header.Get("X-Tc-Action")) + } + })) + defer server.Close() + provider := &tencent{client: server.Client(), secretID: "secretId123", secretKey: strings.Repeat("k", 20), zone: "example.com", baseURL: server.URL, now: func() time.Time { return time.Unix(1700000000, 0) }} + recordID, err := provider.Present(context.Background(), "_acme-challenge.example.com", "proof") + if err != nil || recordID != "7788" { + t.Fatalf("record=%q err=%v", recordID, err) + } + if err = provider.Cleanup(context.Background(), recordID); err != nil { + t.Fatal(err) + } +} + +func TestValidateRejectsUnknownProviderAndHeaderInjection(t *testing.T) { + if err := Validate("unknown", Credential{}); err == nil { + t.Fatal("expected provider error") + } + if err := Validate("cloudflare", Credential{ZoneID: "zone_123456", APIToken: strings.Repeat("x", 20) + "\n"}); err == nil { + t.Fatal("expected secret validation error") + } +} diff --git a/backend/internal/dnsprovider/public_endpoint.go b/backend/internal/dnsprovider/public_endpoint.go new file mode 100644 index 0000000..140f3ac --- /dev/null +++ b/backend/internal/dnsprovider/public_endpoint.go @@ -0,0 +1,62 @@ +package dnsprovider + +import ( + "context" + "errors" + "net" + "net/http" + "net/netip" + "net/url" + "strings" + "time" +) + +func publicEndpoint(raw string) (*url.URL, error) { + u, e := url.Parse(raw) + if e != nil || len(raw) > 512 || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") || strings.ContainsAny(raw, "\r\n\x00") || strings.ContainsAny(u.Path, "?#\\") || strings.EqualFold(u.Hostname(), "localhost") { + return nil, errors.New("DNS API 地址必须为 HTTPS 公网地址,端口为 443,不能包含查询参数或身份信息") + } + if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicIP(ip) { + return nil, errors.New("DNS API 禁止访问内网或保留地址") + } + return u, nil +} +func publicIP(ip netip.Addr) bool { + ip = ip.Unmap() + if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() { + return false + } + for _, v := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "::/96", "64:ff9b::/96", "64:ff9b:1::/48", "2001:db8::/32", "2001::/32", "2002::/16"} { + if netip.MustParsePrefix(v).Contains(ip) { + return false + } + } + return true +} +func publicClient() *http.Client { + transport := &http.Transport{Proxy: nil, TLSHandshakeTimeout: 8 * time.Second, ResponseHeaderTimeout: 15 * time.Second, MaxIdleConnsPerHost: 2, IdleConnTimeout: 20 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, e := net.SplitHostPort(address) + if e != nil || port != "443" { + return nil, errors.New("restricted DNS endpoint") + } + ips, e := net.DefaultResolver.LookupNetIP(ctx, "ip", host) + if e != nil || len(ips) == 0 { + return nil, errors.New("DNS API 域名无法解析") + } + for _, ip := range ips { + if !publicIP(ip) { + return nil, errors.New("DNS API 域名解析到受限地址") + } + } + var last error + for _, ip := range ips { + conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), port)) + if e == nil { + return conn, nil + } + last = e + } + return nil, last + }} + return &http.Client{Transport: transport, Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} +} diff --git a/backend/internal/dnsprovider/west.go b/backend/internal/dnsprovider/west.go new file mode 100644 index 0000000..6d69c24 --- /dev/null +++ b/backend/internal/dnsprovider/west.go @@ -0,0 +1,167 @@ +package dnsprovider + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type west struct { + client *http.Client + zone, baseURL string + credential Credential + now func() time.Time +} + +func (p *west) call(ctx context.Context, action string, v url.Values, out any) error { + base := p.baseURL + if base == "" { + base = "https://api.west.cn/API/v2" + } + endpoint := base + "/domain/" + v.Set("act", action) + if p.credential.DomainKey != "" { + endpoint += "dns/" + v.Set("apidomainkey", p.credential.DomainKey) + } else { + stamp := strconv.FormatInt(p.now().UnixMilli(), 10) + v.Set("username", p.credential.Username) + v.Set("time", stamp) + v.Set("token", md5Hex(p.credential.Username+p.credential.APIKey+stamp)) + } + req, e := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(v.Encode())) + if e != nil { + return e + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + var response struct { + Result int `json:"result"` + Data json.RawMessage `json:"data"` + } + if e = doJSON(p.client, req, &response); e != nil { + return e + } + if response.Result != 200 { + return errors.New("西部数码拒绝请求,请检查 API 密码、单域名密钥或白名单") + } + if out == nil { + return nil + } + return json.Unmarshal(response.Data, out) +} +func (p *west) Present(ctx context.Context, fqdn, value string) (string, error) { + return p.CreateRecord(ctx, fqdn, "TXT", value) +} + +type westRecord struct { + ID json.RawMessage `json:"record_id"` + Hostname string `json:"hostname"` + Type string `json:"record_type"` + Value string `json:"record_value"` +} + +func (p *west) modernRecords(ctx context.Context, fqdn, kind string) ([]westRecord, error) { + var data json.RawMessage + if e := p.call(ctx, "dnsrec.list", url.Values{"domain": {p.zone}, "hostname": {fqdn}, "record_type": {kind}}, &data); e != nil { + return nil, e + } + var list []westRecord + if json.Unmarshal(data, &list) == nil { + return list, nil + } + var wrapped struct { + Items []westRecord `json:"items"` + List []westRecord `json:"list"` + Records []westRecord `json:"records"` + } + if json.Unmarshal(data, &wrapped) != nil { + return nil, errors.New("西部数码记录响应无效") + } + if wrapped.Items != nil { + return wrapped.Items, nil + } + if wrapped.List != nil { + return wrapped.List, nil + } + if wrapped.Records != nil { + return wrapped.Records, nil + } + return nil, errors.New("西部数码未返回解析记录列表") +} +func (p *west) CreateRecord(ctx context.Context, fqdn, kind, value string) (string, error) { + if e := validateRecord(kind, value); e != nil { + return "", e + } + rr, e := relativeRecordName(fqdn, p.zone) + if e != nil { + return "", e + } + if p.credential.DomainKey == "" { + var out struct { + ID json.RawMessage `json:"id"` + } + if e = p.call(ctx, "adddnsrecord", url.Values{"domain": {p.zone}, "host": {rr}, "type": {kind}, "value": {value}, "ttl": {"600"}, "line": {""}}, &out); e != nil { + return "", e + } + id := rawID(out.ID) + if !validIdentifier(id, 1, 128) { + return "", errors.New("西部数码未返回新增记录编号") + } + return id, nil + } + before, e := p.modernRecords(ctx, fqdn, kind) + if e != nil { + return "", e + } + old := map[string]bool{} + for _, r := range before { + old[rawID(r.ID)] = true + } + if e = p.call(ctx, "dnsrec.add", url.Values{"domain": {p.zone}, "hostname": {fqdn}, "record_type": {kind}, "record_value": {value}, "ttl": {"600"}}, nil); e != nil { + return "", e + } + after, e := p.modernRecords(ctx, fqdn, kind) + if e != nil { + return "", e + } + for _, r := range after { + id := rawID(r.ID) + if !old[id] && validIdentifier(id, 1, 128) && r.Hostname == fqdn && r.Type == kind && r.Value == value { + return base64.RawURLEncoding.EncodeToString([]byte(fqdn + "|" + id)), nil + } + } + return "", errors.New("西部数码已接受创建,但未能核对新增记录编号,请管理员核验") +} +func (p *west) Cleanup(ctx context.Context, id string) error { + v := url.Values{"domain": {p.zone}} + action := "deldnsrecord" + if p.credential.DomainKey != "" { + raw, e := base64.RawURLEncoding.DecodeString(id) + if e != nil { + return errors.New("西部数码记录标识无效") + } + parts := strings.Split(string(raw), "|") + if len(parts) != 2 { + return errors.New("西部数码记录标识无效") + } + if _, e = relativeRecordName(parts[0], p.zone); e != nil { + return e + } + id = parts[1] + action = "dnsrec.remove" + v.Set("hostname", parts[0]) + v.Set("record_id", id) + } else { + v.Set("id", id) + } + if !validIdentifier(id, 1, 128) { + return errors.New("西部数码记录编号无效") + } + return p.call(ctx, action, v, nil) +} diff --git a/backend/internal/dnsprovider/zones.go b/backend/internal/dnsprovider/zones.go new file mode 100644 index 0000000..3a5cbc3 --- /dev/null +++ b/backend/internal/dnsprovider/zones.go @@ -0,0 +1,174 @@ +package dnsprovider + +import ( + "context" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +type Zone struct { + ID string `json:"id"` + Name string `json:"name"` +} + +func DiscoverZones(ctx context.Context, name string, c Credential, hint string) ([]Zone, error) { + if name == "cloudflare" && c.ZoneID == "" { + c.ZoneID = "discovery" + } + provider, err := New(name, hint, c) + if err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(ctx, 40*time.Second) + defer cancel() + all := []Zone{} + for page := 1; page <= 20; page++ { + total := 0 + switch p := provider.(type) { + case *cloudflare: + var out struct { + Success bool `json:"success"` + Result []struct { + ID string `json:"id"` + Name string `json:"name"` + } `json:"result"` + Info struct { + TotalCount int `json:"total_count"` + } `json:"result_info"` + } + req, e := http.NewRequestWithContext(ctx, "GET", "https://api.cloudflare.com/client/v4/zones?per_page=100&page="+strconv.Itoa(page), nil) + if e != nil { + return nil, e + } + req.Header.Set("Authorization", "Bearer "+c.APIToken) + if e = doJSON(p.client, req, &out); e != nil { + return nil, e + } + if !out.Success { + return nil, errors.New("Cloudflare 未授权读取 DNS 区域") + } + for _, z := range out.Result { + all = append(all, Zone{z.ID, z.Name}) + } + total = out.Info.TotalCount + case *aliyun: + var out struct { + Code string `json:"Code"` + TotalCount int `json:"TotalCount"` + Domains struct { + Domain []struct { + Name string `json:"DomainName"` + } `json:"Domain"` + } `json:"Domains"` + } + if e := p.call(ctx, "DescribeDomains", url.Values{"PageNumber": {strconv.Itoa(page)}, "PageSize": {"100"}}, &out); e != nil { + return nil, e + } + if out.Code != "" { + return nil, errors.New("阿里云未授权读取域名列表") + } + for _, z := range out.Domains.Domain { + all = append(all, Zone{z.Name, z.Name}) + } + total = out.TotalCount + case *tencent: + var out struct { + Response struct { + Error *providerError `json:"Error"` + Count int `json:"DomainCountInfoAll"` + DomainCount struct { + All int `json:"AllTotal"` + } `json:"DomainCountInfo"` + Domains []struct { + ID uint64 `json:"DomainId"` + Name string `json:"Name"` + } `json:"DomainList"` + } `json:"Response"` + } + if e := p.call(ctx, "DescribeDomainList", map[string]any{"Offset": (page - 1) * 100, "Limit": 100}, &out); e != nil { + return nil, e + } + if out.Response.Error != nil { + return nil, out.Response.Error + } + for _, z := range out.Response.Domains { + all = append(all, Zone{strconv.FormatUint(z.ID, 10), z.Name}) + } + total = out.Response.DomainCount.All + case *west: + if c.DomainKey != "" { + if hint == "" { + return nil, errors.New("单域名密钥请先填写指定域名") + } + if _, e := p.modernRecords(ctx, hint, "TXT"); e != nil { + return nil, e + } + return []Zone{{hint, hint}}, nil + } + var out struct { + Total int `json:"total"` + Items []struct { + Domain string `json:"domain"` + } `json:"items"` + } + if e := p.call(ctx, "getdomains", url.Values{"page": {strconv.Itoa(page)}, "limit": {"100"}}, &out); e != nil { + return nil, e + } + for _, z := range out.Items { + all = append(all, Zone{z.Domain, z.Domain}) + } + total = out.Total + case *dnsmgr: + var out struct { + Total *int `json:"total"` + Rows []struct { + ID jsonID `json:"id"` + Name string `json:"name"` + } `json:"rows"` + } + if e := p.call(ctx, "domain", url.Values{"offset": {strconv.Itoa((page - 1) * 100)}, "limit": {"100"}}, &out); e != nil { + return nil, e + } + if out.Total == nil { + return nil, errors.New("彩虹 DNS 未返回域名列表") + } + for _, z := range out.Rows { + all = append(all, Zone{string(z.ID), z.Name}) + } + total = *out.Total + default: + return nil, errors.New("服务商不支持读取区域列表") + } + if len(all) >= total { + return normalizeZones(all), nil + } + } + return nil, errors.New("域名数量超过 2000,请使用权限更小的 API 票据") +} + +type jsonID string + +func (v *jsonID) UnmarshalJSON(raw []byte) error { + id := rawID(raw) + if !positiveID(id) { + return errors.New("域名编号无效") + } + *v = jsonID(id) + return nil +} +func normalizeZones(items []Zone) []Zone { + out := []Zone{} + seen := map[string]bool{} + for _, z := range items { + z.Name = strings.ToLower(strings.TrimSuffix(z.Name, ".")) + if z.ID != "" && z.Name != "" && !seen[z.Name] { + out = append(out, z) + seen[z.Name] = true + } + } + return out +} diff --git a/backend/internal/executor/gateway.go b/backend/internal/executor/gateway.go new file mode 100644 index 0000000..50bf8b8 --- /dev/null +++ b/backend/internal/executor/gateway.go @@ -0,0 +1,182 @@ +// Package executor is the node-side execution surface. It intentionally has +// no import of store/service/httpapi and cannot schedule control-plane work. +package executor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "sea-vhost/internal/controlwire" + "sea-vhost/internal/nodefiles" + "sea-vhost/internal/panel" +) + +type Gateway struct { + NodeID uint64 + TenantRoot string + BrokerSocket string + AgentSocket string + InternalToken string + // Direct is reserved for in-process tests; deployment always uses the + // independent, unprivileged credential broker over a Unix socket. + Direct panel.Interface + mu sync.Mutex + fileGate sync.Mutex +} + +var nodeHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`) +var agentRoutes = map[string]bool{ + "/v1/database/phpmyadmin":true, + "/v1/scheduler/configure":true, + "/v1/schedule/execute":true, + "/v1/ftp/disconnect":true, + "/v1/site/startup": true, + "/v1/site/settings": true, "/v1/site/log": true, + "/v1/runtime/backups/prune": true, + "/v1/prepare": true, "/v1/quarantine": true, "/v1/web-protection/apply": true, "/v1/web-protection/remove": true, + "/v1/runtime/executable": true, "/v1/runtime/panel-state": true, "/v1/runtime/python/install": true, + "/v1/resources/runtime/terminate": true, "/v1/run-path/release": true, "/v1/trash/prepare": true, + "/v1/ftp/identity": true, "/v1/php/identity": true, "/v1/php/identity/start": true, "/v1/php/identity/stop": true, "/v1/php/identity/remove": true, + "/v1/resources/usage": true, "/v1/resources/processes/terminate": true, "/v1/project/freeze-writes": true, "/v1/ftp/tls": true, "/v1/nginx/network": true, + "/v1/lifecycle/backup": true, "/v1/lifecycle/backup/delete": true, "/v1/lifecycle/project/purge": true, "/v1/import/project": true, + "/v1/database/access": true, + "/v1/credentials/disconnect": true, + "/v1/resources/limits": true, + "/v1/lifecycle/backup/verify": true, + "/v1/runtime/probe": true, "/v1/runtime/php/maintenance": true, "/v1/runtime/python/dependencies": true, +} + +func (g *Gateway) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) { + controlwire.Encode(w, 200, map[string]any{"nodeId": g.NodeID, "protocol": controlwire.Version, "businessDatabase": false, "taskScheduler": false}) + }) + mux.HandleFunc("POST /v1/panel", g.panel) + mux.HandleFunc("POST /v1/files", g.files) + mux.HandleFunc("POST /v1/isolation/", g.isolation) + return controlwire.Authenticated(g.NodeID, mux) +} + +func (g *Gateway) files(w http.ResponseWriter, r *http.Request) { + if !g.fileGate.TryLock() { + http.Error(w, "node file transfer busy", 429) + return + } + defer g.fileGate.Unlock() + var q nodefiles.Request + r.Body = http.MaxBytesReader(w, r.Body, nodefiles.MaxMessageBytes) + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if decoder.Decode(&q) != nil || decoder.Decode(&struct{}{}) != io.EOF || !nodeHostPattern.MatchString(q.HostName) { + http.Error(w, "invalid host file request", 400) + return + } + controlwire.Encode(w, 200, nodefiles.Execute(filepath.Join(g.TenantRoot, q.HostName), q)) +} +func (g *Gateway) panel(w http.ResponseWriter, r *http.Request) { + var input panel.ScopedExecution + if controlwire.Decode(w, r, &input) != nil { + http.Error(w, "invalid scoped panel request", 400) + return + } + g.mu.Lock() + defer g.mu.Unlock() + if g.Direct != nil { + result, err := panel.ExecuteScoped(r.Context(), g.Direct, g.TenantRoot, input) + if err != nil { + http.Error(w, err.Error(), 422) + return + } + controlwire.Encode(w, 200, result) + return + } + body, err := json.Marshal(input) + if err != nil { + http.Error(w, "invalid request", 400) + return + } + g.forward(w, r, g.BrokerSocket, "/v1/scoped-operations", body) +} +func (g *Gateway) isolation(w http.ResponseWriter, r *http.Request) { + route := strings.TrimPrefix(r.URL.Path, "/v1/isolation") + if !agentRoutes[route] { + http.Error(w, "operation is not in the node allowlist", 403) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, controlwire.MaxEnvelopeBytes+1)) + if err != nil || len(body) > controlwire.MaxEnvelopeBytes { + http.Error(w, "invalid node payload", 413) + return + } + var value any + if json.Unmarshal(body, &value) != nil || !validHostIdentities(value) { + http.Error(w, "invalid node host scope", 400) + return + } + g.forward(w, r, g.AgentSocket, route, body) +} +func validHostIdentities(value any) bool { + switch v := value.(type) { + case map[string]any: + for key, item := range v { + if strings.EqualFold(key, "hostName") { + name, ok := item.(string) + if !ok || !nodeHostPattern.MatchString(name) { + return false + } + } + if !validHostIdentities(item) { + return false + } + } + case []any: + for _, item := range v { + if !validHostIdentities(item) { + return false + } + } + } + return true +} +func (g *Gateway) forward(w http.ResponseWriter, r *http.Request, socket, route string, body []byte) { + if socket == "" || g.InternalToken == "" { + http.Error(w, "node execution service is not configured", 503) + return + } + transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket) + }} + defer transport.CloseIdleConnections() + req, err := http.NewRequestWithContext(r.Context(), "POST", "http://unix"+route, bytes.NewReader(body)) + if err != nil { + http.Error(w, "invalid local operation", 400) + return + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+g.InternalToken) + response, err := (&http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect denied") }}).Do(req) + if err != nil { + http.Error(w, "node local execution service unavailable", 502) + return + } + defer response.Body.Close() + output, err := io.ReadAll(io.LimitReader(response.Body, controlwire.MaxEnvelopeBytes+1)) + if err != nil || len(output) > controlwire.MaxEnvelopeBytes { + http.Error(w, "node execution response exceeded limit", 502) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(response.StatusCode) + _, _ = w.Write(output) +} diff --git a/backend/internal/executor/gateway_test.go b/backend/internal/executor/gateway_test.go new file mode 100644 index 0000000..4450698 --- /dev/null +++ b/backend/internal/executor/gateway_test.go @@ -0,0 +1,178 @@ +package executor_test + +import ( + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sea-vhost/internal/controlwire" + "sea-vhost/internal/executor" + "sea-vhost/internal/nodefiles" + "sea-vhost/internal/panel" + "strings" + "testing" + "time" +) + +type testNode struct { + server *httptest.Server + client *http.Client + id uint64 + credentials controlwire.Credentials + sequence int +} + +func startNode(t *testing.T, id uint64, root string) *testNode { + t.Helper() + g := &executor.Gateway{NodeID: id, TenantRoot: root, Direct: panel.NewMock()} + s := httptest.NewUnstartedServer(g.Handler()) + s.Config.ErrorLog = log.New(io.Discard, "", 0) + credentials, identity, err := controlwire.Pair(id, "https://"+s.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + s.TLS, err = controlwire.ServerTLS(identity) + if err != nil { + t.Fatal(err) + } + s.StartTLS() + t.Cleanup(s.Close) + config, err := controlwire.ClientTLS(credentials) + if err != nil { + t.Fatal(err) + } + client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}, Timeout: 10 * time.Second} + t.Cleanup(client.CloseIdleConnections) + return &testNode{server: s, client: client, id: id, credentials: credentials} +} +func (n *testNode) request(t *testing.T, route string, body any) (int, []byte) { + t.Helper() + raw, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + n.sequence++ + r, err := controlwire.NewRequest("POST", n.server.URL, route, n.id, fmt.Sprintf("%032x", n.sequence), raw) + if err != nil { + t.Fatal(err) + } + response, err := n.client.Do(r) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + out, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + return response.StatusCode, out +} + +func TestTwoNodesArePairedAndStateless(t *testing.T) { + rootA := filepath.ToSlash(t.TempDir()) + rootB := filepath.ToSlash(t.TempDir()) + for _, root := range []string{rootA, rootB} { + if err := os.Mkdir(filepath.Join(root, "sv0123456789"), 0750); err != nil { + t.Fatal(err) + } + } + a := startNode(t, 2, rootA) + b := startNode(t, 3, rootB) + empty := json.RawMessage(`{"version":1,"sites":{},"ftp":{},"databases":{}}`) + create := func(n *testNode, root, domain string) panel.ScopedResult { + t.Helper() + request, _ := json.Marshal(map[string]any{"operation": "create_site", "site": panel.SiteSpec{Name: "sv0123456789", Domain: domain, Path: root + "/sv0123456789", RunPath: "/public", Runtime: "PHP", Version: "8.4", RunUser: "sv0123456789", Port: 20000, ProcessLimit: 10}}) + status, raw := n.request(t, "/v1/panel", panel.ScopedExecution{Request: request, Registry: empty}) + if status != 200 { + t.Fatalf("create: %d %s", status, raw) + } + var out panel.ScopedResult + if json.Unmarshal(raw, &out) != nil { + t.Fatal("invalid scoped result") + } + return out + } + first := create(a, rootA, "sv0123456789.a.example.com") + second := create(b, rootB, "sv0123456789.b.example.com") + if string(first.Response) != string(second.Response) { + t.Fatalf("expected colliding native IDs across nodes: %s %s", first.Response, second.Response) + } + req, _ := json.Marshal(map[string]any{"operation": "set_site_state", "id": 1001, "name": "sv0123456789.a.example.com", "enabled": false}) + status, _ := b.request(t, "/v1/panel", panel.ScopedExecution{Request: req, Registry: first.Registry}) + if status == 200 { + t.Fatal("node B accepted node A root snapshot") + } + status, _ = a.request(t, "/v1/panel", panel.ScopedExecution{Request: req, Registry: empty}) + if status == 200 { + t.Fatal("node persisted the previous request registry") + } + status, _ = a.request(t, "/v1/isolation/v1/shell", map[string]any{"command": "id"}) + if status != 403 { + t.Fatalf("shell route: %d", status) + } + status, _ = a.request(t, "/v1/isolation/v1/prepare", map[string]any{"hostName": "root"}) + if status != 400 { + t.Fatalf("root identity: %d", status) + } + r, _ := controlwire.NewRequest("GET", b.server.URL, "/v1/status", b.id, strings.Repeat("a", 32), nil) + if response, err := a.client.Do(r); err == nil { + response.Body.Close() + t.Fatal("node A credentials authenticated to node B") + } + r, _ = controlwire.NewRequest("GET", a.server.URL, "/v1/status", b.id, strings.Repeat("b", 32), nil) + response, err := a.client.Do(r) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != 403 { + t.Fatal("destination identity not checked") + } +} + +func TestFilesStayOnTargetNodeAndRejectReplay(t *testing.T) { + rootA := t.TempDir() + rootB := t.TempDir() + host := "sv0123456789" + for _, root := range []string{rootA, rootB} { + if err := os.Mkdir(filepath.Join(root, host), 0750); err != nil { + t.Fatal(err) + } + } + a := startNode(t, 2, rootA) + b := startNode(t, 3, rootB) + status, raw := a.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "write", Path: "marker.txt", Data: []byte("node-A-only")}) + if status != 200 { + t.Fatalf("write %d %s", status, raw) + } + status, raw = b.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "read", Path: "marker.txt"}) + if status != 200 || !strings.Contains(string(raw), "not_found") { + t.Fatalf("cross-node read: %d %s", status, raw) + } + for _, name := range []string{"../marker.txt", "/etc/passwd", "a/../../x", "x\\..\\y"} { + _, raw = a.request(t, "/v1/files", nodefiles.Request{HostName: host, Operation: "read", Path: name}) + if !strings.Contains(string(raw), "denied") { + t.Fatalf("unsafe path accepted %q: %s", name, raw) + } + } + body, _ := json.Marshal(nodefiles.Request{HostName: host, Operation: "stat", Path: "marker.txt"}) + r, _ := controlwire.NewRequest("POST", a.server.URL, "/v1/files", 2, strings.Repeat("e", 32), body) + response, err := a.client.Do(r) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + r, _ = controlwire.NewRequest("POST", a.server.URL, "/v1/files", 2, strings.Repeat("e", 32), body) + response, err = a.client.Do(r) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode != 409 { + t.Fatalf("replay accepted: %d", response.StatusCode) + } +} diff --git a/backend/internal/files/sandbox.go b/backend/internal/files/sandbox.go new file mode 100644 index 0000000..0f3a691 --- /dev/null +++ b/backend/internal/files/sandbox.go @@ -0,0 +1,151 @@ +package files + +import ( + "errors" + "os" + pathpkg "path" + "path/filepath" + "strings" +) + +var ErrOutsideRoot = errors.New("path escapes project root") +var ErrNotRegular = errors.New("path is not a regular file") + +func Resolve(root, requested string) (string, error) { + rootAbs, err := filepath.Abs(root) + if err != nil { + return "", err + } + if strings.ContainsRune(requested, '\x00') || strings.Contains(requested, "\\") || strings.HasPrefix(requested, "/") { + return "", ErrOutsideRoot + } + cleanRequested := pathpkg.Clean(requested) + if requested == "" { + cleanRequested = "." + } else if cleanRequested != requested { + return "", ErrOutsideRoot + } + for _, part := range strings.Split(cleanRequested, "/") { + if part == ".." { + return "", ErrOutsideRoot + } + } + candidate := filepath.Join(rootAbs, filepath.FromSlash(cleanRequested)) + candidateAbs, err := filepath.Abs(candidate) + if err != nil { + return "", err + } + relative, err := filepath.Rel(rootAbs, candidateAbs) + if err != nil { + return "", err + } + if relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) { + return "", ErrOutsideRoot + } + return candidateAbs, nil +} + +// RejectSymlinks prevents an existing path component from redirecting an operation outside the tenant root. +func RejectSymlinks(root, target string) error { + rootAbs, err := filepath.Abs(root) + if err != nil { + return err + } + targetAbs, err := filepath.Abs(target) + if err != nil { + return err + } + rel, err := filepath.Rel(rootAbs, targetAbs) + if err != nil { + return err + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return ErrOutsideRoot + } + current := rootAbs + for _, part := range strings.Split(rel, string(os.PathSeparator)) { + if part == "." || part == "" { + continue + } + current = filepath.Join(current, part) + info, statErr := os.Lstat(current) + if os.IsNotExist(statErr) { + return nil + } + if statErr != nil { + return statErr + } + if info.Mode()&os.ModeSymlink != 0 { + return ErrOutsideRoot + } + } + return nil +} + +// InspectRegular opens a file through os.Root after rejecting every symlink in +// its path. Deployment checks use this instead of os.Stat so an uploaded link +// can never redirect a privileged panel operation outside the virtual host. +func InspectRegular(root, requested string) (os.FileInfo, error) { + target, err := Resolve(root, requested) + if err != nil { + return nil, err + } + if err = RejectSymlinks(root, target); err != nil { + return nil, err + } + relative, err := filepath.Rel(root, target) + if err != nil { + return nil, err + } + projectRoot, err := os.OpenRoot(root) + if err != nil { + return nil, err + } + defer projectRoot.Close() + file, err := projectRoot.Open(relative) + if err != nil { + return nil, err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, ErrNotRegular + } + return info, nil +} + +// EnsureDirectory creates one final directory below an already prepared +// project path using os.Root. It is used for aaPanel compatibility shims, not +// arbitrary tenant path creation, and refuses links or non-directory targets. +func EnsureDirectory(root, requested string, mode os.FileMode) error { + target, err := Resolve(root, requested) + if err != nil { + return err + } + if err = RejectSymlinks(root, target); err != nil { + return err + } + relative, err := filepath.Rel(root, target) + if err != nil || relative == "." { + return ErrOutsideRoot + } + projectRoot, err := os.OpenRoot(root) + if err != nil { + return err + } + defer projectRoot.Close() + info, statErr := projectRoot.Lstat(relative) + if statErr == nil { + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("path is not a physical directory") + } + return nil + } + if !errors.Is(statErr, os.ErrNotExist) { + return statErr + } + return projectRoot.Mkdir(relative, mode) +} diff --git a/backend/internal/files/sandbox_test.go b/backend/internal/files/sandbox_test.go new file mode 100644 index 0000000..91285e6 --- /dev/null +++ b/backend/internal/files/sandbox_test.go @@ -0,0 +1,72 @@ +package files + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +func TestResolveBlocksTraversal(t *testing.T) { + root := filepath.Join(t.TempDir(), "project") + for _, requested := range []string{ + "../../etc/passwd", + `..\..\secret`, + "/../../outside", + "public/../secret", + "public//index.html", + "public/./index.html", + } { + if _, err := Resolve(root, requested); !errors.Is(err, ErrOutsideRoot) { + t.Errorf("Resolve(%q) error = %v, want ErrOutsideRoot", requested, err) + } + } +} + +func TestInspectRegularRejectsDirectoriesAndReadsFiles(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "app"), 0750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "app", "server.js"), []byte("ok"), 0640); err != nil { + t.Fatal(err) + } + info, err := InspectRegular(root, "app/server.js") + if err != nil || info.Size() != 2 { + t.Fatalf("InspectRegular(file) = %v, %v", info, err) + } + if _, err = InspectRegular(root, "app"); !errors.Is(err, ErrNotRegular) { + t.Fatalf("InspectRegular(directory) error = %v", err) + } +} + +func TestResolveNormalizesInsideRoot(t *testing.T) { + root := filepath.Join(t.TempDir(), "project") + got, err := Resolve(root, "public/assets/app.js") + if err != nil { + t.Fatal(err) + } + want := filepath.Join(root, "public", "assets", "app.js") + if got != want { + t.Fatalf("got %q want %q", got, want) + } +} + +func TestEnsureDirectoryStaysInsidePhysicalProjectPath(t *testing.T) { + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, "app"), 0750); err != nil { + t.Fatal(err) + } + if err := EnsureDirectory(root, "app/node_modules", 0770); err != nil { + t.Fatal(err) + } + if info, err := os.Lstat(filepath.Join(root, "app", "node_modules")); err != nil || !info.IsDir() { + t.Fatalf("compatibility directory was not created: info=%v err=%v", info, err) + } + outside := t.TempDir() + if err := os.Symlink(outside, filepath.Join(root, "linked")); err == nil { + if err = EnsureDirectory(root, "linked/node_modules", 0770); err == nil { + t.Fatal("EnsureDirectory followed a symlink outside the project root") + } + } +} diff --git a/backend/internal/hosting/cron.go b/backend/internal/hosting/cron.go new file mode 100644 index 0000000..f96df66 --- /dev/null +++ b/backend/internal/hosting/cron.go @@ -0,0 +1,95 @@ +package hosting + +import ( + "errors" + "strconv" + "strings" + "time" + _ "time/tzdata" +) + +type Cron struct { + fields [5]map[int]bool + any [5]bool + location *time.Location +} + +func ParseCron(expression, zone string) (Cron, error) { + var c Cron + loc, e := time.LoadLocation(zone) + if e != nil { + return c, errors.New("时区无效") + } + c.location = loc + parts := strings.Fields(expression) + if len(parts) != 5 { + return c, errors.New("计划时间需要五段:分钟 小时 日期 月份 星期") + } + mins := []int{0, 0, 1, 1, 0} + maxs := []int{59, 23, 31, 12, 7} + for i, part := range parts { + c.fields[i] = map[int]bool{} + c.any[i] = strings.HasPrefix(part, "*") + for _, piece := range strings.Split(part, ",") { + step := 1 + rangePart := piece + if strings.Contains(piece, "/") { + items := strings.Split(piece, "/") + if len(items) != 2 { + return c, errors.New("计划时间格式无效") + } + rangePart = items[0] + step, e = strconv.Atoi(items[1]) + if e != nil || step < 1 || step > 60 { + return c, errors.New("计划间隔无效") + } + } + start, end := mins[i], maxs[i] + if rangePart != "*" { + items := strings.Split(rangePart, "-") + if len(items) > 2 { + return c, errors.New("计划范围无效") + } + start, e = strconv.Atoi(items[0]) + if e != nil { + return c, errors.New("计划时间只支持数字、星号、范围和步长") + } + end = start + if len(items) == 2 { + end, e = strconv.Atoi(items[1]) + if e != nil { + return c, errors.New("计划范围无效") + } + } + } + if start < mins[i] || end > maxs[i] || start > end { + return c, errors.New("计划时间超出范围") + } + for n := start; n <= end; n += step { + value := n + if i == 4 && n == 7 { + value = 0 + } + c.fields[i][value] = true + } + } + } + return c, nil +} +func (c Cron) Next(after time.Time) (time.Time, error) { + t := after.UTC().Truncate(time.Minute).Add(time.Minute) + for i := 0; i < 366*24*60; i++ { + local := t.In(c.location) + day := c.fields[2][local.Day()] + week := c.fields[4][int(local.Weekday())] + matchDay := day && week + if !c.any[2] && !c.any[4] { + matchDay = day || week + } + if c.fields[0][local.Minute()] && c.fields[1][local.Hour()] && c.fields[3][int(local.Month())] && matchDay { + return t, nil + } + t = t.Add(time.Minute) + } + return time.Time{}, errors.New("未来一年没有可执行时间") +} diff --git a/backend/internal/hosting/runner.go b/backend/internal/hosting/runner.go new file mode 100644 index 0000000..12870b5 --- /dev/null +++ b/backend/internal/hosting/runner.go @@ -0,0 +1,12 @@ +package hosting + +type RunnerConfig struct { + UID uint32 `json:"uid"` + HostName string `json:"hostName"` + Binary string `json:"binary"` + Arguments []string `json:"arguments"` + Environment map[string]string `json:"environment"` + WorkDir string `json:"workDir"` + LogDir string `json:"logDir"` + SiteName string `json:"siteName"` +} diff --git a/backend/internal/hosting/settings.go b/backend/internal/hosting/settings.go new file mode 100644 index 0000000..230e34e --- /dev/null +++ b/backend/internal/hosting/settings.go @@ -0,0 +1,94 @@ +package hosting + +import ( + "encoding/json" + "errors" + "net/url" + "path" + "regexp" + "strings" +) + +type WebsiteSettings struct { + Rewrite string `json:"rewrite"` + RedirectURL string `json:"redirectURL"` + RedirectCode int `json:"redirectCode"` + ForceHTTPS bool `json:"forceHTTPS"` + Index []string `json:"index"` + Error404 string `json:"error404"` + Error503 string `json:"error503"` + Maintenance bool `json:"maintenance"` +} +type Startup struct { + EntryFile string `json:"entryFile"` + WorkDir string `json:"workDir"` + Arguments []string `json:"arguments"` + Environment map[string]string `json:"environment"` +} + +var simpleFile = regexp.MustCompile(`^[A-Za-z0-9_./-]+$`) +var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,63}$`) + +func DefaultWebsite() WebsiteSettings { + return WebsiteSettings{Rewrite: "none", RedirectCode: 301, Index: []string{"index.php", "index.html", "index.htm"}} +} +func ValidRelative(v string) bool { + return v != "" && v != "." && len(v) <= 255 && simpleFile.MatchString(v) && !strings.HasPrefix(v, "/") && path.Clean(v) == v && !strings.HasPrefix(v, "../") && !strings.Contains(v, "/.sea-") && !strings.HasPrefix(v, ".sea-") && path.Base(v) != ".user.ini" +} +func (v *WebsiteSettings) Validate() error { + if !map[string]bool{"none": true, "wordpress": true, "laravel": true, "thinkphp": true, "spa": true}[v.Rewrite] { + return errors.New("伪静态模板无效") + } + if len(v.Index) < 1 || len(v.Index) > 10 { + return errors.New("请设置 1–10 个默认首页") + } + for _, name := range v.Index { + if !ValidRelative(name) || strings.Contains(name, "/") { + return errors.New("默认首页只能填写文件名") + } + } + for _, name := range []string{v.Error404, v.Error503} { + if name != "" && (!ValidRelative(name) || (!strings.HasSuffix(name, ".html") && !strings.HasSuffix(name, ".htm"))) { + return errors.New("错误页应为网站目录内的 HTML 文件") + } + } + if v.RedirectCode != 301 && v.RedirectCode != 302 { + return errors.New("跳转状态码应为 301 或 302") + } + if v.RedirectURL != "" { + u, e := url.Parse(v.RedirectURL) + if e != nil || u.Hostname() == "" || u.User != nil || (u.Scheme != "http" && u.Scheme != "https") || len(v.RedirectURL) > 2048 || strings.ContainsAny(v.RedirectURL, "\x00\r\n\t \"'{};$\\") { + return errors.New("跳转地址无效") + } + } + return nil +} +func (v *Startup) Validate() error { + if raw, e := json.Marshal(v); e != nil || len(raw) > 24<<10 { + return errors.New("启动配置不能超过 24 KiB") + } + if v.EntryFile != "" && !ValidRelative(v.EntryFile) { + return errors.New("启动入口必须位于网站目录内") + } + if v.WorkDir == "" { + v.WorkDir = "." + } + if v.WorkDir != "." && !ValidRelative(v.WorkDir) { + return errors.New("工作目录必须位于网站目录内") + } + if len(v.Arguments) > 64 || len(v.Environment) > 64 { + return errors.New("启动参数或环境变量过多") + } + for _, arg := range v.Arguments { + if len(arg) > 2048 || strings.ContainsAny(arg, "\x00\r\n") { + return errors.New("启动参数无效") + } + } + for k, value := range v.Environment { + upper := strings.ToUpper(k) + if !envName.MatchString(k) || strings.HasPrefix(upper, "LD_") || strings.HasPrefix(upper, "DYLD_") || map[string]bool{"PORT": true, "PATH": true, "HOME": true, "USER": true, "LOGNAME": true, "SHELL": true, "BASH_ENV": true, "ENV": true}[upper] || len(value) > 4096 || strings.ContainsAny(value, "\x00\r\n") { + return errors.New("环境变量名称被保留,或值包含换行/超过限制") + } + } + return nil +} diff --git a/backend/internal/hosting/settings_test.go b/backend/internal/hosting/settings_test.go new file mode 100644 index 0000000..8ae04b9 --- /dev/null +++ b/backend/internal/hosting/settings_test.go @@ -0,0 +1,60 @@ +package hosting + +import ( + "testing" + "time" +) + +func TestCronTimeZonesAndCalendar(t *testing.T) { + for _, v := range []struct{ expression, zone, after, want string }{{"*/5 * * * *", "Asia/Shanghai", "2026-10-28T00:01:17Z", "2026-10-28T00:05:00Z"}, {"0 8 * * *", "Asia/Shanghai", "2026-10-28T00:00:00Z", "2026-10-29T00:00:00Z"}, {"0 0 * * 7", "UTC", "2026-10-28T00:00:00Z", "2026-11-01T00:00:00Z"}, {"0 0 1 * 1", "UTC", "2026-10-28T00:00:00Z", "2026-11-01T00:00:00Z"}, {"0 0 */2 * 1", "UTC", "2026-10-28T00:00:00Z", "2026-11-09T00:00:00Z"}} { + c, e := ParseCron(v.expression, v.zone) + if e != nil { + t.Fatal(e) + } + after, _ := time.Parse(time.RFC3339, v.after) + got, e := c.Next(after) + if e != nil || got.Format(time.RFC3339) != v.want { + t.Fatalf("%s: %s %v", v.expression, got, e) + } + } + for _, expression := range []string{"@hourly", "60 * * * *", "*/0 * * * *", "* * * * 8", "* * 0 * *", "* * * * */-1", "1-2-3 * * * *", "* * * * ;id"} { + if _, e := ParseCron(expression, "UTC"); e == nil { + t.Fatalf("accepted %q", expression) + } + } + if _, e := ParseCron("* * * * *", "Missing/Zone"); e == nil { + t.Fatal("invalid timezone accepted") + } +} +func TestStartupRejectsControlEnvironmentAndPaths(t *testing.T) { + for _, key := range []string{"LD_PRELOAD", "ld_library_path", "DYLD_INSERT_LIBRARIES", "PATH", "BASH_ENV", "PORT", "A=B"} { + v := Startup{Environment: map[string]string{key: "x"}} + if v.Validate() == nil { + t.Fatalf("accepted %s", key) + } + } + for _, entry := range []string{"../other/app.py", "/etc/passwd", ".sea-runtime/config", "app;id", "a/../../secret"} { + v := Startup{EntryFile: entry} + if v.Validate() == nil { + t.Fatalf("accepted %s", entry) + } + } + v := Startup{Environment: map[string]string{"APP_KEY": "a'$(id)`x`"}, Arguments: []string{"a b", "$(id)"}} + if e := v.Validate(); e != nil { + t.Fatal("literal values should not be shell parsed", e) + } +} +func TestWebsiteRejectsNginxInjection(t *testing.T) { + for _, value := range []string{"https://example.com/;root /etc;", "https://user:pass@example.com/", "https://example.com/$request_uri", "https://example.com/\nreturn 200"} { + v := DefaultWebsite() + v.RedirectURL = value + if v.Validate() == nil { + t.Fatalf("accepted %s", value) + } + } + v := DefaultWebsite() + v.Error503 = "../other/secret.html" + if v.Validate() == nil { + t.Fatal("traversing error page accepted") + } +} diff --git a/backend/internal/httpapi/account.go b/backend/internal/httpapi/account.go new file mode 100644 index 0000000..67ccff5 --- /dev/null +++ b/backend/internal/httpapi/account.go @@ -0,0 +1,164 @@ +package httpapi + +import ( + "fmt" + "net/http" + "strings" + "time" + + "sea-vhost/internal/auth" +) + +func mfaSecretLabel(userID uint64) string { + return fmt.Sprintf("mfa-user:%d", userID) +} + +func (s *Server) accountSecurity(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + security, err := s.store.UserSecurity(r.Context(), user.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取账号安全设置") + return + } + writeJSON(w, http.StatusOK, map[string]any{"mfaEnabled": security.TOTPEnabled}) +} + +func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) { + var input struct { + CurrentPassword string `json:"currentPassword"` + NewPassword string `json:"newPassword"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + if len(input.NewPassword) < 12 || len(input.NewPassword) > 128 || input.NewPassword == input.CurrentPassword { + writeError(w, http.StatusUnprocessableEntity, "新密码应为 12–128 个字符且不能与原密码相同") + return + } + user := currentUser(r) + security, err := s.store.UserSecurity(r.Context(), user.ID) + if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) { + writeError(w, http.StatusUnauthorized, "当前密码不正确") + return + } + hash, err := auth.HashPassword(input.NewPassword) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法更新密码") + return + } + cookie, _ := r.Cookie("sea_session") + if cookie == nil || s.store.ChangePassword(r.Context(), user.ID, hash, cookie.Value) != nil { + writeError(w, http.StatusInternalServerError, "无法更新密码") + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "update", "account_password", "", requestClientIP(r), true, "修改账号密码并注销其他会话") + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) setupMFA(w http.ResponseWriter, r *http.Request) { + var input struct { + CurrentPassword string `json:"currentPassword"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + security, err := s.store.UserSecurity(r.Context(), user.ID) + if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) { + writeError(w, http.StatusUnauthorized, "当前密码不正确") + return + } + if security.TOTPEnabled { + writeError(w, http.StatusConflict, "双重认证已经启用") + return + } + secret, err := auth.NewTOTPSecret() + if err != nil { + writeError(w, http.StatusInternalServerError, "无法生成双重认证密钥") + return + } + ciphertext, err := s.secretBox.Seal(mfaSecretLabel(user.ID), secret) + if err != nil || s.store.SetPendingTOTP(r.Context(), user.ID, ciphertext) != nil { + writeError(w, http.StatusInternalServerError, "无法保存双重认证设置") + return + } + writeJSON(w, http.StatusOK, map[string]any{"secret": secret, "otpauthURI": auth.TOTPURI(secret, user.LoginName)}) +} + +func (s *Server) enableMFA(w http.ResponseWriter, r *http.Request) { + var input struct { + Code string `json:"code"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + security, err := s.store.UserSecurity(r.Context(), user.ID) + secret := "" + if err == nil && len(security.TOTPSecretCiphertext) > 0 { + secret, err = s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext) + } + if err != nil || secret == "" { + writeError(w, http.StatusConflict, "请先生成双重认证密钥") + return + } + if !auth.VerifyTOTP(secret, input.Code, time.Now()) { + writeError(w, http.StatusUnprocessableEntity, "动态验证码无效") + return + } + codes, err := auth.NewRecoveryCodes(10) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法生成恢复码") + return + } + hashes := make([][]byte, 0, len(codes)) + for _, code := range codes { + hashes = append(hashes, auth.RecoveryCodeHash(code)) + } + if err = s.store.EnableTOTP(r.Context(), user.ID, hashes); err != nil { + writeError(w, http.StatusInternalServerError, "无法启用双重认证") + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "enable", "account_mfa", "", requestClientIP(r), true, "启用 TOTP 双重认证") + writeJSON(w, http.StatusOK, map[string]any{"recoveryCodes": codes}) +} + +func (s *Server) disableMFA(w http.ResponseWriter, r *http.Request) { + var input struct { + CurrentPassword string `json:"currentPassword"` + Code string `json:"code"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + security, err := s.store.UserSecurity(r.Context(), user.ID) + if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) { + writeError(w, http.StatusUnauthorized, "当前密码不正确") + return + } + if !security.TOTPEnabled { + writeError(w, http.StatusConflict, "双重认证尚未启用") + return + } + secret, err := s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext) + validCode := err == nil && auth.VerifyTOTP(secret, input.Code, time.Now()) + if !validCode && strings.TrimSpace(input.Code) != "" { + validCode, err = s.store.ConsumeRecoveryCode(r.Context(), user.ID, auth.RecoveryCodeHash(input.Code)) + } + if err != nil || !validCode { + writeError(w, http.StatusUnprocessableEntity, "动态验证码或恢复码无效") + return + } + if err = s.store.DisableTOTP(r.Context(), user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "无法关闭双重认证") + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "disable", "account_mfa", "", requestClientIP(r), true, "关闭 TOTP 双重认证并注销全部会话") + http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1}) + w.WriteHeader(http.StatusNoContent) +} diff --git a/backend/internal/httpapi/admin.go b/backend/internal/httpapi/admin.go new file mode 100644 index 0000000..e2d70ce --- /dev/null +++ b/backend/internal/httpapi/admin.go @@ -0,0 +1,186 @@ +package httpapi + +import ( + "errors" + "net/http" + "net/mail" + "regexp" + "strconv" + "strings" + "time" + + "sea-vhost/internal/store" +) + +var tenantSlugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,46}[a-z0-9]$`) + +type adminPlanInput struct { + Name string `json:"name"` + StorageBytes uint64 `json:"storageBytes"` + DatabaseBytes uint64 `json:"databaseBytes"` + BandwidthBytes uint64 `json:"bandwidthBytes"` + BandwidthMbps uint32 `json:"bandwidthMbps"` + ProcessLimit uint32 `json:"processLimit"` + FTPLimit uint32 `json:"ftpLimit"` + DatabaseLimit uint32 `json:"databaseLimit"` + ProjectLimit uint32 `json:"projectLimit"` +} + +func (s *Server) adminPlans(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + plans, err := s.store.ListPlans(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取套餐") + return + } + writeJSON(w, http.StatusOK, map[string]any{"plans": plans}) + return + } + var input adminPlanInput + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + input.Name = strings.TrimSpace(input.Name) + if err := validatePlan(input); err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + id, err := s.store.CreatePlan(r.Context(), store.NewPlan{Name: input.Name, StorageBytes: input.StorageBytes, DatabaseBytes: input.DatabaseBytes, BandwidthBytes: input.BandwidthBytes, BandwidthMbps: input.BandwidthMbps, ProcessLimit: input.ProcessLimit, FTPLimit: input.FTPLimit, DatabaseLimit: input.DatabaseLimit, ProjectLimit: input.ProjectLimit}) + if err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法创建套餐,请检查名称是否重复") + return + } + user := currentUser(r) + s.store.Log(r.Context(), nil, user.ID, "create", "plan", input.Name, requestClientIP(r), true, "创建套餐 "+input.Name) + writeJSON(w, http.StatusCreated, map[string]any{"id": id}) +} + +func validatePlan(input adminPlanInput) error { + if input.BandwidthMbps > 10000 { + return errors.New("限速应在 0–10000 Mbps 之间,0 为不限速") + } + const maxBytes = uint64(1 << 50) + if len([]rune(input.Name)) < 1 || len([]rune(input.Name)) > 80 { + return errors.New("套餐名称应为 1–80 个字符") + } + if input.StorageBytes < 1<<20 || input.StorageBytes > maxBytes || input.DatabaseBytes < 1<<20 || input.DatabaseBytes > maxBytes || input.BandwidthBytes < 1<<20 || input.BandwidthBytes > maxBytes { + return errors.New("资源容量必须在 1 MB 至 1 PB 之间") + } + if input.ProcessLimit < 1 || input.ProcessLimit > 100000 || input.FTPLimit < 1 || input.FTPLimit > 10000 || input.DatabaseLimit < 1 || input.DatabaseLimit > 10000 || input.ProjectLimit < 1 || input.ProjectLimit > 10000 { + return errors.New("资源数量限制超出允许范围") + } + return nil +} + +func (s *Server) adminTenants(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + items, err := s.store.ListTenants(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取用户") + return + } + writeJSON(w, http.StatusOK, map[string]any{"tenants": items}) + return + } + var input struct { + Slug string `json:"slug"` + Name string `json:"name"` + Email string `json:"email"` + DisplayName string `json:"displayName"` + Password string `json:"password"` + PlanID uint64 `json:"planId"` + ExpiresAt *time.Time `json:"expiresAt"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + 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, "用户标识、名称或密码不符合要求") + return + } + address, err := mail.ParseAddress(strings.TrimSpace(input.Email)) + if err != nil || !strings.EqualFold(address.Address, strings.TrimSpace(input.Email)) { + writeError(w, http.StatusUnprocessableEntity, "邮箱格式不正确") + return + } + 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, "用户名称、管理员名称或套餐无效") + 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}) + if err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法创建用户,请检查标识或邮箱是否重复") + return + } + user := currentUser(r) + s.store.Log(r.Context(), nil, user.ID, "create", "tenant", input.Slug, requestClientIP(r), true, "创建用户 "+input.Name) + writeJSON(w, http.StatusCreated, map[string]any{"id": id}) +} + +func (s *Server) domainApprovalSetting(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + writeJSON(w, http.StatusOK, map[string]any{"enabled": s.store.DomainApproval(r.Context(), s.cfg.DomainApproval)}) + return + } + var input struct { + Enabled bool `json:"enabled"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.store.SetDomainApproval(r.Context(), input.Enabled); err != nil { + writeError(w, http.StatusInternalServerError, "无法保存设置") + return + } + user := currentUser(r) + s.store.Log(r.Context(), nil, user.ID, "update", "domain_approval", "", requestClientIP(r), true, map[bool]string{true: "开启域名审核", false: "关闭域名审核"}[input.Enabled]) + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) adminPendingDomains(w http.ResponseWriter, r *http.Request) { + items, err := s.store.PendingDomains(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取待审核域名") + return + } + writeJSON(w, http.StatusOK, map[string]any{"domains": items}) +} + +func (s *Server) adminReviewDomain(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "域名编号无效") + return + } + var input struct { + Approved bool `json:"approved"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + item, err := s.projects.ReviewDomain(r.Context(), id, input.Approved) + if err != nil { + s.store.Log(r.Context(), nil, user.ID, "review", "domain", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + tenantID := item.TenantID + detail := "拒绝域名 " + item.Domain + if input.Approved { + detail = "批准域名 " + item.Domain + } + s.store.Log(r.Context(), &tenantID, user.ID, "review", "domain", strconv.FormatUint(id, 10), requestClientIP(r), true, detail) + writeJSON(w, http.StatusOK, map[string]any{"domain": item}) +} diff --git a/backend/internal/httpapi/admin_batches.go b/backend/internal/httpapi/admin_batches.go new file mode 100644 index 0000000..d2eaa18 --- /dev/null +++ b/backend/internal/httpapi/admin_batches.go @@ -0,0 +1,708 @@ +package httpapi + +import ( + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/mail" + "regexp" + "strconv" + "strings" + "time" + + "sea-vhost/internal/scope" + "sea-vhost/internal/service" + "sea-vhost/internal/store" +) + +type batchRow struct { + Name string `json:"name,omitempty"` + Slug string `json:"slug,omitempty"` + Email string `json:"email,omitempty"` + DisplayName string `json:"displayName,omitempty"` + Password string `json:"password,omitempty"` + AccountID uint64 `json:"accountId,omitempty"` + Account string `json:"account,omitempty"` + Owner string `json:"owner,omitempty"` + TenantID uint64 `json:"tenantId,omitempty"` + HostID uint64 `json:"hostId,omitempty"` + Host string `json:"host,omitempty"` + OwnershipVersion uint64 `json:"ownershipVersion,omitempty"` + CredentialMode string `json:"credentialMode,omitempty"` + StopServices *bool `json:"stopServices,omitempty"` + ResumeOwnership bool `json:"resumeOwnership,omitempty"` + NodeID uint64 `json:"nodeId,omitempty"` + PlanID uint64 `json:"planId,omitempty"` + Runtime string `json:"runtime,omitempty"` + Version string `json:"version,omitempty"` + RunPath string `json:"runPath,omitempty"` + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + SetExpiry bool `json:"setExpiry,omitempty"` + AutoSSL bool `json:"autoSSL,omitempty"` +} +type batchRequest struct { + RequestKey string `json:"requestKey"` + Operation string `json:"operation"` + Rows []batchRow `json:"rows"` +} +type batchPreviewRow struct { + Row int `json:"row"` + Label string `json:"label"` + Valid bool `json:"valid"` + Detail string `json:"detail"` +} +type batchResult struct { + ResourceID uint64 `json:"resourceId"` + Login string `json:"login,omitempty"` + Password string `json:"password,omitempty"` + HostLogin string `json:"hostLogin,omitempty"` + FTPHost string `json:"ftpHost,omitempty"` + FTPUsername string `json:"ftpUsername,omitempty"` + FTPPassword string `json:"ftpPassword,omitempty"` + DatabaseName string `json:"databaseName,omitempty"` + DatabaseUsername string `json:"databaseUsername,omitempty"` + DatabasePassword string `json:"databasePassword,omitempty"` +} + +var batchKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) +var batchHostNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`) +var batchOperations = map[string]bool{"create_users": true, "create_hosts": true, "assign_hosts": true, "host_subscription": true, "host_start": true, "host_stop": true, "host_password_reset": true, "user_enable": true, "user_disable": true} + +func randomBatchKey() (string, error) { + var raw [16]byte + _, err := rand.Read(raw[:]) + return hex.EncodeToString(raw[:]), err +} +func randomBatchPassword() (string, error) { + var raw [24]byte + _, err := rand.Read(raw[:]) + return "Sv-" + base64.RawURLEncoding.EncodeToString(raw[:]) + "9a", err +} +func batchCipherLabel(ref, kind string, row int) string { + return fmt.Sprintf("admin-batch:%s:%s:%d", ref, kind, row) +} + +func (s *Server) normalizeBatch(ctx context.Context, input *batchRequest) ([]batchPreviewRow, error) { + if !batchOperations[input.Operation] { + return nil, errors.New("不支持此批量操作") + } + limit := 200 + if input.Operation == "create_users" { + limit = 100 + } + if input.Operation == "create_hosts" { + limit = 50 + } + if len(input.Rows) == 0 || len(input.Rows) > limit { + return nil, fmt.Errorf("该操作每批需要 1–%d 条数据", limit) + } + plans, err := s.store.ListPlans(ctx) + if err != nil { + return nil, err + } + if len(plans) == 0 { + return nil, errors.New("请先创建套餐") + } + hosts, err := s.store.ListAdminProjects(ctx) + if err != nil { + return nil, err + } + accounts, err := s.store.ListTenants(ctx) + if err != nil { + return nil, err + } + result := make([]batchPreviewRow, len(input.Rows)) + seen := map[string]bool{} + for index := range input.Rows { + row := &input.Rows[index] + preview := batchPreviewRow{Row: index + 1, Valid: true} + var validation error + switch input.Operation { + case "create_users": + row.Slug = strings.ToLower(strings.TrimSpace(row.Slug)) + row.Email = strings.ToLower(strings.TrimSpace(row.Email)) + row.Name = strings.TrimSpace(row.Name) + row.DisplayName = strings.TrimSpace(row.DisplayName) + if row.PlanID == 0 { + row.PlanID = plans[0].ID + } + if row.DisplayName == "" { + row.DisplayName = row.Name + } + address, e := mail.ParseAddress(row.Email) + if !tenantSlugPattern.MatchString(row.Slug) || len([]rune(row.Name)) < 2 || len([]rune(row.Name)) > 120 || len([]rune(row.DisplayName)) < 2 || len([]rune(row.DisplayName)) > 80 { + validation = errors.New("用户标识、名称或显示名称格式无效") + } else if e != nil || address.Address != row.Email { + validation = errors.New("登录邮箱格式无效") + } else if row.Password != "" && (len(row.Password) < 12 || len(row.Password) > 72) { + validation = errors.New("密码应为 12–72 字节,留空将独立随机生成") + } else if _, e = s.store.Plan(ctx, row.PlanID); e != nil { + validation = errors.New("套餐不存在") + } + key := "user:" + row.Email + slugKey := "slug:" + row.Slug + if validation == nil && (seen[key] || seen[slugKey]) { + validation = errors.New("同批邮箱或用户标识重复") + } + seen[key] = true + seen[slugKey] = 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("邮箱或用户标识已存在") + } + } + preview.Label = row.Email + case "create_hosts": + row.Name = strings.ToLower(strings.TrimSpace(row.Name)) + row.Runtime = strings.TrimSpace(row.Runtime) + row.Version = strings.TrimSpace(row.Version) + if row.RunPath == "" { + row.RunPath = "/public" + } + if row.Owner != "" { + row.TenantID, validation = s.store.ResolveAccount(ctx, row.Owner) + } + if validation == nil && row.TenantID > 0 { + _, validation = s.store.TenantOwner(ctx, row.TenantID) + } + if validation == nil && !batchHostNamePattern.MatchString(row.Name) { + validation = errors.New("主机名称应为 3–50 位小写字母、数字或连字符") + } + if validation == nil { + node, e := s.store.Node(ctx, row.NodeID) + if e != nil || !node.Enabled { + validation = errors.New("节点不存在或未启用") + } + } + if validation == nil { + if _, e := s.store.Plan(ctx, row.PlanID); e != nil { + validation = errors.New("套餐不存在") + } + } + if validation == nil && !map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true}[row.Runtime] { + validation = errors.New("运行环境无效") + } + if validation == nil && (row.Version == "" || len(row.Version) > 80) { + validation = errors.New("请选择已安装版本") + } + if validation == nil && (strings.Contains(row.RunPath, "..") || strings.ContainsAny(row.RunPath, "\\\x00") || len(row.RunPath) > 255) { + validation = errors.New("运行目录无效") + } + preview.Label = row.Name + case "user_enable", "user_disable": + if row.Account != "" { + row.AccountID, validation = s.store.ResolveAnyAccount(ctx, row.Account) + } + found := false + for _, account := range accounts { + if account.ID == row.AccountID { + preview.Label = account.Name + found = true + } + } + if !found { + validation = errors.New("用户账号不存在") + } + key := "account:" + strconv.FormatUint(row.AccountID, 10) + if seen[key] { + validation = errors.New("同批账号重复") + } + seen[key] = true + default: + var host *store.AdminProject + for i := range hosts { + if (row.HostID > 0 && hosts[i].ID == row.HostID) || (row.Host != "" && (hosts[i].HostName == row.Host || strconv.FormatUint(hosts[i].ID, 10) == row.Host)) { + host = &hosts[i] + break + } + } + if host == nil { + validation = errors.New("主机不存在,请使用主机 ID 或随机主机名") + break + } + row.HostID = host.ID + preview.Label = host.HostName + if row.OwnershipVersion != 0 && row.OwnershipVersion != host.OwnershipVersion { + validation = errors.New("主机归属已变化,请刷新后重新预览") + } + row.OwnershipVersion = host.OwnershipVersion + if host.ManagementLocked && !(input.Operation == "assign_hosts" && row.ResumeOwnership) { + validation = store.ErrManagementLocked + } + if host.Status == "failed" || host.Status == "provisioning" { + validation = errors.New("主机尚未完成开通,不能批量管理") + } + key := "host:" + strconv.FormatUint(row.HostID, 10) + if seen[key] { + validation = errors.New("同批主机重复") + } + seen[key] = true + if input.Operation == "assign_hosts" { + if row.CredentialMode == "" { + row.CredentialMode = "preserve" + } + if row.StopServices == nil { + value := true + row.StopServices = &value + } + if row.CredentialMode != "preserve" && row.CredentialMode != "reset" { + validation = errors.New("凭据策略必须为 preserve 或 reset") + } + if row.Owner != "" { + row.TenantID, err = s.store.ResolveAccount(ctx, row.Owner) + if err != nil { + validation = err + } + } + if row.TenantID > 0 { + if _, e := s.store.TenantOwner(ctx, row.TenantID); e != nil { + validation = errors.New("目标用户不存在或已停用") + } + } + if host.ManagementLocked && row.ResumeOwnership { + pending, e := s.store.OwnershipChange(ctx, host.ID) + matches := pending.TargetOwnerID == nil && row.TenantID == 0 || pending.TargetOwnerID != nil && *pending.TargetOwnerID == row.TenantID + if e != nil || pending.State != "pending" || !matches || pending.ExpectedVersion != row.OwnershipVersion || pending.CredentialMode != row.CredentialMode || pending.StopServices != *row.StopServices { + validation = errors.New("恢复操作必须使用未完成任务原有的目标用户、凭据和停站策略") + } + } + } + if input.Operation == "host_subscription" { + if row.PlanID == 0 { + row.PlanID = host.PlanID + } + if _, e := s.store.Plan(ctx, row.PlanID); e != nil { + validation = errors.New("套餐不存在") + } + if !row.SetExpiry { + row.ExpiresAt = host.ExpiresAt + } + } + } + if row.ExpiresAt != nil && (row.ExpiresAt.Year() < 2000 || row.ExpiresAt.Year() > 9999) { + validation = errors.New("到期时间超出允许范围") + } + if preview.Label == "" { + preview.Label = fmt.Sprintf("第 %d 条", index+1) + } + if validation != nil { + preview.Valid = false + preview.Detail = validation.Error() + } else { + preview.Detail = "可以执行" + if input.Operation == "assign_hosts" { + credential := "保留三类密码(旧持有者仍可登录主机、FTP 和数据库)" + if row.CredentialMode == "reset" { + credential = "随机重置主机、FTP、数据库密码并断开旧连接" + } + state := "先停止全部网站" + if row.StopServices != nil && !*row.StopServices { + state = "保持网站当前运行状态" + } + preview.Detail = state + ";" + credential + ";注销旧主机管理会话" + for _, host := range hosts { + if host.ID == row.HostID && !host.ManagementLocked && ((host.OwnerTenantID == nil && row.TenantID == 0) || (host.OwnerTenantID != nil && *host.OwnerTenantID == row.TenantID)) { + preview.Detail = "归属相同,将跳过,不停站也不重置密码" + break + } + } + } + } + result[index] = preview + } + return result, nil +} + +func (s *Server) adminBatchPreview(w http.ResponseWriter, r *http.Request) { + var input batchRequest + if decodeJSON(r, &input) != nil { + writeError(w, 400, "批量数据格式无效") + return + } + rows, err := s.normalizeBatch(r.Context(), &input) + if err != nil { + writeError(w, 422, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"rows": rows}) +} +func (s *Server) adminBatches(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + jobs, err := s.store.AdminBatches(r.Context()) + if err != nil { + writeError(w, 500, "无法读取批量任务") + return + } + writeJSON(w, 200, map[string]any{"batches": jobs}) + return + } + var input batchRequest + if decodeJSON(r, &input) != nil || !batchKeyPattern.MatchString(input.RequestKey) { + writeError(w, 400, "批量数据或请求标识无效") + return + } + original, _ := json.Marshal(input) + mac := hmac.New(sha256.New, []byte(s.cfg.SessionSecret)) + _, _ = mac.Write([]byte("admin-batch-request\x00")) + _, _ = mac.Write(original) + digest := hex.EncodeToString(mac.Sum(nil)) + existing, e := s.store.ExistingAdminBatch(r.Context(), input.RequestKey, digest) + if e != nil { + writeError(w, 409, e.Error()) + return + } + if existing > 0 { + job, e := s.store.AdminBatch(r.Context(), existing, false) + if e != nil { + writeError(w, 500, "无法读取已有批次") + return + } + writeJSON(w, 202, map[string]any{"batch": job}) + return + } + rows, err := s.normalizeBatch(r.Context(), &input) + if err != nil { + writeError(w, 422, err.Error()) + return + } + ref, err := randomBatchKey() + if err != nil { + writeError(w, 500, "无法建立批量任务") + return + } + items := make([]store.AdminBatchItem, len(rows)) + valid := 0 + for index, preview := range rows { + item := store.AdminBatchItem{Row: index + 1, Label: preview.Label, State: "pending"} + if !preview.Valid { + item.State = "failed" + item.Detail = preview.Detail + } else { + valid++ + if input.Operation != "create_users" && input.Operation != "create_hosts" { + target := input.Rows[index].HostID + if input.Operation == "user_enable" || input.Operation == "user_disable" { + target = input.Rows[index].AccountID + } + if target > 0 { + item.ResourceID = &target + } + } + } + raw, _ := json.Marshal(input.Rows[index]) + cipher, e := s.secretBox.Seal(batchCipherLabel(ref, "input", index+1), string(raw)) + if e != nil { + writeError(w, 500, "无法加密任务数据") + return + } + item.InputCipher = cipher + items[index] = item + } + if valid == 0 { + writeJSON(w, 422, map[string]any{"error": map[string]string{"message": "没有可执行的条目,请先修正预览错误"}, "rows": rows}) + return + } + id, err := s.store.CreateAdminBatch(r.Context(), currentUser(r).ID, input.RequestKey, digest, input.Operation, ref, items) + if err != nil { + status := 422 + if errors.Is(err, store.ErrBatchKeyConflict) { + status = 409 + } + writeError(w, status, err.Error()) + return + } + s.store.Log(r.Context(), nil, currentUser(r).ID, "create", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, fmt.Sprintf("提交批量任务 %s,共 %d 项", input.Operation, len(rows))) + job, err := s.store.AdminBatch(r.Context(), id, false) + if err != nil { + writeError(w, 500, "任务已保存,请刷新任务列表") + return + } + writeJSON(w, 202, map[string]any{"batch": job}) +} +func (s *Server) adminBatch(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("batchID"), 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "批次编号无效") + return + } + job, err := s.store.AdminBatch(r.Context(), id, false) + if err != nil { + writeError(w, 404, "批次不存在") + return + } + writeJSON(w, 200, map[string]any{"batch": job}) +} +func (s *Server) adminCancelBatch(w http.ResponseWriter, r *http.Request) { + id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64) + if id == 0 { + writeError(w, 400, "批次编号无效") + return + } + if err := s.store.CancelAdminBatch(r.Context(), id); err != nil { + writeError(w, 500, "无法取消任务") + return + } + _ = s.store.RefreshAdminBatches(r.Context()) + s.store.Log(r.Context(), nil, currentUser(r).ID, "cancel", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, "取消批次未执行项,执行中条目继续完成") + w.WriteHeader(204) +} +func (s *Server) adminBatchDownload(w http.ResponseWriter, r *http.Request) { + id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64) + job, err := s.store.AdminBatch(r.Context(), id, true) + if err != nil { + writeError(w, 404, "批次不存在") + return + } + if job.Pending > 0 { + writeError(w, 409, "请等待批次执行完成再下载") + return + } + if job.SecretsExpireAt == nil || !job.SecretsExpireAt.After(time.Now()) { + writeError(w, 410, "批次凭据已过期;FTP 和数据库凭据仍可在对应主机查看,登录密码可重置") + return + } + type downloadItem struct { + Row int `json:"row"` + Label string `json:"label"` + State string `json:"state"` + ResourceID *uint64 `json:"resourceId,omitempty"` + Detail string `json:"detail"` + Result *batchResult `json:"result,omitempty"` + } + items := make([]downloadItem, 0, len(job.Items)) + for _, item := range job.Items { + record := downloadItem{Row: item.Row, Label: item.Label, State: item.State, ResourceID: item.ResourceID, Detail: item.Detail} + if len(item.ResultCipher) > 0 { + var result batchResult + raw, e := s.secretBox.Open(batchCipherLabel(job.SecretRef, "result", item.Row), item.ResultCipher) + if e != nil || json.Unmarshal([]byte(raw), &result) != nil { + writeError(w, 500, "无法解密批次结果") + return + } + record.Result = &result + } + items = append(items, record) + } + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="sea-vhost-batch-%d.json"`, id)) + job.Items = nil + writeJSON(w, 200, map[string]any{"format": "sea-vhost.batch-result", "version": 1, "batch": job, "items": items}) + s.store.Log(r.Context(), nil, currentUser(r).ID, "download", "admin_batch", strconv.FormatUint(id, 10), requestClientIP(r), true, "下载批次凭据结果") +} + +// RunAdminBatches runs on the controller; the browser never drives the queue. +func (s *Server) RunAdminBatches(ctx context.Context) { + var release func() + for ctx.Err() == nil { + var err error + release, err = s.store.LockBatchWorker(ctx) + if err == nil { + break + } + select { + case <-ctx.Done(): + return + case <-time.After(5 * time.Second): + } + } + if release == nil { + return + } + defer release() + go s.runIntegrationWebhooks(ctx) + if err := s.store.RecoverAdminBatches(ctx); err != nil { + slog.Error("batch recovery failed", "error", err) + return + } + for ctx.Err() == nil { + _ = s.store.RefreshAdminBatches(ctx) + job, item, err := s.store.NextAdminBatchItem(ctx) + if err != nil { + if !errors.Is(err, sql.ErrNoRows) && ctx.Err() == nil { + slog.Error("batch queue read failed", "error", err) + } + select { + case <-ctx.Done(): + return + case <-time.After(time.Second): + } + continue + } + s.executeBatchItem(ctx, job, item) + } +} +func (s *Server) executeBatchItem(parent context.Context, job store.AdminBatch, item store.AdminBatchItem) { + ctx, cancel := context.WithTimeout(scope.WithBatchItem(parent, item.ID), 10*time.Minute) + defer cancel() + state, detail := "succeeded", "已完成" + resource := uint64(0) + var result batchResult + administrator, err := s.store.UserByID(ctx, job.AdministratorID) + apiKey, keyErr := s.store.BatchIntegrationKey(ctx, job.ID) + if keyErr != nil || (apiKey > 0 && !s.store.IntegrationKeyActive(ctx, apiKey)) { + err = errors.New("对接 API 密钥已吊销、过期或不可用") + } + if err != nil || administrator.Role != "admin" { + err = errors.New("创建该批次的管理员已不可用") + detail = err.Error() + } else { + var raw string + raw, err = s.secretBox.Open(batchCipherLabel(job.SecretRef, "input", item.Row), item.InputCipher) + var row batchRow + if err == nil { + err = json.Unmarshal([]byte(raw), &row) + } + if err == nil { + result, err = s.performBatchRow(ctx, job.Operation, row) + resource = result.ResourceID + if err == nil && job.Operation == "assign_hosts" { + detail = fmt.Sprintf("主机 #%d → 用户 #%d(0 为未绑定);凭据 %s;停站 %t", row.HostID, row.TenantID, row.CredentialMode, row.StopServices == nil || *row.StopServices) + } + } + if err != nil { + detail = "执行未完成,请核对目标资源及管理员审计" + if errors.Is(err, service.ErrOwnershipIncomplete) { + detail = err.Error() + } + } + } + var cipher []byte + if err == nil { + raw, _ := json.Marshal(result) + cipher, err = s.secretBox.Seal(batchCipherLabel(job.SecretRef, "result", item.Row), string(raw)) + if err != nil { + detail = "操作已执行但凭据保存未完成,需按资源 ID 核验" + state = "uncertain" + } + } + if err != nil && state != "uncertain" { + state = "failed" + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + state = "uncertain" + detail = "执行超时或被中断,请核验资源,禁止直接重复开通" + } + } + save, cancelSave := context.WithTimeout(context.Background(), 15*time.Second) + defer cancelSave() + if e := s.store.FinishAdminBatchItem(save, item.ID, state, detail, cipher, resource); e != nil { + slog.Error("batch outcome persistence failed", "batch_id", job.ID, "item_id", item.ID) + } + s.store.Log(save, nil, job.AdministratorID, "execute", "admin_batch", strconv.FormatUint(job.ID, 10), "batch", state == "succeeded", fmt.Sprintf("批次 #%d 第 %d 项 %s:%s", job.ID, item.Row, job.Operation, detail)) +} +func (s *Server) performBatchRow(ctx context.Context, operation string, row batchRow) (batchResult, error) { + var result batchResult + if operation == "create_users" { + if row.Password == "" { + var err error + row.Password, err = randomBatchPassword() + if err != nil { + 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}) + result.ResourceID = id + result.Login = row.Email + result.Password = row.Password + return result, err + } + if operation == "user_enable" || operation == "user_disable" { + result.ResourceID = row.AccountID + return result, s.store.SetAccountEnabled(ctx, row.AccountID, operation == "user_enable") + } + if operation == "create_hosts" { + ctx = scope.WithNode(ctx, row.NodeID) + release, err := s.projects.BeginRuntimeMutation(ctx) + if err != nil { + return result, err + } + defer release() + created, err := s.projects.CreateManagedHost(ctx, row.TenantID, service.CreateProjectInput{NodeID: row.NodeID, PlanID: row.PlanID, Name: row.Name, Runtime: row.Runtime, Version: row.Version, RunPath: row.RunPath, AutoSSL: row.AutoSSL}) + if err != nil { + return result, err + } + result = batchResult{ResourceID: created.Project.ID, HostLogin: created.Credentials.HostLogin, Password: created.Credentials.HostPassword, FTPHost: created.Credentials.FTPHost, FTPUsername: created.Credentials.FTPUsername, FTPPassword: created.Credentials.FTPPassword, DatabaseName: created.Credentials.DatabaseName, DatabaseUsername: created.Credentials.DatabaseUsername, DatabasePassword: created.Credentials.DatabasePassword} + err = s.store.SetHostSubscription(ctx, created.Project.ID, row.PlanID, row.ExpiresAt) + return result, err + } + hosts, err := s.store.ListAdminProjects(ctx) + if err != nil { + return result, err + } + var host *store.AdminProject + for i := range hosts { + if hosts[i].ID == row.HostID { + host = &hosts[i] + break + } + } + if host == nil { + return result, store.ErrNotFound + } + result.ResourceID = host.ID + if host.ManualRecycledAt != nil { + return result, errors.New("主机已手动回收,请先恢复") + } + if host.ManagementLocked && !(operation == "assign_hosts" && row.ResumeOwnership) { + return result, store.ErrManagementLocked + } + if host.OwnershipVersion != row.OwnershipVersion { + return result, errors.New("主机归属已变更,拒绝执行旧批次") + } + ctx = scope.WithProject(ctx, host.ID, host.NodeID) + if operation == "host_subscription" { + return result, s.projects.ApplyHostSubscription(ctx, host.ID, row.PlanID, row.ExpiresAt) + } + if operation == "assign_hosts" { + stop := true + if row.StopServices != nil { + stop = *row.StopServices + } + mode := row.CredentialMode + if mode == "" { + mode = "preserve" + } + credentials, e := s.projects.ChangeHostOwner(ctx, host.ID, row.OwnershipVersion, row.TenantID, mode, stop, row.ResumeOwnership) + result.HostLogin = host.HostName + result.Password = credentials.HostPassword + result.FTPUsername = host.HostName + result.FTPHost = host.Domain + result.FTPPassword = credentials.FTPPassword + result.DatabaseName = host.HostName + result.DatabaseUsername = host.HostName + result.DatabasePassword = credentials.DatabasePassword + return result, e + } + if operation == "host_password_reset" { + result.HostLogin = host.HostName + result.Password, err = s.projects.ResetManagedHostLogin(ctx, host.ID, row.OwnershipVersion) + return result, err + } + release, err := s.projects.BeginRuntimeMutation(ctx) + if err != nil { + return result, err + } + defer release() + namespace, project := host.TenantID, host.ID + user := store.User{Role: "host", TenantID: &namespace, ProjectID: &project} + sites, err := s.store.ListSites(ctx, namespace, project) + if err != nil { + return result, err + } + for _, site := range sites { + if _, err = s.projects.SetSiteState(ctx, user, project, site.ID, operation == "host_start"); err != nil { + return result, err + } + } + return result, nil +} diff --git a/backend/internal/httpapi/admin_batches_integration_test.go b/backend/internal/httpapi/admin_batches_integration_test.go new file mode 100644 index 0000000..9eaf3a2 --- /dev/null +++ b/backend/internal/httpapi/admin_batches_integration_test.go @@ -0,0 +1,460 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/go-sql-driver/mysql" + "sea-vhost/internal/auth" + "sea-vhost/internal/config" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/service" + "sea-vhost/internal/store" +) + +type ownershipTestPanel struct { + *panel.Mock + mu sync.Mutex + failDatabase bool + ftpPasswords []string +} + +func (p *ownershipTestPanel) SetFTPPassword(ctx context.Context, id int64, name, password string) error { + p.mu.Lock() + defer p.mu.Unlock() + p.ftpPasswords = append(p.ftpPasswords, password) + return nil +} +func (p *ownershipTestPanel) SetDatabasePassword(ctx context.Context, id int64, name, password string) error { + p.mu.Lock() + defer p.mu.Unlock() + if p.failDatabase { + p.failDatabase = false + return errors.New("injected native database failure") + } + return nil +} + +func TestAdminBatchOwnershipMySQL(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() + if err = db.Migrate(ctx); err != nil { + t.Fatal(err) + } + if err = db.BootstrapAdmin(ctx, "batch-admin@example.invalid", "批量测试管理员", "batch-admin-password-123"); err != nil { + t.Fatal(err) + } + root := t.TempDir() + if err = db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"); err != nil { + t.Fatal(err) + } + admin, err := db.UserByLogin(ctx, "batch-admin@example.invalid") + if err != nil { + t.Fatal(err) + } + secret := "batch-test-session-secret-at-least-thirty-two-characters" + native := &ownershipTestPanel{Mock: panel.NewMock()} + projectService := service.NewProjects(db, native, isolation.Mock{Root: root}, "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, projectService) + handler := api.Handler() + token, err := auth.NewSessionToken(secret) + if err != nil { + t.Fatal(err) + } + if err = db.CreateSession(ctx, admin.ID, token, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + call := func(method, path string, body any, session string) *httptest.ResponseRecorder { + var buffer bytes.Buffer + if body != nil { + _ = json.NewEncoder(&buffer).Encode(body) + } + request := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer) + request.Header.Set("Origin", "https://control.example.invalid") + request.Header.Set("Content-Type", "application/json") + if session != "" { + request.AddCookie(&http.Cookie{Name: "sea_session", Value: session}) + } + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + return response + } + expect := func(response *httptest.ResponseRecorder, status int) { + t.Helper() + if response.Code != status { + t.Fatalf("HTTP %d, want %d: %s", response.Code, status, response.Body.String()) + } + } + path := func(id uint64) string { return "/api/v1/admin/batches/" + strconv.FormatUint(id, 10) } + requestKey := func() string { + key, e := randomBatchKey() + if e != nil { + t.Fatal(e) + } + return key + } + submit := func(input batchRequest) uint64 { + t.Helper() + response := call("POST", "/api/v1/admin/batches", input, token) + expect(response, 202) + var result struct { + Batch store.AdminBatch `json:"batch"` + } + if e := json.Unmarshal(response.Body.Bytes(), &result); e != nil { + t.Fatal(e) + } + return result.Batch.ID + } + var stop context.CancelFunc + var done chan struct{} + startWorker := func() { + worker, cancel := context.WithCancel(ctx) + stop = cancel + done = make(chan struct{}) + go func() { defer close(done); api.RunAdminBatches(worker) }() + } + stopWorker := func() { + if stop != nil { + stop() + select { + case <-done: + case <-time.After(20 * time.Second): + t.Fatal("worker did not stop") + } + stop = nil + } + } + defer stopWorker() + wait := func(id uint64) store.AdminBatch { + t.Helper() + deadline := time.Now().Add(90 * time.Second) + for time.Now().Before(deadline) { + job, e := db.AdminBatch(ctx, id, false) + if e != nil { + t.Fatal(e) + } + if job.Pending == 0 && (job.State == "completed" || job.State == "partial") { + return job + } + time.Sleep(25 * time.Millisecond) + } + t.Fatal("batch did not finish") + return store.AdminBatch{} + } + download := func(id uint64) [][]string { + t.Helper() + response := call("GET", path(id)+"/download", nil, token) + expect(response, 200) + var export struct { + Format string `json:"format"` + Version int `json:"version"` + Items []struct { + Row int `json:"row"` + State string `json:"state"` + Label string `json:"label"` + ResourceID *uint64 `json:"resourceId"` + Detail string `json:"detail"` + Result batchResult `json:"result"` + } `json:"items"` + } + if err := json.Unmarshal(response.Body.Bytes(), &export); err != nil { + t.Fatal(err) + } + if export.Format != "sea-vhost.batch-result" || export.Version != 1 || !strings.Contains(response.Header().Get("Content-Disposition"), ".json") { + t.Fatal("JSON download format mismatch") + } + records := [][]string{{"batch", "row", "state", "label", "resource", "login", "password", "ftpHost", "ftpUser", "ftpPassword", "database", "databaseUser", "databasePassword", "detail"}} + for _, item := range export.Items { + r := item.Result + login := r.Login + if login == "" { + login = r.HostLogin + } + resource := "" + if item.ResourceID != nil { + resource = strconv.FormatUint(*item.ResourceID, 10) + } + records = append(records, []string{strconv.FormatUint(id, 10), strconv.Itoa(item.Row), item.State, item.Label, resource, login, r.Password, r.FTPHost, r.FTPUsername, r.FTPPassword, r.DatabaseName, r.DatabaseUsername, r.DatabasePassword, item.Detail}) + } + return records + } + login := func(identifier, password string) string { + t.Helper() + response := call("POST", "/api/v1/auth/login", map[string]string{"identifier": identifier, "password": password}, "") + expect(response, 200) + for _, cookie := range response.Result().Cookies() { + if cookie.Name == "sea_session" { + return cookie.Value + } + } + t.Fatal("no session cookie") + return "" + } + expect(call("POST", "/api/v1/admin/batches/preview", batchRequest{Operation: "create_users", Rows: []batchRow{{}}}, ""), 401) + users := batchRequest{RequestKey: requestKey(), Operation: "create_users", Rows: []batchRow{{Slug: "batch-user-a", Name: "批量用户甲", Email: "batch-a@example.invalid", DisplayName: "批量用户甲"}, {Slug: "batch-user-b", Name: "批量用户乙", Email: "batch-b@example.invalid", DisplayName: "批量用户乙"}, {Slug: "batch-user-a", Name: "重复用户甲", Email: "batch-a@example.invalid", DisplayName: "重复用户甲"}}} + preview := call("POST", "/api/v1/admin/batches/preview", users, token) + expect(preview, 200) + if !strings.Contains(preview.Body.String(), "同批邮箱或用户标识重复") { + t.Fatal("duplicate import did not fail preview") + } + batchID := submit(users) + startWorker() + job := wait(batchID) + if job.Succeeded != 2 || job.Failed != 1 { + t.Fatalf("partial user batch: %+v", job) + } + records := download(batchID) + if len(records) != 4 || records[1][6] == "" || records[1][6] == records[2][6] { + t.Fatal("missing independent random passwords") + } + aToken, bToken := login(records[1][5], records[1][6]), login(records[2][5], records[2][6]) + userA, err := db.UserByLogin(ctx, records[1][5]) + if err != nil { + t.Fatal(err) + } + userB, err := db.UserByLogin(ctx, records[2][5]) + if err != nil { + t.Fatal(err) + } + if userB.TenantID == nil || *userB.TenantID == *userA.TenantID { + t.Fatal("batch accounts share an identity") + } + if retry := submit(users); retry != batchID { + t.Fatal("same request duplicated the batch") + } + changed := users + changed.Rows = append([]batchRow(nil), users.Rows...) + changed.Rows[0].Name = "不同请求" + expect(call("POST", "/api/v1/admin/batches", changed, token), 409) + for _, endpoint := range []string{"/api/v1/admin/batches", path(batchID), path(batchID) + "/download"} { + expect(call("GET", endpoint, nil, aToken), 403) + } + expect(call("POST", "/api/v1/admin/batches", users, bToken), 403) + stored, err := db.AdminBatch(ctx, batchID, true) + if err != nil { + t.Fatal(err) + } + for _, item := range stored.Items { + if bytes.Contains(item.ResultCipher, []byte(records[1][6])) { + t.Fatal("plaintext password persisted") + } + } + plans, err := db.ListPlans(ctx) + if err != nil { + t.Fatal(err) + } + hostsInput := batchRequest{RequestKey: requestKey(), Operation: "create_hosts", Rows: []batchRow{{Name: "batch-host-a", TenantID: *userA.TenantID, NodeID: 1, PlanID: plans[0].ID, Runtime: "PHP", Version: "8.4", RunPath: "/public"}, {Name: "batch-host-independent", NodeID: 1, PlanID: plans[0].ID, Runtime: "PHP", Version: "8.4", RunPath: "/public"}}} + hostBatch := submit(hostsInput) + job = wait(hostBatch) + if job.Succeeded != 2 { + t.Fatalf("host batch: %+v", job) + } + hostRows := download(hostBatch) + var aHost, independent uint64 + aHost, _ = strconv.ParseUint(hostRows[1][4], 10, 64) + independent, _ = strconv.ParseUint(hostRows[2][4], 10, 64) + hostToken := login(hostRows[1][5], hostRows[1][6]) + independentToken := login(hostRows[2][5], hostRows[2][6]) + resetBatch := submit(batchRequest{RequestKey: requestKey(), Operation: "host_password_reset", Rows: []batchRow{{HostID: independent}}}) + if wait(resetBatch).Succeeded != 1 { + t.Fatal("administrator could not reset independent host login") + } + resetRows := download(resetBatch) + expect(call("GET", "/api/v1/me", nil, independentToken), 401) + independentToken = login(resetRows[1][5], resetRows[1][6]) + dashboard := call("GET", "/api/v1/dashboard", nil, aToken) + expect(dashboard, 200) + var view struct { + Projects []store.Project `json:"projects"` + } + if err = json.Unmarshal(dashboard.Body.Bytes(), &view); err != nil { + t.Fatal(err) + } + if len(view.Projects) != 1 || view.Projects[0].ID != aHost { + t.Fatal("account view leaked independent host") + } + expect(call("GET", "/api/v1/resources", nil, aToken), 200) + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(aHost, 10)+"/credentials", nil, aToken), 200) + for _, session := range []string{aToken, bToken, hostToken} { + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, session), 404) + } + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, independentToken), 200) + independentUser, e := db.UserByLogin(ctx, hostRows[2][5]) + if e != nil { + t.Fatal(e) + } + namespaceBefore := *independentUser.TenantID + bound := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, TenantID: *userB.TenantID}}}) + if wait(bound).Succeeded != 1 { + t.Fatal("initial optional binding failed") + } + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, bToken), 200) + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, aToken), 404) + independentUser, e = db.UserByLogin(ctx, hostRows[2][5]) + if e != nil || *independentUser.TenantID != namespaceBefore || independentUser.TenantName != "批量用户乙" { + t.Fatal("initial binding changed resource identity or failed to update displayed owner") + } + stale := batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, TenantID: *userB.TenantID, OwnershipVersion: 1}}} + expect(call("POST", "/api/v1/admin/batches", stale, token), 422) + expect(call("GET", "/api/v1/me", nil, independentToken), 401) + independentToken = login(resetRows[1][5], resetRows[1][6]) + started := submit(batchRequest{RequestKey: requestKey(), Operation: "host_start", Rows: []batchRow{{HostID: independent}}}) + if wait(started).Succeeded != 1 { + t.Fatal("cannot start bound host") + } + keepRunning := false + transferred := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, TenantID: *userA.TenantID, CredentialMode: "preserve", StopServices: &keepRunning}}}) + if wait(transferred).Succeeded != 1 { + t.Fatal("preserve credentials transfer failed") + } + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, bToken), 404) + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, aToken), 200) + expect(call("GET", "/api/v1/me", nil, independentToken), 401) + independentToken = login(resetRows[1][5], resetRows[1][6]) + current, e := db.Project(ctx, namespaceBefore, independent) + if e != nil || current.Status != "running" { + t.Fatal("keep-running transfer stopped the website") + } + native.mu.Lock() + native.failDatabase = true + native.mu.Unlock() + interrupted := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, CredentialMode: "reset"}}}) + if wait(interrupted).Failed != 1 { + t.Fatal("injected native failure did not stop transfer") + } + pending, e := db.OwnershipChange(ctx, independent) + if e != nil || pending.State != "pending" || len(pending.CredentialsCipher) == 0 { + t.Fatal("failed transition not staged for recovery") + } + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, aToken), 423) + expect(call("GET", "/api/v1/me", nil, independentToken), 401) + expect(call("POST", "/api/v1/admin/batches", batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, CredentialMode: "preserve", ResumeOwnership: true}}}, token), 422) + recoveredBatch := submit(batchRequest{RequestKey: requestKey(), Operation: "assign_hosts", Rows: []batchRow{{HostID: independent, CredentialMode: "reset", ResumeOwnership: true}}}) + if wait(recoveredBatch).Succeeded != 1 { + t.Fatal("explicit ownership recovery failed") + } + native.mu.Lock() + sameStagedPassword := len(native.ftpPasswords) == 2 && native.ftpPasswords[0] == native.ftpPasswords[1] + native.mu.Unlock() + if !sameStagedPassword { + t.Fatal("recovery generated different native credentials") + } + rotated := download(recoveredBatch) + if rotated[1][6] == "" || rotated[1][9] == "" || rotated[1][12] == "" { + t.Fatal("reset result missing credentials") + } + expect(call("POST", "/api/v1/auth/login", map[string]string{"identifier": resetRows[1][5], "password": resetRows[1][6]}, ""), 401) + independentToken = login(rotated[1][5], rotated[1][6]) + expect(call("GET", "/api/v1/projects/"+strconv.FormatUint(independent, 10)+"/credentials", nil, independentToken), 200) + current, e = db.Project(ctx, namespaceBefore, independent) + if e != nil || current.Status != "stopped" { + t.Fatal("default ownership stop was not applied") + } + pending, e = db.OwnershipChange(ctx, independent) + if e != nil || pending.State != "completed" || len(pending.CredentialsCipher) != 0 || pending.TargetOwnerID != nil { + t.Fatal("completed unbind retained staged secrets or owner") + } + filePath := "/api/v1/projects/" + strconv.FormatUint(aHost, 10) + "/files" + expect(call("PUT", filePath, map[string]any{"path": "../must-not-write", "content": "ignored"}, aToken), 400) + for _, session := range []string{aToken, hostToken} { + response := call("GET", "/api/v1/activities?projectId="+strconv.FormatUint(aHost, 10), nil, session) + expect(response, 200) + var logs struct { + Activities []store.Activity `json:"activities"` + } + if e = json.Unmarshal(response.Body.Bytes(), &logs); e != nil { + t.Fatal(e) + } + found := false + for _, event := range logs.Activities { + if event.Actor == "管理员" { + t.Fatal("administrator batch event leaked to customer logs") + } + if event.ResourceType == "file" && event.ProjectID != nil && *event.ProjectID == aHost { + found = true + } + } + if !found { + t.Fatal("resource namespace detached customer host logs") + } + } + expect(call("GET", "/api/v1/activities?projectId="+strconv.FormatUint(aHost, 10), nil, bToken), 404) + summaries, err := db.ListTenants(ctx) + if err != nil || len(summaries) != 2 { + t.Fatalf("resource namespaces leaked into user list: %d %v", len(summaries), err) + } + expiry := time.Now().Add(time.Hour) + sub := submit(batchRequest{RequestKey: requestKey(), Operation: "host_subscription", Rows: []batchRow{{HostID: aHost, PlanID: plans[0].ID, SetExpiry: true, ExpiresAt: &expiry}}}) + if wait(sub).Succeeded != 1 { + t.Fatal("subscription batch failed") + } + disabled := submit(batchRequest{RequestKey: requestKey(), Operation: "user_disable", Rows: []batchRow{{AccountID: *userA.TenantID}}}) + if wait(disabled).Succeeded != 1 { + t.Fatal("disable batch failed") + } + expect(call("GET", "/api/v1/me", nil, aToken), 401) + expect(call("GET", "/api/v1/me", nil, hostToken), 200) + enabled := submit(batchRequest{RequestKey: requestKey(), Operation: "user_enable", Rows: []batchRow{{Account: records[1][5]}}}) + if wait(enabled).Succeeded != 1 { + t.Fatal("enable disabled account by JSON email failed") + } + aToken = login(records[1][5], records[1][6]) + expect(call("GET", "/api/v1/dashboard", nil, aToken), 200) + for _, operation := range []string{"host_stop", "host_start"} { + id := submit(batchRequest{RequestKey: requestKey(), Operation: operation, Rows: []batchRow{{HostID: aHost}}}) + if wait(id).Succeeded != 1 { + t.Fatalf("%s batch failed", operation) + } + } + stopWorker() + cancelInput := batchRequest{RequestKey: requestKey(), Operation: "create_users", Rows: []batchRow{{Slug: "batch-cancelled", Name: "应取消用户", Email: "cancelled@example.invalid", DisplayName: "应取消用户"}}} + cancelled := submit(cancelInput) + expect(call("POST", path(cancelled)+"/cancel", map[string]string{}, token), 204) + if job, e := db.AdminBatch(ctx, cancelled, false); e != nil || job.Pending != 0 || job.Failed != 1 { + t.Fatal("cancel did not stop pending row") + } + recoveryInput := cancelInput + recoveryInput.RequestKey = requestKey() + recoverID := submit(recoveryInput) + _, item, err := db.NextAdminBatchItem(ctx) + if err != nil { + t.Fatal(err) + } + if err = db.RecoverAdminBatches(ctx); err != nil { + t.Fatal(err) + } + if err = db.RefreshAdminBatches(ctx); err != nil { + t.Fatal(err) + } + recovered, err := db.AdminBatch(ctx, recoverID, false) + if err != nil || recovered.Uncertain != 1 || recovered.Pending != 0 || recovered.Items[0].ID != item.ID { + t.Fatal("restart did not preserve uncertain state") + } + if _, err = db.UserByLogin(ctx, "cancelled@example.invalid"); err == nil { + t.Fatal("cancelled/uncertain operation executed") + } + t.Log("real MySQL batch queue, random credentials, idempotency, JSON access, optional owners, account aggregation, enable/disable, subscription, start/stop, cancellation and restart uncertainty passed") +} diff --git a/backend/internal/httpapi/admin_management.go b/backend/internal/httpapi/admin_management.go new file mode 100644 index 0000000..c6ab0ec --- /dev/null +++ b/backend/internal/httpapi/admin_management.go @@ -0,0 +1,468 @@ +package httpapi + +import ( + "encoding/base64" + "encoding/json" + "errors" + "net" + "net/http" + "net/mail" + "net/url" + "sea-vhost/internal/scope" + "strconv" + "strings" + "time" + + "sea-vhost/internal/service" +) + +type secretServiceConfig struct { + AutoCreate bool `json:"autoCreate,omitempty"` + UserPasswordLogin *bool `json:"userPasswordLogin,omitempty"` + AdminPasswordLogin *bool `json:"adminPasswordLogin,omitempty"` + Host string `json:"host,omitempty"` + Port int `json:"port,omitempty"` + Username string `json:"username,omitempty"` + Secret string `json:"secret,omitempty"` + From string `json:"from,omitempty"` + AdminRecipients string `json:"adminRecipients,omitempty"` + StartTLS bool `json:"startTls,omitempty"` + Issuer string `json:"issuer,omitempty"` + ClientID string `json:"clientId,omitempty"` + RedirectURI string `json:"redirectUri,omitempty"` + Enabled bool `json:"enabled,omitempty"` +} + +func (s *Server) adminOverview(w http.ResponseWriter, r *http.Request) { + users, err := s.store.ListTenants(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取用户") + return + } + projects, err := s.store.ListAdminProjects(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取虚拟主机") + return + } + domains, err := s.store.AllDomains(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取域名") + return + } + ips, err := s.store.ListIPAddresses(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取 IP 地址池") + return + } + logs, err := s.store.AdminActivities(r.Context(), 100) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取操作日志") + return + } + writeJSON(w, http.StatusOK, map[string]any{"users": users, "projects": projects, "domains": domains, "ipAddresses": ips, "logs": logs}) +} + +func (s *Server) adminSettings(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + smtp := s.readServiceConfig(r, "smtp_config") + oidc := s.readServiceConfig(r, "oidc_config") + writeJSON(w, http.StatusOK, map[string]any{ + "domainApproval": s.store.DomainApproval(r.Context(), s.cfg.DomainApproval), + "filingRequired": s.store.Setting(r.Context(), "filing_required", "false") == "true", + "cdnCnameTarget": s.store.Setting(r.Context(), "cdn_cname_target", ""), + "graceDays": settingInt(s.store.Setting(r.Context(), "lifecycle_grace_days", "3"), 3), + "recycleDays": settingInt(s.store.Setting(r.Context(), "lifecycle_recycle_days", "7"), 7), + "backupRetentionDays": settingInt(s.store.Setting(r.Context(), "backup_retention_days", "14"), 14), + "smtp": map[string]any{"enabled": smtp.Enabled, "host": smtp.Host, "port": smtp.Port, "username": smtp.Username, "from": smtp.From, "adminRecipients": smtp.AdminRecipients, "startTls": smtp.StartTLS, "secretConfigured": smtp.Secret != ""}, + "oidc": map[string]any{"enabled": oidc.Enabled, "issuer": oidc.Issuer, "clientId": oidc.ClientID, "redirectUri": oidc.RedirectURI, "secretConfigured": oidc.Secret != "", "bindingOnly": !oidc.AutoCreate, "autoCreate": oidc.AutoCreate, "userPasswordLogin": oidcPasswordAllowed(oidc, "tenant"), "adminPasswordLogin": oidcPasswordAllowed(oidc, "admin"), "passwordLogin": oidcPasswordAllowed(oidc, "tenant")}, + }) + return + } + var input struct { + DomainApproval bool `json:"domainApproval"` + FilingRequired bool `json:"filingRequired"` + CDNCnameTarget string `json:"cdnCnameTarget"` + GraceDays int `json:"graceDays"` + RecycleDays int `json:"recycleDays"` + BackupRetentionDays int `json:"backupRetentionDays"` + SMTP secretServiceConfig `json:"smtp"` + OIDC secretServiceConfig `json:"oidc"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + input.CDNCnameTarget = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.CDNCnameTarget), ".")) + if input.GraceDays != 3 || input.RecycleDays != 7 || input.BackupRetentionDays != 14 { + writeError(w, http.StatusUnprocessableEntity, "当前生命周期固定为宽限 3 天、回收保留 7 天、备份保留 14 天") + return + } + if input.CDNCnameTarget != "" && net.ParseIP(input.CDNCnameTarget) == nil && !validHostname(input.CDNCnameTarget) { + writeError(w, http.StatusUnprocessableEntity, "CDN CNAME 目标无效") + return + } + if err := s.validateServiceConfigs(r, &input.SMTP, &input.OIDC); err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + if err := s.store.SetDomainApproval(r.Context(), input.DomainApproval); err != nil { + writeError(w, http.StatusInternalServerError, "无法保存设置") + return + } + for key, value := range map[string]string{"filing_required": strconv.FormatBool(input.FilingRequired), "cdn_cname_target": input.CDNCnameTarget, "lifecycle_grace_days": "3", "lifecycle_recycle_days": "7", "backup_retention_days": "14"} { + if err := s.store.SetSetting(r.Context(), key, value); err != nil { + writeError(w, http.StatusInternalServerError, "无法保存设置") + return + } + } + if err := s.writeServiceConfig(r, "smtp_config", input.SMTP); err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + if err := s.writeServiceConfig(r, "oidc_config", input.OIDC); err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + user := currentUser(r) + s.store.Log(r.Context(), nil, user.ID, "update", "system_settings", "", requestClientIP(r), true, "更新系统、通知与 SSO 设置") + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) validateServiceConfigs(r *http.Request, smtpConfig, oidcConfig *secretServiceConfig) error { + smtpConfig.Host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(smtpConfig.Host), ".")) + smtpConfig.Username = strings.TrimSpace(smtpConfig.Username) + smtpConfig.From = strings.TrimSpace(smtpConfig.From) + smtpConfig.AdminRecipients = strings.TrimSpace(smtpConfig.AdminRecipients) + issuer := strings.TrimSuffix(strings.TrimSpace(oidcConfig.Issuer), "/") + oidcConfig.Issuer = issuer + oidcConfig.ClientID = strings.TrimSpace(oidcConfig.ClientID) + oidcConfig.RedirectURI = strings.TrimSpace(oidcConfig.RedirectURI) + if smtpConfig.Enabled { + if net.ParseIP(smtpConfig.Host) == nil && !validHostname(smtpConfig.Host) { + return errors.New("SMTP 主机无效") + } + if smtpConfig.Port < 1 || smtpConfig.Port > 65535 { + return errors.New("SMTP 端口无效") + } + if parsed, err := mail.ParseAddress(smtpConfig.From); err != nil || parsed.Address != smtpConfig.From { + return errors.New("SMTP 发件地址无效") + } + addresses := strings.FieldsFunc(smtpConfig.AdminRecipients, func(char rune) bool { return char == ',' || char == ';' || char == '\n' }) + if len(addresses) == 0 { + return errors.New("至少需要一个管理员收件地址") + } + for _, address := range addresses { + address = strings.TrimSpace(address) + if parsed, err := mail.ParseAddress(address); err != nil || parsed.Address != address { + return errors.New("管理员收件地址格式无效") + } + } + existing := s.readServiceConfig(r, "smtp_config") + if smtpConfig.Username != "" && strings.TrimSpace(smtpConfig.Secret) == "" && existing.Secret == "" { + return errors.New("SMTP 认证密码不能为空") + } + if smtpConfig.Username != "" && smtpConfig.Port != 465 && !smtpConfig.StartTLS { + return errors.New("SMTP 认证必须启用 TLS") + } + } + existingOIDC := s.readServiceConfig(r, "oidc_config") + if oidcConfig.UserPasswordLogin == nil { + oidcConfig.UserPasswordLogin = existingOIDC.UserPasswordLogin + } + if oidcConfig.AdminPasswordLogin == nil { + oidcConfig.AdminPasswordLogin = existingOIDC.AdminPasswordLogin + } + if !oidcPasswordAllowed(*oidcConfig, "tenant") || !oidcPasswordAllowed(*oidcConfig, "admin") { + candidate := *oidcConfig + if candidate.Secret == "" { + candidate.Secret = existingOIDC.Secret + } + if !validOIDCConfig(candidate) { + return errors.New("关闭密码登录前必须启用并完整配置 SSO") + } + if !oidcPasswordAllowed(candidate, "admin") { + current := currentUser(r) + if _, err := s.store.OIDCIdentity(r.Context(), current.ID, oidcProviderKey(candidate)); err != nil { + return errors.New("请先为当前管理员绑定该 SSO 身份,再关闭管理员密码登录") + } + } + } + if oidcConfig.Enabled { + issuerURL, err := url.Parse(oidcConfig.Issuer) + if err != nil || issuerURL.Scheme != "https" || issuerURL.Host == "" || issuerURL.User != nil || issuerURL.RawQuery != "" || issuerURL.Fragment != "" { + return errors.New("OIDC Issuer 必须是有效的 HTTPS 地址") + } + redirectURL, err := url.Parse(oidcConfig.RedirectURI) + managementDomain := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(s.cfg.ManagementDomain), ".")) + if err != nil || redirectURL.Scheme != "https" || !strings.EqualFold(redirectURL.Hostname(), managementDomain) || redirectURL.Path != "/api/v1/auth/oidc/callback" || redirectURL.RawQuery != "" || redirectURL.Fragment != "" || redirectURL.User != nil { + return errors.New("OIDC 回调地址必须是管理域名下的 /api/v1/auth/oidc/callback") + } + if oidcConfig.ClientID == "" || len(oidcConfig.ClientID) > 255 { + return errors.New("OIDC Client ID 无效") + } + existing := s.readServiceConfig(r, "oidc_config") + if strings.TrimSpace(oidcConfig.Secret) == "" && existing.Secret == "" { + return errors.New("OIDC Client Secret 不能为空") + } + } + return nil +} + +func (s *Server) readServiceConfig(r *http.Request, key string) secretServiceConfig { + raw := s.store.Setting(r.Context(), key, "{}") + var cfg secretServiceConfig + if json.Unmarshal([]byte(raw), &cfg) != nil { + return secretServiceConfig{} + } + if cfg.Secret != "" { + encrypted, err := base64.RawStdEncoding.DecodeString(cfg.Secret) + if err == nil { + if value, openErr := s.secretBox.Open("system/"+key, encrypted); openErr == nil { + cfg.Secret = value + } else { + cfg.Secret = "" + } + } + } + return cfg +} + +func (s *Server) writeServiceConfig(r *http.Request, key string, cfg secretServiceConfig) error { + existing := s.readServiceConfig(r, key) + if strings.TrimSpace(cfg.Secret) == "" { + cfg.Secret = existing.Secret + } + if cfg.Secret != "" { + encrypted, err := s.secretBox.Seal("system/"+key, cfg.Secret) + if err != nil { + return err + } + cfg.Secret = base64.RawStdEncoding.EncodeToString(encrypted) + } + data, err := json.Marshal(cfg) + if err != nil { + return err + } + return s.store.SetSetting(r.Context(), key, string(data)) +} + +func (s *Server) adminIPs(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + items, err := s.store.ListIPAddresses(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取 IP 地址池") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ipAddresses": items}) + return + } + var input struct { + Address string `json:"address"` + AllocationMode string `json:"allocationMode"` + Label string `json:"label"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + ip := net.ParseIP(strings.TrimSpace(input.Address)) + if ip == nil { + writeError(w, http.StatusUnprocessableEntity, "IP 地址无效") + return + } + family := "ipv6" + if ip.To4() != nil { + family = "ipv4" + } + if input.AllocationMode != "shared" && input.AllocationMode != "dedicated" { + writeError(w, http.StatusUnprocessableEntity, "IP 分配方式无效") + return + } + id, err := s.store.CreateIPAddress(r.Context(), ip.String(), family, input.AllocationMode, strings.TrimSpace(input.Label)) + if err != nil { + writeError(w, http.StatusUnprocessableEntity, "IP 已存在或无法添加") + return + } + writeJSON(w, http.StatusCreated, map[string]any{"id": id}) +} + +func (s *Server) adminIP(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "IP 编号无效") + return + } + if err = s.store.DeleteIPAddress(r.Context(), id); err != nil { + writeError(w, http.StatusConflict, "已分配的 IP 不能删除") + return + } + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) adminProjectNetwork(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "虚拟主机编号无效") + return + } + var input struct { + IPID *uint64 `json:"ipId"` + Dedicated bool `json:"dedicated"` + HTTPPort int `json:"httpPort"` + HTTPSPort int `json:"httpsPort"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + if input.HTTPPort < 1 || input.HTTPPort > 65535 || input.HTTPSPort < 1 || input.HTTPSPort > 65535 || input.HTTPPort == input.HTTPSPort { + writeError(w, http.StatusUnprocessableEntity, "HTTP/HTTPS 端口无效") + return + } + if input.Dedicated && input.IPID == nil { + writeError(w, http.StatusUnprocessableEntity, "独立 IP 模式必须选择 IP") + return + } + if err = s.projects.ConfigureProjectNetwork(r.Context(), id, input.IPID, input.Dedicated, input.HTTPPort, input.HTTPSPort); err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法更新网络配置") + return + } + user := currentUser(r) + s.store.Log(r.Context(), nil, user.ID, "update", "project_network", strconv.FormatUint(id, 10), requestClientIP(r), true, "更新虚拟主机 IP 与公开端口") + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) adminPanelSites(w http.ResponseWriter, r *http.Request) { + items, err := s.projects.UnmanagedPanelSites(r.Context()) + if err != nil { + writeError(w, http.StatusBadGateway, "无法读取宝塔站点") + return + } + catalog, err := s.projects.RuntimeCatalog(r.Context()) + if err != nil { + writeError(w, http.StatusBadGateway, "无法读取运行环境") + return + } + writeJSON(w, http.StatusOK, map[string]any{"sites": items, "versions": catalog}) +} + +func (s *Server) adminAdoptPanelSite(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil || id <= 0 { + writeError(w, http.StatusBadRequest, "宝塔站点编号无效") + return + } + var input struct { + PlanID uint64 `json:"planId"` + TenantID uint64 `json:"tenantId"` + Name string `json:"name"` + Runtime string `json:"runtime"` + Version string `json:"version"` + RunPath string `json:"runPath"` + AutoSSL bool `json:"autoSSL"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + created, err := s.projects.Adopt(r.Context(), service.AdoptProjectInput{NodeID: scope.Node(r.Context()), PlanID: input.PlanID, TenantID: input.TenantID, PanelSiteID: id, Name: input.Name, Runtime: input.Runtime, Version: input.Version, RunPath: input.RunPath, AutoSSL: input.AutoSSL}) + user := currentUser(r) + if err != nil { + s.store.Log(r.Context(), nil, user.ID, "adopt", "panel_site", strconv.FormatInt(id, 10), requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(scope.WithProject(r.Context(), created.Project.ID, created.Project.NodeID), &created.Project.TenantID, user.ID, "adopt", "panel_site", strconv.FormatInt(id, 10), requestClientIP(r), true, "接管宝塔站点到虚拟主机 "+created.Project.HostName) + writeJSON(w, http.StatusCreated, created) +} + +func (s *Server) adminDomainMetadata(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "域名编号无效") + return + } + var input struct { + ResolutionMode string `json:"resolutionMode"` + CNAMETarget string `json:"cnameTarget"` + FilingStatus string `json:"filingStatus"` + FilingNumber string `json:"filingNumber"` + FilingNote string `json:"filingNote"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + if input.ResolutionMode != "direct" && input.ResolutionMode != "cname" && input.ResolutionMode != "cdn" { + writeError(w, http.StatusUnprocessableEntity, "解析模式无效") + return + } + if input.FilingStatus != "exempt" && input.FilingStatus != "pending" && input.FilingStatus != "approved" && input.FilingStatus != "rejected" { + writeError(w, http.StatusUnprocessableEntity, "备案状态无效") + return + } + input.CNAMETarget = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.CNAMETarget), ".")) + input.FilingNumber = strings.TrimSpace(input.FilingNumber) + input.FilingNote = strings.TrimSpace(input.FilingNote) + if input.ResolutionMode == "cdn" && input.CNAMETarget == "" { + input.CNAMETarget = s.store.Setting(r.Context(), "cdn_cname_target", "") + } + if input.ResolutionMode == "direct" { + input.CNAMETarget = "" + } + if (input.ResolutionMode != "direct" && !validNodeDomain(input.CNAMETarget)) || len([]rune(input.FilingNumber)) > 80 || len([]rune(input.FilingNote)) > 500 || strings.ContainsAny(input.FilingNumber+input.FilingNote, "\x00") { + writeError(w, 422, "请检查 CNAME 目标、备案号和备注长度;CDN 模式需配置目标域名") + return + } + err = s.store.UpdateDomainPolicy(r.Context(), id, input.ResolutionMode, input.CNAMETarget, input.FilingStatus, input.FilingNumber, input.FilingNote) + s.resourceAudit(r, "update", "domain_policy", id, err, "更新自定义域名解析指引与备案信息") + if err != nil { + writeError(w, 422, "域名配置未保存,请检查是否为可管理的自定义域名") + return + } + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) adminTenantExpiry(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "用户编号无效") + return + } + var input struct { + ExpiresAt *time.Time `json:"expiresAt"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + if err = s.store.SetTenantExpiry(r.Context(), id, input.ExpiresAt); err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法更新到期时间") + return + } + w.WriteHeader(http.StatusNoContent) +} + +func settingInt(value string, fallback int) int { + parsed, err := strconv.Atoi(value) + if err != nil || parsed < 0 { + return fallback + } + return parsed +} +func validHostname(value string) bool { + if len(value) > 253 || value == "" { + return false + } + for _, label := range strings.Split(value, ".") { + if len(label) < 1 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { + return false + } + for _, r := range label { + if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') { + return false + } + } + } + return true +} diff --git a/backend/internal/httpapi/admin_test.go b/backend/internal/httpapi/admin_test.go new file mode 100644 index 0000000..743f196 --- /dev/null +++ b/backend/internal/httpapi/admin_test.go @@ -0,0 +1,24 @@ +package httpapi + +import "testing" + +func TestValidatePlanBoundaries(t *testing.T) { + valid := adminPlanInput{Name: "标准套餐", StorageBytes: 50 << 30, DatabaseBytes: 20 << 30, BandwidthBytes: 500 << 30, ProcessLimit: 100, FTPLimit: 10, DatabaseLimit: 10, ProjectLimit: 10} + if err := validatePlan(valid); err != nil { + t.Fatalf("valid plan rejected: %v", err) + } + invalid := valid + invalid.ProcessLimit = 0 + if err := validatePlan(invalid); err == nil { + t.Fatal("zero process limit was accepted") + } + invalid = valid + invalid.StorageBytes = 1 << 50 + if err := validatePlan(invalid); err != nil { + t.Fatalf("maximum supported capacity rejected: %v", err) + } + invalid.StorageBytes++ + if err := validatePlan(invalid); err == nil { + t.Fatal("capacity above the supported maximum was accepted") + } +} diff --git a/backend/internal/httpapi/audit_filter.go b/backend/internal/httpapi/audit_filter.go new file mode 100644 index 0000000..3881e0a --- /dev/null +++ b/backend/internal/httpapi/audit_filter.go @@ -0,0 +1,59 @@ +package httpapi + +import ( + "net/http" + "sea-vhost/internal/store" + "strconv" + "time" +) + +func (s *Server) adminAudit(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + limit, _ := strconv.Atoi(q.Get("limit")) + page, _ := strconv.Atoi(q.Get("page")) + if limit == 0 { + limit = 100 + } + if page == 0 { + page = 1 + } + if limit < 1 || limit > 500 || page < 1 || page > 100000 || len(q.Get("q")) > 200 || len(q.Get("action")) > 64 { + writeError(w, 422, "筛选范围无效") + return + } + maxID, e := strconv.ParseUint(q.Get("maxId"), 10, 64) + if q.Get("maxId") != "" && e != nil { + writeError(w, 422, "记录范围无效") + return + } + f := store.AuditFilter{MaxID: maxID, Query: q.Get("q"), Action: q.Get("action"), Result: q.Get("result"), Limit: limit, Page: page} + if f.Result != "" && f.Result != "success" && f.Result != "failure" { + writeError(w, 422, "结果筛选无效") + return + } + for _, field := range []string{"from", "to"} { + if value := q.Get(field); value != "" { + t, err := time.Parse(time.RFC3339, value) + if err != nil { + writeError(w, 422, "时间筛选无效") + return + } + if field == "from" { + f.From = &t + } else { + f.To = &t + } + } + } + if f.From != nil && f.To != nil && !f.From.Before(*f.To) { + writeError(w, 422, "结束时间必须晚于开始时间") + return + } + items, total, err := s.store.FilterAdminActivities(r.Context(), f) + if err != nil { + writeError(w, 500, "无法读取操作日志") + return + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, 200, map[string]any{"logs": items, "total": total, "page": page, "limit": limit}) +} diff --git a/backend/internal/httpapi/auth.go b/backend/internal/httpapi/auth.go new file mode 100644 index 0000000..7ff0d0f --- /dev/null +++ b/backend/internal/httpapi/auth.go @@ -0,0 +1,148 @@ +package httpapi + +import ( + "crypto/sha256" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "sea-vhost/internal/auth" + "sea-vhost/internal/store" +) + +func (s *Server) login(w http.ResponseWriter, r *http.Request) { + started := time.Now() + var input struct { + Identifier string `json:"identifier"` + Email string `json:"email"` + Password string `json:"password"` + TOTPCode string `json:"totpCode"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + identifier := strings.TrimSpace(input.Identifier) + if identifier == "" { + identifier = strings.TrimSpace(input.Email) + } + identifier = strings.ToLower(identifier) + clientIP := requestClientIP(r) + ipKey := "ip:" + clientIP + now := time.Now() + if allowed, retryAfter := s.loginLimiter.allow(ipKey, now, loginIPBurst); !allowed { + writeLoginRateLimit(w, retryAfter) + return + } + validInput := len(identifier) >= 3 && len(identifier) <= 254 && len(input.Password) >= 1 && len(input.Password) <= 128 + identifierKey := "" + if validInput { + digest := sha256.Sum256([]byte(identifier)) + identifierKey = "identifier:" + clientIP + ":" + fmt.Sprintf("%x", digest[:12]) + if allowed, retryAfter := s.loginLimiter.allow(identifierKey, now, loginIdentifierBurst); !allowed { + writeLoginRateLimit(w, retryAfter) + return + } + } + user, err := s.store.UserByLogin(r.Context(), identifier) + validPassword := validInput && err == nil && auth.VerifyPasswordConstantWork(user.PasswordHash, input.Password) + if err != nil || !validInput { + validPassword = auth.VerifyPasswordConstantWork("", input.Password) && validPassword + } + if !validPassword { + s.auditLoginFailure(r, user, identifier, "invalid_credentials") + minimumLoginDelay(started) + writeError(w, http.StatusUnauthorized, "账号、主机名或密码不正确") + return + } + if !oidcPasswordAllowed(s.readServiceConfig(r, "oidc_config"), user.Role) { + s.auditLoginFailure(r, user, identifier, "password_login_disabled") + minimumLoginDelay(started) + writeCodedError(w, 403, "password_login_disabled", "该类账号已关闭密码登录,请使用 SSO 登录") + return + } + if user.MFAEnabled { + security, securityErr := s.store.UserSecurity(r.Context(), user.ID) + if securityErr != nil { + writeError(w, http.StatusInternalServerError, "无法验证双重认证") + return + } + secret, openErr := s.secretBox.Open(mfaSecretLabel(user.ID), security.TOTPSecretCiphertext) + validSecondFactor := openErr == nil && auth.VerifyTOTP(secret, input.TOTPCode, time.Now()) + if !validSecondFactor && strings.TrimSpace(input.TOTPCode) != "" { + validSecondFactor, securityErr = s.store.ConsumeRecoveryCode(r.Context(), user.ID, auth.RecoveryCodeHash(input.TOTPCode)) + } + if securityErr != nil { + writeError(w, http.StatusInternalServerError, "无法验证双重认证") + return + } + if !validSecondFactor { + s.auditLoginFailure(r, user, identifier, "mfa_required") + minimumLoginDelay(started) + writeCodedError(w, http.StatusUnauthorized, "mfa_required", "请输入动态验证码或恢复码") + return + } + } + if err = s.issueSession(w, r, user); err != nil { + writeError(w, http.StatusInternalServerError, "无法创建会话") + return + } + s.clearImpersonation(w) + s.loginLimiter.reset(ipKey, identifierKey) + s.store.Log(r.Context(), user.TenantID, user.ID, "login", "session", "", clientIP, true, "登录 Sea vHost") + writeJSON(w, http.StatusOK, map[string]any{"user": user}) +} + +func (s *Server) issueSession(w http.ResponseWriter, r *http.Request, user store.User) error { + token, err := auth.NewSessionToken(s.cfg.SessionSecret) + if err != nil { + return err + } + expires := time.Now().Add(s.cfg.SessionTTL) + if err = s.store.CreateSession(r.Context(), user.ID, token, expires); err != nil { + return err + } + http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: token, Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, Expires: expires, MaxAge: int(s.cfg.SessionTTL.Seconds())}) + return nil +} + +func minimumLoginDelay(started time.Time) { + if remaining := 350*time.Millisecond - time.Since(started); remaining > 0 { + time.Sleep(remaining) + } +} + +func (s *Server) auditLoginFailure(r *http.Request, user store.User, identifier, reason string) { + digest := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(identifier)))) + resourceID := fmt.Sprintf("%x", digest[:12]) + var userID *uint64 + if user.ID != 0 { + userID = &user.ID + } + s.store.LogEvent(r.Context(), user.TenantID, userID, "login", "session", resourceID, requestClientIP(r), false, reason) +} + +func writeLoginRateLimit(w http.ResponseWriter, retryAfter time.Duration) { + seconds := (retryAfter + time.Second - 1) / time.Second + if seconds < 1 { + seconds = 1 + } + w.Header().Set("Retry-After", strconv.FormatInt(int64(seconds), 10)) + writeError(w, http.StatusTooManyRequests, "登录尝试过于频繁,请稍后再试") +} + +func (s *Server) logout(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + s.store.Log(r.Context(), user.TenantID, user.ID, "logout", "session", "", requestClientIP(r), true, "退出 Sea vHost") + if cookie, err := r.Cookie("sea_session"); err == nil { + _ = s.store.DeleteSession(r.Context(), cookie.Value) + } + http.SetCookie(w, &http.Cookie{Name: "sea_session", Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1}) + s.clearImpersonation(w) + w.WriteHeader(http.StatusNoContent) +} +func (s *Server) me(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"user": currentUser(r)}) +} diff --git a/backend/internal/httpapi/certificates.go b/backend/internal/httpapi/certificates.go new file mode 100644 index 0000000..7cfeb00 --- /dev/null +++ b/backend/internal/httpapi/certificates.go @@ -0,0 +1,81 @@ +package httpapi + +import ( + "errors" + "net/http" + "strconv" + + "sea-vhost/internal/service" + "sea-vhost/internal/store" +) + +func (s *Server) requestAutoCertificate(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + user := currentUser(r) + site, err := s.projects.RequestAutoCertificate(r.Context(), user, projectID, siteID) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "automatic_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "自动证书签发或部署失败") + switch { + case errors.Is(err, service.ErrQuotaSuspended): + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + case errors.Is(err, store.ErrNotFound): + writeError(w, http.StatusNotFound, "虚拟主机或网站不存在") + default: + writeError(w, http.StatusUnprocessableEntity, "自动证书申请失败,请确认全部已启用域名均已解析到本服务器,且公网可访问 80 端口") + } + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "automatic_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "自动证书已签发并部署到网站") + writeJSON(w, http.StatusOK, map[string]any{"site": site}) +} + +func (s *Server) installManualCertificate(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + var input struct { + Certificate string `json:"certificate"` + PrivateKey string `json:"privateKey"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + site, err := s.projects.InstallManualCertificate(r.Context(), user, projectID, siteID, input.Certificate, input.PrivateKey) + if err != nil { + // Deliberately record no certificate or private-key material. The resource + // id is enough to correlate this operation with broker/system logs. + s.store.Log(r.Context(), user.TenantID, user.ID, "install", "manual_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "手动证书校验或安装失败") + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "install", "manual_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "安装用户提供的网站证书并关闭自动续签") + writeJSON(w, http.StatusOK, map[string]any{"site": site}) +} + +func (s *Server) disableCertificate(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + user := currentUser(r) + site, err := s.projects.DisableCertificate(r.Context(), user, projectID, siteID) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "disable", "certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "关闭网站证书失败") + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "disable", "certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "关闭网站 SSL 与自动续签") + writeJSON(w, http.StatusOK, map[string]any{"site": site}) +} diff --git a/backend/internal/httpapi/common_management.go b/backend/internal/httpapi/common_management.go new file mode 100644 index 0000000..9e54aee --- /dev/null +++ b/backend/internal/httpapi/common_management.go @@ -0,0 +1,79 @@ +package httpapi + +import ( + "errors" + "net/http" + "sea-vhost/internal/store" + "strconv" +) + +func (s *Server) deletePlan(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "套餐编号无效") + return + } + var input struct { + Confirmation string `json:"confirmation"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + err = s.store.DeleteUnusedPlan(r.Context(), id, input.Confirmation) + if err != nil { + status := 409 + if errors.Is(err, store.ErrNotFound) { + status = 404 + } + writeError(w, status, err.Error()) + return + } + user := currentUser(r) + s.store.Log(r.Context(), nil, user.ID, "delete", "plan", strconv.FormatUint(id, 10), requestClientIP(r), true, "删除未使用套餐 "+input.Confirmation) + w.WriteHeader(204) +} + +func (s *Server) unbindDomain(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "域名编号无效") + return + } + var input struct { + Confirmation string `json:"confirmation"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + // Authorize before revealing the name or validating confirmation. + user := currentUser(r) + item, err := s.store.DomainByID(r.Context(), id) + if err != nil { + writeError(w, 404, "域名不存在") + return + } + if user.Role != "admin" { + if _, err = s.store.ProjectForUser(r.Context(), user, item.ProjectID); err != nil { + writeError(w, 404, "域名不存在") + return + } + } + if input.Confirmation != item.Domain { + writeError(w, 422, "请准确输入要解绑的域名") + return + } + err = s.projects.UnbindDomain(r.Context(), user, id) + if err != nil { + status := 422 + if errors.Is(err, store.ErrNotFound) { + status = 404 + } + s.store.Log(r.Context(), &item.TenantID, user.ID, "unbind", "domain", item.Domain, requestClientIP(r), false, err.Error()) + writeError(w, status, err.Error()) + return + } + s.store.Log(r.Context(), &item.TenantID, user.ID, "unbind", "domain", item.Domain, requestClientIP(r), true, "解绑自定义域名,保留网站文件、数据库和其他域名") + w.WriteHeader(204) +} diff --git a/backend/internal/httpapi/dns_credentials.go b/backend/internal/httpapi/dns_credentials.go new file mode 100644 index 0000000..63e1864 --- /dev/null +++ b/backend/internal/httpapi/dns_credentials.go @@ -0,0 +1,245 @@ +package httpapi + +import ( + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + "sea-vhost/internal/service" + "sea-vhost/internal/store" +) + +func (s *Server) dnsCredentials(w http.ResponseWriter, r *http.Request) { + s.handleDNSCredentials(w, r, false) +} + +func (s *Server) adminDNSCredentials(w http.ResponseWriter, r *http.Request) { + s.handleDNSCredentials(w, r, true) +} + +func (s *Server) handleDNSCredentials(w http.ResponseWriter, r *http.Request, platform bool) { + user := currentUser(r) + switch r.Method { + case http.MethodGet: + items, err := s.projects.ListDNSCredentials(r.Context(), user, platform) + if err != nil { + writeError(w, http.StatusForbidden, err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"credentials": items}) + case http.MethodPost: + var input service.DNSCredentialInput + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + item, err := s.projects.SaveDNSCredential(r.Context(), user, platform, 0, input) + if err != nil { + writeDNSCredentialError(w, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "create", "dns_credential", strconv.FormatUint(item.ID, 10), requestClientIP(r), true, "新增加密 DNS 凭据 "+item.Provider+" / "+item.ZoneName) + writeJSON(w, http.StatusCreated, map[string]any{"credential": item}) + default: + w.Header().Set("Allow", "GET, POST") + writeError(w, http.StatusMethodNotAllowed, "不支持的请求方法") + } +} + +func (s *Server) dnsCredential(w http.ResponseWriter, r *http.Request) { + s.handleDNSCredential(w, r, false) +} + +func (s *Server) adminDNSCredential(w http.ResponseWriter, r *http.Request) { + s.handleDNSCredential(w, r, true) +} + +func (s *Server) testDNSCredential(w http.ResponseWriter, r *http.Request) { + s.handleTestDNSCredential(w, r, false) +} + +func (s *Server) testAdminDNSCredential(w http.ResponseWriter, r *http.Request) { + s.handleTestDNSCredential(w, r, true) +} + +func (s *Server) handleTestDNSCredential(w http.ResponseWriter, r *http.Request, platform bool) { + id, err := strconv.ParseUint(r.PathValue("credentialID"), 10, 64) + if err != nil || id == 0 { + writeError(w, http.StatusBadRequest, "凭据编号无效") + return + } + user := currentUser(r) + item, testErr := s.projects.TestDNSCredential(r.Context(), user, platform, id) + if testErr != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "test", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), false, "DNS 凭据连通性测试失败") + switch { + case errors.Is(testErr, store.ErrNotFound): + writeError(w, http.StatusNotFound, "DNS 凭据不存在") + case errors.Is(testErr, store.ErrDNSCredentialTestCooldown): + w.Header().Set("Retry-After", "60") + writeError(w, http.StatusTooManyRequests, "DNS 凭据刚刚测试过,请一分钟后重试") + default: + writeError(w, http.StatusUnprocessableEntity, testErr.Error()) + } + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "test", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), true, "随机 TXT 记录已创建并按记录编号删除") + writeJSON(w, http.StatusOK, map[string]any{"credential": item}) +} + +func (s *Server) handleDNSCredential(w http.ResponseWriter, r *http.Request, platform bool) { + id, err := strconv.ParseUint(r.PathValue("credentialID"), 10, 64) + if err != nil || id == 0 { + writeError(w, http.StatusBadRequest, "凭据编号无效") + return + } + user := currentUser(r) + switch r.Method { + case http.MethodPut: + var input service.DNSCredentialInput + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + item, saveErr := s.projects.SaveDNSCredential(r.Context(), user, platform, id, input) + if saveErr != nil { + writeDNSCredentialError(w, saveErr) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "update", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), true, "替换加密 DNS 凭据 "+item.Provider+" / "+item.ZoneName) + writeJSON(w, http.StatusOK, map[string]any{"credential": item}) + case http.MethodDelete: + if err = s.projects.DeleteDNSCredential(r.Context(), user, platform, id); err != nil { + if errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusNotFound, "DNS 凭据不存在") + return + } + if errors.Is(err, store.ErrDNSCredentialInUse) { + writeError(w, http.StatusConflict, "该凭据仍被托管 DNS 记录使用,请先删除对应解析记录") + return + } + writeError(w, http.StatusUnprocessableEntity, "删除 DNS 凭据失败") + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "delete", "dns_credential", strconv.FormatUint(id, 10), requestClientIP(r), true, "删除 DNS 凭据;已签发证书不受影响") + w.WriteHeader(http.StatusNoContent) + default: + w.Header().Set("Allow", "PUT, DELETE") + writeError(w, http.StatusMethodNotAllowed, "不支持的请求方法") + } +} + +func (s *Server) domainDNS(w http.ResponseWriter, r *http.Request) { + s.handleDomainDNS(w, r) +} + +func (s *Server) adminDomainDNS(w http.ResponseWriter, r *http.Request) { + s.handleDomainDNS(w, r) +} + +func (s *Server) handleDomainDNS(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeError(w, http.StatusBadRequest, "域名编号无效") + return + } + user := currentUser(r) + var item store.DomainResource + if r.Method == http.MethodPost { + item, err = s.projects.ProvisionDomainDNS(r.Context(), user, id) + } else if r.Method == http.MethodDelete { + item, err = s.projects.RemoveDomainDNS(r.Context(), user, id) + } else { + w.Header().Set("Allow", "POST, DELETE") + writeError(w, http.StatusMethodNotAllowed, "不支持的请求方法") + return + } + if err != nil { + status := http.StatusUnprocessableEntity + if errors.Is(err, store.ErrNotFound) { + status = http.StatusNotFound + } + s.store.Log(r.Context(), user.TenantID, user.ID, strings.ToLower(r.Method), "domain_dns", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error()) + writeError(w, status, err.Error()) + return + } + action := "创建" + if r.Method == http.MethodDelete { + action = "删除" + } + s.store.Log(r.Context(), user.TenantID, user.ID, strings.ToLower(r.Method), "domain_dns", strconv.FormatUint(id, 10), requestClientIP(r), true, action+"托管 CNAME 记录") + writeJSON(w, http.StatusOK, map[string]any{"domain": item}) +} + +func writeDNSCredentialError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, store.ErrNotFound): + writeError(w, http.StatusNotFound, "DNS 凭据不存在") + case strings.Contains(err.Error(), "保存 DNS 凭据失败"): + writeError(w, http.StatusUnprocessableEntity, "该作用域下已存在相同 DNS 区域,或凭据保存失败") + case strings.Contains(err.Error(), "权限") || strings.Contains(err.Error(), "用户账号"): + writeError(w, http.StatusForbidden, err.Error()) + default: + writeError(w, http.StatusUnprocessableEntity, err.Error()) + } +} + +func (s *Server) requestDNSCertificate(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + user := currentUser(r) + site, automation, err := s.projects.RequestDNSCertificate(r.Context(), user, projectID, siteID) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "dns_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), false, "DNS-01 证书签发失败") + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "issue", "dns_certificate", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "DNS-01 证书已按域名路由签发并部署") + writeJSON(w, http.StatusOK, map[string]any{"site": site, "automation": automation}) +} + +func (s *Server) certificateAutomation(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + item, err := s.projects.CertificateAutomation(r.Context(), currentUser(r), projectID, siteID) + if errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusNotFound, "证书续期配置不存在") + return + } + if err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法读取证书续期状态") + return + } + writeJSON(w, http.StatusOK, map[string]any{"automation": item}) +} + +func (s *Server) discoverDNSZones(w http.ResponseWriter, r *http.Request) { + u := currentUser(r) + if allowed, _ := s.catalogLimiter.allow(fmt.Sprintf("dns-zones:%d", u.ID), time.Now(), 10); !allowed { + writeError(w, 429, "域名读取过于频繁,请稍后再试") + return + } + var input service.DNSCredentialInput + if decodeJSON(r, &input) != nil { + writeError(w, 400, "DNS 票据格式无效") + return + } + zones, err := s.projects.DiscoverDNSZones(r.Context(), u, u.Role == "admin", input) + if err != nil { + writeError(w, 422, err.Error()) + return + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, 200, map[string]any{"zones": zones}) +} diff --git a/backend/internal/httpapi/file_actions.go b/backend/internal/httpapi/file_actions.go new file mode 100644 index 0000000..cfbffaf --- /dev/null +++ b/backend/internal/httpapi/file_actions.go @@ -0,0 +1,102 @@ +package httpapi + +import ( + "net/http" + "path/filepath" + "sea-vhost/internal/nodefiles" + "strings" +) + +func (s *Server) fileActions(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, 400, "主机编号无效") + return + } + user := currentUser(r) + project, err := s.store.Project(r.Context(), *user.TenantID, id) + if err != nil { + writeError(w, 404, "主机不存在") + return + } + root, err := s.projects.OpenFiles(r.Context(), project.Path) + if err != nil { + writeError(w, 503, "文件服务不可用") + return + } + defer root.Close() + if r.Method == "GET" { + out, e := root.Action(nodefiles.Request{Operation: "trash_list"}) + if e != nil { + writeError(w, 422, "无法读取回收站") + return + } + writeJSON(w, 200, map[string]any{"entries": out.Trash}) + return + } + var input struct { + Action string `json:"action"` + Path string `json:"path"` + To string `json:"to"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "文件操作格式无效") + return + } + if !map[string]bool{"mkdir": true, "move": true, "copy": true, "zip": true, "extract": true, "restore": true}[input.Action] { + writeError(w, 422, "不支持此操作") + return + } + if input.Action != "restore" { + source, e := safeProjectName(project.Path, input.Path) + if e != nil || source == "." { + writeError(w, 400, "源路径无效") + return + } + input.Path = filepath.ToSlash(source) + if input.Action=="mkdir"{for _,part:=range strings.Split(input.Path,"/"){if strings.HasPrefix(part,".sea-")||part==".user.ini"{writeError(w,400,"不能创建系统保留目录");return}}} + } + if input.Action != "mkdir" { + dest, e := safeProjectName(project.Path, input.To) + if e != nil || dest == "." { + writeError(w, 400, "目标路径无效") + return + } + input.To = filepath.ToSlash(dest) + } + if input.Action == "move" { + sites, e := s.store.ListSites(r.Context(), project.TenantID, id) + if e != nil { + writeError(w, 503, "无法核对运行目录") + return + } + for _, site := range sites { + run := strings.TrimPrefix(site.RunPath, "/") + if run == input.Path || strings.HasPrefix(run, input.Path+"/") { + writeError(w, 409, "该目录仍被网站使用,请先修改网站运行目录") + return + } + } + } + if err = s.projects.CheckStorageWrite(r.Context(), project.TenantID, 0); err != nil { + writeFileQuotaError(w, err) + return + } + plan, usage, err := s.store.PlanAndUsage(r.Context(), project.TenantID) + if err != nil { + writeError(w, 503, "无法读取主机限额") + return + } + budget := uint64(0) + if usage.StorageBytes < plan.StorageBytes { + budget = plan.StorageBytes - usage.StorageBytes + } + _, err = root.Action(nodefiles.Request{Operation: input.Action, Path: input.Path, To: input.To, Budget: budget}) + if err != nil { + writeError(w, 422, "文件操作未完成:目标必须不存在,路径须在主机目录内;复制/解压总量不得超过剩余空间及 256 MiB") + return + } + _ = s.projects.CheckStorageWrite(r.Context(), project.TenantID, 0) + s.logFile(r, project.TenantID, input.Action, "文件操作 "+input.Action+":"+input.Path) + w.WriteHeader(204) +} diff --git a/backend/internal/httpapi/files.go b/backend/internal/httpapi/files.go new file mode 100644 index 0000000..f1adcb7 --- /dev/null +++ b/backend/internal/httpapi/files.go @@ -0,0 +1,422 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "os" + pathpkg "path" + "path/filepath" + "strconv" + "strings" + "time" + + fileguard "sea-vhost/internal/files" + "sea-vhost/internal/nodefiles" + "sea-vhost/internal/scope" + "sea-vhost/internal/service" + "sea-vhost/internal/store" +) + +type fileEntry struct { + Name string `json:"name"` + Path string `json:"path"` + Directory bool `json:"directory"` + Size int64 `json:"size"` + Modified time.Time `json:"modified"` +} + +func (s *Server) files(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "项目编号无效") + return + } + user := currentUser(r) + if user.ProjectID != nil && *user.ProjectID != id { + writeError(w, http.StatusNotFound, "项目不存在") + return + } + project, err := s.store.Project(r.Context(), *user.TenantID, id) + if err != nil { + writeError(w, http.StatusNotFound, "项目不存在") + return + } + if r.Method != http.MethodGet { + tracked := &fileAuditResponse{ResponseWriter: w} + w = tracked + defer func() { + if tracked.status >= 400 { + s.logFile(r, project.TenantID, "file_operation", fmt.Sprintf("文件操作失败(HTTP %d)", tracked.status)) + } + }() + } + switch r.Method { + case http.MethodGet: + s.listFiles(w, r, project.Path) + case http.MethodPost: + s.uploadFile(w, r, project.TenantID, project.Path) + case http.MethodPut: + s.writeTextFile(w, r, project.TenantID, project.Path) + case http.MethodDelete: + s.trashFile(w, r, user, project.ID, project.TenantID, project.Path) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +type fileAuditResponse struct { + http.ResponseWriter + status int +} + +func (w *fileAuditResponse) WriteHeader(status int) { + if w.status == 0 { + w.status = status + w.ResponseWriter.WriteHeader(status) + } +} +func (w *fileAuditResponse) Write(body []byte) (int, error) { + if w.status == 0 { + w.WriteHeader(http.StatusOK) + } + return w.ResponseWriter.Write(body) +} +func (s *Server) logFile(r *http.Request, tenantID uint64, action, detail string) { + user := currentUser(r) + s.store.Log(r.Context(), &tenantID, user.ID, action, "file", strconv.FormatUint(scope.Project(r.Context()), 10), requestClientIP(r), action != "file_operation", detail) +} + +func safeProjectPath(root, requested string) (string, error) { + path, err := fileguard.Resolve(root, requested) + if err != nil { + return "", err + } + if err = fileguard.RejectSymlinks(root, path); err != nil { + return "", err + } + return path, nil +} + +func safeProjectName(root, requested string) (string, error) { + absolute, err := fileguard.Resolve(root, requested) + if err != nil { + return "", err + } + relative, err := filepath.Rel(root, absolute) + if err != nil { + return "", err + } + if relative == "." { + return ".", nil + } + virtualPath := filepath.ToSlash(relative) + if nodefiles.IsProtectedPath(virtualPath) { + return "", fileguard.ErrOutsideRoot + } + return relative, nil +} + +func displayProjectName(name string) string { + if name == "." { + return "" + } + return filepath.ToSlash(name) +} + +func (s *Server) listFiles(w http.ResponseWriter, r *http.Request, root string) { + requested := r.URL.Query().Get("path") + name, err := safeProjectName(root, requested) + if err != nil { + writeError(w, http.StatusBadRequest, "路径无效") + return + } + projectRoot, err := s.projects.OpenFiles(r.Context(), root) + if err != nil { + writeError(w, http.StatusNotFound, "项目目录不存在") + return + } + defer projectRoot.Close() + if r.URL.Query().Get("download") == "1" { + s.downloadFile(w, r, projectRoot, name) + return + } + directory, err := projectRoot.Open(name) + if err != nil { + writeError(w, http.StatusNotFound, "目录不存在") + return + } + defer directory.Close() + entries, err := directory.ReadDir(-1) + if err != nil { + writeError(w, http.StatusNotFound, "目录不存在") + return + } + result := make([]fileEntry, 0, len(entries)) + for _, entry := range entries { + if nodefiles.IsProtectedPath(entry.Name()) { + continue + } + info, err := entry.Info() + if err != nil { + continue + } + result = append(result, fileEntry{Name: entry.Name(), Path: displayProjectName(filepath.Join(name, entry.Name())), Directory: entry.IsDir(), Size: info.Size(), Modified: info.ModTime()}) + } + writeJSON(w, http.StatusOK, map[string]any{"path": displayProjectName(name), "entries": result, "uploadLimit": s.cfg.UploadLimitBytes}) +} +func (s *Server) downloadFile(w http.ResponseWriter, r *http.Request, root *nodefiles.Root, name string) { + file, err := root.Open(name) + if err != nil { + writeError(w, http.StatusNotFound, "文件不存在") + return + } + defer file.Close() + info, err := file.Stat() + if err != nil || info.IsDir() { + writeError(w, http.StatusNotFound, "文件不存在") + return + } + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filepath.Base(name))) + http.ServeContent(w, r, filepath.Base(name), info.ModTime(), file) +} + +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)) + return + } + if r.MultipartForm != nil { + defer r.MultipartForm.RemoveAll() + } + source, header, err := r.FormFile("file") + if err != nil { + writeError(w, http.StatusBadRequest, "缺少上传文件") + return + } + defer source.Close() + dir, err := safeProjectName(root, r.FormValue("path")) + if err != nil { + writeError(w, http.StatusBadRequest, "路径无效") + return + } + name := filepath.Base(strings.ReplaceAll(header.Filename, "\\", "/")) + if name == "." || name == ".." || name == "" { + writeError(w, http.StatusBadRequest, "文件名无效") + return + } + target, err := safeProjectName(root, pathpkg.Join(dir, name)) + if err != nil { + writeError(w, http.StatusBadRequest, "路径无效") + return + } + flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL + if r.FormValue("overwrite") == "true" { + flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC + } + projectRoot, err := s.projects.OpenFiles(r.Context(), root) + if err != nil { + writeError(w, http.StatusNotFound, "项目目录不存在") + return + } + defer projectRoot.Close() + if header.Size < 0 || header.Size > s.cfg.UploadLimitBytes { + writeError(w, http.StatusBadRequest, "无法确定上传文件大小") + return + } + additionalBytes := uint64(header.Size) + if r.FormValue("overwrite") == "true" { + if existing, statErr := projectRoot.Lstat(target); statErr == nil && existing.Mode().IsRegular() && existing.Size() > 0 { + oldSize := uint64(existing.Size()) + if oldSize >= additionalBytes { + additionalBytes = 0 + } else { + additionalBytes -= oldSize + } + } + } + if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additionalBytes); err != nil { + writeFileQuotaError(w, err) + return + } + destination, err := projectRoot.OpenFile(target, flag, 0660) + if err != nil { + writeError(w, http.StatusConflict, "文件已存在或不可写") + return + } + defer destination.Abort() + written, err := io.Copy(destination, io.LimitReader(source, s.cfg.UploadLimitBytes+1)) + if err != nil || written > s.cfg.UploadLimitBytes { + writeError(w, http.StatusRequestEntityTooLarge, uploadLimitMessage(s.cfg.UploadLimitBytes)) + return + } + if err = destination.Close(); err != nil { + writeFileCommitError(w, err) + return + } + s.logFile(r, tenantID, "upload", "上传文件:"+filepath.ToSlash(target)) + writeJSON(w, http.StatusCreated, map[string]any{"name": name, "size": written}) +} + +func uploadLimitMessage(limit int64) string { + return fmt.Sprintf("单文件不能超过 %d MB", (limit+(1024*1024)-1)/(1024*1024)) +} + +func (s *Server) writeTextFile(w http.ResponseWriter, r *http.Request, tenantID uint64, root string) { + var input struct { + Path string `json:"path"` + Content string `json:"content"` + Overwrite bool `json:"overwrite"` + } + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误或文本文件超过 1 MB") + return + } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + path, err := safeProjectName(root, input.Path) + if err != nil { + writeError(w, http.StatusBadRequest, "路径无效") + return + } + projectRoot, err := s.projects.OpenFiles(r.Context(), root) + if err != nil { + writeError(w, http.StatusNotFound, "项目目录不存在") + return + } + defer projectRoot.Close() + additionalBytes := uint64(len(input.Content)) + if input.Overwrite { + if existing, statErr := projectRoot.Lstat(path); statErr == nil && existing.Mode().IsRegular() && existing.Size() > 0 { + oldSize := uint64(existing.Size()) + if oldSize >= additionalBytes { + additionalBytes = 0 + } else { + additionalBytes -= oldSize + } + } + } + if err = s.projects.CheckStorageWrite(r.Context(), tenantID, additionalBytes); err != nil { + writeFileQuotaError(w, err) + return + } + flag := os.O_WRONLY | os.O_CREATE | os.O_EXCL + if input.Overwrite { + flag = os.O_WRONLY | os.O_CREATE | os.O_TRUNC + } + destination, err := projectRoot.OpenFile(path, flag, 0660) + if err != nil { + writeError(w, http.StatusConflict, "文件已存在或不可写") + return + } + defer destination.Abort() + if _, err = destination.Write([]byte(input.Content)); err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法保存文件") + return + } + if err = destination.Close(); err != nil { + writeFileCommitError(w, err) + return + } + s.logFile(r, tenantID, "write", "保存文本文件:"+filepath.ToSlash(path)) + w.WriteHeader(http.StatusNoContent) +} + +func writeFileCommitError(w http.ResponseWriter, err error) { + if errors.Is(err, os.ErrExist) { + writeError(w, http.StatusConflict, "文件已存在,确认后才可覆盖") + return + } + writeError(w, http.StatusUnprocessableEntity, "文件提交失败,请刷新目录核对后再操作") +} + +func writeFileQuotaError(w http.ResponseWriter, err error) { + if errors.Is(err, store.ErrManagementLocked) { + writeCodedError(w, 423, "management_locked", err.Error()) + return + } + if errors.Is(err, store.ErrHostNotWritable) { + writeCodedError(w, http.StatusLocked, "host_not_writable", err.Error()) + return + } + if errors.Is(err, service.ErrQuotaSuspended) { + writeCodedError(w, http.StatusLocked, "quota_suspended", "资源套餐已超额,当前仅允许读取或永久清理数据") + return + } + if errors.Is(err, service.ErrStorageQuotaExceeded) { + writeCodedError(w, http.StatusInsufficientStorage, "storage_quota_exceeded", "存储空间不足,请先永久删除文件或清空回收站") + return + } + slog.Warn("file quota verification unavailable", "error", err) + w.Header().Set("Retry-After", "3") + writeCodedError(w, http.StatusServiceUnavailable, "resource_check_unavailable", "暂时无法核对资源用量,请稍后重试") +} + +func (s *Server) trashFile(w http.ResponseWriter, r *http.Request, user store.User, projectID, tenantID uint64, root string) { + if r.URL.Query().Get("emptyTrash") == "1" { + if err := s.projects.PrepareTrash(r.Context(), user, projectID); err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法安全清空回收站") + return + } + projectRoot, err := s.projects.OpenFiles(r.Context(), root) + if err != nil { + writeError(w, http.StatusNotFound, "项目目录不存在") + return + } + defer projectRoot.Close() + if err = projectRoot.RemoveAll(".sea-trash"); err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法清空回收站") + return + } + // Refresh immediately so a tenant that has cleaned enough data does not + // have to wait for the next one-minute monitor cycle. + _ = s.projects.CheckStorageWrite(r.Context(), tenantID, 0) + s.logFile(r, tenantID, "empty_trash", "清空主机回收站") + w.WriteHeader(http.StatusNoContent) + return + } + path, err := safeProjectName(root, r.URL.Query().Get("path")) + if err != nil || path == "." { + writeError(w, http.StatusBadRequest, "路径无效") + return + } + path = filepath.ToSlash(path) + if path == ".sea-trash" || strings.HasPrefix(path, ".sea-trash/") { + writeError(w, http.StatusBadRequest, "路径无效") + return + } + sites, err := s.store.ListSites(r.Context(), tenantID, projectID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法核对网站运行目录") + return + } + candidate := "/" + strings.TrimPrefix(path, "/") + for _, site := range sites { + runPath := filepath.ToSlash(filepath.Clean(site.RunPath)) + if candidate == runPath || strings.HasPrefix(runPath, candidate+"/") { + writeError(w, http.StatusConflict, "该目录仍被网站使用,请先删除或修改网站") + return + } + } + projectRoot, err := s.projects.OpenFiles(r.Context(), root) + if err != nil { + writeError(w, http.StatusNotFound, "项目目录不存在") + return + } + defer projectRoot.Close() + if _, err = projectRoot.Action(nodefiles.Request{Operation: "trash", Path: path}); err != nil { + writeError(w, http.StatusUnprocessableEntity, "无法移动到回收站") + return + } + + s.logFile(r, tenantID, "trash", "移入回收站:"+path) + w.WriteHeader(http.StatusNoContent) +} diff --git a/backend/internal/httpapi/files_test.go b/backend/internal/httpapi/files_test.go new file mode 100644 index 0000000..0d08164 --- /dev/null +++ b/backend/internal/httpapi/files_test.go @@ -0,0 +1,126 @@ +package httpapi + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + fileguard "sea-vhost/internal/files" + "sea-vhost/internal/nodefiles" + "sea-vhost/internal/service" +) + +func TestBufferedFileCommitConflictReturns409WithoutOverwriting(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "existing.txt") + if err := os.WriteFile(path, []byte("original-content"), 0600); err != nil { + t.Fatal(err) + } + root := nodefiles.New(context.Background(), "sv0123456789", func(_ context.Context, request nodefiles.Request) (nodefiles.Response, error) { + return nodefiles.Execute(dir, request), nil + }) + file, err := root.OpenFile("existing.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + t.Fatal(err) + } + defer file.Abort() + if _, err = file.Write([]byte("unconfirmed-replacement")); err != nil { + t.Fatal(err) + } + err = file.Close() + if !errors.Is(err, os.ErrExist) { + t.Fatalf("expected a commit-time conflict, got %v", err) + } + response := httptest.NewRecorder() + writeFileCommitError(response, err) + if response.Code != http.StatusConflict { + t.Fatalf("commit conflict must be HTTP 409, got %d", response.Code) + } + data, err := os.ReadFile(path) + if err != nil || string(data) != "original-content" { + t.Fatalf("unconfirmed upload changed existing content: %v", err) + } +} + +func TestFileCommitFailureDoesNotExposeInternalDetails(t *testing.T) { + response := httptest.NewRecorder() + writeFileCommitError(response, errors.New("private-path-and-diagnostic")) + if response.Code != http.StatusUnprocessableEntity || strings.Contains(response.Body.String(), "private-path-and-diagnostic") { + t.Fatalf("unsafe commit failure: %d %s", response.Code, response.Body.String()) + } +} + +func TestFileQuotaFailureRemainsClosedAndDoesNotExposeInternalError(t *testing.T) { + for _, test := range []struct { + err error + want int + }{ + {service.ErrQuotaSuspended, http.StatusLocked}, + {service.ErrStorageQuotaExceeded, http.StatusInsufficientStorage}, + {errors.New("internal database diagnostic"), http.StatusServiceUnavailable}, + } { + response := httptest.NewRecorder() + writeFileQuotaError(response, test.err) + if response.Code != test.want || strings.Contains(response.Body.String(), "internal database diagnostic") { + t.Fatalf("unsafe quota response: %d %s", response.Code, response.Body.String()) + } + if test.want == http.StatusServiceUnavailable && response.Header().Get("Retry-After") != "3" { + t.Fatal("temporarily unavailable verification must indicate when to retry") + } + } +} + +func TestSafeProjectNameRejectsAmbiguousAndInternalPaths(t *testing.T) { + root := t.TempDir() + for _, requested := range []string{ + "../outside", + "public/../outside", + "public//index.html", + `.sea-trash`, + `.sea-trash/deleted.txt`, + } { + if _, err := safeProjectName(root, requested); !errors.Is(err, fileguard.ErrOutsideRoot) { + t.Errorf("safeProjectName(%q) error = %v, want ErrOutsideRoot", requested, err) + } + } +} + +func TestProjectRootBlocksSymlinkSwapOutsideTenant(t *testing.T) { + base := t.TempDir() + root := filepath.Join(base, "project") + outside := filepath.Join(base, "outside.txt") + if err := os.Mkdir(root, 0750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(outside, []byte("root-equivalent-secret"), 0600); err != nil { + t.Fatal(err) + } + victim := filepath.Join(root, "config.txt") + if err := os.WriteFile(victim, []byte("tenant-data"), 0640); err != nil { + t.Fatal(err) + } + name, err := safeProjectName(root, "config.txt") + if err != nil { + t.Fatal(err) + } + if err = os.Remove(victim); err != nil { + t.Fatal(err) + } + if err = os.Symlink(outside, victim); err != nil { + t.Skipf("symlink creation is unavailable: %v", err) + } + + projectRoot, err := os.OpenRoot(root) + if err != nil { + t.Fatal(err) + } + defer projectRoot.Close() + if _, err = projectRoot.ReadFile(name); err == nil { + t.Fatal("directory-scoped file operation followed a swapped symlink outside the tenant root") + } +} diff --git a/backend/internal/httpapi/ftp_management.go b/backend/internal/httpapi/ftp_management.go new file mode 100644 index 0000000..5793111 --- /dev/null +++ b/backend/internal/httpapi/ftp_management.go @@ -0,0 +1,3 @@ +package httpapi +import("net/http";"strconv") +func(s *Server)manageFTP(w http.ResponseWriter,r *http.Request){id,_:=projectID(r);var input struct{Action string `json:"action"`};if decodeJSON(r,&input)!=nil{writeError(w,400,"操作格式无效");return};password,e:=s.projects.ManageFTP(r.Context(),currentUser(r),id,input.Action);u:=currentUser(r);s.store.Log(r.Context(),u.TenantID,u.ID,input.Action,"ftp",strconv.FormatUint(id,10),requestClientIP(r),e==nil,"管理主机 FTP:"+input.Action);if e!=nil{writeError(w,422,e.Error());return};writeJSON(w,200,map[string]any{"password":password})} diff --git a/backend/internal/httpapi/hosting_features_integration_test.go b/backend/internal/httpapi/hosting_features_integration_test.go new file mode 100644 index 0000000..52154c2 --- /dev/null +++ b/backend/internal/httpapi/hosting_features_integration_test.go @@ -0,0 +1,243 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/go-sql-driver/mysql" + "net/http" + "net/http/httptest" + "os" + "sea-vhost/internal/auth" + "sea-vhost/internal/config" + "sea-vhost/internal/hosting" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/service" + "sea-vhost/internal/store" + "strings" + "testing" + "time" +) + +func TestHostingFeaturesMySQL(t *testing.T) { + dsn := os.Getenv("SEA_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("disposable MySQL schema not supplied") + } + parsed, e := mysql.ParseDSN(dsn) + if e != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") { + t.Fatal("refusing a non-test schema") + } + db, e := store.Open(dsn) + if e != nil { + t.Fatal(e) + } + defer db.Close() + ctx := context.Background() + if e = db.Migrate(ctx); e != nil { + t.Fatal(e) + } + if e = db.BootstrapAdmin(ctx, "features-admin@example.invalid", "功能测试管理员", "features-admin-password-123"); e != nil { + t.Fatal(e) + } + root := t.TempDir() + if e = db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid"); e != nil { + t.Fatal(e) + } + admin, _ := db.UserByLogin(ctx, "features-admin@example.invalid") + secret := "features-test-secret-longer-than-thirty-two-characters" + native := panel.NewMock() + 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) + handler := server.Handler() + session := func(u store.User) string { + token, e := auth.NewSessionToken(secret) + if e != nil { + t.Fatal(e) + } + if e = db.CreateSession(ctx, u.ID, token, time.Now().Add(time.Hour)); e != nil { + t.Fatal(e) + } + return token + } + adminToken := session(admin) + call := func(method, path string, body any, token, bearer, idempotency string) *httptest.ResponseRecorder { + var b bytes.Buffer + if body != nil { + json.NewEncoder(&b).Encode(body) + } + r := httptest.NewRequest(method, "https://control.example.invalid"+path, &b) + r.Header.Set("Origin", "https://control.example.invalid") + r.Header.Set("Content-Type", "application/json") + if token != "" { + r.AddCookie(&http.Cookie{Name: "sea_session", Value: token}) + } + if bearer != "" { + r.Header.Set("Authorization", "Bearer "+bearer) + } + if idempotency != "" { + r.Header.Set("Idempotency-Key", idempotency) + } + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + return w + } + expect := func(w *httptest.ResponseRecorder, status int) { + t.Helper() + if w.Code != status { + t.Fatalf("got %d want %d: %s", w.Code, status, w.Body.String()) + } + } + plans, _ := db.ListPlans(ctx) + user := func(slug string) store.User { + w := call("POST", "/api/v1/admin/tenants", map[string]any{"slug": slug, "name": slug, "displayName": slug, "planId": plans[0].ID, "email": slug + "@example.invalid", "password": "features-user-password-123"}, adminToken, "", "") + expect(w, 201) + u, e := db.UserByLogin(ctx, slug+"@example.invalid") + if e != nil { + t.Fatal(e) + } + return u + } + a, b := user("features-a"), user("features-b") + aToken, bToken := session(a), session(b) + created, e := projects.CreateManagedHost(ctx, *a.TenantID, service.CreateProjectInput{Name: "features-host", NodeID: 1, PlanID: plans[0].ID, Runtime: "PHP", Version: "8.4", RunPath: "/public"}) + if e != nil { + t.Fatal(e) + } + p := created.Project + scoped := scope.WithProject(scope.WithAccount(ctx, *a.TenantID), p.ID, p.NodeID) + sites, e := db.ListSites(scoped, p.TenantID, p.ID) + if e != nil || len(sites) != 1 { + t.Fatal("site missing", e) + } + site := sites[0] + base := fmt.Sprintf("/api/v1/projects/%d", p.ID) + hostUser, e := db.UserByLogin(ctx, p.HostName) + if e != nil { + t.Fatal(e) + } + hostToken := session(hostUser) + settings := hosting.DefaultWebsite() + settings.Index = []string{"home.html", "index.php"} + settings.Maintenance = true + expect(call("PUT", fmt.Sprintf("%s/sites/%d/settings", base, site.ID), settings, aToken, "", ""), 204) + expect(call("GET", fmt.Sprintf("%s/sites/%d/settings", base, site.ID), nil, bToken, "", ""), 404) + startup := hosting.Startup{WorkDir: ".", Environment: map[string]string{"APP_SECRET": "features-encrypted-marker"}} + expect(call("PUT", fmt.Sprintf("%s/sites/%d/startup", base, site.ID), startup, aToken, "", ""), 204) + cipher, e := db.StartupCipher(ctx, site.ID) + if e != nil || bytes.Contains(cipher, []byte("features-encrypted-marker")) { + t.Fatal("environment not encrypted") + } + startup.Environment["LD_PRELOAD"] = "evil.so" + expect(call("PUT", fmt.Sprintf("%s/sites/%d/startup", base, site.ID), startup, aToken, "", ""), 422) + expect(call("POST", base+"/ftp", map[string]string{"action": "disable"}, aToken, "", ""), 200) + ftp, e := db.ListFTPResources(scoped, p.TenantID, &p.ID) + if e != nil || ftp[0].Enabled { + t.Fatal("FTP disable not persisted", e) + } + expect(call("POST", base+"/ftp", map[string]string{"action": "reset"}, aToken, "", ""), 200) + expect(call("POST", base+"/ftp", map[string]string{"action": "enable"}, aToken, "", ""), 200) + expect(call("GET", base+"/database-admin/", nil, aToken, "", ""), 200) + expect(call("GET", base+"/database-admin/", nil, bToken, "", ""), 404) + task := store.UserSchedule{ProjectID: p.ID, SiteID: site.ID, Name: "功能测试任务", Cron: "*/5 * * * *", Timezone: "Asia/Shanghai", Kind: "php", Version: "8.4", Target: "task.php", Arguments: []string{"features-task-secret"}, Enabled: false} + expect(call("GET", "/api/v1/schedules", nil, hostToken, "", ""), 403) + expect(call("POST", "/api/v1/schedules", task, hostToken, "", ""), 403) + w := call("POST", "/api/v1/schedules", task, aToken, "", "") + expect(w, 200) + var id struct { + ID uint64 `json:"id"` + } + json.Unmarshal(w.Body.Bytes(), &id) + taskID := id.ID + saved, e := db.UserSchedule(ctx, a.ID, taskID) + if e != nil || bytes.Contains(saved.ConfigCipher, []byte("features-task-secret")) || saved.Target != "" { + t.Fatal("task inputs not encrypted", e) + } + expect(call("GET", fmt.Sprintf("/api/v1/schedules/%d/runs", taskID), nil, bToken, "", ""), 404) + expect(call("POST", fmt.Sprintf("/api/v1/schedules/%d/run", taskID), nil, aToken, "", ""), 200) + if e = projects.DispatchUserSchedules(ctx); e != nil { + t.Fatal(e) + } + runs, e := projects.ScheduleRuns(ctx, a, taskID) + if e != nil || len(runs) != 1 || runs[0].State != "succeeded" { + t.Fatalf("scheduled run %+v %v", runs, e) + } + for i := 0; i < 9; i++ { + task.Name = fmt.Sprint("任务", i) + expect(call("POST", "/api/v1/schedules", task, aToken, "", ""), 200) + } + expect(call("POST", "/api/v1/schedules", task, aToken, "", ""), 422) + version, _ := db.ProjectOwnershipVersion(ctx, p.ID) + if _, e = db.BeginOwnershipChange(ctx, p.ID, version, *b.TenantID, "preserve", false, false, nil); e != nil { + t.Fatal(e) + } + saved, e = db.UserSchedule(ctx, a.ID, taskID) + if e != nil || saved.Enabled || saved.LastState != "ownership_paused" { + t.Fatal("ownership change failed to pause task", e) + } + expect(call("POST", fmt.Sprintf("/api/v1/schedules/%d/run", taskID), nil, aToken, "", ""), 422) + makeKey := func(scopes []string) (uint64, string) { + w := call("POST", "/api/v1/admin/integration-keys", map[string]any{"name": "测试 API", "scopes": scopes, "expiresAt": time.Now().Add(time.Hour)}, adminToken, "", "") + expect(w, 201) + var v struct { + ID uint64 `json:"id"` + Token string `json:"token"` + } + json.Unmarshal(w.Body.Bytes(), &v) + return v.ID, v.Token + } + _, readKey := makeKey([]string{"hosts:read", "tasks:read"}) + expect(call("GET", "/api/integration/v1/hosts", nil, "", readKey, ""), 200) + expect(call("GET", "/api/integration/v1/users", nil, "", readKey, ""), 403) + expect(call("GET", "/api/integration/v1/hosts", nil, adminToken, "", ""), 401) + expect(call("POST", "/api/v1/admin/integration-keys", map[string]any{}, aToken, "", ""), 403) + keyID, key := makeKey([]string{"users:write", "users:read", "tasks:read", "credentials:read"}) + input := map[string]any{"rows": []map[string]string{{"slug": "api-user", "name": "API 用户", "email": "api-user@example.invalid"}}} + expect(call("POST", "/api/integration/v1/users", input, "", key, ""), 400) + w = call("POST", "/api/integration/v1/users", input, "", key, "feature-idempotency-1") + expect(w, 202) + var job struct { + Batch store.AdminBatch `json:"batch"` + } + json.Unmarshal(w.Body.Bytes(), &job) + batchID := job.Batch.ID + w = call("POST", "/api/integration/v1/users", input, "", key, "feature-idempotency-1") + expect(w, 202) + json.Unmarshal(w.Body.Bytes(), &job) + if job.Batch.ID != batchID { + t.Fatal("idempotency duplicated batch") + } + expect(call("POST", "/api/integration/v1/users", map[string]any{"rows": []batchRow{{Slug: "changed-user", Name: "changed", Email: "changed@example.invalid"}}}, "", key, "feature-idempotency-1"), 409) + expect(call("GET", fmt.Sprintf("/api/integration/v1/tasks/%d", batchID), nil, "", readKey, ""), 404) + expect(call("GET", fmt.Sprintf("/api/integration/v1/tasks/%d", batchID), nil, "", key, ""), 200) + expect(call("DELETE", fmt.Sprintf("/api/v1/admin/integration-keys/%d", keyID), nil, adminToken, "", ""), 204) + expect(call("GET", "/api/integration/v1/users", nil, "", key, ""), 401) + jobRecord, item, e := db.NextAdminBatchItem(ctx) + if e != nil { + t.Fatal(e) + } + server.executeBatchItem(ctx, jobRecord, item) + jobRecord, e = db.AdminBatch(ctx, batchID, false) + if e != nil || jobRecord.Items[0].State != "failed" { + t.Fatal("revoked key still executed queued work", e) + } + cancelled, cancel := context.WithCancel(scope.WithProject(ctx, p.ID, p.NodeID)) + cancel() + db.Log(cancelled, &p.TenantID, a.ID, "update", "file", "cancel-audit", "", true, "completed-before-disconnect") + logs, e := db.AdminActivities(ctx, 100) + if e != nil { + t.Fatal(e) + } + found := false + for _, log := range logs { + if log.Detail == "completed-before-disconnect" { + found = true + } + } + if !found { + t.Fatal("request cancellation discarded a completed operation audit") + } +} diff --git a/backend/internal/httpapi/impersonation.go b/backend/internal/httpapi/impersonation.go new file mode 100644 index 0000000..b51cfd1 --- /dev/null +++ b/backend/internal/httpapi/impersonation.go @@ -0,0 +1,78 @@ +package httpapi + +import ( + "context" + "net/http" + "sea-vhost/internal/auth" + "sea-vhost/internal/store" + "strconv" + "time" +) + +const realAdministratorKey contextKey = "real_administrator" +const impersonationCookie = "sea_impersonation" + +func (s *Server) startImpersonation(w http.ResponseWriter, r *http.Request) { + var input struct { + TenantID uint64 `json:"tenantId"` + ProjectID uint64 `json:"projectId"` + } + if decodeJSON(r, &input) != nil || (input.TenantID == 0) == (input.ProjectID == 0) { + writeError(w, 400, "请选择一个用户或主机") + return + } + target, err := s.store.ImpersonationTarget(r.Context(), input.TenantID, input.ProjectID) + if err != nil { + writeError(w, 404, "目标账号不存在或不可用") + return + } + parent, err := r.Cookie("sea_session") + if err != nil { + writeError(w, 401, "管理员登录已失效") + return + } + token, err := auth.NewSessionToken(s.cfg.SessionSecret) + if err != nil { + writeError(w, 500, "无法建立代入会话") + return + } + administrator := currentUser(r) + expires := time.Now().Add(30 * time.Minute) + if err = s.store.CreateImpersonation(r.Context(), parent.Value, token, administrator.ID, target.ID, expires); err != nil { + writeError(w, 500, "无法建立代入会话") + return + } + target, err = s.store.ImpersonationUser(r.Context(), parent.Value, token, administrator.ID) + if err != nil { + writeError(w, 500, "无法核对代入权限") + return + } + http.SetCookie(w, &http.Cookie{Name: impersonationCookie, Value: token, Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, Expires: *target.ImpersonationExpiresAt, MaxAge: int(time.Until(*target.ImpersonationExpiresAt).Seconds())}) + s.store.Log(r.Context(), target.TenantID, administrator.ID, "start", "impersonation", strconv.FormatUint(target.ID, 10), requestClientIP(r), true, "管理员快捷进入 "+target.Role+" 账号 "+target.LoginName) + writeJSON(w, 200, map[string]any{"user": target}) +} + +func (s *Server) stopImpersonation(w http.ResponseWriter, r *http.Request) { + administrator, ok := r.Context().Value(realAdministratorKey).(store.User) + if !ok { + administrator = currentUser(r) + } + if administrator.Role != "admin" { + writeError(w, 403, "需要原管理员会话") + return + } + parent, _ := r.Cookie("sea_session") + child, _ := r.Cookie(impersonationCookie) + if parent != nil && child != nil { + if err := s.store.StopImpersonation(r.Context(), parent.Value, child.Value); err != nil { + writeError(w, 500, "无法退出代入会话") + return + } + } + s.clearImpersonation(w) + s.store.Log(context.WithoutCancel(r.Context()), nil, administrator.ID, "stop", "impersonation", "", requestClientIP(r), true, "管理员退出代入模式") + writeJSON(w, 200, map[string]any{"user": administrator}) +} +func (s *Server) clearImpersonation(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{Name: impersonationCookie, Value: "", Path: "/", HttpOnly: true, Secure: s.cfg.CookieSecure, SameSite: http.SameSiteStrictMode, MaxAge: -1}) +} diff --git a/backend/internal/httpapi/impersonation_integration_test.go b/backend/internal/httpapi/impersonation_integration_test.go new file mode 100644 index 0000000..81da94b --- /dev/null +++ b/backend/internal/httpapi/impersonation_integration_test.go @@ -0,0 +1,214 @@ +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/scope" + "sea-vhost/internal/service" + "sea-vhost/internal/store" + "strconv" + "strings" + "testing" + "time" +) + +func TestAdministratorImpersonationMySQL(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() + if err = db.Migrate(ctx); err != nil { + t.Fatal(err) + } + if err = db.BootstrapAdmin(ctx, "imp-admin@example.invalid", "测试管理员", "test-admin-password-123"); err != nil { + t.Fatal(err) + } + administrator, err := db.UserByLogin(ctx, "imp-admin@example.invalid") + if err != nil { + t.Fatal(err) + } + plans, _ := db.ListPlans(ctx) + tenant, err := db.CreateTenant(ctx, store.NewTenant{Slug: "imp-test", Name: "代入测试用户", Email: "imp-user@example.invalid", DisplayName: "测试用户", Password: "test-user-password-123", PlanID: plans[0].ID}) + if err != nil { + t.Fatal(err) + } + customer, err := db.UserByLogin(ctx, "imp-user@example.invalid") + if err != nil { + t.Fatal(err) + } + hosts := []uint64{} + for _, name := range []string{"sv7777777777", "sv8888888888"} { + id, e := db.InsertProject(ctx, store.NewProject{NodeID: 1, PlanID: plans[0].ID, TenantID: tenant, HostName: name, Slug: name, Runtime: "PHP", Version: "8.4", Path: "/www/wwwroot/seavHost/vHost/" + name, RunPath: "/public", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-only-hash"}) + if e != nil { + t.Fatal(e) + } + if e = db.CompleteProject(scope.WithProject(ctx, id, 1), id, int64(1000+id), int64(2000+id), int64(3000+id), name, name, name, []byte("test"), []byte("test"), "running", "", "", false); e != nil { + t.Fatal(e) + } + hosts = append(hosts, id) + } + secret := "integration-session-secret-at-least-32-characters" + makeSession := func(id uint64) string { + token, e := auth.NewSessionToken(secret) + if e != nil { + t.Fatal(e) + } + if e = db.CreateSession(ctx, id, token, time.Now().Add(time.Hour)); e != nil { + t.Fatal(e) + } + return token + } + parent, otherParent, userToken := makeSession(administrator.ID), makeSession(administrator.ID), makeSession(customer.ID) + projects := service.NewProjects(db, &panel.Mock{}, isolation.Mock{}, "hosts.example.invalid", "/www/wwwroot/seavHost/vHost", true, secret, "control.example.invalid") + server := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects).Handler() + call := func(path, method string, body any, parent, child string) *httptest.ResponseRecorder { + var buffer bytes.Buffer + if body != nil { + _ = json.NewEncoder(&buffer).Encode(body) + } + request := httptest.NewRequest(method, "https://control.example.invalid"+path, &buffer) + request.Header.Set("Origin", "https://control.example.invalid") + request.Header.Set("Content-Type", "application/json") + if parent != "" { + request.AddCookie(&http.Cookie{Name: "sea_session", Value: parent}) + } + if child != "" { + request.AddCookie(&http.Cookie{Name: impersonationCookie, Value: child}) + } + response := httptest.NewRecorder() + server.ServeHTTP(response, request) + return response + } + expect := func(response *httptest.ResponseRecorder, status int) { + t.Helper() + if response.Code != status { + t.Fatalf("HTTP %d, want %d: %s", response.Code, status, response.Body.String()) + } + } + childFrom := func(response *httptest.ResponseRecorder) string { + t.Helper() + for _, cookie := range response.Result().Cookies() { + if cookie.Name == impersonationCookie { + if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode { + t.Fatal("unsafe delegated cookie") + } + return cookie.Value + } + } + t.Fatal("missing delegated cookie") + return "" + } + expect(call("/api/v1/admin/impersonation", "POST", map[string]any{"tenantId": tenant}, "", ""), 401) + for _, path := range []string{"/api/v1/admin/tenants", "/api/v1/admin/plans", "/api/v1/admin/domains/pending", "/api/v1/admin/overview", "/api/v1/admin/settings/domain-approval"} { + expect(call(path, "GET", nil, parent, ""), 200) + } + expect(call("/api/v1/admin/impersonation", "POST", map[string]any{"tenantId": tenant}, userToken, ""), 403) + start := call("/api/v1/admin/impersonation", "POST", map[string]any{"tenantId": tenant}, parent, "") + expect(start, 200) + child := childFrom(start) + expect(call("/api/v1/admin/nodes", "GET", nil, parent, child), 403) + expect(call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, child), 403) + expect(call("/api/v1/account/password", "PUT", map[string]any{}, parent, child), 403) + expect(call("/api/v1/auth/oidc/start?mode=bind", "GET", nil, parent, child), 403) + expect(call("/api/v1/me", "GET", nil, child, ""), 401) + expect(call("/api/v1/me", "GET", nil, otherParent, child), 401) + expect(call("/api/v1/me", "GET", nil, userToken, child), 403) + expect(call("/api/v1/auth/impersonation/stop", "POST", map[string]any{}, parent, child), 200) + expect(call("/api/v1/me", "GET", nil, parent, child), 401) + start = call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, "") + expect(start, 200) + child = childFrom(start) + expect(call("/api/v1/projects/"+strconv.FormatUint(hosts[1], 10)+"/files", "GET", nil, parent, child), 404) + response := call("/api/v1/projects/"+strconv.FormatUint(hosts[0], 10)+"/files", "PUT", map[string]any{"path": "../invalid", "content": "must-not-write"}, parent, child) + expect(response, 400) + hostContext := scope.WithProject(ctx, hosts[0], 1) + items, e := db.Activities(hostContext, tenant, 100) + if e != nil { + t.Fatal(e) + } + for _, item := range items { + if item.ResourceType == "file" { + t.Fatal("delegated administrator file action leaked to host") + } + } + items, e = db.Activities(ctx, tenant, 100) + if e != nil { + t.Fatal(e) + } + for _, item := range items { + if item.ResourceType == "impersonation" || item.ResourceType == "file" { + t.Fatal("administrator action leaked to user") + } + } + audit, e := db.AdminActivities(ctx, 100) + if e != nil { + t.Fatal(e) + } + found := false + for _, item := range audit { + if item.ResourceType == "file" && item.AdministratorID != nil && *item.AdministratorID == administrator.ID && item.ImpersonatedUserID != nil { + found = true + } + } + if !found { + t.Fatal("real administrator and target missing from audit") + } + activeHost, err := db.UserByLogin(ctx, "sv7777777777") + if err != nil { + t.Fatal(err) + } + if err = db.ChangePassword(ctx, activeHost.ID, "test-changed-hash", "not-a-session"); err != nil { + t.Fatal(err) + } + expect(call("/api/v1/me", "GET", nil, parent, child), 401) + start = call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, "") + expect(start, 200) + child = childFrom(start) + expired, _ := auth.NewSessionToken(secret) + if err = db.CreateImpersonation(ctx, parent, expired, administrator.ID, activeHost.ID, time.Now().Add(-time.Minute)); err != nil { + t.Fatal(err) + } + expect(call("/api/v1/me", "GET", nil, parent, expired), 401) + if err = db.CreateImpersonation(ctx, parent, expired, administrator.ID, administrator.ID, time.Now().Add(time.Minute)); err == nil { + t.Fatal("administrator cannot be a delegated target") + } + start = call("/api/v1/admin/impersonation", "POST", map[string]any{"projectId": hosts[0]}, parent, "") + expect(start, 200) + child = childFrom(start) + if e = db.DeleteSession(ctx, parent); e != nil { + t.Fatal(e) + } + expect(call("/api/v1/me", "GET", nil, parent, child), 401) + // Expiration is an expected host restriction, not a failed quota probe. + expires := time.Now().Add(-time.Minute) + if err = db.SetHostSubscription(ctx, hosts[0], plans[0].ID, &expires); err != nil { + t.Fatal(err) + } + response = call("/api/v1/projects/"+strconv.FormatUint(hosts[0], 10)+"/files", "PUT", map[string]any{"path": "expired.txt", "content": "must-not-write"}, userToken, "") + expect(response, http.StatusLocked) + if !strings.Contains(response.Body.String(), "host_not_writable") { + t.Fatal("expired write did not explain the host restriction") + } + if err = db.HostWritable(scope.WithProject(ctx, hosts[1], 1), tenant); err != nil { + t.Fatalf("expiration affected sibling host: %v", err) + } +} diff --git a/backend/internal/httpapi/integration_api.go b/backend/internal/httpapi/integration_api.go new file mode 100644 index 0000000..d52b57c --- /dev/null +++ b/backend/internal/httpapi/integration_api.go @@ -0,0 +1,210 @@ +package httpapi + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "slices" + "strconv" + "strings" + "time" +) + +const integrationKeyContext contextKey = "integration-key" + +var integrationScopes = []string{"users:read", "users:write", "hosts:read", "hosts:write", "tasks:read", "credentials:read"} + +func tokenHash(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} +func (s *Server) adminIntegrationKeys(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + rows, e := s.store.IntegrationKeys(r.Context()) + if e != nil { + writeError(w, 503, "无法读取 API 密钥") + return + } + deliveries, e := s.store.IntegrationWebhooks(r.Context(), false) + if e != nil { + writeError(w, 503, "无法读取回调记录") + return + } + writeJSON(w, 200, map[string]any{"keys": rows, "scopes": integrationScopes, "webhooks": deliveries}) + return + } + u := currentUser(r) + if r.Method == "DELETE" { + id, _ := strconv.ParseUint(r.PathValue("keyID"), 10, 64) + if e := s.store.RevokeIntegrationKey(r.Context(), id); e != nil { + writeError(w, 503, "吊销失败") + return + } + s.store.Log(r.Context(), nil, u.ID, "revoke", "integration_key", fmt.Sprint(id), requestClientIP(r), true, "吊销管理端 API 密钥") + w.WriteHeader(204) + return + } + var input struct { + Name string `json:"name"` + Scopes []string `json:"scopes"` + ExpiresAt time.Time `json:"expiresAt"` + WebhookURL string `json:"webhookURL"` + } + if decodeJSON(r, &input) != nil || strings.TrimSpace(input.Name) == "" || len(input.Name) > 120 || len(input.Scopes) < 1 || len(input.Scopes) > len(integrationScopes) || !input.ExpiresAt.After(time.Now()) || input.ExpiresAt.After(time.Now().AddDate(1, 0, 0)) { + writeError(w, 400, "名称、权限或有效期无效;有效期最长一年") + return + } + for _, v := range input.Scopes { + if !slices.Contains(integrationScopes, v) { + writeError(w, 400, "权限范围无效") + return + } + } + if input.WebhookURL != "" { + if _, e := validateWebhookURL(input.WebhookURL); e != nil { + writeError(w, 422, e.Error()) + return + } + } + raw := make([]byte, 32) + if _, e := rand.Read(raw); e != nil { + writeError(w, 500, "无法生成密钥") + return + } + token := "svh_live_" + hex.EncodeToString(raw) + prefix := token[:21] + secret := "" + var cipher []byte + if input.WebhookURL != "" { + if _, e := rand.Read(raw); e != nil { + writeError(w, 500, "无法生成回调密钥") + return + } + secret = hex.EncodeToString(raw) + var e error + cipher, e = s.secretBox.Seal("integration-webhook:"+prefix, secret) + if e != nil { + writeError(w, 500, "无法保存回调密钥") + return + } + } + id, e := s.store.CreateIntegrationKey(r.Context(), store.IntegrationKey{AdministratorID: u.ID, Name: input.Name, Prefix: prefix, Scopes: input.Scopes, ExpiresAt: input.ExpiresAt, WebhookURL: input.WebhookURL, WebhookSecret: cipher}, tokenHash(token)) + if e != nil { + writeError(w, 503, "无法保存 API 密钥") + return + } + s.store.Log(r.Context(), nil, u.ID, "create", "integration_key", fmt.Sprint(id), requestClientIP(r), true, "签发管理端 API 密钥") + writeJSON(w, 201, map[string]any{"id": id, "token": token, "webhookSecret": secret}) +} +func (s *Server) requireIntegration(scopeName string, next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + header := r.Header.Get("Authorization") + if !strings.HasPrefix(header, "Bearer ") || len(header) != len("Bearer svh_live_")+64 { + writeError(w, 401, "需要管理端 API 密钥") + return + } + key, e := s.store.IntegrationKeyByToken(r.Context(), tokenHash(strings.TrimPrefix(header, "Bearer "))) + if e != nil { + writeError(w, 401, "API 密钥无效、过期或已吊销") + return + } + if !slices.Contains(key.Scopes, scopeName) { + writeError(w, 403, "API 密钥缺少权限:"+scopeName) + return + } + u, e := s.store.UserByID(r.Context(), key.AdministratorID) + if e != nil || u.Role != "admin" { + writeError(w, 401, "管理账号已失效") + return + } + s.store.TouchIntegrationKey(r.Context(), key.ID) + ctx := context.WithValue(context.WithValue(r.Context(), userKey, u), integrationKeyContext, key) + ctx = scope.WithIntegrationKey(ctx, key.ID) + next(w, r.WithContext(ctx)) + } +} +func (s *Server) integrationList(w http.ResponseWriter, r *http.Request) { + if r.PathValue("resource") == "users" { + rows, e := s.store.ListTenants(r.Context()) + if e != nil { + writeError(w, 503, "无法读取用户") + return + } + writeJSON(w, 200, map[string]any{"users": rows}) + return + } + rows, e := s.store.ListAdminProjects(r.Context()) + if e != nil { + writeError(w, 503, "无法读取主机") + return + } + writeJSON(w, 200, map[string]any{"hosts": rows}) +} +func (s *Server) integrationWrite(w http.ResponseWriter, r *http.Request) { + key := r.Context().Value(integrationKeyContext).(store.IntegrationKey) + idempotency := r.Header.Get("Idempotency-Key") + if len(idempotency) < 8 || len(idempotency) > 128 || strings.ContainsAny(idempotency, "\x00\r\n") { + writeError(w, 400, "写请求必须提供 8–128 字节的 Idempotency-Key") + return + } + var input struct { + Operation string `json:"operation"` + Rows []batchRow `json:"rows"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式无效") + return + } + kind := r.PathValue("resource") + if kind == "users" { + if input.Operation == "" { + input.Operation = "create_users" + } + if !slices.Contains([]string{"create_users", "user_enable", "user_disable"}, input.Operation) { + writeError(w, 403, "用户接口不支持此操作") + return + } + } else { + if input.Operation == "" { + input.Operation = "create_hosts" + } + if !slices.Contains([]string{"create_hosts", "assign_hosts", "host_subscription", "host_start", "host_stop", "host_password_reset"}, input.Operation) { + writeError(w, 403, "主机接口不支持此操作") + return + } + } + sum := sha256.Sum256([]byte(fmt.Sprintf("integration:%d:%s", key.ID, idempotency))) + raw, _ := json.Marshal(batchRequest{RequestKey: hex.EncodeToString(sum[:16]), Operation: input.Operation, Rows: input.Rows}) + r.Body = io.NopCloser(bytes.NewReader(raw)) + r.ContentLength = int64(len(raw)) + s.adminBatches(w, r) +} +func (s *Server) integrationTask(w http.ResponseWriter, r *http.Request) { + id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64) + key := r.Context().Value(integrationKeyContext).(store.IntegrationKey) + owner, e := s.store.BatchIntegrationKey(r.Context(), id) + if e != nil || owner != key.ID { + writeError(w, 404, "任务不存在") + return + } + if strings.HasSuffix(r.URL.Path, "/download") { + s.adminBatchDownload(w, r) + } else { + s.adminBatch(w, r) + } +} +func webhookSignature(secret, stamp, event string, body []byte) string { + mac := hmac.New(sha256.New, []byte(secret)) + fmt.Fprintf(mac, "%s.%s.", stamp, event) + mac.Write(body) + return hex.EncodeToString(mac.Sum(nil)) +} diff --git a/backend/internal/httpapi/integration_docs.go b/backend/internal/httpapi/integration_docs.go new file mode 100644 index 0000000..9bcf81e --- /dev/null +++ b/backend/internal/httpapi/integration_docs.go @@ -0,0 +1,49 @@ +package httpapi + +import "net/http" + +const integrationAPIDocs = `# Sea vHost 管理端对接 API v1 + +管理端“对接 API”签发密钥。请求头:Authorization: Bearer 。 +不使用浏览器登录 Cookie。所有请求与返回均为 JSON。 + +GET /api/integration/v1/users(users:read) +GET /api/integration/v1/hosts(hosts:read) +POST /api/integration/v1/users(users:write) +POST /api/integration/v1/hosts(hosts:write) +GET /api/integration/v1/tasks/{id}(tasks:read) +GET /api/integration/v1/tasks/{id}/download(credentials:read) + +写入必须带 Idempotency-Key: <8–128 字节的唯一标识>。相同密钥和标识重试返回原任务;数据不同返回 409。 +POST 返回 202 {"batch":{"id":123,...}};主控后台执行,可轮询 tasks/{id}。 +任务仅能由提交该任务的 API 密钥读取。吊销、过期后无法调用,队列剩余条目停止;已开始的操作会完成并保存结果。 + +请求示例: +{"operation":"create_users","rows":[{"slug":"customer01","name":"客户一","email":"user@example.com"}]} +{"operation":"create_hosts","rows":[{"name":"站点一","tenantId":123,"nodeId":1,"planId":1,"runtime":"PHP","version":"8.4","runPath":"/public","autoSSL":false}]} +密码留空独立随机生成。tenantId 为 0 时不绑定用户,仍可使用独立主机账号。 + +用户操作:create_users / user_enable / user_disable。 +主机操作:create_hosts / assign_hosts / host_subscription / host_start / host_stop / host_password_reset。 +批量最多:用户 100;主机创建 50;管理 200。 +管理 rows 使用 hostId,建议包含查询返回的 ownershipVersion,避免误操作已转移主机。 +assign_hosts: tenantId(0 解绑)、credentialMode(preserve/reset)、stopServices(默认 true)。 +host_subscription: planId、setExpiry:true、expiresAt(RFC3339 或 null,null 为长期)。 +user_enable/user_disable: accountId 为用户归属账号编号。 +所有操作拒绝任意宝塔 API、系统路径或 shell 命令。 + +下载为 sea-vhost.batch-result v1 JSON;凭据结果仅保留 24 小时。 +回调不包含密码或输入,仅有批次状态与成功/失败计数。 + +回调请求:POST HTTPS 地址(443),禁止内网与保留地址,禁止重定向。 +X-Sea-Event: 唯一事件 ID;X-Sea-Timestamp: Unix 秒; +X-Sea-Signature: sha256=。 +签名内容:timestamp + "." + eventId + "." + 原始 JSON 字节。 +使用创建时显示的独立 webhookSecret,验证时间偏差不超过 5 分钟,以事件 ID 去重。 +回调有至少一次投递语义;返回 2xx 确认。重试间隔 1/2/4/8/16/32/64 分钟,总计最多 8 次。 +吊销或过期后停止投递。` + +func integrationDocs(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = w.Write([]byte(integrationAPIDocs)) +} diff --git a/backend/internal/httpapi/integration_webhooks.go b/backend/internal/httpapi/integration_webhooks.go new file mode 100644 index 0000000..f472133 --- /dev/null +++ b/backend/internal/httpapi/integration_webhooks.go @@ -0,0 +1,136 @@ +package httpapi + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/netip" + "net/url" + "sea-vhost/internal/store" + "strconv" + "strings" + "time" +) + +func validateWebhookURL(raw string) (*url.URL, error) { + u, e := url.Parse(raw) + if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Port() != "" && u.Port() != "443") || len(raw) > 2048 || strings.ContainsAny(raw, "\r\n\x00") { + return nil, errors.New("回调地址必须为 HTTPS 公网地址,端口为 443,不能包含凭据或查询参数") + } + if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicWebhookIP(ip) { + return nil, errors.New("回调禁止使用内网或保留地址") + } + if strings.EqualFold(u.Hostname(), "localhost") { + return nil, errors.New("回调禁止使用本机地址") + } + return u, nil +} +func publicWebhookIP(ip netip.Addr) bool { + ip = ip.Unmap() + if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() { + return false + } + for _, cidr := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "2001::/32", "2002::/16"} { + if netip.MustParsePrefix(cidr).Contains(ip) { + return false + } + } + return true +} +func webhookClient(ctx context.Context, u *url.URL) (*http.Client, error) { + resolved, e := net.DefaultResolver.LookupNetIP(ctx, "ip", u.Hostname()) + if e != nil || len(resolved) == 0 { + return nil, errors.New("DNS unavailable") + } + for _, ip := range resolved { + if !publicWebhookIP(ip) { + return nil, errors.New("DNS resolved to a restricted address") + } + } + transport := &http.Transport{Proxy: nil, TLSClientConfig: &tls.Config{ServerName: u.Hostname(), MinVersion: tls.VersionTLS12}, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var last error + for _, ip := range resolved { + conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), "443")) + if e == nil { + return conn, nil + } + last = e + } + return nil, last + }} + return &http.Client{Transport: transport, Timeout: 12 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, nil +} +func (s *Server) runIntegrationWebhooks(ctx context.Context) { + for ctx.Err() == nil { + _ = s.store.QueueIntegrationWebhooks(ctx) + rows, e := s.store.IntegrationWebhooks(ctx, true) + if e == nil { + for _, v := range rows { + if ctx.Err() != nil { + return + } + s.deliverIntegrationWebhook(ctx, v) + } + } + select { + case <-ctx.Done(): + return + case <-time.After(30 * time.Second): + } + } +} +func (s *Server) deliverIntegrationWebhook(ctx context.Context, v store.IntegrationWebhook) { + task, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + delivered := false + status := 0 + defer func() { + done, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + _ = s.store.FinishIntegrationWebhook(done, v, delivered, status) + }() + u, e := validateWebhookURL(v.URL) + if e != nil { + return + } + secret, e := s.secretBox.Open("integration-webhook:"+v.Prefix, v.Secret) + if e != nil { + return + } + job, e := s.store.AdminBatch(task, v.BatchID, false) + if e != nil { + return + } + job.Items = nil + body, _ := json.Marshal(map[string]any{"event": "batch.completed", "eventId": v.EventID, "batch": job}) + stamp := strconv.FormatInt(time.Now().Unix(), 10) + client, e := webhookClient(task, u) + if e != nil { + return + } + defer client.CloseIdleConnections() + request, e := http.NewRequestWithContext(task, "POST", v.URL, bytes.NewReader(body)) + if e != nil { + return + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-Sea-Event", v.EventID) + request.Header.Set("X-Sea-Timestamp", stamp) + request.Header.Set("X-Sea-Signature", "sha256="+webhookSignature(secret, stamp, v.EventID, body)) + if !s.store.IntegrationKeyActive(task, v.KeyID) { + return + } + response, e := client.Do(request) + if e != nil { + return + } + defer response.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) + status = response.StatusCode + delivered = status >= 200 && status < 300 +} diff --git a/backend/internal/httpapi/integration_webhooks_test.go b/backend/internal/httpapi/integration_webhooks_test.go new file mode 100644 index 0000000..3ff54d3 --- /dev/null +++ b/backend/internal/httpapi/integration_webhooks_test.go @@ -0,0 +1,30 @@ +package httpapi + +import ( + "net/netip" + "testing" +) + +func TestWebhookNetworkRestrictions(t *testing.T) { + for _, raw := range []string{"http://example.com/callback", "https://127.0.0.1/cb", "https://[::1]/cb", "https://[::ffff:127.0.0.1]/cb", "https://10.0.0.1/cb", "https://100.64.1.2/cb", "https://169.254.169.254/latest", "https://user:password@example.com/cb", "https://example.com:9443/cb", "https://example.com/cb?token=secret", "https://localhost/cb"} { + if _, e := validateWebhookURL(raw); e == nil { + t.Fatalf("accepted unsafe callback %q", raw) + } + } + if _, e := validateWebhookURL("https://billing.example.com/callback"); e != nil { + t.Fatal(e) + } + for _, ip := range []string{"192.168.1.2", "0.0.0.0", "224.0.0.1", "198.18.0.1", "2001:db8::1", "fc00::1"} { + if publicWebhookIP(netip.MustParseAddr(ip)) { + t.Fatalf("accepted %s", ip) + } + } +} +func TestWebhookSignatureBindsTimeEventAndExactBody(t *testing.T) { + signature := webhookSignature("secret", "100", "event", []byte(`{"id":1}`)) + for _, s := range []string{webhookSignature("other", "100", "event", []byte(`{"id":1}`)), webhookSignature("secret", "101", "event", []byte(`{"id":1}`)), webhookSignature("secret", "100", "another", []byte(`{"id":1}`)), webhookSignature("secret", "100", "event", []byte(`{ "id":1}`))} { + if signature == s { + t.Fatal("signature failed to bind request") + } + } +} diff --git a/backend/internal/httpapi/json.go b/backend/internal/httpapi/json.go new file mode 100644 index 0000000..16eb804 --- /dev/null +++ b/backend/internal/httpapi/json.go @@ -0,0 +1,32 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "io" + "net/http" +) + +func decodeJSON(r *http.Request, destination any) error { + decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(destination); err != nil { + return err + } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + return errors.New("request body must contain one JSON object") + } + return nil +} +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]any{"error": map[string]string{"message": message}}) +} + +func writeCodedError(w http.ResponseWriter, status int, code, message string) { + writeJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}}) +} diff --git a/backend/internal/httpapi/node_tasks.go b/backend/internal/httpapi/node_tasks.go new file mode 100644 index 0000000..19cdf62 --- /dev/null +++ b/backend/internal/httpapi/node_tasks.go @@ -0,0 +1,55 @@ +package httpapi + +import ( + "net/http" + "sea-vhost/internal/scope" + "strconv" + "strings" +) + +func (s *Server) adminNodeTasks(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + if err != nil || id < 2 { + writeError(w, 400, "远程节点编号无效") + return + } + items, err := s.store.ControlTasks(r.Context(), id) + if err != nil { + writeError(w, 500, "无法读取节点执行记录") + return + } + writeJSON(w, 200, map[string]any{"tasks": items}) +} +func (s *Server) adminResolveNodeTask(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + task, e := strconv.ParseUint(r.PathValue("taskID"), 10, 64) + if err != nil || e != nil { + writeError(w, 400, "任务编号无效") + return + } + var input struct { + Note string `json:"note"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + if err = s.store.ResolveControlTask(r.Context(), id, task, strings.TrimSpace(input.Note)); err != nil { + writeError(w, 422, err.Error()) + return + } + s.store.Log(r.Context(), nil, currentUser(r).ID, "reconcile", "node_task", strconv.FormatUint(task, 10), requestClientIP(r), true, input.Note) + w.WriteHeader(204) +} +func (s *Server) adminReconcileNode(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + if err != nil { + writeError(w, 400, "节点编号无效") + return + } + if err = s.projects.ReconcileNodeIdentities(scope.WithNode(r.Context(), id)); err != nil { + writeError(w, 422, err.Error()) + return + } + w.WriteHeader(204) +} diff --git a/backend/internal/httpapi/nodes.go b/backend/internal/httpapi/nodes.go new file mode 100644 index 0000000..5a2605b --- /dev/null +++ b/backend/internal/httpapi/nodes.go @@ -0,0 +1,232 @@ +package httpapi + +import ( + "errors" + "net/http" + "path" + "sea-vhost/internal/controlwire" + "sea-vhost/internal/scope" + "sea-vhost/internal/service" + "sea-vhost/internal/store" + "strconv" + "strings" + "time" +) + +func (s *Server) adminNodes(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + items, err := s.store.Nodes(r.Context()) + if err != nil { + writeError(w, 500, "无法读取节点") + return + } + writeJSON(w, 200, map[string]any{"nodes": items}) + return + } + var input store.Node + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + normalizeNodeMetadata(&input) + if err := validateNodeMetadata(input, false); err != nil { + writeError(w, 422, err.Error()) + return + } + id, err := s.store.CreateNode(r.Context(), input) + if err != nil { + writeError(w, 422, "无法新增节点,请检查地址是否重复") + return + } + s.resourceAudit(r, "create", "node", id, nil, "新增节点 "+input.Name) + writeJSON(w, 201, map[string]any{"id": id}) +} +func validNodeDomain(s string) bool { + if len(s) > 253 { + return false + } + for _, p := range strings.Split(s, ".") { + if len(p) < 1 || len(p) > 63 || p[0] == '-' || p[len(p)-1] == '-' { + return false + } + for _, c := range p { + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { + return false + } + } + } + return strings.Contains(s, ".") +} +func nodeID(r *http.Request) (uint64, error) { return strconv.ParseUint(r.PathValue("nodeID"), 10, 64) } +func (s *Server) adminPairNode(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + if err != nil || id < 2 { + writeError(w, 400, "请选择远程节点") + return + } + if s.cluster == nil { + writeError(w, 503, "节点管理未初始化") + return + } + identity, err := s.cluster.Pair(r.Context(), id) + if err != nil { + writeError(w, 422, "无法生成节点配对材料") + return + } + node, _ := s.store.Node(r.Context(), id) + s.store.Log(r.Context(), nil, currentUser(r).ID, "pair", "node", strconv.FormatUint(id, 10), requestClientIP(r), true, "重新签发节点身份,节点已停用,部署后需探测启用") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Content-Disposition", "attachment; filename=sea-node-config.json") + writeJSON(w, 200, map[string]any{"identity": identity, "address": ":9443", "tenantRoot": node.TenantRoot, "brokerSocket": "/run/sea-vhost-panel/broker.sock", "agentSocket": "/run/sea-vhost/agent.sock"}) +} +func (s *Server) adminProbeNode(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + if err != nil || s.cluster == nil { + writeError(w, 400, "节点编号无效") + return + } + if err = s.cluster.Probe(r.Context(), id); err != nil { + writeError(w, 502, err.Error()) + return + } + w.WriteHeader(204) +} +func (s *Server) adminNode(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + if err != nil { + writeError(w, 400, "节点编号无效") + return + } + var input struct { + Enabled bool `json:"enabled"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + if id == 1 && input.Enabled && s.cfg.ControllerOnly { + writeError(w, 422, "独立主控不提供本机托管功能,请新增被控节点") + return + } + if input.Enabled && id != 1 { + if s.cluster == nil { + writeError(w, 503, "节点管理未初始化") + return + } + if err = s.cluster.Probe(r.Context(), id); err != nil { + writeError(w, 422, "双向 TLS 和节点身份探测通过后才能启用") + return + } + } + existing, lookupErr := s.store.Node(r.Context(), id) + if lookupErr != nil { + writeError(w, 404, "节点不存在") + return + } + if existing.Enabled == input.Enabled { + w.WriteHeader(204) + return + } + if s.store.SetNodeEnabled(r.Context(), id, input.Enabled) != nil { + writeError(w, 422, "无法更新节点状态") + return + } + if input.Enabled { + nodeCtx := scope.WithNode(r.Context(), id) + blocked, checkErr := s.store.RuntimeMutationBlocked(nodeCtx) + if checkErr != nil { + writeError(w, 500, "无法核对节点维护状态") + return + } + if !blocked { + if err = s.projects.ReconcileNodeIdentities(nodeCtx); err != nil { + _ = s.store.SetNodeEnabled(r.Context(), id, false) + writeError(w, 422, "节点已连接,但主机身份核验未通过:"+err.Error()) + return + } + } + } + + w.WriteHeader(204) +} +func (s *Server) adminCreateHost(w http.ResponseWriter, r *http.Request) { + var input struct { + TenantID uint64 `json:"tenantId"` + NodeID uint64 `json:"nodeId"` + PlanID uint64 `json:"planId"` + Name string `json:"name"` + Runtime string `json:"runtime"` + Version string `json:"version"` + RunPath string `json:"runPath"` + CustomDomain string `json:"customDomain"` + AutoSSL bool `json:"autoSSL"` + ExpiresAt *time.Time `json:"expiresAt"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + ctx := scope.WithNode(r.Context(), input.NodeID) + release, err := s.projects.BeginRuntimeMutation(ctx) + if err != nil { + writeError(w, 423, err.Error()) + return + } + defer release() + result, err := s.projects.CreateManagedHost(ctx, input.TenantID, service.CreateProjectInput{NodeID: input.NodeID, PlanID: input.PlanID, Name: input.Name, Runtime: input.Runtime, Version: input.Version, RunPath: input.RunPath, CustomDomain: input.CustomDomain, AutoSSL: input.AutoSSL}) + if err != nil { + writeError(w, 422, err.Error()) + return + } + if err = s.store.SetHostSubscription(r.Context(), result.Project.ID, input.PlanID, input.ExpiresAt); err != nil { + writeError(w, 500, "主机已创建,但到期设置保存失败,请在主机管理中重新设置") + return + } + s.store.Log(scope.WithProject(r.Context(), result.Project.ID, result.Project.NodeID), &result.Project.TenantID, currentUser(r).ID, "create", "project", strconv.FormatUint(result.Project.ID, 10), requestClientIP(r), true, "管理员开通主机") + writeJSON(w, 201, result) +} +func (s *Server) adminHostSubscription(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, 400, "主机编号无效") + return + } + var input struct { + PlanID uint64 `json:"planId"` + ExpiresAt *time.Time `json:"expiresAt"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + if _, err = s.store.Plan(r.Context(), input.PlanID); err != nil { + writeError(w, 422, "套餐不存在") + return + } + if err = s.projects.ApplyHostSubscription(r.Context(), id, input.PlanID, input.ExpiresAt); err != nil { + s.store.Log(r.Context(), nil, currentUser(r).ID, "update", "host_subscription", strconv.FormatUint(id, 10), requestClientIP(r), false, "主机套餐或身份核验未完成") + writeError(w, 422, "套餐保存或节点身份核验未完成:"+err.Error()) + return + } + s.store.Log(r.Context(), nil, currentUser(r).ID, "update", "host_subscription", strconv.FormatUint(id, 10), requestClientIP(r), true, "更新主机套餐与到期时间") + w.WriteHeader(204) +} + +func normalizeNodeMetadata(n *store.Node) { + n.Name = strings.TrimSpace(n.Name) + n.RootDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(n.RootDomain), ".")) + n.FTPCertificateDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(n.FTPCertificateDomain), ".")) +} +func validateNodeMetadata(n store.Node, local bool) error { + if !local { + if _, err := controlwire.ValidateEndpoint(n.Endpoint); err != nil { + return err + } + } else if n.Endpoint != "local" { + return errors.New("本机执行入口不可修改") + } + if n.Name == "" || len([]rune(n.Name)) > 80 || strings.ContainsAny(n.Name, "\x00\r\n") || !validNodeDomain(n.RootDomain) || !validNodeDomain(n.FTPCertificateDomain) || !path.IsAbs(n.TenantRoot) || path.Clean(n.TenantRoot) != n.TenantRoot || !strings.HasPrefix(n.TenantRoot, "/www/wwwroot/") || len(n.TenantRoot) > 500 || strings.ContainsAny(n.TenantRoot, "\\\x00\r\n") { + return errors.New("节点名称、域名或主机根目录无效") + } + return nil +} diff --git a/backend/internal/httpapi/oidc.go b/backend/internal/httpapi/oidc.go new file mode 100644 index 0000000..0018dfc --- /dev/null +++ b/backend/internal/httpapi/oidc.go @@ -0,0 +1,272 @@ +package httpapi + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "net/http" + "net/url" + "strings" + "time" + + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" + + "sea-vhost/internal/auth" + "sea-vhost/internal/store" +) + +const oidcProviderName = "oidc" + +func (s *Server) oidcStatus(w http.ResponseWriter, r *http.Request) { + cfg := s.readServiceConfig(r, "oidc_config") + writeJSON(w, http.StatusOK, map[string]any{"enabled": validOIDCConfig(cfg), "autoCreate": cfg.AutoCreate, "userPasswordLogin": oidcPasswordAllowed(cfg, "tenant"), "adminPasswordLogin": oidcPasswordAllowed(cfg, "admin"), "hostPasswordLogin": true}) +} + +func (s *Server) oidcStart(w http.ResponseWriter, r *http.Request) { + if _, err := r.Cookie(impersonationCookie); err == nil { + writeError(w, 403, "请先退出代入模式再进行第三方登录或绑定") + return + } + cfg := s.readServiceConfig(r, "oidc_config") + if !validOIDCConfig(cfg) { + writeError(w, http.StatusServiceUnavailable, "OIDC 登录尚未启用") + return + } + mode := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("mode"))) + if mode == "" { + mode = "login" + } + var userID *uint64 + var parentSession string + if mode == "bind" { + cookie, err := r.Cookie("sea_session") + if err != nil { + writeError(w, http.StatusUnauthorized, "请先使用密码登录后绑定") + return + } + user, err := s.userFromToken(r.Context(), cookie.Value) + if err != nil { + writeError(w, http.StatusUnauthorized, "登录已失效") + return + } + if user.Role == "host" { + writeError(w, 403, "主机账号不可绑定 SSO") + return + } + userID = &user.ID + parentSession = cookie.Value + } else if mode != "login" { + writeError(w, http.StatusBadRequest, "OIDC 模式无效") + return + } + provider, oauth, err := oidcClient(r.Context(), cfg) + if err != nil { + writeError(w, http.StatusBadGateway, "无法连接 OIDC 服务") + return + } + _ = provider + state, err := randomURLToken(32) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法创建 OIDC 状态") + return + } + verifier, err := randomURLToken(48) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法创建 OIDC 校验参数") + return + } + nonce, err := randomURLToken(32) + if err != nil || s.store.CreateScopedOIDCState(r.Context(), state, userID, mode, verifier, nonce, oidcProviderKey(cfg), parentSession, time.Now().Add(10*time.Minute)) != nil { + writeError(w, http.StatusInternalServerError, "无法保存 OIDC 状态") + return + } + challenge := sha256.Sum256([]byte(verifier)) + authorizationURL := oauth.AuthCodeURL(state, + oidc.Nonce(nonce), + oauth2.SetAuthURLParam("code_challenge", base64.RawURLEncoding.EncodeToString(challenge[:])), + oauth2.SetAuthURLParam("code_challenge_method", "S256"), + ) + setOIDCCookie(w, "sea_oidc_flow", state, 600) + writeJSON(w, http.StatusOK, map[string]string{"url": authorizationURL}) +} + +func (s *Server) oidcCallback(w http.ResponseWriter, r *http.Request) { + if _, err := r.Cookie(impersonationCookie); err == nil { + writeError(w, 403, "请先退出代入模式再进行第三方登录或绑定") + return + } + stateValue := strings.TrimSpace(r.URL.Query().Get("state")) + code := strings.TrimSpace(r.URL.Query().Get("code")) + if stateValue == "" || code == "" || len(stateValue) > 256 || len(code) > 4096 { + redirectOIDCResult(w, r, "error") + return + } + flow, flowErr := r.Cookie("sea_oidc_flow") + if flowErr != nil || flow.Value != stateValue { + redirectOIDCResult(w, r, "expired") + return + } + setOIDCCookie(w, "sea_oidc_flow", "", -1) + state, err := s.store.ConsumeOIDCState(r.Context(), stateValue) + if err != nil { + redirectOIDCResult(w, r, "expired") + return + } + cfg := s.readServiceConfig(r, "oidc_config") + if state.ProviderKey != oidcProviderKey(cfg) { + redirectOIDCResult(w, r, "provider_changed") + return + } + if state.Mode == "bind" && state.UserID != nil && !s.store.ActiveOIDCBindSession(r.Context(), state.SessionHash, *state.UserID) { + redirectOIDCResult(w, r, "expired") + return + } + + provider, oauth, err := oidcClient(r.Context(), cfg) + if err != nil { + redirectOIDCResult(w, r, "provider") + return + } + token, err := oauth.Exchange(r.Context(), code, oauth2.SetAuthURLParam("code_verifier", state.Verifier)) + if err != nil { + redirectOIDCResult(w, r, "exchange") + return + } + rawIDToken, ok := token.Extra("id_token").(string) + if !ok || rawIDToken == "" { + redirectOIDCResult(w, r, "token") + return + } + idToken, err := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID}).Verify(r.Context(), rawIDToken) + if err != nil { + redirectOIDCResult(w, r, "verify") + return + } + var claims struct { + Subject string `json:"sub"` + Name string `json:"name"` + EmailVerified bool `json:"email_verified"` + Email string `json:"email"` + Nonce string `json:"nonce"` + } + if idToken.Claims(&claims) != nil || claims.Subject == "" || claims.Nonce != state.Nonce || len(claims.Subject) > 255 || len(claims.Email) > 190 { + redirectOIDCResult(w, r, "claims") + return + } + if state.Mode == "bind" && state.UserID != nil { + if err = s.store.BindOIDCIdentity(r.Context(), *state.UserID, oidcProviderKey(cfg), claims.Subject, claims.Email); err != nil { + redirectOIDCResult(w, r, "conflict") + return + } + user, _ := s.store.UserByID(r.Context(), *state.UserID) + s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "oidc_identity", "", requestClientIP(r), true, "绑定第三方 OIDC 身份") + redirectOIDCResult(w, r, "bound") + return + } + user, err := s.store.UserByOIDC(r.Context(), oidcProviderKey(cfg), claims.Subject) + if err != nil { + if !errors.Is(err, store.ErrNotFound) { + redirectOIDCResult(w, r, "session") + return + } + ticket, e := randomURLToken(32) + if e != nil { + redirectOIDCResult(w, r, "session") + return + } + pending := store.PendingOIDCLogin{Provider: oidcProviderKey(cfg), Subject: claims.Subject, Email: strings.ToLower(strings.TrimSpace(claims.Email)), DisplayName: truncateOIDCName(claims.Name), EmailVerified: claims.EmailVerified, ExpiresAt: time.Now().UTC().Add(5 * time.Minute)} + if e = s.store.CreatePendingOIDCLogin(r.Context(), ticket, pending); e != nil { + redirectOIDCResult(w, r, "session") + return + } + setOIDCCookie(w, "sea_oidc_pending", ticket, 300) + redirectOIDCResult(w, r, "complete") + return + } + if user.Role == "host" { + redirectOIDCResult(w, r, "host_not_allowed") + return + } + if err = s.issueSession(w, r, user); err != nil { + redirectOIDCResult(w, r, "session") + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "login", "oidc_session", "", requestClientIP(r), true, "通过已绑定的 OIDC 身份登录") + redirectOIDCResult(w, r, "login") +} + +func (s *Server) accountOIDC(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + cfg := s.readServiceConfig(r, "oidc_config") + if user.Role == "host" { + if r.Method == http.MethodGet { + writeJSON(w, 200, map[string]any{"enabled": false, "bound": false, "email": ""}) + return + } + writeError(w, 403, "主机账号不可绑定 SSO") + return + } + if r.Method == http.MethodGet { + identity, err := s.store.OIDCIdentity(r.Context(), user.ID, oidcProviderKey(cfg)) + writeJSON(w, http.StatusOK, map[string]any{"enabled": validOIDCConfig(cfg), "bound": err == nil, "email": identity.Email, "canUnbind": oidcPasswordAllowed(cfg, user.Role)}) + return + } + if !oidcPasswordAllowed(cfg, user.Role) { + writeError(w, 409, "请先恢复该类账号的密码登录,再解除 SSO 绑定") + return + } + var input struct { + CurrentPassword string `json:"currentPassword"` + } + if decodeJSON(r, &input) != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + security, err := s.store.UserSecurity(r.Context(), user.ID) + if err != nil || !auth.VerifyPasswordConstantWork(security.PasswordHash, input.CurrentPassword) { + writeError(w, http.StatusUnauthorized, "当前密码不正确") + return + } + if err = s.store.DeleteOIDCIdentity(r.Context(), user.ID, oidcProviderKey(cfg)); err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "无法解除 OIDC 绑定") + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "unbind", "oidc_identity", "", requestClientIP(r), true, "解除第三方 OIDC 身份绑定") + w.WriteHeader(http.StatusNoContent) +} + +func oidcClient(ctx context.Context, cfg secretServiceConfig) (*oidc.Provider, *oauth2.Config, error) { + if !validOIDCConfig(cfg) { + return nil, nil, errors.New("invalid OIDC config") + } + provider, err := oidc.NewProvider(ctx, strings.TrimSuffix(cfg.Issuer, "/")) + if err != nil { + return nil, nil, err + } + oauth := &oauth2.Config{ClientID: cfg.ClientID, ClientSecret: cfg.Secret, Endpoint: provider.Endpoint(), RedirectURL: cfg.RedirectURI, Scopes: []string{oidc.ScopeOpenID, "profile", "email"}} + return provider, oauth, nil +} + +func validOIDCConfig(cfg secretServiceConfig) bool { + if !cfg.Enabled || cfg.Secret == "" || cfg.ClientID == "" || cfg.Issuer == "" || cfg.RedirectURI == "" { + return false + } + issuer, issuerErr := url.Parse(cfg.Issuer) + redirect, redirectErr := url.Parse(cfg.RedirectURI) + return issuerErr == nil && redirectErr == nil && issuer.Scheme == "https" && issuer.Host != "" && issuer.User == nil && redirect.Scheme == "https" && redirect.Host != "" && redirect.User == nil +} + +func randomURLToken(size int) (string, error) { + data := make([]byte, size) + if _, err := rand.Read(data); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func redirectOIDCResult(w http.ResponseWriter, r *http.Request, result string) { + http.Redirect(w, r, "/?oidc="+url.QueryEscape(result), http.StatusSeeOther) +} diff --git a/backend/internal/httpapi/oidc_policy.go b/backend/internal/httpapi/oidc_policy.go new file mode 100644 index 0000000..8e51b75 --- /dev/null +++ b/backend/internal/httpapi/oidc_policy.go @@ -0,0 +1,175 @@ +package httpapi + +import ( + "crypto/sha256" + "encoding/hex" + "net/http" + "net/mail" + "strings" + "time" + + "sea-vhost/internal/auth" + "sea-vhost/internal/store" +) + +func oidcProviderKey(c secretServiceConfig) string { + digest := sha256.Sum256([]byte(strings.TrimSuffix(strings.TrimSpace(c.Issuer), "/"))) + return "oidc:" + hex.EncodeToString(digest[:16]) +} +func oidcPasswordAllowed(c secretServiceConfig, role string) bool { + var v *bool + switch role { + case "admin": + v = c.AdminPasswordLogin + case "tenant": + v = c.UserPasswordLogin + default: + return true + } + return v == nil || *v +} +func setOIDCCookie(w http.ResponseWriter, name, value string, age int) { + http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/api/v1/auth/oidc", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age}) +} +func truncateOIDCName(v string) string { + chars := []rune(strings.TrimSpace(v)) + if len(chars) > 80 { + chars = chars[:80] + } + return string(chars) +} +func validSSOEmail(p store.PendingOIDCLogin) bool { + m, e := mail.ParseAddress(p.Email) + return p.EmailVerified && e == nil && m.Address == p.Email && len(p.Email) <= 190 +} + +func (s *Server) pendingOIDCLogin(w http.ResponseWriter, r *http.Request) { + cookie, e := r.Cookie("sea_oidc_pending") + if e != nil { + writeJSON(w, 200, map[string]any{"pending": false}) + return + } + p, e := s.store.PendingOIDCLogin(r.Context(), cookie.Value) + cfg := s.readServiceConfig(r, "oidc_config") + if e != nil || !validOIDCConfig(cfg) || p.Provider != oidcProviderKey(cfg) { + setOIDCCookie(w, "sea_oidc_pending", "", -1) + writeJSON(w, 200, map[string]any{"pending": false}) + return + } + writeJSON(w, 200, map[string]any{"pending": true, "allowCreate": cfg.AutoCreate && validSSOEmail(p), "email": p.Email, "displayName": p.DisplayName}) +} + +func (s *Server) completeOIDCLogin(w http.ResponseWriter, r *http.Request) { + if _, e := r.Cookie(impersonationCookie); e == nil { + writeError(w, 403, "请先返回管理视图") + return + } + var input struct { + Action string `json:"action"` + Identifier string `json:"identifier"` + Password string `json:"password"` + TOTPCode string `json:"totpCode"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + cookie, e := r.Cookie("sea_oidc_pending") + if e != nil { + writeError(w, 401, "SSO 登录请求已失效,请重新登录") + return + } + p, e := s.store.PendingOIDCLogin(r.Context(), cookie.Value) + cfg := s.readServiceConfig(r, "oidc_config") + if e != nil || !validOIDCConfig(cfg) || p.Provider != oidcProviderKey(cfg) { + writeError(w, 401, "SSO 登录请求已失效,请重新登录") + return + } + if allowed, retry := s.loginLimiter.allow("oidc-complete:"+requestClientIP(r), time.Now(), loginIPBurst); !allowed { + writeLoginRateLimit(w, retry) + return + } + var target uint64 + var created *store.NewTenant + switch input.Action { + case "bind": + started := time.Now() + u, err := s.store.UserByLogin(r.Context(), strings.ToLower(strings.TrimSpace(input.Identifier))) + hash := "" + if err == nil { + hash = u.PasswordHash + } + ok := auth.VerifyPasswordConstantWork(hash, input.Password) + if err != nil || !ok || u.Role == "host" || len(input.Password) > 128 { + minimumLoginDelay(started) + writeError(w, 401, "账号或密码不正确,主机账号不可绑定 SSO") + return + } + if !oidcPasswordAllowed(cfg, u.Role) { + writeError(w, 403, "该账号已关闭密码登录,请通过已绑定的 SSO 身份登录") + return + } + if u.MFAEnabled { + security, e := s.store.UserSecurity(r.Context(), u.ID) + if e != nil { + writeError(w, 500, "无法验证双重认证") + return + } + secret, e := s.secretBox.Open(mfaSecretLabel(u.ID), security.TOTPSecretCiphertext) + valid := e == nil && auth.VerifyTOTP(secret, input.TOTPCode, time.Now()) + if !valid && strings.TrimSpace(input.TOTPCode) != "" { + valid, e = s.store.ConsumeRecoveryCode(r.Context(), u.ID, auth.RecoveryCodeHash(input.TOTPCode)) + } + if e != nil || !valid { + writeCodedError(w, 401, "mfa_required", "请输入有效的动态验证码或恢复码") + return + } + } + target = u.ID + case "create": + if !cfg.AutoCreate || !validSSOEmail(p) { + writeError(w, 403, "当前不允许创建 SSO 用户,或第三方邮箱尚未验证") + return + } + random, e := randomURLToken(32) + if e != nil { + writeError(w, 500, "无法创建账号") + return + } + password, e := auth.HashPassword(random) + if e != nil { + writeError(w, 500, "无法创建账号") + return + } + name := p.DisplayName + if name == "" { + name = "SSO 用户" + } + digest := sha256.Sum256([]byte(random)) + created = &store.NewTenant{Slug: "sso-" + hex.EncodeToString(digest[:10]), Name: name, DisplayName: name, Email: p.Email, Password: password, PlanID: 1} + default: + writeError(w, 422, "请选择绑定账号或创建账号") + return + } + target, e = s.store.CompletePendingOIDC(r.Context(), cookie.Value, oidcProviderKey(cfg), target, created) + if e != nil { + writeError(w, 409, "无法完成绑定或建号:请求可能已使用,或账号邮箱/SSO 身份已被绑定;相同邮箱不会自动合并") + return + } + setOIDCCookie(w, "sea_oidc_pending", "", -1) + u, e := s.store.UserByID(r.Context(), target) + if e != nil { + writeError(w, 401, "账号不可用") + return + } + if e = s.issueSession(w, r, u); e != nil { + writeError(w, 500, "绑定已完成,请重新使用 SSO 登录") + return + } + detail := "SSO 登录时绑定已有用户" + if created != nil { + detail = "SSO 首次登录创建普通用户,未开通虚拟主机" + } + s.store.Log(r.Context(), u.TenantID, u.ID, "login", "oidc_session", "", requestClientIP(r), true, detail) + writeJSON(w, 200, map[string]any{"completed": true}) +} diff --git a/backend/internal/httpapi/oidc_policy_test.go b/backend/internal/httpapi/oidc_policy_test.go new file mode 100644 index 0000000..13ee69f --- /dev/null +++ b/backend/internal/httpapi/oidc_policy_test.go @@ -0,0 +1,33 @@ +package httpapi + +import ( + "sea-vhost/internal/store" + "testing" +) + +func TestOIDCPasswordPolicyDoesNotAffectHosts(t *testing.T) { + off := false + c := secretServiceConfig{UserPasswordLogin: &off, AdminPasswordLogin: &off} + if !oidcPasswordAllowed(c, "host") || oidcPasswordAllowed(c, "admin") || oidcPasswordAllowed(c, "tenant") { + t.Fatal("password policy scope incorrect") + } + if !oidcPasswordAllowed(secretServiceConfig{}, "admin") || !oidcPasswordAllowed(secretServiceConfig{}, "tenant") { + t.Fatal("old settings must preserve password login") + } +} +func TestOIDCProviderIdentityIncludesIssuer(t *testing.T) { + a := oidcProviderKey(secretServiceConfig{Issuer: "https://id.example.com"}) + if a != oidcProviderKey(secretServiceConfig{Issuer: "https://id.example.com/"}) || a == oidcProviderKey(secretServiceConfig{Issuer: "https://other.example.com"}) || len(a) > 40 { + t.Fatal("issuer isolation invalid") + } +} +func TestSSOAutomaticCreationRequiresVerifiedEmail(t *testing.T) { + for _, p := range []store.PendingOIDCLogin{{Email: "a@example.com"}, {Email: "not-an-email", EmailVerified: true}, {Email: "Name ", EmailVerified: true}} { + if validSSOEmail(p) { + t.Fatal("untrusted email accepted") + } + } + if !validSSOEmail(store.PendingOIDCLogin{Email: "a@example.com", EmailVerified: true}) { + t.Fatal("verified email rejected") + } +} diff --git a/backend/internal/httpapi/phpmyadmin.go b/backend/internal/httpapi/phpmyadmin.go new file mode 100644 index 0000000..30d590f --- /dev/null +++ b/backend/internal/httpapi/phpmyadmin.go @@ -0,0 +1,93 @@ +package httpapi + +import ( + "io" + "net/http" + "net/url" + "sea-vhost/internal/isolation" + "strconv" + "strings" +) + +func (s *Server) phpMyAdmin(w http.ResponseWriter, r *http.Request) { + id, _ := projectID(r) + base := "/api/v1/projects/" + strconv.FormatUint(id, 10) + "/database-admin/" + relative := r.PathValue("pmaPath") + if r.Method != "GET" && r.Method != "POST" && r.Method != "HEAD" { + writeError(w, 405, "不支持的请求方法") + return + } + if s.cfg.ManagementDomain == "" { + writeError(w, 503, "未设置管理域名") + return + } + body, e := io.ReadAll(io.LimitReader(r.Body, (2<<20)+1)) + if e != nil || len(body) > 2<<20 { + writeError(w, 413, "phpMyAdmin 单次请求上限为 2 MiB") + return + } + var cookies []string + for _, c := range r.Cookies() { + if !strings.HasPrefix(strings.ToLower(c.Name), "sea_") { + cookies = append(cookies, c.Name+"="+c.Value) + } + } + out, e := s.projects.PHPMyAdmin(r.Context(), currentUser(r), id, isolation.PHPMyAdminRequest{Method: r.Method, Path: relative, Query: r.URL.RawQuery, Body: body, Cookie: strings.Join(cookies, "; "), ContentType: r.Header.Get("Content-Type"), BaseURI: "https://" + s.cfg.ManagementDomain + base}) + if e != nil { + writeError(w, 502, "phpMyAdmin 暂不可用,请检查节点上的 phpMyAdmin / PHP 安装") + return + } + for _, name := range []string{"Content-Type", "Content-Disposition", "Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP"} { + if value := out.Header.Get(name); value != "" { + w.Header().Set(name, value) + } + } + for _, cookie := range (&http.Response{Header: out.Header}).Cookies() { + if strings.HasPrefix(strings.ToLower(cookie.Name), "sea_") { + continue + } + cookie.Domain = "" + cookie.Path = base + cookie.Secure = true + cookie.HttpOnly = true + cookie.SameSite = http.SameSiteStrictMode + http.SetCookie(w, cookie) + } + if location := out.Header.Get("Location"); location != "" { + u, e := url.Parse(location) + if e != nil || u.User != nil || (u.Host != "" && !strings.EqualFold(u.Host, s.cfg.ManagementDomain)) || (u.Scheme != "" && u.Scheme != "https") { + writeError(w, 502, "phpMyAdmin 返回了无效跳转") + return + } + if u.IsAbs() || strings.HasPrefix(u.Path, "/") { + if !strings.HasPrefix(u.Path, base) { + writeError(w, 502, "phpMyAdmin 跳转超出数据库管理范围") + return + } + } else { + u.Path = base + strings.TrimPrefix(u.Path, "./") + } + w.Header().Set("Location", u.String()) + } + if pmaNeedsAudit(r) { + u := currentUser(r) + s.store.Log(r.Context(), u.TenantID, u.ID, "manage", "database", strconv.FormatUint(id, 10), requestClientIP(r), out.Status < 400, "使用 phpMyAdmin 管理主机数据库") + } + w.WriteHeader(out.Status) + if r.Method != "HEAD" { + _, _ = w.Write(out.Body) + } +} + +func pmaNeedsAudit(r *http.Request) bool { + if r.Method != http.MethodPost { + return false + } + // These are phpMyAdmin's automatic UI preferences/tree requests. Unknown + // routes, SQL execution, imports and other POSTs remain auditable. + switch r.URL.Query().Get("route") { + case "/config/get", "/config/set", "/navigation": + return false + } + return true +} diff --git a/backend/internal/httpapi/phpmyadmin_test.go b/backend/internal/httpapi/phpmyadmin_test.go new file mode 100644 index 0000000..52dc3c0 --- /dev/null +++ b/backend/internal/httpapi/phpmyadmin_test.go @@ -0,0 +1,18 @@ +package httpapi + +import ( + "net/http/httptest" + "testing" +) + +func TestPMAAuditKeepsSQLAndUnknownWrites(t *testing.T) { + for _, tc := range []struct { + method, route string + want bool + }{{"POST", "/config/get", false}, {"POST", "/config/set", false}, {"POST", "/navigation", false}, {"POST", "/sql", true}, {"POST", "/import", true}, {"POST", "/unrecognized", true}, {"POST", "", true}, {"GET", "/sql", false}} { + r := httptest.NewRequest(tc.method, "https://control.vhost.ser888.cn/?route="+tc.route, nil) + if pmaNeedsAudit(r) != tc.want { + t.Fatalf("audit %s %s", tc.method, tc.route) + } + } +} diff --git a/backend/internal/httpapi/projects.go b/backend/internal/httpapi/projects.go new file mode 100644 index 0000000..779d330 --- /dev/null +++ b/backend/internal/httpapi/projects.go @@ -0,0 +1,387 @@ +package httpapi + +import ( + "errors" + "fmt" + "net/http" + "sea-vhost/internal/scope" + "strconv" + "strings" + "time" + + "sea-vhost/internal/service" + "sea-vhost/internal/store" +) + +func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + plan, usage, err := s.store.PlanAndUsage(r.Context(), *user.TenantID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取套餐信息") + return + } + projects, err := s.projectsForUser(r, user) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取项目") + return + } + activities, err := s.store.Activities(r.Context(), *user.TenantID, 10) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取操作日志") + return + } + writeJSON(w, http.StatusOK, map[string]any{"plan": plan, "usage": usage, "projects": projects, "activities": activities, "hostScoped": user.ProjectID != nil, "domainApproval": s.store.DomainApproval(r.Context(), s.cfg.DomainApproval), "rootDomain": s.cfg.RootDomain, "projectRoot": s.cfg.TenantRoot}) +} + +func (s *Server) activities(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + if value := r.URL.Query().Get("projectId"); value != "" { + id, err := strconv.ParseUint(value, 10, 64) + if err != nil || id != scope.Project(r.Context()) { + writeError(w, http.StatusNotFound, "主机不存在") + return + } + } + items, err := s.store.Activities(r.Context(), *user.TenantID, 100) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取操作日志") + return + } + writeJSON(w, http.StatusOK, map[string]any{"activities": items}) +} + +func (s *Server) runtimeCatalog(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + if allowed, retryAfter := s.catalogLimiter.allow(fmt.Sprintf("runtime:%d", user.ID), time.Now(), 30); !allowed { + seconds := (retryAfter + time.Second - 1) / time.Second + w.Header().Set("Retry-After", strconv.FormatInt(int64(seconds), 10)) + writeError(w, http.StatusTooManyRequests, "运行环境查询过于频繁,请稍后再试") + return + } + catalog, err := s.projects.RuntimeCatalog(r.Context()) + if err != nil { + writeError(w, http.StatusBadGateway, "无法读取宝塔运行环境") + return + } + writeJSON(w, http.StatusOK, map[string]any{"versions": catalog}) +} + +func (s *Server) listProjects(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + projects, err := s.projectsForUser(r, user) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取项目") + return + } + writeJSON(w, http.StatusOK, map[string]any{"projects": projects}) +} + +func (s *Server) projectsForUser(r *http.Request, user store.User) ([]store.Project, error) { + if user.ProjectID != nil { + project, err := s.store.Project(r.Context(), *user.TenantID, *user.ProjectID) + if err != nil { + return nil, err + } + projects := []store.Project{project} + return projects, s.store.FillProjectBandwidth(r.Context(), projects) + } + projects, err := s.store.ListProjects(r.Context(), *user.TenantID) + if err != nil { + return nil, err + } + return projects, s.store.FillProjectBandwidth(r.Context(), projects) +} + +func (s *Server) createProject(w http.ResponseWriter, r *http.Request) { + var input service.CreateProjectInput + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + result, err := s.projects.Create(r.Context(), user, input) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "create", "project", input.Name, requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(scope.WithProject(r.Context(), result.Project.ID, result.Project.NodeID), user.TenantID, user.ID, "create", "project", strconv.FormatUint(result.Project.ID, 10), requestClientIP(r), true, "创建项目 "+result.Project.Slug) + writeJSON(w, http.StatusCreated, result) +} + +func projectID(r *http.Request) (uint64, error) { return strconv.ParseUint(r.PathValue("id"), 10, 64) } + +func writeProjectMutationError(w http.ResponseWriter, status int, err error) { + if errors.Is(err, store.ErrManagementLocked) { + writeCodedError(w, 423, "management_locked", err.Error()) + return + } + if errors.Is(err, store.ErrHostNotWritable) { + writeCodedError(w, http.StatusLocked, "host_not_writable", err.Error()) + return + } + if errors.Is(err, service.ErrQuotaSuspended) { + writeCodedError(w, http.StatusLocked, "quota_suspended", "资源套餐已超额,当前仅允许读取、停止服务或清理数据") + return + } + writeError(w, status, err.Error()) +} + +func (s *Server) setProjectState(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "项目编号无效") + return + } + var input struct { + Enabled bool `json:"enabled"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + if err = s.projects.SetState(r.Context(), user, id, input.Enabled); err != nil { + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "state", "project", strconv.FormatUint(id, 10), requestClientIP(r), true, map[bool]string{true: "启动项目", false: "停止项目"}[input.Enabled]) + w.WriteHeader(http.StatusNoContent) +} +func (s *Server) setProjectRunPath(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "项目编号无效") + return + } + var input struct { + RunPath string `json:"runPath"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + project, err := s.projects.SetRunPath(r.Context(), user, id, input.RunPath) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "update", "run_path", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "update", "run_path", strconv.FormatUint(id, 10), requestClientIP(r), true, "运行目录改为 "+project.RunPath) + writeJSON(w, http.StatusOK, map[string]any{"project": project}) +} + +func (s *Server) projectCredentials(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "主机编号无效") + return + } + result, err := s.projects.Credentials(r.Context(), currentUser(r), id) + if err != nil { + status := http.StatusUnprocessableEntity + if errors.Is(err, store.ErrNotFound) { + status = http.StatusNotFound + } + writeError(w, status, "无法读取主机凭据") + return + } + writeJSON(w, http.StatusOK, map[string]any{"credentials": result.Credentials}) +} + +func (s *Server) resetHostPassword(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "主机编号无效") + return + } + user := currentUser(r) + password, err := s.projects.ResetHostPassword(r.Context(), user, id) + if err != nil { + status := http.StatusUnprocessableEntity + if errors.Is(err, store.ErrNotFound) { + status = http.StatusNotFound + } + s.store.Log(r.Context(), user.TenantID, user.ID, "reset", "host_password", strconv.FormatUint(id, 10), requestClientIP(r), false, err.Error()) + writeError(w, status, err.Error()) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "reset", "host_password", strconv.FormatUint(id, 10), requestClientIP(r), true, "重置主机登录密码并注销旧会话") + writeJSON(w, http.StatusOK, map[string]string{"password": password}) +} + +func (s *Server) projectSites(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "主机编号无效") + return + } + user := currentUser(r) + if r.Method == http.MethodGet { + sites, readErr := s.projects.Sites(r.Context(), user, id) + if readErr != nil { + writeError(w, http.StatusNotFound, "虚拟主机不存在") + return + } + writeJSON(w, http.StatusOK, map[string]any{"sites": sites}) + return + } + var input service.CreateSiteInput + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + site, err := s.projects.CreateSite(r.Context(), user, id, input) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "create", "site", input.Name, requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "create", "site", strconv.FormatUint(site.ID, 10), requestClientIP(r), true, "创建网站 "+site.Name) + writeJSON(w, http.StatusCreated, map[string]any{"site": site}) +} + +func siteID(r *http.Request) (uint64, error) { + return strconv.ParseUint(r.PathValue("siteID"), 10, 64) +} + +func (s *Server) setSiteState(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + var input struct { + Enabled bool `json:"enabled"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + site, err := s.projects.SetSiteState(r.Context(), user, projectID, siteID, input.Enabled) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "state", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "state", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), true, map[bool]string{true: "启动网站", false: "停止网站"}[input.Enabled]) + writeJSON(w, http.StatusOK, map[string]any{"site": site}) +} + +func (s *Server) checkSiteDeployment(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + var input struct { + EntryFile string `json:"entryFile"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + check, err := s.projects.CheckDeployment(r.Context(), user, projectID, siteID, input.EntryFile) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "check", "deployment", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error()) + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "check", "deployment", strconv.FormatUint(siteID, 10), requestClientIP(r), check.Ready, check.Message) + writeJSON(w, http.StatusOK, map[string]any{"check": check}) +} + +func (s *Server) deploySite(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + var input struct { + EntryFile string `json:"entryFile"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + site, err := s.projects.DeploySite(r.Context(), user, projectID, siteID, input.EntryFile) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "deploy", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "deploy", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "语言项目已启动并接入 Nginx") + writeJSON(w, http.StatusOK, map[string]any{"site": site}) +} + +func (s *Server) deleteSite(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + user := currentUser(r) + if err := s.projects.DeleteSite(r.Context(), user, projectID, siteID); err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "delete", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), false, err.Error()) + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "delete", "site", strconv.FormatUint(siteID, 10), requestClientIP(r), true, "删除网站配置,保留主机目录文件") + w.WriteHeader(http.StatusNoContent) +} +func (s *Server) bindDomain(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, http.StatusBadRequest, "项目编号无效") + return + } + var input struct { + Domain string `json:"domain"` + } + if err = decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + domain, err := s.projects.BindDomain(r.Context(), user, id, strings.TrimSpace(input.Domain)) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), true, "绑定自定义域名") + writeJSON(w, http.StatusAccepted, map[string]any{"domain": domain}) +} + +func (s *Server) bindSiteDomain(w http.ResponseWriter, r *http.Request) { + projectID, projectErr := projectID(r) + siteID, siteErr := siteID(r) + if projectErr != nil || siteErr != nil { + writeError(w, http.StatusBadRequest, "网站编号无效") + return + } + var input struct { + Domain string `json:"domain"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "请求格式错误") + return + } + user := currentUser(r) + domain, err := s.projects.BindSiteDomain(r.Context(), user, projectID, siteID, strings.TrimSpace(input.Domain)) + if err != nil { + s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), false, err.Error()) + writeProjectMutationError(w, http.StatusUnprocessableEntity, err) + return + } + s.store.Log(r.Context(), user.TenantID, user.ID, "bind", "domain", input.Domain, requestClientIP(r), true, "为网站 "+strconv.FormatUint(siteID, 10)+" 绑定自定义域名") + writeJSON(w, http.StatusAccepted, map[string]any{"domain": domain}) +} diff --git a/backend/internal/httpapi/resource_crud.go b/backend/internal/httpapi/resource_crud.go new file mode 100644 index 0000000..1410bf9 --- /dev/null +++ b/backend/internal/httpapi/resource_crud.go @@ -0,0 +1,220 @@ +package httpapi + +import ( + "errors" + "net/http" + "net/mail" + "sea-vhost/internal/store" + "strconv" + "strings" +) + +func (s *Server) resourceAudit(r *http.Request, action, kind string, id uint64, err error, detail string) { + s.store.Log(r.Context(), nil, currentUser(r).ID, action, kind, strconv.FormatUint(id, 10), requestClientIP(r), err == nil, detail) +} +func (s *Server) adminAccount(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("id"), 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "用户编号无效") + return + } + p, err := s.store.AccountProfile(r.Context(), id) + if err != nil { + writeError(w, 404, "用户不存在或已删除") + return + } + if r.Method == http.MethodGet { + writeJSON(w, 200, p) + return + } + if r.Method == http.MethodDelete { + var input struct { + Confirmation string `json:"confirmation"` + } + if decodeJSON(r, &input) != nil || input.Confirmation != p.Slug { + writeError(w, 422, "请输入用户标识确认删除") + return + } + err = s.store.DeleteAccount(r.Context(), id) + s.resourceAudit(r, "delete", "account", id, err, "删除用户 "+p.Slug+",保留审计记录") + if err != nil { + writeError(w, 409, "无法删除用户:请先解绑或转移全部主机,并确认没有正在执行的归属变更") + return + } + w.WriteHeader(204) + return + } + var input store.AccountProfile + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + input.Name = strings.TrimSpace(input.Name) + input.DisplayName = strings.TrimSpace(input.DisplayName) + 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, "请检查用户名称、联系人姓名和登录邮箱") + return + } + err = s.store.UpdateAccount(r.Context(), id, input) + s.resourceAudit(r, "update", "account", id, err, "更新用户资料 "+p.Slug) + if err != nil { + writeError(w, 422, "无法保存用户资料,请检查登录邮箱是否重复") + return + } + w.WriteHeader(204) +} +func (s *Server) adminHostRecord(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, 400, "主机编号无效") + return + } + hosts, err := s.store.ListAdminProjects(r.Context()) + if err != nil { + writeError(w, 500, "无法读取主机") + return + } + var host *store.AdminProject + for i := range hosts { + if hosts[i].ID == id { + host = &hosts[i] + break + } + } + if host == nil { + writeError(w, 404, "主机不存在") + return + } + if r.Method == http.MethodGet { + writeJSON(w, 200, host) + return + } + if r.Method == http.MethodDelete { + var input struct { + Confirmation string `json:"confirmation"` + } + if decodeJSON(r, &input) != nil || input.Confirmation != host.HostName { + writeError(w, 422, "请输入主机名确认回收") + return + } + err = s.projects.RecycleManagedHost(r.Context(), id) + s.resourceAudit(r, "recycle", "project", id, err, "手动回收主机 "+host.HostName+";7 天后清理,备份保留 14 天") + if err != nil { + writeError(w, 409, err.Error()) + return + } + w.WriteHeader(204) + return + } + var input struct { + Name string `json:"name"` + AllowRuntimeChange *bool `json:"allowRuntimeChange"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + input.Name = strings.TrimSpace(input.Name) + if len([]rune(input.Name)) < 1 || len([]rune(input.Name)) > 50 || strings.ContainsAny(input.Name, "\x00\r\n") { + writeError(w, 422, "主机显示名称应为 1–50 个字符") + return + } + err = s.store.RenameHost(r.Context(), id, input.Name) + if err == nil && input.AllowRuntimeChange != nil { + err = s.store.SetRuntimePolicy(r.Context(), id, *input.AllowRuntimeChange) + } + s.resourceAudit(r, "update", "project", id, err, "修改主机显示名称 "+host.HostName) + if err != nil { + writeError(w, 409, "无法修改名称,请检查主机是否正在回收或处理归属变更") + return + } + w.WriteHeader(204) +} +func (s *Server) adminRestoreHost(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, 400, "主机编号无效") + return + } + err = s.projects.RestoreManagedHost(r.Context(), id) + s.resourceAudit(r, "restore", "project", id, err, "恢复手动回收主机;网站和 FTP 保持停止,计划任务保持暂停") + if err != nil { + writeError(w, 409, err.Error()) + return + } + w.WriteHeader(204) +} +func (s *Server) adminNodeRecord(w http.ResponseWriter, r *http.Request) { + id, err := nodeID(r) + if err != nil || id == 0 { + writeError(w, 400, "节点编号无效") + return + } + existing, err := s.store.Node(r.Context(), id) + if err != nil { + writeError(w, 404, "节点不存在或已删除") + return + } + if r.Method == http.MethodGet { + writeJSON(w, 200, existing) + return + } + if r.Method == http.MethodDelete { + var input struct { + Confirmation string `json:"confirmation"` + } + if decodeJSON(r, &input) != nil || input.Confirmation != existing.Name { + writeError(w, 422, "请输入节点名称确认删除") + return + } + err = s.projects.DeleteManagedNode(r.Context(), id) + s.resourceAudit(r, "delete", "node", id, err, "删除节点 "+existing.Name+",撤销主控保存的连接凭据") + } else { + var input store.Node + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + normalizeNodeMetadata(&input) + if err = validateNodeMetadata(input, existing.Transport == "local"); err != nil { + writeError(w, 422, err.Error()) + return + } + err = s.projects.UpdateManagedNode(r.Context(), id, input) + s.resourceAudit(r, "update", "node", id, err, "更新节点配置 "+existing.Name) + } + if err != nil { + if errors.Is(err, store.ErrNotFound) { + writeError(w, 404, "节点不存在或已删除") + } else { + writeError(w, 409, err.Error()) + } + return + } + w.WriteHeader(204) +} + +func (s *Server) adminDetachRecycledHost(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + if err != nil { + writeError(w, 400, "主机编号无效") + return + } + var input struct { + Version uint64 `json:"ownershipVersion"` + Confirmation string `json:"confirmation"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请求格式错误") + return + } + err = s.store.DetachRecycledHost(r.Context(), id, input.Version, input.Confirmation) + s.resourceAudit(r, "unbind", "project", id, err, "手动解绑回收主机的用户,保持回收状态与保留期限") + if err != nil { + writeError(w, 409, err.Error()) + return + } + w.WriteHeader(204) +} diff --git a/backend/internal/httpapi/resource_crud_integration_test.go b/backend/internal/httpapi/resource_crud_integration_test.go new file mode 100644 index 0000000..1ea6421 --- /dev/null +++ b/backend/internal/httpapi/resource_crud_integration_test.go @@ -0,0 +1,521 @@ +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/scope" + "sea-vhost/internal/service" + "sea-vhost/internal/store" + "strconv" + "strings" + "testing" + "time" +) + +func TestResourceCRUDMySQL(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() + if err = db.Migrate(ctx); err != nil { + t.Fatal(err) + } + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + must(db.BootstrapAdmin(ctx, "crud-admin@example.invalid", "CRUD 管理员", "crud-admin-password-123")) + admin, err := db.UserByLogin(ctx, "crud-admin@example.invalid") + must(err) + root := t.TempDir() + must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid")) + 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) + 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 b bytes.Buffer + if body != nil { + must(json.NewEncoder(&b).Encode(body)) + } + r := httptest.NewRequest(method, "https://control.example.invalid"+path, &b) + 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()) + } + } + + t.Run("node runtime queue is serial and permits unrelated submissions", func(t *testing.T) { + ids := []uint64{} + for _, v := range []string{"queue-a", "queue-b", "queue-c"} { + id, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: v}) + must(e) + ids = append(ids, id) + } + if _, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "queue-a"}); e == nil { + t.Fatal("duplicate queued work accepted") + } + first, e := db.ClaimRuntimeJob(ctx) + must(e) + if first.ID != ids[0] { + t.Fatal("queue not FIFO") + } + if _, e = db.ClaimRuntimeJob(ctx); e == nil { + t.Fatal("two runtime jobs execute concurrently on one node") + } + must(db.UpdateRuntimeJob(ctx, first.ID, "completed", "verified", "test")) + second, e := db.ClaimRuntimeJob(ctx) + must(e) + if second.ID != ids[1] { + t.Fatal("wrong queued task") + } + must(db.UpdateRuntimeJob(ctx, second.ID, "interrupted", "installing", "test interruption")) + if _, e = db.ClaimRuntimeJob(ctx); e == nil { + t.Fatal("unverified task did not block later execution") + } + must(db.RetryRuntimeJob(scope.WithNode(ctx, 1), second.ID)) + again, e := db.ClaimRuntimeJob(ctx) + must(e) + if again.ID != second.ID { + t.Fatal("resume skipped interrupted work") + } + must(db.UpdateRuntimeJob(ctx, again.ID, "completed", "verified", "test")) + last, e := db.ClaimRuntimeJob(ctx) + must(e) + must(db.UpdateRuntimeJob(ctx, last.ID, "completed", "verified", "test")) + }) + account, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-customer", Name: "CRUD 用户", Email: "crud-customer@example.invalid", DisplayName: "测试联系人", Password: "crud-customer-password-123", PlanID: 1}) + must(err) + user, err := db.UserByLogin(ctx, "crud-customer@example.invalid") + must(err) + userToken, err := auth.NewSessionToken(secret) + must(err) + must(db.CreateSession(ctx, user.ID, userToken, time.Now().Add(time.Hour))) + ap := "/api/v1/admin/tenants/" + strconv.FormatUint(account, 10) + expect(call("GET", ap, nil, ""), 401) + expect(call("GET", ap, nil, userToken), 403) + expect(call("GET", "/api/v1/admin/audit", nil, userToken), 403) + db.Log(ctx, nil, admin.ID, "filter_test", "account", "test", "127.0.0.1", false, "ui19-audit-filter") + expect(call("GET", "/api/v1/admin/audit?q=ui19-audit-filter&result=failure&limit=50&page=1", nil, token), 200) + filtered, total, e := db.FilterAdminActivities(ctx, store.AuditFilter{Query: "ui19-audit-filter", Result: "failure", Limit: 50, Page: 1}) + must(e) + if len(filtered) != 1 || total != 1 || filtered[0].Success { + t.Fatal("audit filter ignored criteria") + } + expect(call("GET", ap, nil, token), 200) + expect(call("PUT", ap, map[string]any{"name": "更新用户", "displayName": "更新联系人", "email": "crud-updated@example.invalid"}, token), 204) + if _, err = db.UserByLogin(ctx, "crud-customer@example.invalid"); err == nil { + t.Fatal("old email still authenticates") + } + if _, err = db.UserBySession(ctx, userToken); err == nil { + t.Fatal("email change did not revoke old session") + } + user, err = db.UserByLogin(ctx, "crud-updated@example.invalid") + must(err) + 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 + 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 { + t.Fatal("unconfigured language site exposes its document root") + } + hp := "/api/v1/admin/projects/" + strconv.FormatUint(id, 10) + expect(call("PUT", hp, map[string]string{"name": "更新主机名称"}, token), 204) + host, err := db.Project(ctx, created.Project.TenantID, id) + must(err) + if host.HostName != created.Project.HostName || host.Path != created.Project.Path || host.Slug != "更新主机名称" { + t.Fatal("rename changed physical identity") + } + sites, err := db.ListSites(ctx, created.Project.TenantID, id) + must(err) + if len(sites) == 0 { + t.Fatal("missing primary site") + } + if _, e := projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "Node.js", "v22.23.3", ""); e == nil { + t.Fatal("cross-language change bypassed host policy") + } + runtimeJob, e := projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "PHP", "8.2", "") + must(e) + must(db.UpdateRuntimeJob(ctx, runtimeJob, "completed", "verified", "queue-only permission test")) + expect(call("PUT", hp, map[string]any{"name": host.Slug, "allowRuntimeChange": true}, token), 204) + policyHost, e := db.Project(ctx, host.TenantID, id) + must(e) + if !policyHost.AllowRuntimeChange { + t.Fatal("host runtime policy not persisted") + } + runtimeJob, e = projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "Node.js", "v22.23.3", "") + must(e) + must(db.UpdateRuntimeJob(ctx, runtimeJob, "completed", "verified", "queue-only permission test")) + // An unresolved tenant runtime job locks only its host; node-level recovery remains available. + localJob, e := projects.SubmitSiteRuntime(scope.WithAccount(ctx, account), user, id, sites[0].ID, "PHP", "8.2", "") + must(e) + must(db.UpdateRuntimeJob(ctx, localJob, "interrupted", "switching", "local recovery test")) + ownBlocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, id, 1)) + must(e) + otherBlocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, pending.Project.ID, 1)) + must(e) + nodeBlocked, e := db.RuntimeMutationBlocked(scope.WithNode(ctx, 1)) + must(e) + if !ownBlocked || otherBlocked || nodeBlocked { + t.Fatal("tenant runtime recovery escaped its host scope") + } + independent, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "recovery-check"}) + must(e) + claimed, e := db.ClaimRuntimeJob(ctx) + must(e) + if claimed.ID != independent { + t.Fatal("host recovery blocked other queued work") + } + must(db.UpdateRuntimeJob(ctx, independent, "completed", "verified", "test")) + must(db.UpdateRuntimeJob(ctx, localJob, "failed", "failed", "test cleanup")) + must(db.AddCustomDomainForSite(ctx, created.Project.TenantID, id, sites[0].ID, "crud-policy.example.invalid", "pending", 100)) + domain, err := db.DomainByName(ctx, created.Project.TenantID, id, sites[0].ID, "crud-policy.example.invalid") + must(err) + policyPath := "/api/v1/admin/domains/" + strconv.FormatUint(domain.ID, 10) + "/metadata" + policy := map[string]string{"resolutionMode": "cname", "cnameTarget": host.Domain, "filingStatus": "approved", "filingNumber": "测试备案号", "filingNote": "事务验收"} + expect(call("PUT", policyPath, policy, token), 204) + expect(call("PUT", policyPath, policy, token), 204) + policy["filingStatus"] = "exempt" + expect(call("PUT", policyPath, policy, token), 204) + updatedDomain, err := db.DomainByID(ctx, domain.ID) + must(err) + if updatedDomain.FilingStatus != "exempt" || updatedDomain.CNAME != host.Domain { + t.Fatal("domain policy not saved atomically") + } + policy["cnameTarget"] = "https://invalid.example.invalid/path" + expect(call("PUT", policyPath, policy, token), 422) + // Removing pending/approved custom names never removes the assigned name or site. + unbindPath := "/api/v1/admin/domains/" + strconv.FormatUint(domain.ID, 10) + expect(call("DELETE", unbindPath, map[string]string{"confirmation": "wrong.example.invalid"}, token), 422) + expect(call("DELETE", unbindPath, map[string]string{"confirmation": domain.Domain}, token), 204) + if _, err = db.DomainByID(ctx, domain.ID); err == nil { + t.Fatal("unbound custom domain remains") + } + domains, err := db.ListDomains(ctx, host.TenantID, &id) + must(err) + for _, d := range domains { + if d.Kind == "assigned" { + expect(call("DELETE", "/api/v1/admin/domains/"+strconv.FormatUint(d.ID, 10), map[string]string{"confirmation": d.Domain}, token), 422) + } + } + // A host account can unbind its own approved custom name, while a user + // without ownership cannot reach the same operation. + must(db.AddCustomDomainForSite(ctx, host.TenantID, id, sites[0].ID, "crud-approved.example.invalid", "approved", 100)) + approvedDomain, err := db.DomainByName(ctx, host.TenantID, id, sites[0].ID, "crud-approved.example.invalid") + must(err) + hostUser, err := db.UserByLogin(ctx, host.HostName) + must(err) + hostToken, err := auth.NewSessionToken(secret) + must(err) + must(db.CreateSession(ctx, hostUser.ID, hostToken, time.Now().Add(time.Hour))) + t.Run("panel updates never freeze host writes and migrations stay local", func(t *testing.T) { + // The isolation mock records a path without creating its directory. + if e := os.MkdirAll(host.Path, 0700); e != nil { + t.Fatal(e) + } + filePath := "/api/v1/projects/" + strconv.FormatUint(id, 10) + "/files" + patch, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: "7.4.33", TargetVersion: "7.4.34"}) + must(e) + for _, status := range []string{"running", "interrupted"} { + must(db.UpdateRuntimeJob(ctx, patch, status, "installing", "panel update scope regression")) + for _, projectID := range []uint64{0, id, pending.Project.ID} { + blocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, projectID, 1)) + must(e) + if blocked { + t.Fatalf("PHP component %s blocked project %d", status, projectID) + } + release, e := projects.BeginRuntimeMutation(scope.WithProject(ctx, projectID, 1)) + must(e) + release() + } + expect(call("PUT", filePath, map[string]any{"path": "panel-update-" + status + ".txt", "content": "unrelated host remains writable"}, hostToken), 204) + } + must(db.UpdateRuntimeJob(ctx, patch, "completed", "verified", "test cleanup")) + // 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) + 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) + workerDone := make(chan struct{}) + go func() { defer close(workerDone); gateProjects.RunRuntimeMaintenance(workerCtx) }() + defer func() { + stopWorker() + select { + case <-workerDone: + case <-time.After(5 * time.Second): + t.Error("runtime worker did not stop") + } + }() + select { + case <-gatePanel.entered: + case <-time.After(5 * time.Second): + t.Fatal("runtime worker never reached the panel queue") + } + body := strings.NewReader(`{"path":"panel-worker-busy.txt","content":"writes remain available"}`) + request := httptest.NewRequest("PUT", "https://control.example.invalid"+filePath, body) + request.Header.Set("Origin", "https://control.example.invalid") + request.Header.Set("Content-Type", "application/json") + request.AddCookie(&http.Cookie{Name: "sea_session", Value: hostToken}) + response := httptest.NewRecorder() + gateServer.Handler().ServeHTTP(response, request) + if response.Code != 204 { + t.Fatalf("busy panel froze unrelated host writes: HTTP %d %s", response.Code, response.Body.String()) + } + stopWorker() + select { + case <-workerDone: + case <-time.After(5 * time.Second): + t.Fatal("runtime worker did not stop") + } + must(db.UpdateRuntimeJob(ctx, busyJob, "failed", "failed", "test cleanup")) + for _, action := range []string{"migrate", "runtime_change"} { + siteID := sites[0].ID + job, e := db.CreateRuntimeJob(scope.WithNode(ctx, 1), store.RuntimeJob{Action: action, Runtime: "PHP", FromVersion: "8.4", TargetVersion: "8.2", SiteID: &siteID}) + must(e) + must(db.UpdateRuntimeJob(ctx, job, "interrupted", "switching", "target host only")) + for _, projectID := range []uint64{0, id, pending.Project.ID} { + blocked, e := db.RuntimeMutationBlocked(scope.WithProject(ctx, projectID, 1)) + must(e) + if blocked != (projectID == id) { + t.Fatalf("%s scope mismatch for project %d", action, projectID) + } + } + expect(call("PUT", filePath, map[string]any{"path": "conflicting-site-switch.txt", "content": "must be rejected"}, hostToken), 423) + must(db.UpdateRuntimeJob(ctx, job, "failed", "failed", "test cleanup")) + } + }) + foreignAccount, err := db.CreateTenant(ctx, store.NewTenant{Slug: "crud-foreign", Name: "外部用户", Email: "foreign@example.invalid", DisplayName: "外部", Password: "foreign-password-123", PlanID: 1}) + must(err) + _ = foreignAccount + foreignUser, err := db.UserByLogin(ctx, "foreign@example.invalid") + must(err) + foreignToken, err := auth.NewSessionToken(secret) + must(err) + must(db.CreateSession(ctx, foreignUser.ID, foreignToken, time.Now().Add(time.Hour))) + userDomainPath := "/api/v1/domains/" + strconv.FormatUint(approvedDomain.ID, 10) + expect(call("DELETE", userDomainPath, map[string]string{"confirmation": approvedDomain.Domain}, foreignToken), 404) + expect(call("DELETE", userDomainPath, map[string]string{"confirmation": approvedDomain.Domain}, hostToken), 204) + must(db.UpdateQuotaMeasurement(scope.WithProject(ctx, id, 1), host.TenantID, store.Usage{BandwidthBytes: 36 << 20}, time.Now().UTC(), nil, false)) + dashboardResponse := call("GET", "/api/v1/dashboard", nil, hostToken) + expect(dashboardResponse, 200) + var measured struct { + Projects []store.Project `json:"projects"` + } + must(json.Unmarshal(dashboardResponse.Body.Bytes(), &measured)) + if len(measured.Projects) != 1 || measured.Projects[0].ID != id || measured.Projects[0].BandwidthBytes != 36<<20 { + t.Fatal("dashboard did not return scoped measured host traffic") + } + if _, err = db.Site(ctx, host.TenantID, id, sites[0].ID); err != nil { + t.Fatal("unbinding removed site") + } + planID, err := db.CreatePlan(ctx, store.NewPlan{Name: "unused-copy", StorageBytes: 1 << 30, DatabaseBytes: 1 << 30, BandwidthBytes: 1 << 30, ProcessLimit: 10, FTPLimit: 1, DatabaseLimit: 1, ProjectLimit: 1}) + must(err) + pp := "/api/v1/admin/plans/" + strconv.FormatUint(planID, 10) + expect(call("DELETE", pp, map[string]string{"confirmation": "wrong"}, token), 409) + expect(call("DELETE", pp, map[string]string{"confirmation": "unused-copy"}, token), 204) + if _, err = db.Plan(ctx, planID); err == nil { + t.Fatal("deleted plan visible") + } + if err = db.DeleteUnusedPlan(ctx, 1, "基础套餐"); err == nil { + t.Fatal("default plan deleted") + } + expect(call("DELETE", ap, map[string]string{"confirmation": "crud-customer"}, token), 409) + expect(call("DELETE", hp, map[string]string{"confirmation": "wrong-host"}, token), 422) + expect(call("DELETE", hp, map[string]string{"confirmation": host.HostName}, token), 204) + first, err := db.HostLifecycle(ctx, id) + must(err) + if first.State != "recycle" || first.PurgeAfter == nil || time.Until(*first.PurgeAfter) < 167*time.Hour { + t.Fatal("incorrect manual recycle window") + } + expect(call("DELETE", hp, map[string]string{"confirmation": host.HostName}, token), 204) + second, err := db.HostLifecycle(ctx, id) + must(err) + if !first.PurgeAfter.Equal(*second.PurgeAfter) { + t.Fatal("retry extended retention") + } + if _, err = db.UserByLogin(ctx, host.HostName); err == nil { + t.Fatal("recycled host still authenticates") + } + if err = db.HostWritable(scope.WithProject(ctx, id, 1), host.TenantID); err == nil { + t.Fatal("recycled host writable") + } + if err = db.SetHostSubscription(ctx, id, 1, nil); err == nil { + t.Fatal("ordinary renewal restored manual deletion") + } + if _, err = db.ProjectForUser(scope.WithAccount(ctx, account), user, id); err == nil { + t.Fatal("recycled host visible to previous owner") + } + expect(call("DELETE", ap, map[string]string{"confirmation": "crud-customer"}, token), 409) + recycleHosts, e := db.ListAdminProjects(ctx) + must(e) + var recycledVersion uint64 + for _, h := range recycleHosts { + if h.ID == id { + recycledVersion = h.OwnershipVersion + } + } + expect(call("DELETE", hp+"/recycled-owner", map[string]any{"ownershipVersion": recycledVersion + 1, "confirmation": host.HostName}, token), 409) + expect(call("DELETE", hp+"/recycled-owner", map[string]any{"ownershipVersion": recycledVersion, "confirmation": host.HostName}, token), 204) + explicitOwner, e := db.ProjectOwner(ctx, id) + must(e) + if explicitOwner != nil { + t.Fatal("explicit recycled detach failed") + } + expect(call("POST", hp+"/restore", nil, token), 204) + restored, err := db.Project(ctx, host.TenantID, id) + must(err) + if restored.Status == "running" { + t.Fatal("restore auto-started site") + } + must(db.HostWritable(scope.WithProject(ctx, id, 1), host.TenantID)) + ftps, err := db.ListFTPResources(scope.WithProject(ctx, id, 1), host.TenantID, &id) + must(err) + for _, ftp := range ftps { + if ftp.Enabled { + t.Fatal("restore auto-enabled FTP") + } + } + // Reassigning away permits deleting the account while retaining host access. + hosts, err := db.ListAdminProjects(ctx) + must(err) + var version uint64 + for _, h := range hosts { + if h.ID == id { + version = h.OwnershipVersion + } + } + _, err = projects.ChangeHostOwner(scope.WithProject(ctx, id, 1), id, version, 0, "preserve", true, false) + must(err) + expect(call("DELETE", ap, map[string]string{"confirmation": "crud-customer"}, token), 204) + if _, err = db.AccountProfile(ctx, account); err == nil { + t.Fatal("deleted account still visible") + } + if err = db.SetAccountEnabled(ctx, account, true); err == nil { + t.Fatal("batch re-enabled deleted account") + } + if err = db.SetTenantExpiry(ctx, account, nil); err == nil { + t.Fatal("legacy expiry re-enabled deleted account") + } + if _, err = db.UserByLogin(ctx, "crud-updated@example.invalid"); err == nil { + t.Fatal("deleted user authenticates") + } + // Local node cannot be deleted, and existing hosts prevent deleting a remote. + expect(call("DELETE", "/api/v1/admin/nodes/1", map[string]string{"confirmation": "本机节点"}, token), 409) + node := store.Node{Name: "CRUD 节点", Endpoint: "https://crud.example.invalid:9443", RootDomain: "hosts.example.invalid", TenantRoot: "/www/wwwroot/seavHost/vHost", FTPCertificateDomain: "control.example.invalid"} + nodeID, err := db.CreateNode(ctx, node) + must(err) + np := "/api/v1/admin/nodes/" + strconv.FormatUint(nodeID, 10) + expect(call("GET", np, nil, token), 200) + node.Name = "更新节点" + expect(call("PATCH", np, node, token), 204) + stored, err := db.Node(ctx, nodeID) + must(err) + if stored.Enabled || stored.Name != "更新节点" { + t.Fatal("metadata edit changed enable flag") + } + must(db.SetNodeEnabled(ctx, nodeID, true)) + expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409) + must(db.SetNodeEnabled(ctx, nodeID, false)) + // Backups and uncertain controller tasks both block deletion. + must(db.CreateTenantBackup(scope.WithNode(ctx, nodeID), host.TenantID, id, host.HostName, "/test/crud-backup.tar", 1, time.Now().Add(14*24*time.Hour), 1)) + expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409) + backups, err := db.ExpiredTenantBackups(ctx, time.Now().Add(15*24*time.Hour), 100) + must(err) + for _, b := range backups { + if b.NodeID == nodeID { + must(db.MarkTenantBackupDeleted(ctx, b.ID)) + } + } + taskID, err := db.StartControlTask(ctx, nodeID, 0, "crud/test", "11111111111111111111111111111111") + must(err) + expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409) + must(db.FinishControlTask(ctx, taskID, "uncertain", "test")) + expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 409) + must(db.FinishControlTask(ctx, taskID, "succeeded", "verified")) + expect(call("DELETE", np, map[string]string{"confirmation": node.Name}, token), 204) + if _, err = db.Node(ctx, nodeID); err == nil { + t.Fatal("deleted node visible") + } + must(db.SetNodeCredentials(ctx, nodeID, []byte("revoked"))) + if err = db.SetNodeEnabled(ctx, nodeID, true); err == nil { + t.Fatal("deleted node re-enabled") + } + expect(call("GET", np, nil, token), 404) +} + +type pendingStatePanel struct { + *panel.Mock + states map[int64]bool +} + +type busyPatchPanel struct { + *panel.Mock + entered chan struct{} +} + +func (p *busyPatchPanel) PHPRuntimeUpdatePending(ctx context.Context, _ string) (bool, error) { + close(p.entered) + <-ctx.Done() + return false, ctx.Err() +} +func (*busyPatchPanel) UpdatePHPRuntime(context.Context, string, string) error { return nil } +func (*busyPatchPanel) ManagedRuntime(context.Context, int64) (panel.RuntimeSpec, error) { + return panel.RuntimeSpec{}, nil +} +func (*busyPatchPanel) ReplaceManagedRuntime(context.Context, int64, panel.RuntimeSpec) error { + return nil +} + +type patchProbeIsolation struct{ isolation.Mock } + +func (patchProbeIsolation) MaintainPHP(context.Context, isolation.PHPMaintenanceSpec) (isolation.PHPState, error) { + return isolation.PHPState{Version: "7.4.33"}, nil +} +func (patchProbeIsolation) ProbeRuntime(context.Context, isolation.RuntimeProbeSpec) (isolation.RuntimeObservation, error) { + return isolation.RuntimeObservation{Healthy: true}, nil +} +func (patchProbeIsolation) CopyPythonDependencies(context.Context, isolation.PanelRuntimeSpec, string) error { + return nil +} + +func (p *pendingStatePanel) SetSiteState(_ context.Context, id int64, _ string, enabled bool) error { + p.states[id] = enabled + return nil +} diff --git a/backend/internal/httpapi/resources.go b/backend/internal/httpapi/resources.go new file mode 100644 index 0000000..04f6981 --- /dev/null +++ b/backend/internal/httpapi/resources.go @@ -0,0 +1,29 @@ +package httpapi + +import "net/http" + +func (s *Server) resources(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + tenantID := *user.TenantID + domains, err := s.store.ListDomains(r.Context(), tenantID, user.ProjectID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取域名资源") + return + } + ftpAccounts, err := s.store.ListFTPResources(r.Context(), tenantID, user.ProjectID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取 FTP 资源") + return + } + databases, err := s.store.ListDatabaseResources(r.Context(), tenantID, user.ProjectID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取数据库资源") + return + } + sites, err := s.store.ListTenantSites(r.Context(), tenantID, user.ProjectID) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法读取网站资源") + return + } + writeJSON(w, http.StatusOK, map[string]any{"domains": domains, "ftpAccounts": ftpAccounts, "databases": databases, "sites": sites}) +} diff --git a/backend/internal/httpapi/runtime_environments.go b/backend/internal/httpapi/runtime_environments.go new file mode 100644 index 0000000..fa3e8e7 --- /dev/null +++ b/backend/internal/httpapi/runtime_environments.go @@ -0,0 +1,59 @@ +package httpapi + +import ( + "net/http" + "slices" + "strings" +) + +var installableRuntimes = []string{"Node.js", "Python", "Go", "Java"} +var installableRuntimeComponents = []string{"Node.js", "Python"} + +func (s *Server) adminRuntimeEnvironments(w http.ResponseWriter, r *http.Request) { + items, err := s.projects.RuntimeEnvironments(r.Context()) + if err != nil { + writeError(w, http.StatusBadGateway, "无法读取宝塔运行环境") + return + } + writeJSON(w, http.StatusOK, map[string]any{"environments": items}) +} + +func (s *Server) adminInstallRuntimeComponent(w http.ResponseWriter, r *http.Request) { + runtimeName := strings.TrimSpace(r.PathValue("runtime")) + if !slices.Contains(installableRuntimeComponents, runtimeName) { + writeError(w, http.StatusUnprocessableEntity, "仅支持安装官方免费 Node.js 或 Python 管理组件") + return + } + user := currentUser(r) + if err := s.projects.InstallRuntimeComponent(r.Context(), runtimeName); err != nil { + s.store.Log(r.Context(), nil, user.ID, "install", "runtime_component", runtimeName, requestClientIP(r), false, err.Error()) + writeError(w, http.StatusBadGateway, "运行环境组件安装失败") + return + } + s.store.Log(r.Context(), nil, user.ID, "install", "runtime_component", runtimeName, requestClientIP(r), true, "安装官方免费 "+runtimeName+" 管理组件") + writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true}) +} + +func (s *Server) adminInstallRuntimeEnvironment(w http.ResponseWriter, r *http.Request) { + runtimeName := strings.TrimSpace(r.PathValue("runtime")) + if !slices.Contains(installableRuntimes, runtimeName) { + writeError(w, http.StatusUnprocessableEntity, "不支持安装该运行环境") + return + } + var input struct { + Version string `json:"version"` + } + if err := decodeJSON(r, &input); err != nil || strings.TrimSpace(input.Version) == "" { + writeError(w, http.StatusBadRequest, "请选择运行环境版本") + return + } + input.Version = strings.TrimSpace(input.Version) + user := currentUser(r) + if err := s.projects.InstallRuntimeEnvironment(r.Context(), runtimeName, input.Version); err != nil { + s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), false, err.Error()) + writeError(w, http.StatusBadGateway, "运行环境安装任务提交失败") + return + } + s.store.Log(r.Context(), nil, user.ID, "install", "runtime_environment", runtimeName+"/"+input.Version, requestClientIP(r), true, "提交 "+runtimeName+" "+input.Version+" 安装任务") + writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true}) +} diff --git a/backend/internal/httpapi/runtime_maintenance.go b/backend/internal/httpapi/runtime_maintenance.go new file mode 100644 index 0000000..466c5c1 --- /dev/null +++ b/backend/internal/httpapi/runtime_maintenance.go @@ -0,0 +1,84 @@ +package httpapi + +import ( + "net/http" + "strconv" +) + +func (s *Server) adminRuntimeMaintenance(w http.ResponseWriter, r *http.Request) { + targets, jobs, err := s.projects.RuntimeMaintenanceState(r.Context()) + if err != nil { + writeError(w, 502, "无法读取运行环境维护状态") + return + } + writeJSON(w, 200, map[string]any{"sites": targets, "jobs": jobs}) +} +func (s *Server) adminUpdatePHPPatch(w http.ResponseWriter, r *http.Request) { + var input struct { + Branch string `json:"branch"` + Target string `json:"target"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "请选择 PHP 分支与目标补丁版本") + return + } + id, err := s.projects.SubmitPHPPatch(r.Context(), input.Branch, input.Target) + s.logRuntimeMaintenance(r, "php_patch", "PHP/"+input.Target, err) + if err != nil { + writeError(w, 422, err.Error()) + return + } + writeJSON(w, 202, map[string]any{"jobId": id}) +} +func (s *Server) adminMigrateSiteRuntime(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("siteID"), 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "站点编号无效") + return + } + var input struct { + Version string `json:"version"` + AllowBranchChange bool `json:"allowBranchChange"` + EntryFile string `json:"entryFile"` + } + if decodeJSON(r, &input) != nil || input.Version == "" { + writeError(w, 400, "请选择目标版本") + return + } + jobID, err := s.projects.SubmitRuntimeMigration(r.Context(), id, input.Version, input.AllowBranchChange, input.EntryFile) + s.logRuntimeMaintenance(r, "migrate", r.PathValue("siteID")+"/"+input.Version, err) + if err != nil { + writeError(w, 422, err.Error()) + return + } + writeJSON(w, 202, map[string]any{"jobId": jobID}) +} +func (s *Server) adminResumeRuntimeMaintenance(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("jobID"), 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "任务编号无效") + return + } + err = s.projects.ResumeRuntimeMaintenance(r.Context(), id) + s.logRuntimeMaintenance(r, "resume", r.PathValue("jobID"), err) + if err != nil { + writeError(w, 409, "任务无法恢复,或已有其他维护任务正在执行") + return + } + writeJSON(w, 202, map[string]bool{"ok": true}) +} +func (s *Server) adminCheckRuntimeUpdates(w http.ResponseWriter, r *http.Request) { + id, err := s.projects.SubmitRuntimeCheck(r.Context()) + if err != nil { + writeError(w, 409, err.Error()) + return + } + writeJSON(w, 202, map[string]any{"jobId": id}) +} +func (s *Server) logRuntimeMaintenance(r *http.Request, action, target string, err error) { + detail := "已提交运行环境维护任务" + if err != nil { + detail = err.Error() + } + s.store.Log(r.Context(), nil, currentUser(r).ID, action, "runtime_maintenance", target, requestClientIP(r), err == nil, detail) +} diff --git a/backend/internal/httpapi/scheduler_bridge.go b/backend/internal/httpapi/scheduler_bridge.go new file mode 100644 index 0000000..fc90037 --- /dev/null +++ b/backend/internal/httpapi/scheduler_bridge.go @@ -0,0 +1,117 @@ +package httpapi + +import ( + "context" + "crypto/hmac" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "net/http" + "sea-vhost/internal/schedulerbridge" + "sea-vhost/internal/store" + "strconv" + "time" +) + +func (s *Server) schedulerKey(ctx context.Context, node uint64, create bool) (string, error) { + label := fmt.Sprintf("scheduler-trigger:%d", node) + raw, e := s.store.SystemSecret(ctx, label) + if e != nil && !errors.Is(e, store.ErrNotFound) { + return "", e + } + if len(raw) == 0 && create { + key := make([]byte, 32) + if _, e = rand.Read(key); e != nil { + return "", e + } + cipher, e := s.secretBox.Seal(label, hex.EncodeToString(key)) + if e != nil { + return "", e + } + if e = s.store.InsertSystemSecretIfAbsent(ctx, label, cipher); e != nil { + return "", e + } + raw, e = s.store.SystemSecret(ctx, label) + if e != nil { + return "", e + } + } + if len(raw) == 0 { + return "", fmt.Errorf("not configured") + } + return s.secretBox.Open(label, raw) +} +func (s *Server) adminScheduler(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + node, _ := strconv.ParseUint(s.store.Setting(r.Context(), "scheduler_node_id", "0"), 10, 64) + last, _ := s.store.LastSchedulerTick(r.Context()) + writeJSON(w, 200, map[string]any{"nodeId": node, "lastTick": last}) + return + } + var v struct { + NodeID uint64 `json:"nodeId"` + } + if decodeJSON(r, &v) != nil || v.NodeID == 0 { + writeError(w, 400, "请选择调度触发节点") + return + } + if s.cfg.ManagementDomain == "" { + writeError(w, 422, "请先设置管理域名") + return + } + key, e := s.schedulerKey(r.Context(), v.NodeID, true) + if e == nil { + e = s.projects.ConfigureSystemScheduler(r.Context(), schedulerbridge.Config{NodeID: v.NodeID, Controller: "https://" + s.cfg.ManagementDomain, Key: key}) + } + if e == nil { + e = s.store.SetSetting(r.Context(), "scheduler_node_id", fmt.Sprint(v.NodeID)) + } + if e != nil { + writeError(w, 422, "调度器配置失败:"+e.Error()) + return + } + u := currentUser(r) + s.store.Log(r.Context(), nil, u.ID, "configure", "scheduler", "", requestClientIP(r), true, "配置宝塔每分钟系统调度器") + w.WriteHeader(204) +} +func (s *Server) schedulerTick(w http.ResponseWriter, r *http.Request) { + nodeText := r.Header.Get("X-Sea-Node") + stamp := r.Header.Get("X-Sea-Time") + nonce := r.Header.Get("X-Sea-Nonce") + signature := r.Header.Get("X-Sea-Signature") + node, e := strconv.ParseUint(nodeText, 10, 64) + when, te := strconv.ParseInt(stamp, 10, 64) + nonceRaw, ne := hex.DecodeString(nonce) + if e != nil || te != nil || ne != nil || len(nonceRaw) != 16 || time.Since(time.Unix(when, 0)) > 30*time.Second || time.Until(time.Unix(when, 0)) > 30*time.Second || s.store.Setting(r.Context(), "scheduler_node_id", "0") != nodeText { + writeError(w, 401, "调度身份无效") + return + } + n, e := s.store.Node(r.Context(), node) + key, ke := s.schedulerKey(r.Context(), node, false) + if e != nil || !n.Enabled || ke != nil || !hmac.Equal([]byte(signature), []byte(schedulerbridge.Signature(key, nodeText, stamp, nonce))) { + writeError(w, 401, "调度身份无效") + return + } + if !s.schedulerRunning.TryLock() { + w.WriteHeader(204) + return + } + claimed, e := s.store.ClaimSchedulerTick(r.Context(), node) + if e != nil || !claimed { + s.schedulerRunning.Unlock() + if e != nil { + writeError(w, 503, "调度暂不可用") + } else { + w.WriteHeader(204) + } + return + } + go func() { + defer s.schedulerRunning.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + defer cancel() + _ = s.projects.QueueUserSchedules(ctx) + }() + w.WriteHeader(202) +} diff --git a/backend/internal/httpapi/server.go b/backend/internal/httpapi/server.go new file mode 100644 index 0000000..a5689d3 --- /dev/null +++ b/backend/internal/httpapi/server.go @@ -0,0 +1,593 @@ +package httpapi + +import ( + "context" + "errors" + "log/slog" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "sea-vhost/internal/auth" + "sea-vhost/internal/cluster" + "sea-vhost/internal/config" + "sea-vhost/internal/scope" + "sea-vhost/internal/secrets" + "sea-vhost/internal/service" + "sea-vhost/internal/store" + "strconv" +) + +type contextKey string + +const userKey contextKey = "user" + +type Server struct { + cfg config.Config + store *store.Store + projects *service.Projects + mux *http.ServeMux + loginLimiter *loginLimiter + catalogLimiter *loginLimiter + secretBox *secrets.Box + cluster *cluster.Manager + schedulerRunning sync.Mutex +} + +func New(cfg config.Config, database *store.Store, projects *service.Projects) *Server { + s := &Server{cfg: cfg, store: database, projects: projects, mux: http.NewServeMux(), loginLimiter: newLoginLimiter(), catalogLimiter: newLoginLimiter(), secretBox: secrets.New(cfg.SessionSecret)} + s.routes() + return s +} + +func (s *Server) Handler() http.Handler { return s.security(s.mux) } + +func (s *Server) WithCluster(manager *cluster.Manager) *Server { s.cluster = manager; return s } + +func (s *Server) routes() { + s.mux.HandleFunc("GET /api/integration/v1/docs", integrationDocs) + s.mux.HandleFunc("/api/v1/projects/{id}/database-admin/{pmaPath...}", s.requireTenant(s.phpMyAdmin)) + s.mux.HandleFunc("GET /api/v1/admin/integration-keys", s.requireAdmin(s.adminIntegrationKeys)) + s.mux.HandleFunc("POST /api/v1/admin/integration-keys", s.requireAdmin(s.adminIntegrationKeys)) + s.mux.HandleFunc("DELETE /api/v1/admin/integration-keys/{keyID}", s.requireAdmin(s.adminIntegrationKeys)) + s.mux.HandleFunc("GET /api/integration/v1/{resource}", func(w http.ResponseWriter, r *http.Request) { + kind := r.PathValue("resource") + if kind != "users" && kind != "hosts" { + writeError(w, 404, "接口不存在") + return + } + s.requireIntegration(kind+":read", s.integrationList)(w, r) + }) + s.mux.HandleFunc("POST /api/integration/v1/{resource}", func(w http.ResponseWriter, r *http.Request) { + kind := r.PathValue("resource") + if kind != "users" && kind != "hosts" { + writeError(w, 404, "接口不存在") + return + } + s.requireIntegration(kind+":write", s.integrationWrite)(w, r) + }) + s.mux.HandleFunc("GET /api/integration/v1/tasks/{batchID}", s.requireIntegration("tasks:read", s.integrationTask)) + s.mux.HandleFunc("GET /api/integration/v1/tasks/{batchID}/download", s.requireIntegration("credentials:read", s.integrationTask)) + s.mux.HandleFunc("POST /api/v1/system/scheduler/tick", s.schedulerTick) + s.mux.HandleFunc("GET /api/v1/admin/scheduler", s.requireAdmin(s.adminScheduler)) + s.mux.HandleFunc("POST /api/v1/admin/scheduler", s.requireAdmin(s.adminScheduler)) + s.mux.HandleFunc("GET /api/v1/schedules", s.requireUserAccount(s.userSchedules)) + s.mux.HandleFunc("POST /api/v1/schedules", s.requireUserAccount(s.userSchedules)) + s.mux.HandleFunc("PUT /api/v1/schedules/{scheduleID}", s.requireUserAccount(s.userSchedules)) + s.mux.HandleFunc("DELETE /api/v1/schedules/{scheduleID}", s.requireUserAccount(s.userSchedules)) + s.mux.HandleFunc("POST /api/v1/schedules/{scheduleID}/{action}", s.requireUserAccount(s.userSchedules)) + s.mux.HandleFunc("GET /api/v1/schedules/{scheduleID}/runs", s.requireUserAccount(s.userSchedules)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/ftp", s.requireTenant(s.manageFTP)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/runtime", s.requireTenant(s.siteRuntime)) + s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/runtime", s.requireTenant(s.siteRuntime)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/startup", s.requireTenant(s.siteStartup)) + s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/startup", s.requireTenant(s.siteStartup)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/settings", s.requireTenant(s.siteSettings)) + s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/settings", s.requireTenant(s.siteSettings)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/logs", s.requireTenant(s.siteLog)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/metrics", s.requireTenant(s.hostMetrics)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/file-actions", s.requireTenant(s.fileActions)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/file-actions", s.requireTenant(s.fileActions)) + s.mux.HandleFunc("POST /api/v1/admin/batches/preview", s.requireAdmin(s.adminBatchPreview)) + s.mux.HandleFunc("GET /api/v1/admin/batches", s.requireAdmin(s.adminBatches)) + s.mux.HandleFunc("POST /api/v1/admin/batches", s.requireAdmin(s.adminBatches)) + s.mux.HandleFunc("GET /api/v1/admin/batches/{batchID}", s.requireAdmin(s.adminBatch)) + s.mux.HandleFunc("POST /api/v1/admin/batches/{batchID}/cancel", s.requireAdmin(s.adminCancelBatch)) + s.mux.HandleFunc("GET /api/v1/admin/batches/{batchID}/download", s.requireAdmin(s.adminBatchDownload)) + s.mux.HandleFunc("POST /api/v1/admin/impersonation", s.requireAdmin(s.startImpersonation)) + s.mux.HandleFunc("POST /api/v1/auth/impersonation/stop", s.requireAuth(s.stopImpersonation)) + s.mux.HandleFunc("GET /api/v1/activities", s.requireTenant(s.activities)) + s.mux.HandleFunc("GET /api/v1/admin/nodes/{nodeID}/tasks", s.requireAdmin(s.adminNodeTasks)) + s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/tasks/{taskID}/resolve", s.requireAdmin(s.adminResolveNodeTask)) + s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/reconcile", s.requireAdmin(s.adminReconcileNode)) + s.mux.HandleFunc("GET /api/v1/admin/nodes", s.requireAdmin(s.adminNodes)) + s.mux.HandleFunc("POST /api/v1/admin/nodes", s.requireAdmin(s.adminNodes)) + s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/pair", s.requireAdmin(s.adminPairNode)) + s.mux.HandleFunc("POST /api/v1/admin/nodes/{nodeID}/probe", s.requireAdmin(s.adminProbeNode)) + s.mux.HandleFunc("PUT /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNode)) + s.mux.HandleFunc("GET /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNodeRecord)) + s.mux.HandleFunc("PATCH /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNodeRecord)) + s.mux.HandleFunc("DELETE /api/v1/admin/nodes/{nodeID}", s.requireAdmin(s.adminNodeRecord)) + s.mux.HandleFunc("GET /api/v1/admin/projects/{id}", s.requireAdmin(s.adminHostRecord)) + s.mux.HandleFunc("PUT /api/v1/admin/projects/{id}", s.requireAdmin(s.adminHostRecord)) + s.mux.HandleFunc("DELETE /api/v1/admin/projects/{id}", s.requireAdmin(s.adminHostRecord)) + s.mux.HandleFunc("POST /api/v1/admin/projects/{id}/restore", s.requireAdmin(s.adminRestoreHost)) + s.mux.HandleFunc("GET /api/v1/admin/tenants/{id}", s.requireAdmin(s.adminAccount)) + s.mux.HandleFunc("PUT /api/v1/admin/tenants/{id}", s.requireAdmin(s.adminAccount)) + s.mux.HandleFunc("DELETE /api/v1/admin/tenants/{id}", s.requireAdmin(s.adminAccount)) + s.mux.HandleFunc("POST /api/v1/admin/projects", s.requireAdmin(s.adminCreateHost)) + s.mux.HandleFunc("PUT /api/v1/admin/projects/{id}/subscription", s.requireAdmin(s.adminHostSubscription)) + s.mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"status": "ok"}) + }) + s.mux.HandleFunc("GET /api/v1/setup/status", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"required": false}) + }) + s.mux.HandleFunc("POST /api/v1/auth/login", s.login) + s.mux.HandleFunc("GET /api/v1/auth/oidc/status", s.oidcStatus) + s.mux.HandleFunc("GET /api/v1/auth/oidc/pending", s.pendingOIDCLogin) + s.mux.HandleFunc("POST /api/v1/auth/oidc/complete", s.completeOIDCLogin) + s.mux.HandleFunc("GET /api/v1/auth/oidc/start", s.oidcStart) + s.mux.HandleFunc("GET /api/v1/auth/oidc/callback", s.oidcCallback) + s.mux.HandleFunc("POST /api/v1/auth/logout", s.requireAuth(s.logout)) + s.mux.HandleFunc("GET /api/v1/me", s.requireAuth(s.me)) + s.mux.HandleFunc("GET /api/v1/account/security", s.requireAuth(s.accountSecurity)) + s.mux.HandleFunc("PUT /api/v1/account/password", s.requireAuth(s.changePassword)) + s.mux.HandleFunc("POST /api/v1/account/mfa/setup", s.requireAuth(s.setupMFA)) + s.mux.HandleFunc("POST /api/v1/account/mfa/enable", s.requireAuth(s.enableMFA)) + s.mux.HandleFunc("POST /api/v1/account/mfa/disable", s.requireAuth(s.disableMFA)) + s.mux.HandleFunc("GET /api/v1/account/oidc", s.requireAuth(s.accountOIDC)) + s.mux.HandleFunc("DELETE /api/v1/account/oidc", s.requireAuth(s.accountOIDC)) + s.mux.HandleFunc("GET /api/v1/dashboard", s.requireTenant(s.dashboard)) + s.mux.HandleFunc("GET /api/v1/runtime-catalog", s.requireTenant(s.runtimeCatalog)) + s.mux.HandleFunc("GET /api/v1/projects", s.requireTenant(s.listProjects)) + s.mux.HandleFunc("POST /api/v1/projects", s.requireTenant(s.createProject)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/state", s.requireTenant(s.setProjectState)) + s.mux.HandleFunc("PUT /api/v1/projects/{id}/run-path", s.requireTenant(s.setProjectRunPath)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/credentials", s.requireTenant(s.projectCredentials)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/host-password/reset", s.requireTenant(s.resetHostPassword)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/sites", s.requireTenant(s.projectSites)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites", s.requireTenant(s.projectSites)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/state", s.requireTenant(s.setSiteState)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/deployment/check", s.requireTenant(s.checkSiteDeployment)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/deployment", s.requireTenant(s.deploySite)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/certificate/auto", s.requireTenant(s.requestAutoCertificate)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/certificate/dns", s.requireTenant(s.requestDNSCertificate)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/sites/{siteID}/certificate", s.requireTenant(s.certificateAutomation)) + s.mux.HandleFunc("PUT /api/v1/projects/{id}/sites/{siteID}/certificate/manual", s.requireTenant(s.installManualCertificate)) + s.mux.HandleFunc("DELETE /api/v1/projects/{id}/sites/{siteID}/certificate", s.requireTenant(s.disableCertificate)) + s.mux.HandleFunc("POST /api/v1/dns-credentials/discover", s.requireTenantAdmin(s.discoverDNSZones)) + s.mux.HandleFunc("GET /api/v1/dns-credentials", s.requireTenantAdmin(s.dnsCredentials)) + s.mux.HandleFunc("POST /api/v1/dns-credentials", s.requireTenantAdmin(s.dnsCredentials)) + s.mux.HandleFunc("PUT /api/v1/dns-credentials/{credentialID}", s.requireTenantAdmin(s.dnsCredential)) + s.mux.HandleFunc("DELETE /api/v1/dns-credentials/{credentialID}", s.requireTenantAdmin(s.dnsCredential)) + s.mux.HandleFunc("POST /api/v1/dns-credentials/{credentialID}/test", s.requireTenantAdmin(s.testDNSCredential)) + s.mux.HandleFunc("DELETE /api/v1/projects/{id}/sites/{siteID}", s.requireTenant(s.deleteSite)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/domains", s.requireTenant(s.bindDomain)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/sites/{siteID}/domains", s.requireTenant(s.bindSiteDomain)) + s.mux.HandleFunc("POST /api/v1/domains/{id}/dns", s.requireTenant(s.domainDNS)) + s.mux.HandleFunc("DELETE /api/v1/domains/{id}/dns", s.requireTenant(s.domainDNS)) + s.mux.HandleFunc("DELETE /api/v1/domains/{id}", s.requireTenant(s.unbindDomain)) + s.mux.HandleFunc("GET /api/v1/resources", s.requireTenant(s.resources)) + s.mux.HandleFunc("GET /api/v1/projects/{id}/files", s.requireTenant(s.files)) + s.mux.HandleFunc("POST /api/v1/projects/{id}/files", s.requireTenant(s.files)) + s.mux.HandleFunc("PUT /api/v1/projects/{id}/files", s.requireTenant(s.files)) + s.mux.HandleFunc("DELETE /api/v1/projects/{id}/files", s.requireTenant(s.files)) + s.mux.HandleFunc("GET /api/v1/admin/tenants", s.requireAdmin(s.adminTenants)) + s.mux.HandleFunc("POST /api/v1/admin/tenants", s.requireAdmin(s.adminTenants)) + s.mux.HandleFunc("GET /api/v1/admin/plans", s.requireAdmin(s.adminPlans)) + s.mux.HandleFunc("POST /api/v1/admin/plans", s.requireAdmin(s.adminPlans)) + s.mux.HandleFunc("DELETE /api/v1/admin/plans/{id}", s.requireAdmin(s.deletePlan)) + s.mux.HandleFunc("DELETE /api/v1/admin/domains/{id}", s.requireAdmin(s.unbindDomain)) + s.mux.HandleFunc("GET /api/v1/admin/settings/domain-approval", s.requireAdmin(s.domainApprovalSetting)) + s.mux.HandleFunc("PUT /api/v1/admin/settings/domain-approval", s.requireAdmin(s.domainApprovalSetting)) + s.mux.HandleFunc("GET /api/v1/admin/domains/pending", s.requireAdmin(s.adminPendingDomains)) + s.mux.HandleFunc("POST /api/v1/admin/domains/{id}/review", s.requireAdmin(s.adminReviewDomain)) + s.mux.HandleFunc("POST /api/v1/admin/domains/{id}/dns", s.requireAdmin(s.adminDomainDNS)) + s.mux.HandleFunc("DELETE /api/v1/admin/domains/{id}/dns", s.requireAdmin(s.adminDomainDNS)) + s.mux.HandleFunc("POST /api/v1/admin/dns-credentials/discover", s.requireAdmin(s.discoverDNSZones)) + s.mux.HandleFunc("GET /api/v1/admin/dns-credentials", s.requireAdmin(s.adminDNSCredentials)) + s.mux.HandleFunc("POST /api/v1/admin/dns-credentials", s.requireAdmin(s.adminDNSCredentials)) + s.mux.HandleFunc("PUT /api/v1/admin/dns-credentials/{credentialID}", s.requireAdmin(s.adminDNSCredential)) + s.mux.HandleFunc("DELETE /api/v1/admin/dns-credentials/{credentialID}", s.requireAdmin(s.adminDNSCredential)) + s.mux.HandleFunc("POST /api/v1/admin/dns-credentials/{credentialID}/test", s.requireAdmin(s.testAdminDNSCredential)) + s.mux.HandleFunc("GET /api/v1/admin/overview", s.requireAdmin(s.adminOverview)) + s.mux.HandleFunc("GET /api/v1/admin/settings", s.requireAdmin(s.adminSettings)) + s.mux.HandleFunc("PUT /api/v1/admin/settings", s.requireAdmin(s.adminSettings)) + s.mux.HandleFunc("GET /api/v1/admin/ip-addresses", s.requireAdmin(s.adminIPs)) + s.mux.HandleFunc("POST /api/v1/admin/ip-addresses", s.requireAdmin(s.adminIPs)) + s.mux.HandleFunc("DELETE /api/v1/admin/ip-addresses/{id}", s.requireAdmin(s.adminIP)) + s.mux.HandleFunc("PUT /api/v1/admin/projects/{id}/network", s.requireAdmin(s.adminProjectNetwork)) + s.mux.HandleFunc("GET /api/v1/admin/panel-sites", s.requireAdmin(s.adminPanelSites)) + s.mux.HandleFunc("POST /api/v1/admin/panel-sites/{id}/adopt", s.requireAdmin(s.adminAdoptPanelSite)) + s.mux.HandleFunc("DELETE /api/v1/admin/projects/{id}/recycled-owner", s.requireAdmin(s.adminDetachRecycledHost)) + s.mux.HandleFunc("GET /api/v1/admin/audit", s.requireAdmin(s.adminAudit)) + s.mux.HandleFunc("GET /api/v1/admin/runtime-environments", s.requireAdmin(s.adminRuntimeEnvironments)) + s.mux.HandleFunc("GET /api/v1/admin/runtime-maintenance", s.requireAdmin(s.adminRuntimeMaintenance)) + s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/check", s.requireAdmin(s.adminCheckRuntimeUpdates)) + s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/php", s.requireAdmin(s.adminUpdatePHPPatch)) + s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/sites/{siteID}", s.requireAdmin(s.adminMigrateSiteRuntime)) + s.mux.HandleFunc("POST /api/v1/admin/runtime-maintenance/jobs/{jobID}/resume", s.requireAdmin(s.adminResumeRuntimeMaintenance)) + s.mux.HandleFunc("POST /api/v1/admin/runtime-components/{runtime}/install", s.requireAdmin(s.adminInstallRuntimeComponent)) + s.mux.HandleFunc("POST /api/v1/admin/runtime-environments/{runtime}/install", s.requireAdmin(s.adminInstallRuntimeEnvironment)) + s.mux.HandleFunc("PUT /api/v1/admin/domains/{id}/metadata", s.requireAdmin(s.adminDomainMetadata)) + s.mux.HandleFunc("PUT /api/v1/admin/tenants/{id}/expiry", s.requireAdmin(s.adminTenantExpiry)) +} + +func (s *Server) security(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Referrer-Policy", "same-origin") + w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + if !s.allowedRequestHost(r) { + writeError(w, http.StatusMisdirectedRequest, "请求主机不在管理域名白名单") + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions && !sameOrigin(r) { + writeError(w, http.StatusForbidden, "不允许跨站请求") + return + } + defer func() { + if recovered := recover(); recovered != nil { + slog.Error("HTTP panic", "error", recovered) + writeError(w, http.StatusInternalServerError, "服务器内部错误") + } + }() + next.ServeHTTP(w, r) + }) +} + +func (s *Server) allowedRequestHost(r *http.Request) bool { + wanted := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(s.cfg.ManagementDomain), ".")) + if wanted == "" { + return true + } + host := remoteHost(r.Host) + if strings.EqualFold(strings.TrimSuffix(host, "."), wanted) { + return true + } + if r.URL.Path == "/healthz" && isLoopbackRemote(r.RemoteAddr) { + ip := net.ParseIP(strings.Trim(host, "[]")) + return strings.EqualFold(host, "localhost") || (ip != nil && ip.IsLoopback()) + } + return false +} + +func sameOrigin(r *http.Request) bool { + if strings.EqualFold(r.Header.Get("Sec-Fetch-Site"), "cross-site") { + return false + } + origin := r.Header.Get("Origin") + if origin == "" { + return true + } + parsed, err := url.Parse(origin) + if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { + return false + } + if parsed.Scheme != "http" && parsed.Scheme != "https" { + return false + } + return strings.EqualFold(parsed.Scheme, requestScheme(r)) && strings.EqualFold(parsed.Host, r.Host) +} + +func requestScheme(r *http.Request) string { + if r.TLS != nil { + return "https" + } + if isLoopbackRemote(r.RemoteAddr) { + forwarded := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0])) + if forwarded == "http" || forwarded == "https" { + return forwarded + } + } + return "http" +} + +func requestClientIP(r *http.Request) string { + if isLoopbackRemote(r.RemoteAddr) { + if forwarded := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP"))); forwarded != nil { + return forwarded.String() + } + } + host := remoteHost(r.RemoteAddr) + if parsed := net.ParseIP(host); parsed != nil { + return parsed.String() + } + return "unknown" +} + +func isLoopbackRemote(remote string) bool { + ip := net.ParseIP(remoteHost(remote)) + return ip != nil && ip.IsLoopback() +} + +func remoteHost(remote string) string { + if host, _, err := net.SplitHostPort(remote); err == nil { + return strings.Trim(host, "[]") + } + return strings.Trim(remote, "[]") +} + +const ( + loginWindow = 5 * time.Minute + loginIPBurst = 60 + loginIdentifierBurst = 20 + loginLimiterMaxKeys = 4096 +) + +type loginAttempt struct { + windowStart time.Time + count int +} + +type loginLimiter struct { + mu sync.Mutex + attempts map[string]loginAttempt + lastSweep time.Time +} + +func newLoginLimiter() *loginLimiter { + return &loginLimiter{attempts: make(map[string]loginAttempt)} +} + +func (l *loginLimiter) allow(key string, now time.Time, limit int) (bool, time.Duration) { + l.mu.Lock() + defer l.mu.Unlock() + if l.lastSweep.IsZero() || now.Sub(l.lastSweep) >= time.Minute || now.Before(l.lastSweep) { + for candidate, attempt := range l.attempts { + if now.Before(attempt.windowStart) || now.Sub(attempt.windowStart) >= loginWindow { + delete(l.attempts, candidate) + } + } + for candidate := range l.attempts { + if len(l.attempts) <= loginLimiterMaxKeys { + break + } + delete(l.attempts, candidate) + } + l.lastSweep = now + } + attempt, found := l.attempts[key] + if !found || now.Before(attempt.windowStart) || now.Sub(attempt.windowStart) >= loginWindow { + if !found && len(l.attempts) >= loginLimiterMaxKeys { + for candidate := range l.attempts { + delete(l.attempts, candidate) + break + } + } + l.attempts[key] = loginAttempt{windowStart: now, count: 1} + return true, 0 + } + if attempt.count >= limit { + return false, loginWindow - now.Sub(attempt.windowStart) + } + attempt.count++ + l.attempts[key] = attempt + return true, 0 +} + +func (l *loginLimiter) reset(keys ...string) { + l.mu.Lock() + defer l.mu.Unlock() + for _, key := range keys { + delete(l.attempts, key) + } +} + +func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("sea_session") + if err != nil { + writeError(w, http.StatusUnauthorized, "请先登录") + return + } + user, err := s.userFromToken(r.Context(), cookie.Value) + if err != nil { + writeError(w, http.StatusUnauthorized, "登录已失效") + return + } + ctx := context.WithValue(r.Context(), userKey, user) + if child, err := r.Cookie(impersonationCookie); err == nil { + if user.Role != "admin" { + s.clearImpersonation(w) + writeError(w, 403, "代入会话必须绑定原管理员登录") + return + } + ctx = context.WithValue(ctx, realAdministratorKey, user) + if r.URL.Path != "/api/v1/auth/impersonation/stop" { + if !auth.ValidateSessionToken(s.cfg.SessionSecret, child.Value) { + s.clearImpersonation(w) + writeError(w, 401, "代入会话已失效,请返回管理员") + return + } + effective, err := s.store.ImpersonationUser(ctx, cookie.Value, child.Value, user.ID) + if err != nil { + s.clearImpersonation(w) + writeError(w, 401, "代入会话已失效,请返回管理员") + return + } + ctx = context.WithValue(scope.WithAdministrator(ctx, user.ID), userKey, effective) + if strings.HasPrefix(r.URL.Path, "/api/v1/account/") { + writeError(w, 403, "代入期间不能修改或绑定账号登录安全设置") + return + } + } + } + next(w, r.WithContext(ctx)) + } +} +func (s *Server) requireTenant(next http.HandlerFunc) http.HandlerFunc { + return s.requireAuth(func(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + if user.TenantID == nil { + writeError(w, http.StatusForbidden, "该接口仅供用户或主机账号使用") + return + } + if user.Role == "tenant" { + r = r.WithContext(scope.WithAccount(r.Context(), *user.TenantID)) + } + if r.Method == "POST" && r.URL.Path == "/api/v1/projects" { + writeError(w, 403, "请联系管理员开通虚拟主机") + return + } + projectID := uint64(0) + if strings.HasPrefix(r.URL.Path, "/api/v1/projects/") { + projectID, _ = strconv.ParseUint(r.PathValue("id"), 10, 64) + if projectID == 0 { + writeError(w, 400, "主机编号无效") + return + } + } + if value := r.URL.Query().Get("projectId"); value != "" { + requestedID, err := strconv.ParseUint(value, 10, 64) + if err != nil || requestedID == 0 { + writeError(w, 400, "主机编号无效") + return + } + if projectID != 0 && requestedID != projectID { + writeError(w, 404, "主机不存在") + return + } + projectID = requestedID + } + if projectID == 0 && user.ProjectID != nil { + projectID = *user.ProjectID + } + if strings.HasPrefix(r.URL.Path, "/api/v1/domains/") { + id, _ := strconv.ParseUint(r.PathValue("id"), 10, 64) + d, err := s.store.DomainByID(r.Context(), id) + if err != nil { + writeError(w, 404, "域名不存在") + return + } + projectID = d.ProjectID + } + if projectID > 0 { + p, err := s.store.ProjectForUser(r.Context(), user, projectID) + if err != nil || (user.ProjectID != nil && *user.ProjectID != projectID) { + if errors.Is(err, store.ErrManagementLocked) { + writeError(w, 423, err.Error()) + return + } + writeError(w, 404, "主机不存在") + return + } + user.TenantID = &p.TenantID + r = r.WithContext(context.WithValue(scope.WithProject(r.Context(), p.ID, p.NodeID), userKey, user)) + if !(r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/runtime")) { + accessRelease, accessErr := s.projects.BeginHostAccess(p.ID) + if accessErr != nil { + writeError(w, 423, accessErr.Error()) + return + } + defer accessRelease() + // Recheck sessions and ownership after acquiring the host gate. + parent, _ := r.Cookie("sea_session") + if parent == nil { + writeError(w, 401, "登录已失效") + return + } + effective, authErr := s.userFromToken(r.Context(), parent.Value) + if child, childErr := r.Cookie(impersonationCookie); childErr == nil && authErr == nil { + effective, authErr = s.store.ImpersonationUser(r.Context(), parent.Value, child.Value, effective.ID) + } + if authErr != nil || effective.ID != user.ID { + writeError(w, 401, "登录已失效") + return + } + if _, accessErr = s.store.ProjectForUser(r.Context(), user, p.ID); accessErr != nil { + writeError(w, 404, "主机不存在或归属已变化") + return + } + } + } + if r.Method != "GET" && strings.HasPrefix(r.URL.Path, "/api/v1/projects") { + release, err := s.projects.BeginRuntimeMutation(r.Context()) + if err != nil { + if !errors.Is(err, service.ErrRuntimeSwitchPending) && !errors.Is(err, service.ErrNodeConfigurationBusy) { + writeError(w, http.StatusInternalServerError, "无法核对主机操作状态,请稍后重试") + return + } + w.Header().Set("Retry-After", "10") + writeError(w, http.StatusLocked, err.Error()) + return + } + defer release() + } + next(w, r) + }) +} +func (s *Server) requireTenantAdmin(next http.HandlerFunc) http.HandlerFunc { + return s.requireAuth(func(w http.ResponseWriter, r *http.Request) { + user := currentUser(r) + if user.Role != "tenant" || user.TenantID == nil { + writeError(w, http.StatusForbidden, "只有用户账号可以管理 DNS 凭据") + return + } + next(w, r) + }) +} +func (s *Server) requireAdmin(next http.HandlerFunc) http.HandlerFunc { + return s.requireAuth(func(w http.ResponseWriter, r *http.Request) { + if currentUser(r).Role != "admin" { + writeError(w, http.StatusForbidden, "需要管理员权限") + return + } + ctx := r.Context() + if value := r.URL.Query().Get("nodeId"); value != "" { + id, err := strconv.ParseUint(value, 10, 64) + if err != nil || id == 0 { + writeError(w, 400, "节点编号无效") + return + } + ctx = scope.WithNode(ctx, id) + } + if strings.HasPrefix(r.URL.Path, "/api/v1/admin/projects/") { + id, _ := strconv.ParseUint(r.PathValue("id"), 10, 64) + node, _, err := s.store.ProjectPlacement(ctx, id) + if err != nil { + writeError(w, 404, "主机不存在") + return + } + ctx = scope.WithProject(ctx, id, node) + } + if strings.HasPrefix(r.URL.Path, "/api/v1/admin/domains/") && r.PathValue("id") != "" { + id, _ := strconv.ParseUint(r.PathValue("id"), 10, 64) + d, err := s.store.DomainByID(ctx, id) + if err != nil { + writeError(w, 404, "域名不存在") + return + } + node, _, err := s.store.ProjectPlacement(ctx, d.ProjectID) + if err != nil { + writeError(w, 404, "主机不存在") + return + } + ctx = scope.WithProject(ctx, d.ProjectID, node) + } + if value := r.PathValue("siteID"); value != "" { + id, _ := strconv.ParseUint(value, 10, 64) + node, err := s.store.NodeForSite(ctx, id) + if err != nil { + writeError(w, 404, "网站不存在") + return + } + ctx = scope.WithNode(ctx, node) + } + r = r.WithContext(ctx) + next(w, r) + }) +} +func (s *Server) userFromToken(ctx context.Context, token string) (store.User, error) { + if !auth.ValidateSessionToken(s.cfg.SessionSecret, token) { + return store.User{}, errors.New("invalid token") + } + return s.store.UserBySession(ctx, token) +} +func currentUser(r *http.Request) store.User { return r.Context().Value(userKey).(store.User) } diff --git a/backend/internal/httpapi/server_test.go b/backend/internal/httpapi/server_test.go new file mode 100644 index 0000000..06fbd43 --- /dev/null +++ b/backend/internal/httpapi/server_test.go @@ -0,0 +1,91 @@ +package httpapi + +import ( + "net/http/httptest" + "testing" + "time" +) + +func TestSameOriginRequiresMatchingSchemeAndHost(t *testing.T) { + request := httptest.NewRequest("POST", "http://console.example/api/v1/auth/login", nil) + request.RemoteAddr = "127.0.0.1:42000" + request.Header.Set("X-Forwarded-Proto", "https") + + tests := []struct { + name string + origin string + fetchSite string + wantAllowed bool + }{ + {name: "matching", origin: "https://console.example", wantAllowed: true}, + {name: "matching trailing slash", origin: "https://console.example/", wantAllowed: true}, + {name: "missing origin", wantAllowed: true}, + {name: "wrong scheme", origin: "http://console.example", wantAllowed: false}, + {name: "wrong host", origin: "https://attacker.example", wantAllowed: false}, + {name: "origin path", origin: "https://console.example/path", wantAllowed: false}, + {name: "null origin", origin: "null", wantAllowed: false}, + {name: "cross site fetch", origin: "https://console.example", fetchSite: "cross-site", wantAllowed: false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + request.Header.Set("Origin", test.origin) + request.Header.Set("Sec-Fetch-Site", test.fetchSite) + if got := sameOrigin(request); got != test.wantAllowed { + t.Fatalf("sameOrigin() = %v, want %v", got, test.wantAllowed) + } + }) + } +} + +func TestForwardedHeadersAreTrustedOnlyFromLoopback(t *testing.T) { + request := httptest.NewRequest("GET", "http://console.example/", nil) + request.Header.Set("X-Forwarded-Proto", "https") + request.Header.Set("X-Real-IP", "203.0.113.77") + + request.RemoteAddr = "198.51.100.8:44000" + if got := requestScheme(request); got != "http" { + t.Fatalf("untrusted request scheme = %q", got) + } + if got := requestClientIP(request); got != "198.51.100.8" { + t.Fatalf("untrusted client IP = %q", got) + } + + request.RemoteAddr = "[::1]:44000" + if got := requestScheme(request); got != "https" { + t.Fatalf("trusted request scheme = %q", got) + } + if got := requestClientIP(request); got != "203.0.113.77" { + t.Fatalf("trusted client IP = %q", got) + } +} + +func TestLoginLimiterBlocksExpiresAndResets(t *testing.T) { + limiter := newLoginLimiter() + now := time.Date(2026, time.October, 14, 8, 0, 0, 0, time.UTC) + for attempt := 0; attempt < 2; attempt++ { + if allowed, _ := limiter.allow("identifier:user@example.test", now, 2); !allowed { + t.Fatalf("attempt %d was unexpectedly blocked", attempt+1) + } + } + if allowed, retryAfter := limiter.allow("identifier:user@example.test", now, 2); allowed || retryAfter != loginWindow { + t.Fatalf("blocked attempt = (%v, %v), want (false, %v)", allowed, retryAfter, loginWindow) + } + if allowed, _ := limiter.allow("identifier:user@example.test", now.Add(loginWindow), 2); !allowed { + t.Fatal("attempt was not allowed after the window expired") + } + limiter.reset("identifier:user@example.test") + if allowed, _ := limiter.allow("identifier:user@example.test", now, 2); !allowed { + t.Fatal("attempt was not allowed after reset") + } +} + +func TestLoginLimiterBoundsTrackedKeys(t *testing.T) { + limiter := newLoginLimiter() + now := time.Date(2026, time.October, 14, 8, 0, 0, 0, time.UTC) + for index := 0; index < loginLimiterMaxKeys+100; index++ { + limiter.allow(string(rune(index+1)), now, 1) + } + if got := len(limiter.attempts); got > loginLimiterMaxKeys { + t.Fatalf("tracked keys = %d, want at most %d", got, loginLimiterMaxKeys) + } +} diff --git a/backend/internal/httpapi/site_runtime.go b/backend/internal/httpapi/site_runtime.go new file mode 100644 index 0000000..dd5cc45 --- /dev/null +++ b/backend/internal/httpapi/site_runtime.go @@ -0,0 +1,62 @@ +package httpapi + +import ( + "net/http" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "strconv" +) + +func (s *Server) siteRuntime(w http.ResponseWriter, r *http.Request) { + id, err := projectID(r) + sid, e := siteID(r) + if err != nil || e != nil { + writeError(w, 400, "网站编号无效") + return + } + u := currentUser(r) + if r.Method == "GET" { + p, e := s.store.ProjectForUser(r.Context(), u, id) + if e != nil { + writeError(w, 404, "主机不存在") + return + } + if _, e = s.store.Site(r.Context(), p.TenantID, id, sid); e != nil { + writeError(w, 404, "网站不存在") + return + } + jobs, e := s.store.RuntimeJobs(scope.WithNode(r.Context(), p.NodeID)) + if e != nil { + writeError(w, 500, "无法读取环境任务") + return + } + own := []store.RuntimeJob{} + for _, j := range jobs { + if j.SiteID != nil && *j.SiteID == sid { + own = append(own, j) + } + } + writeJSON(w, 200, map[string]any{"jobs": own}) + return + } + var input struct { + Runtime string `json:"runtime"` + Version string `json:"version"` + EntryFile string `json:"entryFile"` + } + if decodeJSON(r, &input) != nil { + writeError(w, 400, "环境设置格式无效") + return + } + job, err := s.projects.SubmitSiteRuntime(r.Context(), u, id, sid, input.Runtime, input.Version, input.EntryFile) + detail := "提交网站运行环境切换任务" + if err != nil { + detail = err.Error() + } + s.store.Log(r.Context(), u.TenantID, u.ID, "update", "site_runtime", strconv.FormatUint(sid, 10), requestClientIP(r), err == nil, detail) + if err != nil { + writeError(w, 422, err.Error()) + return + } + writeJSON(w, 202, map[string]any{"jobId": job}) +} diff --git a/backend/internal/httpapi/site_settings.go b/backend/internal/httpapi/site_settings.go new file mode 100644 index 0000000..d2ea760 --- /dev/null +++ b/backend/internal/httpapi/site_settings.go @@ -0,0 +1,54 @@ +package httpapi + +import ( + "net/http" + "sea-vhost/internal/hosting" + "strconv" +) + +func (s *Server) siteSettings(w http.ResponseWriter, r *http.Request) { + project, _ := projectID(r) + site, _ := strconv.ParseUint(r.PathValue("siteID"), 10, 64) + if r.Method == "GET" { + v, e := s.projects.WebsiteSettings(r.Context(), currentUser(r), project, site) + if e != nil { + writeError(w, 404, "网站不存在或无法读取设置") + return + } + writeJSON(w, 200, map[string]any{"settings": v}) + return + } + var v hosting.WebsiteSettings + if decodeJSON(r, &v) != nil { + writeError(w, 400, "设置格式无效") + return + } + if e := s.projects.SetWebsiteSettings(r.Context(), currentUser(r), project, site, v); e != nil { + writeError(w, 422, e.Error()) + return + } + u := currentUser(r) + s.store.Log(r.Context(), u.TenantID, u.ID, "update", "site", strconv.FormatUint(site, 10), requestClientIP(r), true, "更新网站基础设置") + w.WriteHeader(204) +} +func (s *Server) siteLog(w http.ResponseWriter, r *http.Request) { + project, _ := projectID(r) + site, _ := strconv.ParseUint(r.PathValue("siteID"), 10, 64) + lines, _ := strconv.Atoi(r.URL.Query().Get("lines")) + v, e := s.projects.SiteLog(r.Context(), currentUser(r), project, site, r.URL.Query().Get("kind"), r.URL.Query().Get("search"), lines) + if e != nil { + writeError(w, 422, "无法读取该网站日志") + return + } + writeJSON(w, 200, v) +} +func (s *Server) hostMetrics(w http.ResponseWriter, r *http.Request) { + project, _ := projectID(r) + days, _ := strconv.Atoi(r.URL.Query().Get("days")) + v, e := s.store.HostMetrics(r.Context(), project, days) + if e != nil { + writeError(w, 503, "无法读取资源历史") + return + } + writeJSON(w, 200, map[string]any{"samples": v, "retentionDays": 30, "cpuUnit": "100% = 一个 CPU 核心"}) +} diff --git a/backend/internal/httpapi/sso_integration_test.go b/backend/internal/httpapi/sso_integration_test.go new file mode 100644 index 0000000..cb641f3 --- /dev/null +++ b/backend/internal/httpapi/sso_integration_test.go @@ -0,0 +1,324 @@ +package httpapi + +import ( + "bytes" + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/json" + "fmt" + "github.com/coreos/go-oidc/v3/oidc" + "github.com/go-sql-driver/mysql" + "net/http" + "net/http/httptest" + "net/url" + "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 TestSSOLoginMySQL(t *testing.T) { + dsn := os.Getenv("SEA_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("disposable MySQL schema not supplied") + } + parsed, e := mysql.ParseDSN(dsn) + if e != nil || !strings.HasPrefix(parsed.DBName, "svh_cluster_test_") { + t.Fatal("refusing non-test schema") + } + db, e := store.Open(dsn) + if e != nil { + t.Fatal(e) + } + defer db.Close() + ctx := context.Background() + must := func(e error) { + t.Helper() + if e != nil { + t.Fatal(e) + } + } + must(db.Migrate(ctx)) + must(db.Migrate(ctx)) + raw, e := sql.Open("mysql", dsn) + must(e) + defer raw.Close() + must(db.BootstrapAdmin(ctx, "sso-admin@example.invalid", "SSO 管理员", "sso-admin-password-123")) + admin, e := db.UserByLogin(ctx, "sso-admin@example.invalid") + must(e) + root := t.TempDir() + must(db.InitializeLocalNode(ctx, "hosts.example.invalid", root, "control.example.invalid")) + secret := "sso-test-session-key-at-least-thirty-two-characters" + projects := service.NewProjects(db, panel.NewMock(), isolation.Mock{Root: root}, "hosts.example.invalid", root, true, secret, "control.example.invalid") + app := New(config.Config{SessionSecret: secret, ManagementDomain: "control.example.invalid", CookieSecure: true, SessionTTL: time.Hour}, db, projects) + key, e := rsa.GenerateKey(rand.Reader, 2048) + must(e) + var issuer, nonce, subject, email string + verified := true + idp := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/.well-known/openid-configuration": + json.NewEncoder(w).Encode(map[string]any{"issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", "jwks_uri": issuer + "/keys", "id_token_signing_alg_values_supported": []string{"RS256"}}) + case "/keys": + json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]any{"kty": "RSA", "use": "sig", "alg": "RS256", "kid": "test", "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": "AQAB"}}}) + case "/token": + _ = r.ParseForm() + if r.Form.Get("code_verifier") == "" { + t.Error("PKCE verifier missing") + } + encode := func(v any) string { b, _ := json.Marshal(v); return base64.RawURLEncoding.EncodeToString(b) } + message := encode(map[string]any{"alg": "RS256", "kid": "test"}) + "." + encode(map[string]any{"iss": issuer, "sub": subject, "aud": "sso-client", "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Unix(), "nonce": nonce, "email": email, "email_verified": verified, "name": "SSO 测试用户"}) + sum := sha256.Sum256([]byte(message)) + signature, e := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:]) + if e != nil { + t.Error(e) + } + json.NewEncoder(w).Encode(map[string]any{"access_token": "test-access", "token_type": "Bearer", "expires_in": 3600, "id_token": message + "." + base64.RawURLEncoding.EncodeToString(signature)}) + default: + w.WriteHeader(404) + } + })) + defer idp.Close() + issuer = idp.URL + cfg := secretServiceConfig{Enabled: true, Issuer: issuer, ClientID: "sso-client", Secret: "test-client-secret", RedirectURI: "https://control.example.invalid/api/v1/auth/oidc/callback", AutoCreate: true} + must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) + type jar map[string]string + count := 0 + call := func(method, path string, body any, cookies jar) *httptest.ResponseRecorder { + t.Helper() + var b bytes.Buffer + if body != nil { + must(json.NewEncoder(&b).Encode(body)) + } + r := httptest.NewRequest(method, "https://control.example.invalid"+path, &b) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Origin", "https://control.example.invalid") + count++ + r.RemoteAddr = fmt.Sprintf("192.0.2.%d:1234", 1+count%200) + r = r.WithContext(oidc.ClientContext(r.Context(), idp.Client())) + for name, value := range cookies { + r.AddCookie(&http.Cookie{Name: name, Value: value}) + } + w := httptest.NewRecorder() + app.Handler().ServeHTTP(w, r) + for _, c := range w.Result().Cookies() { + if c.MaxAge < 0 { + delete(cookies, c.Name) + } else { + cookies[c.Name] = c.Value + } + } + 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()) + } + } + session := func(u store.User) jar { + token, e := auth.NewSessionToken(secret) + must(e) + must(db.CreateSession(ctx, u.ID, token, time.Now().Add(time.Hour))) + return jar{"sea_session": token} + } + startMode := func(c jar, mode string) string { + w := call("GET", "/api/v1/auth/oidc/start?mode="+mode, nil, c) + expect(w, 200) + var out map[string]string + must(json.Unmarshal(w.Body.Bytes(), &out)) + u, e := url.Parse(out["url"]) + must(e) + nonce = u.Query().Get("nonce") + if u.Query().Get("code_challenge_method") != "S256" { + t.Fatal("PKCE not enabled") + } + return u.Query().Get("state") + } + start := func(c jar) string { return startMode(c, "login") } + callback := func(c jar, state string) *httptest.ResponseRecorder { + return call("GET", "/api/v1/auth/oidc/callback?state="+url.QueryEscape(state)+"&code=test-code", nil, c) + } + off := false + localID, e := db.CreateTenant(ctx, store.NewTenant{Slug: "sso-existing", Name: "已有用户", DisplayName: "已有用户", Email: "existing@example.invalid", Password: "existing-password-123", PlanID: 1}) + must(e) + _ = localID + local, e := db.UserByLogin(ctx, "existing@example.invalid") + must(e) + t.Run("authenticated frontend binding does not merge by email", func(t *testing.T) { + c := jar{} + subject = "external-local" + email = "existing@example.invalid" + state := start(c) + absent := jar{} + w := callback(absent, state) + expect(w, 303) + if strings.Contains(w.Header().Get("Location"), "complete") { + t.Fatal("callback accepted without browser state") + } + w = callback(c, state) + expect(w, 303) + if !strings.Contains(w.Header().Get("Location"), "complete") { + t.Fatal(w.Header().Get("Location")) + } + if _, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject); e == nil { + t.Fatal("email silently linked") + } + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 409) + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "bind", "identifier": local.Email, "password": "wrong"}, c), 401) + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "bind", "identifier": local.Email, "password": "existing-password-123"}, c), 200) + linked, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject) + must(e) + if linked.ID != local.ID { + t.Fatal("wrong account binding") + } + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 401) + c = jar{} + w = callback(c, start(c)) + expect(w, 303) + if !strings.Contains(w.Header().Get("Location"), "login") { + t.Fatal("bound identity could not login") + } + }) + t.Run("ordinary account creation has no host and is single use", func(t *testing.T) { + c := jar{} + subject = "fresh-subject" + email = "new-sso@example.invalid" + expect(callback(c, start(c)), 303) + oldTicket := c["sea_oidc_pending"] + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 200) + u, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject) + must(e) + if u.Role != "tenant" || u.ProjectID != nil { + t.Fatal("SSO granted unexpected privileges") + } + n, e := db.CountProjects(ctx, *u.TenantID) + must(e) + if n != 0 { + t.Fatal("SSO created a host") + } + replay := jar{"sea_oidc_pending": oldTicket} + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, replay), 401) + if _, e = db.UserByOIDC(ctx, oidcProviderKey(cfg), "FRESH-SUBJECT"); e == nil { + t.Fatal("subject lookup is case insensitive") + } + }) + t.Run("new users need verified email and enabled creation", func(t *testing.T) { + c := jar{} + subject = "unverified" + email = "notverified@example.invalid" + verified = false + expect(callback(c, start(c)), 303) + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 403) + verified = true + cfg.AutoCreate = false + must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) + c = jar{} + subject = "registration-off" + email = "off@example.invalid" + expect(callback(c, start(c)), 303) + expect(call("POST", "/api/v1/auth/oidc/complete", map[string]any{"action": "create"}, c), 403) + }) + t.Run("host SSO is rejected and password policy is enforced by API", func(t *testing.T) { + hash, e := auth.HashPassword("host-test-password-123") + must(e) + result, e := raw.Exec(`INSERT INTO users(email,login_name,display_name,password_hash,role) VALUES('host-sso@example.invalid','host-sso','主机账号',?,'host')`, hash) + must(e) + id, e := result.LastInsertId() + must(e) + host, e := db.UserByID(ctx, uint64(id)) + must(e) + expect(call("GET", "/api/v1/auth/oidc/start?mode=bind", nil, session(host)), 403) + cfg.UserPasswordLogin = &off + cfg.AdminPasswordLogin = &off + must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) + expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": local.Email, "password": "existing-password-123"}, jar{}), 403) + expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": admin.Email, "password": "sso-admin-password-123"}, jar{}), 403) + expect(call("POST", "/api/v1/auth/login", map[string]any{"identifier": "host-sso", "password": "host-test-password-123"}, jar{}), 200) + expect(call("DELETE", "/api/v1/account/oidc", map[string]any{"currentPassword": "existing-password-123"}, session(local)), 409) + c := jar{} + subject = "external-local" + email = local.Email + expect(callback(c, start(c)), 303) + if c["sea_session"] == "" { + t.Fatal("password restriction blocked SSO") + } + }) + t.Run("nonce mismatch and consumed state are rejected", func(t *testing.T) { + c := jar{} + state := start(c) + nonce = "wrong-nonce" + w := callback(c, state) + expect(w, 303) + if !strings.Contains(w.Header().Get("Location"), "claims") { + t.Fatal("wrong nonce accepted") + } + if c["sea_oidc_pending"] != "" { + t.Fatal("invalid token created continuation") + } + expect(callback(c, state), 303) + }) + t.Run("issuer changes invalidate pending login", func(t *testing.T) { + c := jar{} + state := start(c) + changed := cfg + changed.Issuer = "https://other.example.invalid" + must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", changed)) + w := callback(c, state) + expect(w, 303) + if !strings.Contains(w.Header().Get("Location"), "provider_changed") { + t.Fatal(w.Header().Get("Location")) + } + must(app.writeServiceConfig(httptest.NewRequest("PUT", "https://control.example.invalid", nil), "oidc_config", cfg)) + }) + t.Run("settings reject disabling SSO while passwords closed", func(t *testing.T) { + body := map[string]any{"graceDays": 3, "recycleDays": 7, "backupRetentionDays": 14, "smtp": secretServiceConfig{}, "oidc": secretServiceConfig{Enabled: false, UserPasswordLogin: &off, AdminPasswordLogin: &off}} + expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 422) + body["oidc"] = cfg + expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 422) + }) + t.Run("bind callback tolerates Strict session cookie but requires live parent", func(t *testing.T) { + c := session(admin) + subject = "admin-binding" + email = admin.Email + state := startMode(c, "bind") + delete(c, "sea_session") + w := callback(c, state) + expect(w, 303) + if !strings.Contains(w.Header().Get("Location"), "bound") { + t.Fatal(w.Header().Get("Location")) + } + bound, e := db.UserByOIDC(ctx, oidcProviderKey(cfg), subject) + must(e) + if bound.ID != admin.ID { + t.Fatal("wrong administrator identity") + } + body := map[string]any{"graceDays": 3, "recycleDays": 7, "backupRetentionDays": 14, "smtp": secretServiceConfig{}, "oidc": cfg} + expect(call("PUT", "/api/v1/admin/settings", body, session(admin)), 204) + c = session(admin) + subject = "revoked-parent" + state = startMode(c, "bind") + hash := sha256.Sum256([]byte(c["sea_session"])) + _, e = raw.Exec(`DELETE FROM sessions WHERE token_hash=?`, hash[:]) + must(e) + delete(c, "sea_session") + w = callback(c, state) + expect(w, 303) + if !strings.Contains(w.Header().Get("Location"), "expired") { + t.Fatal("revoked initiating session accepted") + } + }) + +} diff --git a/backend/internal/httpapi/startup.go b/backend/internal/httpapi/startup.go new file mode 100644 index 0000000..f639c35 --- /dev/null +++ b/backend/internal/httpapi/startup.go @@ -0,0 +1,33 @@ +package httpapi + +import ( + "net/http" + "sea-vhost/internal/hosting" + "strconv" +) + +func (s *Server) siteStartup(w http.ResponseWriter, r *http.Request) { + id, _ := projectID(r) + site, _ := strconv.ParseUint(r.PathValue("siteID"), 10, 64) + u := currentUser(r) + if r.Method == "GET" { + v, e := s.projects.Startup(r.Context(), u, id, site) + if e != nil { + writeError(w, 404, "无法读取启动配置") + return + } + writeJSON(w, 200, map[string]any{"startup": v}) + return + } + var v hosting.Startup + if decodeJSON(r, &v) != nil { + writeError(w, 400, "启动设置格式无效") + return + } + if e := s.projects.SetStartup(r.Context(), u, id, site, v); e != nil { + writeError(w, 422, e.Error()) + return + } + s.store.Log(r.Context(), u.TenantID, u.ID, "update", "site", strconv.FormatUint(site, 10), requestClientIP(r), true, "更新网站环境变量与启动配置") + w.WriteHeader(204) +} diff --git a/backend/internal/httpapi/user_schedules.go b/backend/internal/httpapi/user_schedules.go new file mode 100644 index 0000000..6d5c5eb --- /dev/null +++ b/backend/internal/httpapi/user_schedules.go @@ -0,0 +1,72 @@ +package httpapi + +import ( + "net/http" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "strconv" +) + +func (s *Server) requireUserAccount(next http.HandlerFunc) http.HandlerFunc { + return s.requireAuth(func(w http.ResponseWriter, r *http.Request) { + u := currentUser(r) + if u.Role != "tenant" || u.TenantID == nil { + writeError(w, 403, "计划任务仅供用户账号使用") + return + } + next(w, r.WithContext(scope.WithAccount(r.Context(), *u.TenantID))) + }) +} +func (s *Server) userSchedules(w http.ResponseWriter, r *http.Request) { + if action := r.PathValue("action"); action != "" && action != "run" { + writeError(w, 404, "操作不存在") + return + } + u := currentUser(r) + id, _ := strconv.ParseUint(r.PathValue("scheduleID"), 10, 64) + if r.Method == "GET" { + if r.PathValue("scheduleID") != "" { + items, e := s.projects.ScheduleRuns(r.Context(), u, id) + if e != nil { + writeError(w, 404, "任务不存在") + return + } + writeJSON(w, 200, map[string]any{"runs": items}) + return + } + items, e := s.projects.UserSchedules(r.Context(), u) + if e != nil { + writeError(w, 503, "无法读取计划任务") + return + } + writeJSON(w, 200, map[string]any{"schedules": items}) + return + } + var err error + action := "update" + if r.Method == "DELETE" { + err = s.store.DeleteUserSchedule(r.Context(), u.ID, id) + action = "delete" + } else if r.PathValue("action") == "run" { + err = s.store.RequestUserScheduleRun(r.Context(), u.ID, id) + action = "queue" + } else { + var input store.UserSchedule + if decodeJSON(r, &input) != nil { + writeError(w, 400, "任务配置格式无效") + return + } + input.ID = id + var saved uint64 + saved, err = s.projects.SaveUserSchedule(r.Context(), u, input) + if err == nil { + id = saved + } + } + s.store.Log(r.Context(), u.TenantID, u.ID, action, "schedule", strconv.FormatUint(id, 10), requestClientIP(r), err == nil, "管理用户计划任务") + if err != nil { + writeError(w, 422, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"id": id}) +} diff --git a/backend/internal/identity/id.go b/backend/internal/identity/id.go new file mode 100644 index 0000000..e685edb --- /dev/null +++ b/backend/internal/identity/id.go @@ -0,0 +1,14 @@ +package identity + +import ( + "crypto/rand" + "encoding/hex" +) + +func New(prefix string) (string, error) { + data := make([]byte, 16) + if _, err := rand.Read(data); err != nil { + return "", err + } + return prefix + "_" + hex.EncodeToString(data), nil +} diff --git a/backend/internal/isolation/agent.go b/backend/internal/isolation/agent.go new file mode 100644 index 0000000..c830fe4 --- /dev/null +++ b/backend/internal/isolation/agent.go @@ -0,0 +1,671 @@ +package isolation + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" +) + +var safeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`) + +type Agent struct { + Root string + BackupRoot string + LegacyRoot string + FileOwner string + NodePIDRoot string + NginxVhostRoot, NginxBinary string + PurePWBinary string + PHPStateRoot, PHPRunRoot string + PythonManagerRoot string + PythonBuildRoot string + PythonMetadataBaseURL string + PythonMetadataCacheRoot string + PythonSourceBaseURLs []string + UsageStatePath, NginxLogRoot string + CertificateRoot, PureFTPConfig, PureFTPPem string + runCommand func(context.Context, string, ...string) error + lookupUID func(string) (uint64, error) + InternalToken string + databaseAdminDSN string + FTPLogPath string +} + +func (a Agent) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /v1/database/phpmyadmin",a.authorizeInternal(a.phpMyAdmin)) + mux.HandleFunc("POST /v1/scheduler/configure",a.authorizeInternal(a.configureSchedulerBridge)) + mux.HandleFunc("POST /v1/schedule/execute",a.authorizeInternal(a.executeSchedule)) + mux.HandleFunc("POST /v1/ftp/disconnect",a.authorizeInternal(a.disconnectFTP)) + mux.HandleFunc("POST /v1/site/startup",a.authorizeInternal(a.configureStartup)) + mux.HandleFunc("POST /v1/site/settings",a.authorizeInternal(a.configureWebsite)) + mux.HandleFunc("POST /v1/site/log",a.authorizeInternal(a.readSiteLog)) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + _, _ = w.Write([]byte(`{"status":"ok"}`)) + }) + mux.HandleFunc("POST /v1/prepare", a.authorizeInternal(a.prepare)) + mux.HandleFunc("POST /v1/quarantine", a.authorizeInternal(a.quarantine)) + mux.HandleFunc("POST /v1/web-protection/apply", a.authorizeInternal(a.applyWebProtection)) + mux.HandleFunc("POST /v1/web-protection/remove", a.authorizeInternal(a.removeWebProtection)) + mux.HandleFunc("POST /v1/runtime/executable", a.authorizeInternal(a.prepareExecutable)) + mux.HandleFunc("POST /v1/runtime/panel-state", a.authorizeInternal(a.preparePanelRuntime)) + mux.HandleFunc("POST /v1/runtime/python/install", a.authorizeInternal(a.installPythonRuntime)) + mux.HandleFunc("POST /v1/runtime/probe", a.authorizeInternal(a.probeRuntime)) + mux.HandleFunc("POST /v1/runtime/php/maintenance", a.authorizeInternal(a.maintainPHP)) + mux.HandleFunc("POST /v1/runtime/backups/prune", a.authorizeInternal(a.pruneRuntimeBackups)) + mux.HandleFunc("POST /v1/runtime/python/dependencies", a.authorizeInternal(a.copyPythonDependencies)) + mux.HandleFunc("POST /v1/run-path/release", a.authorizeInternal(a.releaseRunPath)) + mux.HandleFunc("POST /v1/trash/prepare", a.authorizeInternal(a.prepareTrash)) + mux.HandleFunc("POST /v1/ftp/identity", a.authorizeInternal(a.configureFTPIdentity)) + mux.HandleFunc("POST /v1/credentials/disconnect",a.authorizeInternal(a.disconnectCredentialSessions)) + mux.HandleFunc("POST /v1/php/identity", a.authorizeInternal(a.configurePHPIdentity)) + mux.HandleFunc("POST /v1/php/identity/start", a.authorizeInternal(a.startPHPIdentity)) + mux.HandleFunc("POST /v1/php/identity/stop", a.authorizeInternal(a.stopPHPIdentity)) + mux.HandleFunc("POST /v1/php/identity/remove", a.authorizeInternal(a.removePHPIdentity)) + mux.HandleFunc("POST /v1/resources/usage", a.authorizeInternal(a.resourceUsage)) + mux.HandleFunc("POST /v1/resources/processes/terminate", a.authorizeInternal(a.terminateProcesses)) + mux.HandleFunc("POST /v1/resources/runtime/terminate", a.authorizeInternal(a.terminateRuntime)) + mux.HandleFunc("POST /v1/project/freeze-writes", a.authorizeInternal(a.freezeWrites)) + mux.HandleFunc("POST /v1/ftp/tls", a.authorizeInternal(a.configureFTPTLS)) + mux.HandleFunc("POST /v1/nginx/network", a.authorizeInternal(a.configureNginxNetwork)) + mux.HandleFunc("POST /v1/database/access", a.authorizeInternal(a.configureDatabaseAccess)) + mux.HandleFunc("POST /v1/resources/limits", a.authorizeInternal(a.configureTrafficLimits)) + mux.HandleFunc("POST /v1/lifecycle/backup", a.authorizeInternal(a.createProjectBackup)) + mux.HandleFunc("POST /v1/lifecycle/backup/delete", a.authorizeInternal(a.deleteProjectBackup)) + mux.HandleFunc("POST /v1/lifecycle/backup/verify", a.authorizeInternal(a.verifyProjectBackup)) + mux.HandleFunc("POST /v1/lifecycle/project/purge", a.authorizeInternal(a.purgeProject)) + mux.HandleFunc("POST /v1/import/project", a.authorizeInternal(a.importLegacyProject)) + return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){limit:=int64(64<<10);if r.URL.Path=="/v1/database/phpmyadmin"{limit=4<<20};r.Body=http.MaxBytesReader(w,r.Body,limit);mux.ServeHTTP(w,r)}) +} + +// freezeWrites leaves the unprivileged Sea vHost file service as owner so the +// tenant can delete content and recover below quota, while removing write +// access from the per-host runtime/FTP identity. Existing runtime-created +// files are first reclaimed because their owner may be the host identity. +func (a Agent) freezeWrites(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + if err = requirePhysicalDirectory(projectRoot); err != nil { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + fileOwner := a.FileOwner + if fileOwner == "" { + fileOwner = "sea-vhost" + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + // aaPanel's immutable .user.ini is already root-owned and read-only. Exclude + // it from recursive ownership/ACL operations so the quota transition never + // needs to relax PHP's open_basedir guard. + if err = a.command(ctx, "find", projectRoot, "-xdev", "!", "-name", ".user.ini", "-exec", "chown", "-h", fileOwner+":"+spec.HostName, "{}", "+"); err != nil || + a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "chmod", "u+rwx,g+rX,g-w,o-rwx", "{}", "+") != nil || + a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "!", "-name", ".user.ini", "-exec", "chmod", "u+rw,g+r,g-w,o-rwx", "{}", "+") != nil || + a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", "u:www:r-x,m::r-x,d:u:"+fileOwner+":rwx,d:u:www:r-x,d:g::r-x,d:m::r-x,d:o::---", "{}", "+") != nil || + a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "!", "-name", ".user.ini", "-exec", "setfacl", "-m", "u:www:r--,m::r--,o::---", "{}", "+") != nil { + http.Error(w, "cannot freeze project writes", http.StatusInternalServerError) + return + } + runtimeRoot := filepath.Join(projectRoot, ".sea-runtime") + if err = requirePhysicalDirectory(runtimeRoot); err == nil { + if err = a.command(ctx, "find", runtimeRoot, "-xdev", "-exec", "setfacl", "-m", "u:www:---", "{}", "+"); err != nil { + http.Error(w, "cannot preserve private runtime directory", http.StatusInternalServerError) + return + } + } else if !errors.Is(err, os.ErrNotExist) { + http.Error(w, "unsafe private runtime directory", http.StatusPreconditionFailed) + return + } + if err = a.freezeFTPLogin(ctx, spec.HostName); err != nil { + http.Error(w, "cannot freeze FTP login", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) authorizeInternal(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if a.InternalToken != "" { + supplied := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if len(supplied) != len(a.InternalToken) || subtle.ConstantTimeCompare([]byte(supplied), []byte(a.InternalToken)) != 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + } + next(w, r) + } +} + +// releaseRunPath removes only aaPanel's immutable PHP isolation file from an +// exact managed run directory after its site has been deleted. Source files +// are deliberately retained and remain owned by the Sea vHost file service. +func (a Agent) releaseRunPath(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + runDirectory, err := physicalRunDirectory(projectRoot, spec.RunPath) + if errors.Is(err, os.ErrNotExist) { + w.WriteHeader(http.StatusOK) + return + } + if err != nil { + http.Error(w, "unsafe project run directory", http.StatusPreconditionFailed) + return + } + if err = a.removeUserINI(r.Context(), filepath.Join(runDirectory, ".user.ini")); err != nil { + http.Error(w, "cannot release PHP isolation file", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +// prepareTrash makes interrupted/deleted-site trash removable by the +// unprivileged API process. It may only unlock and remove regular .user.ini +// files below the fixed .sea-trash directory; it never deletes tenant data. +func (a Agent) prepareTrash(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + trash := filepath.Join(projectRoot, ".sea-trash") + info, err := os.Lstat(trash) + if errors.Is(err, os.ErrNotExist) { + w.WriteHeader(http.StatusOK) + return + } + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + http.Error(w, "unsafe trash directory", http.StatusPreconditionFailed) + return + } + files, err := findProjectUserINIFiles(trash, 128) + if err != nil { + http.Error(w, "unsafe PHP isolation file in trash", http.StatusPreconditionFailed) + return + } + for _, file := range files { + if err = a.removeUserINI(r.Context(), file); err != nil { + http.Error(w, "cannot release PHP isolation file in trash", http.StatusInternalServerError) + return + } + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) removeUserINI(parent context.Context, file string) error { + info, err := os.Lstat(file) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("PHP isolation file is not a regular file") + } + ctx, cancel := context.WithTimeout(parent, 10*time.Second) + defer cancel() + if err = a.command(ctx, "chattr", "-i", file); err != nil { + return err + } + return os.Remove(file) +} + +func (a Agent) command(ctx context.Context, name string, args ...string) error { + if a.runCommand != nil { + return a.runCommand(ctx, name, args...) + } + return command(ctx, name, args...) +} + +func (a Agent) commandAt(ctx context.Context, directory, name string, args ...string) error { + if a.runCommand != nil { + return a.runCommand(ctx, name, args...) + } + cmd := exec.CommandContext(ctx, name, args...) + cmd.Dir = directory + cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} + output, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output))) + } + return nil +} + +func (a Agent) prepareExecutable(w http.ResponseWriter, r *http.Request) { + var input ExecutableSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) || input.Project.TenantID == 0 || input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 || !validExecutablePath(input.RelativePath) { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + projectRoot, err := a.projectPath(input.Project) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + root, err := os.OpenRoot(projectRoot) + if err != nil { + http.Error(w, "project root unavailable", http.StatusPreconditionFailed) + return + } + defer root.Close() + info, err := root.Lstat(input.RelativePath) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + http.Error(w, "runtime entry is not a regular file", http.StatusPreconditionFailed) + return + } + if err = root.Chmod(input.RelativePath, 0750); err != nil { + http.Error(w, "cannot mark runtime entry executable", http.StatusInternalServerError) + return + } + if err = a.command(r.Context(), "setfacl", "-m", "u:www:r--,g::r-x,m::r-x,o::---", filepath.Join(projectRoot, filepath.FromSlash(input.RelativePath))); err != nil { + http.Error(w, "cannot apply executable identity ACL", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func validExecutablePath(value string) bool { + if value == "" || len(value) > 255 || strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || filepath.ToSlash(filepath.Clean("/"+value)) != "/"+value { + return false + } + for _, segment := range strings.Split(value, "/") { + if segment == "" || segment == "." || segment == ".." || len(segment) > 100 { + return false + } + for _, character := range segment { + if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) { + return false + } + } + } + return true +} +func (a Agent) decode(w http.ResponseWriter, r *http.Request) (ProjectSpec, bool) { + var spec ProjectSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if spec.RunPath == "" { + spec.RunPath = "/" + } + if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(spec.HostName) || !validProjectRunPath(spec.RunPath) || spec.TenantID == 0 || spec.TenantID > 9_999_999_999 || spec.StorageBytes == 0 || spec.ProcessLimit == 0 || spec.ProcessLimit > 100_000 { + http.Error(w, "invalid request", http.StatusBadRequest) + return ProjectSpec{}, false + } + return spec, true +} +func (a Agent) projectPath(spec ProjectSpec) (string, error) { + base, err := filepath.Abs(a.Root) + if err != nil { + return "", err + } + projectRoot := filepath.Join(base, spec.HostName) + relative, err := filepath.Rel(base, projectRoot) + if err != nil || relative != spec.HostName || strings.Contains(relative, string(os.PathSeparator)) { + return "", errors.New("path outside root") + } + return projectRoot, nil +} +func (a Agent) prepare(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + runtimeUser := spec.HostName + fileOwner := a.FileOwner + if fileOwner == "" { + fileOwner = "sea-vhost" + } + runtimeGroup := runtimeUser + base := filepath.Dir(projectRoot) + if err = ensureDirectory(base, 0755); err != nil { + http.Error(w, "unsafe tenant root", http.StatusPreconditionFailed) + return + } + if err = a.ensureHostIdentity(ctx, spec, projectRoot); err != nil { + http.Error(w, "cannot create isolated project identity", http.StatusInternalServerError) + return + } + // /www/wwwroot is shared with aaPanel and may already contain sites. Never + // change its owner or mode; Sea vHost only mutates its random host directory. + if err = ensureDirectory(projectRoot, 0770); err != nil { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + if err = ensureProjectRunDirectory(projectRoot, spec.RunPath); err != nil { + http.Error(w, "unsafe project run directory", http.StatusPreconditionFailed) + return + } + userINIFiles, err := findProjectUserINIFiles(projectRoot, 64) + if err != nil { + http.Error(w, "unsafe PHP isolation file", http.StatusPreconditionFailed) + return + } + unlockedUserINI := make([]string, 0, len(userINIFiles)) + defer func() { + if len(unlockedUserINI) == 0 { + return + } + lockCtx, cancelLock := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelLock() + for _, userINI := range unlockedUserINI { + _ = command(lockCtx, "chattr", "+i", userINI) + } + }() + for _, userINI := range userINIFiles { + if err = command(ctx, "chattr", "-i", userINI); err != nil { + http.Error(w, "cannot unlock PHP isolation file", http.StatusInternalServerError) + return + } + unlockedUserINI = append(unlockedUserINI, userINI) + } + if err = a.command(ctx, "setfacl", "-Rb", projectRoot); err != nil { + http.Error(w, "cannot reset project ACL", http.StatusInternalServerError) + return + } + if err = a.command(ctx, "chown", "-hR", fileOwner+":"+runtimeGroup, projectRoot); err != nil { + http.Error(w, "cannot set project owner", http.StatusInternalServerError) + return + } + if err = a.command(ctx, "chmod", "-R", "u+rwX,g+rwX,o-rwx", projectRoot); err != nil || a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "chmod", "g+s", "{}", "+") != nil { + http.Error(w, "cannot set project permissions", http.StatusInternalServerError) + return + } + if err = a.applyProjectACL(ctx, projectRoot, fileOwner); err != nil { + http.Error(w, "cannot apply isolated project ACL", http.StatusInternalServerError) + return + } + for _, userINI := range userINIFiles { + if err = a.command(ctx, "chown", "root:root", userINI); err != nil || a.command(ctx, "chmod", "0644", userINI) != nil || a.command(ctx, "chattr", "+i", userINI) != nil { + http.Error(w, "cannot secure PHP isolation file", http.StatusInternalServerError) + return + } + } + unlockedUserINI = nil + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(Prepared{RootPath: filepath.ToSlash(projectRoot), RunUser: runtimeUser}) +} + +func (a Agent) ensureHostIdentity(ctx context.Context, spec ProjectSpec, projectRoot string) error { + name := spec.HostName + if err := a.command(ctx, "getent", "group", name); err != nil { + if err = a.command(ctx, "groupadd", "--system", name); err != nil { + return err + } + } + // The OS identity is only a process/ownership boundary. It deliberately has + // no usable home directory; FTP keeps its independent Pure-FTPd chroot at + // projectRoot and does not rely on the passwd home field. + const disabledHome = "/nonexistent" + if err := a.command(ctx, "id", "-u", name); err != nil { + // aaPanel's built-in Python project model intentionally ignores system + // accounts below UID_MIN. Allocate from the normal UID range while still + // disabling login, passwords and home-directory creation. This preserves + // process isolation without depending on a panel-version-specific user + // whitelist. + if err = a.command(ctx, "useradd", "--gid", name, "--home-dir", disabledHome, "--no-create-home", "--shell", "/usr/sbin/nologin", name); err != nil { + return err + } + } + if err := a.command(ctx, "usermod", "--gid", name, "--groups", name, "--home", disabledHome, "--shell", "/usr/sbin/nologin", name); err != nil { + return err + } + return a.command(ctx, "passwd", "--lock", name) +} + +func (a Agent) applyProjectACL(ctx context.Context, projectRoot, fileOwner string) error { + directoryACL := "u:www:r-x,m::rwx,d:u:" + fileOwner + ":rwx,d:u:www:r-x,d:g::rwx,d:m::rwx,d:o::---" + if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", directoryACL, "{}", "+"); err != nil { + return err + } + if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "-exec", "setfacl", "-m", "u:www:r--,m::rw-,o::---", "{}", "+"); err != nil { + return err + } + // A directory repair must not revoke execution from existing Go binaries, + // venv tools or tenant scripts. www remains read-only even on these files. + if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "-perm", "/111", "-exec", "setfacl", "-m", "u:www:r--,m::rwx,o::---", "{}", "+"); err != nil { + return err + } + // Every website can use its own run directory. Preserve private runtime + // trees at all depths, and never follow venv executable symlinks while + // applying ACLs (those may point to shared server-owned interpreters). + return filepath.WalkDir(projectRoot, func(current string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() && entry.Name() == ".sea-runtime" { + if err := a.securePythonRuntimeACL(ctx, current); err != nil { + return err + } + return filepath.SkipDir + } + return nil + }) +} + +func findProjectUserINIFiles(projectRoot string, limit int) ([]string, error) { + files := make([]string, 0, 2) + err := filepath.WalkDir(projectRoot, func(current string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.Type()&os.ModeSymlink != 0 { + if entry.Name() == ".user.ini" { + return errors.New("PHP isolation file is a symlink") + } + return nil + } + if entry.Name() != ".user.ini" { + return nil + } + info, err := entry.Info() + if err != nil || !info.Mode().IsRegular() { + return errors.New("PHP isolation file is not regular") + } + files = append(files, current) + if len(files) > limit { + return errors.New("too many PHP isolation files") + } + return nil + }) + return files, err +} + +func (a Agent) quarantine(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + source := projectRoot + info, statErr := os.Lstat(source) + if statErr != nil && os.IsNotExist(statErr) { + w.WriteHeader(http.StatusOK) + return + } + if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + trash := filepath.Join(a.Root, ".sea-vhost-quarantine") + if err = ensureDirectory(trash, 0700); err != nil || a.command(ctx, "chown", "root:root", trash) != nil || a.command(ctx, "chmod", "0700", trash) != nil { + http.Error(w, "cannot create quarantine", http.StatusInternalServerError) + return + } + target := filepath.Join(trash, fmt.Sprintf("%s-%d", spec.HostName, time.Now().Unix())) + if err = os.Rename(source, target); err != nil { + http.Error(w, "cannot quarantine", http.StatusInternalServerError) + return + } + // Named ACL entries are stored by numeric UID. Remove any Node.js PID + // access before deleting the account so a future UID reuse cannot inherit + // access to another host's process state. Restore the project directory if + // revocation fails so deletion remains safely retryable. + if err = a.revokeNodePIDAccess(ctx, spec.HostName); err != nil { + _ = os.Rename(target, source) + http.Error(w, "cannot revoke isolated Node.js PID access", http.StatusInternalServerError) + return + } + if a.command(ctx, "id", "-u", spec.HostName) == nil { + if err = a.command(ctx, "userdel", spec.HostName); err != nil { + http.Error(w, "cannot remove isolated project identity", http.StatusInternalServerError) + return + } + } + if a.command(ctx, "getent", "group", spec.HostName) == nil { + if err = a.command(ctx, "groupdel", spec.HostName); err != nil { + http.Error(w, "cannot remove isolated project group", http.StatusInternalServerError) + return + } + } + w.WriteHeader(http.StatusOK) +} +func command(ctx context.Context, name string, args ...string) error { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} + output, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output))) + } + return nil +} + +func ensureDirectory(path string, mode os.FileMode) error { + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + if err = os.Mkdir(path, mode); err != nil { + return err + } + info, err = os.Lstat(path) + } + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("path is not a physical directory") + } + return nil +} + +func ensureProjectRunDirectory(projectRoot, runPath string) error { + if !validProjectRunPath(runPath) { + return errors.New("invalid run path") + } + if runPath == "/" { + return nil + } + root, err := os.OpenRoot(projectRoot) + if err != nil { + return err + } + defer root.Close() + current := "" + for _, segment := range strings.Split(strings.TrimPrefix(runPath, "/"), "/") { + if current == "" { + current = segment + } else { + current += "/" + segment + } + info, statErr := root.Lstat(current) + if errors.Is(statErr, os.ErrNotExist) { + if err = root.Mkdir(current, 0770); err != nil { + return err + } + info, statErr = root.Lstat(current) + } + if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("run path is not a physical directory") + } + } + return nil +} + +func physicalRunDirectory(projectRoot, runPath string) (string, error) { + if !validProjectRunPath(runPath) { + return "", errors.New("invalid run path") + } + root, err := os.OpenRoot(projectRoot) + if err != nil { + return "", err + } + defer root.Close() + if runPath == "/" { + return projectRoot, nil + } + current := "" + for _, segment := range strings.Split(strings.TrimPrefix(runPath, "/"), "/") { + if current == "" { + current = segment + } else { + current += "/" + segment + } + info, statErr := root.Lstat(current) + if statErr != nil { + return "", statErr + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", errors.New("run path is not a physical directory") + } + } + return filepath.Join(projectRoot, filepath.FromSlash(strings.TrimPrefix(runPath, "/"))), nil +} + +func validProjectRunPath(value string) bool { + if value == "/" { + return true + } + if len(value) < 2 || len(value) > 255 || !strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || filepath.ToSlash(filepath.Clean(value)) != value { + return false + } + for _, segment := range strings.Split(strings.TrimPrefix(value, "/"), "/") { + if segment == "" || segment == "." || segment == ".." || len(segment) > 80 { + return false + } + for _, character := range segment { + if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) { + return false + } + } + } + return true +} diff --git a/backend/internal/isolation/agent_test.go b/backend/internal/isolation/agent_test.go new file mode 100644 index 0000000..ea49ce9 --- /dev/null +++ b/backend/internal/isolation/agent_test.go @@ -0,0 +1,657 @@ +package isolation + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func lifecycleRequest(t *testing.T, agent Agent, route string, value any) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(body)) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, request) + return response +} + +func TestLifecycleBackupArchivesOnlyManagedProject(t *testing.T) { + root, backupRoot := t.TempDir(), t.TempDir() + hostName := "sv0123456789" + projectRoot := filepath.Join(root, hostName) + if err := os.MkdirAll(filepath.Join(projectRoot, "public"), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(projectRoot, "public", "marker.txt"), []byte("tenant-marker"), 0600); err != nil { + t.Fatal(err) + } + response := lifecycleRequest(t, Agent{Root: root, BackupRoot: backupRoot}, "/v1/lifecycle/backup", ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}) + if response.Code != http.StatusOK { + t.Fatalf("backup status=%d body=%s", response.Code, response.Body.String()) + } + var backup ProjectBackup + if err := json.Unmarshal(response.Body.Bytes(), &backup); err != nil { + t.Fatal(err) + } + file, err := os.Open(backup.ArchivePath) + if err != nil { + t.Fatal(err) + } + defer file.Close() + gzipReader, err := gzip.NewReader(file) + if err != nil { + t.Fatal(err) + } + tarReader := tar.NewReader(gzipReader) + found := false + for { + header, nextErr := tarReader.Next() + if errors.Is(nextErr, io.EOF) { + break + } + if nextErr != nil { + t.Fatal(nextErr) + } + if header.Name == hostName+"/public/marker.txt" { + found = true + } + if strings.Contains(header.Name, "..") || strings.HasPrefix(header.Name, "/") { + t.Fatalf("unsafe archive path %q", header.Name) + } + } + if !found { + t.Fatal("managed marker was not archived") + } +} + +func TestLifecyclePurgeIsIdempotentAndRemovesIdentity(t *testing.T) { + root := t.TempDir() + hostName := "sv0123456789" + projectRoot := filepath.Join(root, hostName) + if err := os.MkdirAll(projectRoot, 0700); err != nil { + t.Fatal(err) + } + commands := make([]string, 0, 4) + agent := Agent{Root: root, runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + if name == "id" || name == "getent" { + return nil + } + return nil + }} + spec := ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1} + response := lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec) + if response.Code != http.StatusOK { + t.Fatalf("purge status=%d body=%s", response.Code, response.Body.String()) + } + if _, err := os.Stat(projectRoot); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("project directory still exists: %v", err) + } + joined := strings.Join(commands, "\n") + if !strings.Contains(joined, "userdel "+hostName) || !strings.Contains(joined, "groupdel "+hostName) { + t.Fatalf("identity cleanup missing: %s", joined) + } + commands = nil + agent.runCommand = func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return errors.New("missing") + } + response = lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec) + if response.Code != http.StatusOK || strings.Contains(strings.Join(commands, "\n"), "userdel") { + t.Fatalf("retry was not idempotent: status=%d commands=%v", response.Code, commands) + } +} + +func TestAgentHealthCheck(t *testing.T) { + request := httptest.NewRequest(http.MethodGet, "/healthz", nil) + response := httptest.NewRecorder() + Agent{}.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"status":"ok"`) { + t.Fatalf("unexpected health response: %d %s", response.Code, response.Body.String()) + } +} + +func TestAgentMutationRequiresInternalToken(t *testing.T) { + agent := Agent{InternalToken: strings.Repeat("i", 32)} + request := httptest.NewRequest(http.MethodPost, "/v1/prepare", strings.NewReader(`{}`)) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated mutation status = %d, want 401", response.Code) + } +} + +func TestHostIdentityHasNoUsableHomeDirectory(t *testing.T) { + commands := make([]string, 0, 2) + agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + if name == "getent" || name == "id" { + return errors.New("not found") + } + return nil + }} + if err := agent.ensureHostIdentity(context.Background(), ProjectSpec{HostName: "sv0123456789"}, "/www/wwwroot/seavHost/vHost/sv0123456789"); err != nil { + t.Fatal(err) + } + joined := strings.Join(commands, "\n") + if !strings.Contains(joined, "usermod --gid sv0123456789 --groups sv0123456789 --home /nonexistent --shell /usr/sbin/nologin sv0123456789") { + t.Fatalf("identity did not use the disabled home: %s", joined) + } + if strings.Contains(joined, "--home /www/wwwroot") { + t.Fatalf("project root was used as an OS home: %s", joined) + } + if !strings.Contains(joined, "useradd --gid sv0123456789 --home-dir /nonexistent --no-create-home --shell /usr/sbin/nologin sv0123456789") { + t.Fatalf("identity was not allocated from the normal UID range: %s", joined) + } + if strings.Contains(joined, "useradd --system") { + t.Fatalf("identity used a system UID rejected by aaPanel Python: %s", joined) + } +} + +func TestPreparePanelRuntimeGrantsOnlyNodePIDDirectoryAccess(t *testing.T) { + root := filepath.Join(t.TempDir(), "wwwroot") + pidRoot := filepath.Join(t.TempDir(), "pids") + hostName := "sv0123456789" + if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(pidRoot, 0755); err != nil { + t.Fatal(err) + } + commands := make([]string, 0, 2) + agent := Agent{ + Root: root, NodePIDRoot: pidRoot, + lookupUID: func(string) (uint64, error) { return 1001, nil }, + runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return nil + }, + } + spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Node.js"} + body, _ := json.Marshal(spec) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body))) + if response.Code != http.StatusOK { + t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String()) + } + joined := strings.Join(commands, "\n") + if !strings.Contains(joined, "chmod +t "+pidRoot) || !strings.Contains(joined, "setfacl -m u:"+hostName+":rwx,m::rwx "+pidRoot) { + t.Fatalf("unexpected Node.js compatibility commands: %s", joined) + } + if strings.Contains(joined, filepath.Join(root, hostName)+" ") { + t.Fatalf("Node.js compatibility grant escaped the fixed PID directory: %s", joined) + } +} + +func TestPreparePanelRuntimeRejectsLegacyPythonUID(t *testing.T) { + root := filepath.Join(t.TempDir(), "wwwroot") + hostName := "sv0123456789" + if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil { + t.Fatal(err) + } + agent := Agent{Root: root, lookupUID: func(string) (uint64, error) { return 999, nil }} + spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName} + body, _ := json.Marshal(spec) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body))) + if response.Code != http.StatusPreconditionFailed || !strings.Contains(response.Body.String(), "legacy host UID") { + t.Fatalf("legacy Python UID status = %d, body = %s", response.Code, response.Body.String()) + } +} + +func TestPreparePanelRuntimeCreatesIsolatedPythonVirtualEnvironment(t *testing.T) { + root := filepath.Join(t.TempDir(), "wwwroot") + managerRoot := filepath.Join(t.TempDir(), "versions") + hostName := "sv0123456789" + projectRoot := filepath.Join(root, hostName) + basePython := filepath.Join(managerRoot, "3.12.0", "bin", "python3") + if err := os.MkdirAll(projectRoot, 0770); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(basePython), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(basePython, []byte("test"), 0755); err != nil { + t.Fatal(err) + } + commands := make([]string, 0, 3) + agent := Agent{ + Root: root, FileOwner: "sea-vhost", PythonManagerRoot: managerRoot, + lookupUID: func(string) (uint64, error) { return 1001, nil }, + runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + if name == "runuser" { + venvPath := args[len(args)-1] + if err := os.MkdirAll(filepath.Join(venvPath, "bin"), 0770); err != nil { + return err + } + return os.WriteFile(filepath.Join(venvPath, "bin", "python3"), []byte("test"), 0755) + } + return nil + }, + } + spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName} + body, _ := json.Marshal(spec) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body))) + if response.Code != http.StatusOK { + t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String()) + } + venvPath := filepath.Join(projectRoot, ".sea-runtime", "python", hostName+"-3.12.0") + joined := strings.Join(commands, "\n") + if !strings.Contains(joined, "runuser -u "+hostName+" -- "+basePython+" -m venv --system-site-packages "+venvPath) { + t.Fatalf("Python venv command was not confined: %s", joined) + } + if !strings.Contains(joined, "-xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") { + t.Fatalf("Python ACL command did not exclude virtualenv symlinks: %s", joined) + } +} + +func TestFreezeWritesReclaimsOwnershipAndRemovesRuntimeWriteAccess(t *testing.T) { + root := filepath.Join(t.TempDir(), "wwwroot") + hostName := "sv0123456789" + projectRoot := filepath.Join(root, hostName) + if err := os.MkdirAll(projectRoot, 0770); err != nil { + t.Fatal(err) + } + commands := make([]string, 0, 5) + agent := Agent{Root: root, FileOwner: "sea-vhost", PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return nil + }} + spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1} + body, _ := json.Marshal(spec) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body))) + if response.Code != http.StatusOK { + t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String()) + } + joined := strings.Join(commands, "\n") + for _, expected := range []string{ + "chown -h sea-vhost:" + hostName, + "chmod u+rwx,g+rX,g-w,o-rwx", + "chmod u+rw,g+r,g-w,o-rwx", + "d:g::r-x,d:m::r-x", + "u:www:r--,m::r--", + } { + if !strings.Contains(joined, expected) { + t.Fatalf("freeze commands missing %q: %s", expected, joined) + } + } + if !strings.Contains(joined, "! -name .user.ini") { + t.Fatalf("freeze commands did not preserve immutable .user.ini: %s", joined) + } +} + +func TestFreezeWritesKeepsRuntimeDirectoryPrivate(t *testing.T) { + root := filepath.Join(t.TempDir(), "wwwroot") + hostName := "sv0123456789" + projectRoot := filepath.Join(root, hostName) + if err := os.MkdirAll(filepath.Join(projectRoot, ".sea-runtime"), 0770); err != nil { + t.Fatal(err) + } + commands := make([]string, 0, 6) + agent := Agent{Root: root, PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return nil + }} + spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1} + body, _ := json.Marshal(spec) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body))) + if response.Code != http.StatusOK { + t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String()) + } + joined := strings.Join(commands, "\n") + if !strings.Contains(joined, filepath.Join(projectRoot, ".sea-runtime")+" -xdev -exec setfacl -m u:www:---") { + t.Fatalf("freeze did not restore the runtime privacy ACL: %s", joined) + } +} + +func TestBandwidthMeterCountsOnlyCompleteCurrentMonthLines(t *testing.T) { + root := t.TempDir() + logPath := filepath.Join(root, "example.test.log") + initial := "127.0.0.1 - - [30/Sep/2026:23:59:59 +0800] \"GET /old HTTP/1.1\" 200 90 \"-\" \"test\"\n" + + "127.0.0.1 - - [18/Oct/2026:10:00:00 +0800] \"GET / HTTP/1.1\" 200 120 \"-\" \"test\"\n" + if err := os.WriteFile(logPath, []byte(initial), 0600); err != nil { + t.Fatal(err) + } + cursor, err := measureDomainLog(logPath, trafficCursor{Month: "2026-10"}, "2026-10") + if err != nil || cursor.Bytes != 120 { + t.Fatalf("cursor=%+v err=%v", cursor, err) + } + completeOffset := cursor.Offset + file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + t.Fatal(err) + } + _, _ = file.WriteString("127.0.0.1 - - [18/Oct/2026:10:00:01 +0800] \"GET /next HTTP/1.1\" 200 45") + _ = file.Close() + cursor, err = measureDomainLog(logPath, cursor, "2026-10") + if err != nil || cursor.Bytes != 120 || cursor.Offset != completeOffset { + t.Fatalf("partial cursor=%+v err=%v", cursor, err) + } + file, _ = os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600) + _, _ = file.WriteString(" \"-\" \"test\"\n") + _ = file.Close() + cursor, err = measureDomainLog(logPath, cursor, "2026-10") + if err != nil || cursor.Bytes != 165 { + t.Fatalf("completed cursor=%+v err=%v", cursor, err) + } +} + +func TestMeasureProjectStorageCountsManagedTreeWithoutFollowingSymlinks(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "private", "nested"), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "index.html"), []byte("12345"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "private", "nested", "data.bin"), []byte("1234567"), 0600); err != nil { + t.Fatal(err) + } + outside := filepath.Join(t.TempDir(), "outside.bin") + if err := os.WriteFile(outside, make([]byte, 1024*1024), 0600); err != nil { + t.Fatal(err) + } + link := filepath.Join(root, "outside-link") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("symlink creation is unavailable: %v", err) + } + usage, err := measureProjectStorage(root) + if err != nil { + t.Fatal(err) + } + linkInfo, err := os.Lstat(link) + if err != nil { + t.Fatal(err) + } + want := uint64(12 + linkInfo.Size()) + if usage != want { + t.Fatalf("usage = %d, want %d", usage, want) + } +} + +func TestMeasureProjectStorageRejectsSymlinkRoot(t *testing.T) { + realRoot := t.TempDir() + link := filepath.Join(t.TempDir(), "host-link") + if err := os.Symlink(realRoot, link); err != nil { + t.Skipf("symlink creation is unavailable: %v", err) + } + if _, err := measureProjectStorage(link); err == nil { + t.Fatal("symlink project root was accepted") + } +} + +func TestPHPAdapterUsesPrivateSocketWithoutDuplicatingAAPanelLocation(t *testing.T) { + adapter := renderPHPNginxAdapter("/run/sea-vhost-php/sv0123456789.sock") + if strings.Contains(adapter, "location ~ [^/]\\.php(/|$)") { + t.Fatal("adapter duplicates aaPanel's shared PHP location") + } + if !strings.Contains(adapter, "location ~ ^.+\\.php(?:/|$)") || + !strings.Contains(adapter, "fastcgi_pass unix:/run/sea-vhost-php/sv0123456789.sock;") { + t.Fatalf("adapter does not route PHP to the private socket:\n%s", adapter) + } +} + +func TestPHPConfigRunsMasterAsPreselectedHostIdentity(t *testing.T) { + paths := phpIdentityPaths{ + config: "/var/lib/sea-vhost-agent/php/sv0123456789.conf", + pid: "/run/sea-vhost-php/sv0123456789/php-fpm.pid", + socket: "/run/sea-vhost-php/sv0123456789/php-fpm.sock", + } + spec := PHPIdentitySpec{ + Project: ProjectSpec{HostName: "sv0123456789"}, + SiteName: "sv0123456789", ProcessLimit: 4, + } + config := renderPHPIdentityConfig(spec, "/www/wwwroot/seavHost/vHost/sv0123456789", "/www/wwwroot/seavHost/vHost/sv0123456789/.sea-runtime/php", paths) + for _, forbidden := range []string{"listen.owner", "listen.group"} { + if strings.Contains(config, forbidden) { + t.Fatalf("non-root PHP master config contains root-only directive %q", forbidden) + } + } + for _, required := range []string{paths.pid, paths.socket, "/.sea-runtime/php/fpm-error.log", "user = sv0123456789", "group = sv0123456789"} { + if !strings.Contains(config, required) { + t.Fatalf("PHP config is missing %q:\n%s", required, config) + } + } +} + +func TestEnsureProjectRunDirectoryCreatesOnlyPhysicalChildren(t *testing.T) { + root := t.TempDir() + if err := ensureProjectRunDirectory(root, "/apps/web/public"); err != nil { + t.Fatal(err) + } + if info, err := os.Lstat(filepath.Join(root, "apps", "web", "public")); err != nil || !info.IsDir() { + t.Fatalf("run directory was not created: info=%v err=%v", info, err) + } + if err := os.Symlink(filepath.Join(root, "apps"), filepath.Join(root, "linked")); err == nil { + if err = ensureProjectRunDirectory(root, "/linked/public"); err == nil { + t.Fatal("symlinked run directory was accepted") + } + } + for _, unsafe := range []string{"/../etc", "/public/../etc", "/has space", `C:\\Windows`} { + if ensureProjectRunDirectory(root, unsafe) == nil { + t.Fatalf("unsafe run path %q was accepted", unsafe) + } + } +} + +func TestFindProjectUserINIFilesIncludesNestedFilesAndRejectsSymlinks(t *testing.T) { + root := t.TempDir() + public := filepath.Join(root, "public") + if err := os.MkdirAll(public, 0750); err != nil { + t.Fatal(err) + } + for _, name := range []string{filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")} { + if err := os.WriteFile(name, []byte("open_basedir=/tmp"), 0644); err != nil { + t.Fatal(err) + } + } + files, err := findProjectUserINIFiles(root, 4) + if err != nil || len(files) != 2 { + t.Fatalf("files=%#v err=%v", files, err) + } + if err = os.Remove(filepath.Join(public, ".user.ini")); err != nil { + t.Fatal(err) + } + if err = os.Symlink(filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")); err != nil { + t.Skipf("symlink creation is unavailable: %v", err) + } + if _, err = findProjectUserINIFiles(root, 4); err == nil { + t.Fatal("symlinked .user.ini was accepted") + } +} + +func TestReleaseRunPathRemovesOnlyExactIsolationFile(t *testing.T) { + root := filepath.Join(t.TempDir(), "wwwroot") + hostName := "sv0123456789" + runDirectory := filepath.Join(root, hostName, "apps", "web") + if err := os.MkdirAll(runDirectory, 0770); err != nil { + t.Fatal(err) + } + userINI := filepath.Join(runDirectory, ".user.ini") + source := filepath.Join(runDirectory, "index.php") + if err := os.WriteFile(userINI, []byte("open_basedir=/tmp"), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(source, []byte(" 1 { + http.Error(w, "invalid backup verification", 400) + return + } + directory, err := a.backupDirectory(backup.TenantID) + path := filepath.Clean(backup.ArchivePath) + if err != nil || filepath.Dir(path) != directory || !strings.HasPrefix(filepath.Base(path), backup.HostName+"-") || !strings.HasSuffix(path, ".tar.gz") { + http.Error(w, "unsafe backup path", 400) + return + } + if err = verifyRecoveryArchive(r.Context(), path, backup.HostName, backup.DatabaseCount); err != nil { + http.Error(w, "recovery archive is missing, incomplete or corrupt", 412) + return + } + w.WriteHeader(200) +} + +func verifyRecoveryArchive(ctx context.Context, path, hostName string, count int) error { + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("unsafe recovery archive") + } + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + compressed, err := gzip.NewReader(file) + if err != nil { + return err + } + defer compressed.Close() + reader := tar.NewReader(compressed) + type database struct { + Name, Path, SHA256 string + Bytes int64 + } + var manifest struct { + Format int + HostName string + Databases []database + } + hashes := map[string]string{} + sizes := map[string]int64{} + hasManifest := false + for { + if ctx.Err() != nil { + return ctx.Err() + } + header, nextErr := reader.Next() + if nextErr == io.EOF { + break + } + if nextErr != nil { + return nextErr + } + if header.Name == ".sea-vhost-backup/manifest.json" { + if hasManifest || header.Size > 64<<10 { + return errors.New("invalid recovery manifest") + } + data, readErr := io.ReadAll(reader) + if readErr != nil { + return readErr + } + if json.Unmarshal(data, &manifest) != nil { + return errors.New("invalid recovery manifest") + } + hasManifest = true + } else if strings.HasPrefix(header.Name, ".sea-vhost-backup/databases/") { + if header.Name != ".sea-vhost-backup/databases/"+hostName+".sql" || header.Typeflag != tar.TypeReg || hashes[header.Name] != "" { + return errors.New("invalid database archive entry") + } + digest := sha256.New() + size, copyErr := io.Copy(digest, reader) + if copyErr != nil { + return copyErr + } + hashes[header.Name] = fmt.Sprintf("%x", digest.Sum(nil)) + sizes[header.Name] = size + } else { + if _, err = io.Copy(io.Discard, reader); err != nil { + return err + } + } + } + // Read the gzip trailer as well; tar's end marker alone does not validate CRC. + if _, err = io.Copy(io.Discard, compressed); err != nil { + return err + } + if !hasManifest || manifest.Format != 2 || manifest.HostName != hostName || len(manifest.Databases) != count || len(hashes) != count { + return errors.New("incomplete recovery archive") + } + for _, db := range manifest.Databases { + if db.Name != hostName || db.SHA256 != hashes[db.Path] || db.Bytes != sizes[db.Path] || db.Bytes == 0 { + return errors.New("database recovery checksum mismatch") + } + } + return nil +} diff --git a/backend/internal/isolation/client.go b/backend/internal/isolation/client.go new file mode 100644 index 0000000..a74d0a2 --- /dev/null +++ b/backend/internal/isolation/client.go @@ -0,0 +1,184 @@ +package isolation + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "strings" + "time" +) + +type Client struct { + http *http.Client + longHTTP *http.Client + internalToken string +} + +func NewTransportClient(transport http.RoundTripper) *Client { + return &Client{http: &http.Client{Transport: transport, Timeout: 30 * time.Second}, longHTTP: &http.Client{Transport: transport, Timeout: 2 * time.Hour}} +} + +func NewClient(socket string, internalToken ...string) *Client { + transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket) + }} + token := "" + if len(internalToken) > 0 { + token = strings.TrimSpace(internalToken[0]) + } + return &Client{http: &http.Client{Transport: transport, Timeout: 30 * time.Second}, longHTTP: &http.Client{Transport: transport, Timeout: 2 * time.Hour}, internalToken: token} +} +func (c *Client) Ping(ctx context.Context) error { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://unix/healthz", nil) + if err != nil { + return err + } + if c.internalToken != "" { + request.Header.Set("Authorization", "Bearer "+c.internalToken) + } + response, err := c.http.Do(request) + if err != nil { + return fmt.Errorf("isolation agent: %w", err) + } + defer response.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4<<10)) + if response.StatusCode != http.StatusOK { + return fmt.Errorf("isolation agent health check failed (%d)", response.StatusCode) + } + return nil +} +func (c *Client) request(ctx context.Context, path string, input any, out any) error { + return c.requestWithClient(ctx, c.http, path, input, out) +} + +func (c *Client) requestLong(ctx context.Context, path string, input any, out any) error { + return c.requestWithClient(ctx, c.longHTTP, path, input, out) +} + +func (c *Client) requestWithClient(ctx context.Context, client *http.Client, path string, input any, out any) error { + body, err := json.Marshal(input) + if err != nil { + return err + } + request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://unix"+path, bytes.NewReader(body)) + if err != nil { + return err + } + request.Header.Set("Content-Type", "application/json") + if c.internalToken != "" { + request.Header.Set("Authorization", "Bearer "+c.internalToken) + } + response, err := client.Do(request) + if err != nil { + return fmt.Errorf("isolation agent: %w", err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + message, _ := io.ReadAll(io.LimitReader(response.Body, 512)) + detail := strings.TrimSpace(string(message)) + if detail == "" { + detail = "unspecified error" + } + return fmt.Errorf("isolation agent rejected request (%d): %s", response.StatusCode, detail) + } + if out != nil { + return json.NewDecoder(response.Body).Decode(out) + } + return nil +} +func (c *Client) Prepare(ctx context.Context, spec ProjectSpec) (Prepared, error) { + var result Prepared + err := c.request(ctx, "/v1/prepare", spec, &result) + return result, err +} +func (c *Client) Quarantine(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/quarantine", spec, nil) +} +func (c *Client) ApplyWebProtection(ctx context.Context, spec WebProtectionSpec) error { + return c.request(ctx, "/v1/web-protection/apply", spec, nil) +} +func (c *Client) RemoveWebProtection(ctx context.Context, spec WebProtectionSpec) error { + return c.request(ctx, "/v1/web-protection/remove", spec, nil) +} +func (c *Client) PrepareExecutable(ctx context.Context, spec ExecutableSpec) error { + return c.request(ctx, "/v1/runtime/executable", spec, nil) +} +func (c *Client) PreparePanelRuntime(ctx context.Context, spec PanelRuntimeSpec) error { + return c.request(ctx, "/v1/runtime/panel-state", spec, nil) +} +func (c *Client) InstallPythonRuntime(ctx context.Context, version string) error { + return c.requestLong(ctx, "/v1/runtime/python/install", PythonRuntimeInstallSpec{Version: version}, nil) +} +func (c *Client) TerminateRuntime(ctx context.Context, spec RuntimeProcessSpec) error { + return c.request(ctx, "/v1/resources/runtime/terminate", spec, nil) +} +func (c *Client) ReleaseRunPath(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/run-path/release", spec, nil) +} +func (c *Client) PrepareTrash(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/trash/prepare", spec, nil) +} +func (c *Client) ConfigureFTPIdentity(ctx context.Context, spec FTPIdentitySpec) error { + return c.request(ctx, "/v1/ftp/identity", spec, nil) +} +func (c *Client) ConfigurePHPIdentity(ctx context.Context, spec PHPIdentitySpec) error { + return c.request(ctx, "/v1/php/identity", spec, nil) +} +func (c *Client) SetPHPIdentityState(ctx context.Context, spec PHPIdentitySpec, enabled bool) error { + path := "/v1/php/identity/stop" + if enabled { + path = "/v1/php/identity/start" + } + return c.request(ctx, path, spec, nil) +} +func (c *Client) RemovePHPIdentity(ctx context.Context, spec PHPIdentitySpec) error { + return c.request(ctx, "/v1/php/identity/remove", spec, nil) +} +func (c *Client) ResourceUsage(ctx context.Context, spec ResourceUsageSpec) (ResourceUsage, error) { + var result ResourceUsage + err := c.request(ctx, "/v1/resources/usage", spec, &result) + return result, err +} +func (c *Client) TerminateProcesses(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/resources/processes/terminate", spec, nil) +} +func (c *Client) FreezeWrites(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/project/freeze-writes", spec, nil) +} +func (c *Client) ConfigureDatabaseAccess(ctx context.Context, spec DatabaseAccessSpec) error { + return c.request(ctx, "/v1/database/access", spec, nil) +} +func (c *Client) ConfigureTrafficLimits(ctx context.Context, spec TrafficLimitSpec) error { + return c.request(ctx, "/v1/resources/limits", spec, nil) +} +func (c *Client) ConfigureFTPTLS(ctx context.Context, domain string) (string, error) { + var result struct { + Policy string `json:"policy"` + } + err := c.request(ctx, "/v1/ftp/tls", map[string]string{"domain": domain}, &result) + return result.Policy, err +} +func (c *Client) ConfigureNginxNetwork(ctx context.Context, spec NginxNetworkSpec) error { + return c.request(ctx, "/v1/nginx/network", spec, nil) +} +func (c *Client) CreateProjectBackup(ctx context.Context, spec ProjectSpec) (ProjectBackup, error) { + var result ProjectBackup + err := c.requestLong(ctx, "/v1/lifecycle/backup", spec, &result) + return result, err +} +func (c *Client) DeleteProjectBackup(ctx context.Context, backup ProjectBackup) error { + return c.request(ctx, "/v1/lifecycle/backup/delete", backup, nil) +} +func (c *Client) VerifyProjectBackup(ctx context.Context, backup ProjectBackup) error { + return c.requestLong(ctx, "/v1/lifecycle/backup/verify", backup, nil) +} +func (c *Client) PurgeProject(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/lifecycle/project/purge", spec, nil) +} +func (c *Client) ImportLegacyProject(ctx context.Context, spec LegacyImportSpec) error { + return c.requestLong(ctx, "/v1/import/project", spec, nil) +} diff --git a/backend/internal/isolation/credential_sessions.go b/backend/internal/isolation/credential_sessions.go new file mode 100644 index 0000000..b54d6d0 --- /dev/null +++ b/backend/internal/isolation/credential_sessions.go @@ -0,0 +1,77 @@ +package isolation + +import ( + "context" + "database/sql" + "errors" + "github.com/go-sql-driver/mysql" + "net/http" + "strconv" +) + +type CredentialSessions interface { + DisconnectCredentialSessions(context.Context, ProjectSpec) error +} + +func (c *Client) DisconnectCredentialSessions(ctx context.Context, spec ProjectSpec) error { + return c.request(ctx, "/v1/credentials/disconnect", spec, nil) +} +func (Mock) DisconnectCredentialSessions(context.Context, ProjectSpec) error { return nil } +func (a Agent) disconnectCredentialSessions(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + root, err := a.projectPath(spec) + if err != nil || !managedWebHostPattern.MatchString(spec.HostName) || requirePhysicalDirectory(root) != nil { + http.Error(w, "invalid managed identity", 412) + return + } + db, err := a.openMySQL(r.Context()) + if err != nil { + http.Error(w, "database session inspection unavailable", 412) + return + } + defer db.Close() + if err = disconnectManagedDatabaseSessions(r.Context(), db, spec.HostName); err != nil { + http.Error(w, "cannot revoke managed database sessions", 412) + return + } + if err = disconnectFTPSessions(r.Context(), spec.HostName); err != nil { + http.Error(w, "cannot revoke managed FTP sessions", 412) + return + } + w.WriteHeader(200) +} +func disconnectManagedDatabaseSessions(ctx context.Context, db *sql.DB, name string) error { + if !managedWebHostPattern.MatchString(name) { + return errors.New("invalid database identity") + } + rows, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name) + if err != nil { + return err + } + var ids []uint64 + for rows.Next() { + var id uint64 + if err = rows.Scan(&id); err != nil { + rows.Close() + return err + } + ids = append(ids, id) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + for _, id := range ids { + if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil { + var native *mysql.MySQLError + if !errors.As(err, &native) || native.Number != 1094 { + return err + } + } + } + return nil +} diff --git a/backend/internal/isolation/credential_sessions_linux.go b/backend/internal/isolation/credential_sessions_linux.go new file mode 100644 index 0000000..1211d72 --- /dev/null +++ b/backend/internal/isolation/credential_sessions_linux.go @@ -0,0 +1,60 @@ +//go:build linux + +package isolation + +import ( + "context" + "errors" + "os" + "strconv" + "strings" + "syscall" +) + +func disconnectFTPSessions(ctx context.Context, identity string) error { + uid, err := identityUID(identity) + if err != nil { + return err + } + pids, err := identityPIDs(identity) + if err != nil { + return err + } + for _, pid := range pids { + if ctx.Err() != nil { + return ctx.Err() + } + process, e := os.FindProcess(pid) + if e != nil { + continue + } + base := "/proc/" + strconv.Itoa(pid) + exe, exeErr := os.Readlink(base + "/exe") + status, readErr := os.ReadFile(base + "/status") + // CAP_SYS_PTRACE is intentionally absent from the agent. Linux can deny + // /proc//exe across UIDs; status Name/Uid remain readable. Restrict the + // fallback to this host's UID and the exact FTP daemon name, with the pidfd + // acquired before either read so a recycled PID cannot target another task. + if readErr == nil && statusHasUID(status, uid) && managedFTPProcess(status, exe, exeErr != nil) { + e = process.Kill() + if e != nil && !errors.Is(e, os.ErrProcessDone) && !errors.Is(e, syscall.ESRCH) { + process.Release() + return e + } + } + process.Release() + } + return nil +} + +func managedFTPProcess(status []byte, exe string, unreadable bool) bool { + if !unreadable { + return strings.HasPrefix(exe, "/www/server/pure-ftpd/") && strings.HasSuffix(exe, "/pure-ftpd") + } + for _, line := range strings.Split(string(status), "\n") { + if strings.HasPrefix(line, "Name:") { + return strings.TrimSpace(strings.TrimPrefix(line, "Name:")) == "pure-ftpd" + } + } + return false +} diff --git a/backend/internal/isolation/credential_sessions_linux_test.go b/backend/internal/isolation/credential_sessions_linux_test.go new file mode 100644 index 0000000..f9122f6 --- /dev/null +++ b/backend/internal/isolation/credential_sessions_linux_test.go @@ -0,0 +1,16 @@ +//go:build linux + +package isolation + +import "testing" + +func TestFTPSessionIdentificationDoesNotSelectRuntimeProcesses(t *testing.T) { + for _, test := range []struct { + name, exe string + unreadable, want bool + }{{"pure-ftpd", "/www/server/pure-ftpd/sbin/pure-ftpd", false, true}, {"node", "/www/server/nodejs/node", false, false}, {"node", "", true, false}, {"pure-ftpd", "/usr/bin/node", false, false}, {"pure-ftpd", "", true, true}, {"pure-ftpd-other", "", true, false}} { + if got := managedFTPProcess([]byte("Name:\t"+test.name+"\nUid:\t1001\t1001\t1001\t1001\n"), test.exe, test.unreadable); got != test.want { + t.Errorf("FTP match %s: %t", test.name, got) + } + } +} diff --git a/backend/internal/isolation/credential_sessions_other.go b/backend/internal/isolation/credential_sessions_other.go new file mode 100644 index 0000000..35051fd --- /dev/null +++ b/backend/internal/isolation/credential_sessions_other.go @@ -0,0 +1,12 @@ +//go:build !linux + +package isolation + +import ( + "context" + "errors" +) + +func disconnectFTPSessions(context.Context, string) error { + return errors.New("credential sessions require Linux") +} diff --git a/backend/internal/isolation/database_access.go b/backend/internal/isolation/database_access.go new file mode 100644 index 0000000..d6d9f74 --- /dev/null +++ b/backend/internal/isolation/database_access.go @@ -0,0 +1,211 @@ +package isolation + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "io" + "net/http" + "os/exec" + "strconv" + "strings" + "time" + + "github.com/go-sql-driver/mysql" +) + +// Root credentials stay inside the root agent. The fixed, isolated Python +// program reads only aaPanel's local configuration; no shell or supplied code. +func (a Agent) mysqlConfig(ctx context.Context) (*mysql.Config, error) { + if a.databaseAdminDSN != "" { + return mysql.ParseDSN(a.databaseAdminDSN) + } + command := exec.CommandContext(ctx, "/www/server/panel/pyenv/bin/python3", "-I", "-c", `import os,sys,json,re +from pathlib import Path +os.chdir('/www/server/panel');sys.path.insert(0,'/www/server/panel/class');import public +password=public.M('config').where('id=?',(1,)).getField('mysql_root') +assert isinstance(password,str) and password +port=3306 +socket='/tmp/mysql.sock' +p=Path('/etc/my.cnf') +if p.is_file(): + text=p.read_text();section=False + for line in text.splitlines(): + line=line.strip() + if line.startswith('['):section=line.lower()=='[mysqld]' + elif section: + m=re.fullmatch(r'port\s*=\s*(\d+)\s*(?:[#;].*)?',line) + if m:port=int(m.group(1)) + m=re.fullmatch(r'socket\s*=\s*(/[^\s#;]+)\s*(?:[#;].*)?',line) + if m:socket=m.group(1) +assert 1<=port<=65535 +print(json.dumps({'password':password,'port':port,'socket':socket}))`) + data, err := command.Output() + if err != nil || len(data) > 64<<10 { + return nil, errors.New("cannot read local MySQL administrator configuration") + } + var value struct { + Password string + Port int + Socket string + } + if json.Unmarshal(data, &value) != nil || value.Password == "" || value.Port < 1 || value.Port > 65535 { + return nil, errors.New("invalid local MySQL administrator configuration") + } + cfg := mysql.NewConfig() + cfg.User = "root" + cfg.Passwd = value.Password + cfg.Net = "unix" + cfg.Addr = value.Socket + if !strings.HasPrefix(cfg.Addr, "/") || strings.ContainsAny(cfg.Addr, "\r\n\x00") { + return nil, errors.New("invalid MySQL socket path") + } + if strings.HasPrefix(cfg.Addr, "/tmp/") { + cfg.Addr = "/etc/sea-vhost-mysql/host-tmp/" + strings.TrimPrefix(cfg.Addr, "/tmp/") + } + cfg.Timeout = 5 * time.Second + cfg.ReadTimeout = 30 * time.Second + cfg.WriteTimeout = 30 * time.Second + return cfg, nil +} + +func (a Agent) openMySQL(ctx context.Context) (*sql.DB, error) { + cfg, err := a.mysqlConfig(ctx) + if err != nil { + return nil, err + } + db, err := sql.Open("mysql", cfg.FormatDSN()) + if err != nil { + return nil, errors.New("cannot initialize local MySQL administrator connection") + } + db.SetMaxOpenConns(1) + if db.PingContext(ctx) != nil { + db.Close() + return nil, errors.New("cannot connect to local MySQL administrator") + } + return db, nil +} + +func (a Agent) configureDatabaseAccess(w http.ResponseWriter, r *http.Request) { + var spec DatabaseAccessSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Database != spec.Project.HostName || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 { + http.Error(w, "invalid managed database identity", 400) + return + } + root, err := a.projectPath(spec.Project) + if err != nil || requirePhysicalDirectory(root) != nil { + http.Error(w, "managed project root unavailable", 412) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) + defer cancel() + db, err := a.openMySQL(ctx) + if err == nil { + defer db.Close() + err = setDatabaseAccess(ctx, db, spec.Database, spec.ReadOnly, spec.BlockCleanup) + } + if err != nil { + http.Error(w, "cannot enforce managed database access: "+err.Error(), 412) + return + } + w.WriteHeader(200) +} + +func setDatabaseAccess(ctx context.Context, db *sql.DB, name string, readOnly, blockCleanup bool) error { + if !managedWebHostPattern.MatchString(name) { + return errors.New("invalid database name") + } + cleanupPrivilege := "Y" + if blockCleanup { + cleanupPrivilege = "N" + } + rows, err := db.QueryContext(ctx, `SELECT u.Host,COALESCE(d.Insert_priv,'N'),COALESCE(d.Select_priv='Y' AND d.Delete_priv=? AND d.Drop_priv=? AND d.Insert_priv='N' AND d.Update_priv='N' AND d.Create_priv='N' AND d.Grant_priv='N' AND d.References_priv='N' AND d.Index_priv='N' AND d.Alter_priv='N' AND d.Create_tmp_table_priv='N' AND d.Lock_tables_priv='N' AND d.Create_view_priv='N' AND d.Show_view_priv='N' AND d.Create_routine_priv='N' AND d.Alter_routine_priv='N' AND d.Execute_priv='N' AND d.Event_priv='N' AND d.Trigger_priv='N',FALSE) FROM mysql.user u LEFT JOIN mysql.db d ON d.User=u.User AND d.Host=u.Host AND d.Db=? WHERE u.User=?`, cleanupPrivilege, cleanupPrivilege, name, name) + if err != nil { + return errors.New("cannot inspect managed account") + } + type account struct { + host, insert string + readOnly bool + } + var accounts []account + for rows.Next() { + var item account + if err = rows.Scan(&item.host, &item.insert, &item.readOnly); err != nil { + rows.Close() + return err + } + if item.host != "localhost" && item.host != "127.0.0.1" && item.host != "::1" && item.host != "%" { + rows.Close() + return errors.New("unexpected managed account host") + } + accounts = append(accounts, item) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + if len(accounts) == 0 { + return errors.New("managed account not found") + } + changed := false + for _, item := range accounts { + if (readOnly && item.readOnly) || (!readOnly && item.insert == "Y") { + continue + } + accountSQL := "'" + name + "'@'" + item.host + "'" + if _, err = db.ExecContext(ctx, "REVOKE ALL PRIVILEGES, GRANT OPTION FROM "+accountSQL); err != nil { + return errors.New("cannot revoke managed account privileges") + } + privileges := "ALL PRIVILEGES" + if readOnly { + privileges = "SELECT, DELETE, DROP" + if blockCleanup { + privileges = "SELECT" + } + } + if _, err = db.ExecContext(ctx, "GRANT "+privileges+" ON `"+name+"`.* TO "+accountSQL); err != nil { + return errors.New("cannot grant managed account recovery privileges") + } + changed = true + } + if !changed && !readOnly { + return nil + } + // Existing sessions cache database grants. Disconnect only this exact user, + // so pooled connections and transactions cannot retain the old write access. + sessions, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name) + if err != nil { + return errors.New("cannot inspect managed database sessions") + } + var ids []uint64 + for sessions.Next() { + var id uint64 + if err = sessions.Scan(&id); err != nil { + sessions.Close() + return err + } + ids = append(ids, id) + } + err = sessions.Err() + sessions.Close() + if err != nil { + return err + } + for _, id := range ids { + if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil { + var mysqlErr *mysql.MySQLError + if !errors.As(err, &mysqlErr) || mysqlErr.Number != 1094 { + return errors.New("cannot disconnect managed database session") + } + } + } + return nil +} + +func mysqlOptionValue(value string) string { + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`, "\r", `\r`).Replace(value) + `"` +} diff --git a/backend/internal/isolation/database_backup_test.go b/backend/internal/isolation/database_backup_test.go new file mode 100644 index 0000000..0efa270 --- /dev/null +++ b/backend/internal/isolation/database_backup_test.go @@ -0,0 +1,112 @@ +package isolation + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "testing" +) + +func TestDatabaseBackupManifestAndSQLAreInSameArchive(t *testing.T) { + root := t.TempDir() + sql := []byte("CREATE TABLE marker(value TEXT); INSERT INTO marker VALUES ('SEA-BACKUP-SENTINEL');\n") + file := filepath.Join(t.TempDir(), "db.sql") + if err := os.WriteFile(file, sql, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "index.php"), []byte(" 0 { + n := min(len(data), 65535) + header := []byte{1, kind, 0, 1, byte(n >> 8), byte(n), 0, 0} + if _, e := conn.Write(header); e != nil { + return e + } + if _, e := conn.Write(data[:n]); e != nil { + return e + } + data = data[n:] + } + return nil + } + empty := func(kind byte) error { _, e := conn.Write([]byte{1, kind, 0, 1, 0, 0, 0, 0}); return e } + if e = record(1, []byte{0, 1, 0, 0, 0, 0, 0, 0}); e != nil { + return 0, nil, nil, e + } + var encoded bytes.Buffer + length := func(n int) { + if n < 128 { + encoded.WriteByte(byte(n)) + } else { + var value [4]byte + binary.BigEndian.PutUint32(value[:], uint32(n)|0x80000000) + encoded.Write(value[:]) + } + } + for name, value := range params { + length(len(name)) + length(len(value)) + encoded.WriteString(name) + encoded.WriteString(value) + } + if e = record(4, encoded.Bytes()); e == nil { + e = empty(4) + } + if e == nil { + e = record(5, body) + } + if e == nil { + e = empty(5) + } + if e != nil { + return 0, nil, nil, e + } + var output bytes.Buffer + for { + var header [8]byte + if _, e = io.ReadFull(conn, header[:]); e != nil { + return 0, nil, nil, e + } + if header[0] != 1 || header[2] != 0 || header[3] != 1 { + return 0, nil, nil, errors.New("invalid FastCGI record") + } + n := int(binary.BigEndian.Uint16(header[4:6])) + content := make([]byte, n+int(header[6])) + if _, e = io.ReadFull(conn, content); e != nil { + return 0, nil, nil, e + } + switch header[1] { + case 6: + if output.Len()+n > 2<<20 { + return 0, nil, nil, errors.New("phpMyAdmin response exceeds 2 MiB") + } + output.Write(content[:n]) + case 3: + if n < 8 || binary.BigEndian.Uint32(content[:4]) != 0 || content[4] != 0 { + return 0, nil, nil, errors.New("phpMyAdmin process failed") + } + reader := bufio.NewReader(bytes.NewReader(output.Bytes())) + headers, e := textproto.NewReader(reader).ReadMIMEHeader() + if e != nil { + return 0, nil, nil, e + } + status := 200 + if raw := headers.Get("Status"); raw != "" { + if len(raw) < 3 { + return 0, nil, nil, errors.New("invalid CGI status") + } + status, e = strconv.Atoi(raw[:3]) + if e != nil || status < 100 || status > 599 { + return 0, nil, nil, errors.New("invalid CGI status") + } + } + headers.Del("Status") + data, e := io.ReadAll(reader) + return status, http.Header(headers), data, e + } + } +} diff --git a/backend/internal/isolation/ftp_freeze.go b/backend/internal/isolation/ftp_freeze.go new file mode 100644 index 0000000..eef323b --- /dev/null +++ b/backend/internal/isolation/ftp_freeze.go @@ -0,0 +1,63 @@ +package isolation + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "strings" +) + +// The panel's disabled state still permits 127.0.0.1. A suspended host must +// also reject local FTP clients; normal TCP peers cannot originate at 0.0.0.0. +// The panel's enable operation clears this source restriction on recovery. +func (a Agent) freezeFTPLogin(ctx context.Context, username string) error { + binary := a.PurePWBinary + if binary == "" { + binary = "/www/server/pure-ftpd/bin/pure-pw" + } + if !filepath.IsAbs(binary) || filepath.Base(binary) != "pure-pw" || !safeName.MatchString(username) { + return errors.New("invalid FTP freeze identity") + } + directory := filepath.Join(filepath.Dir(filepath.Dir(binary)), "etc") + if a.PureFTPConfig != "" { + directory = filepath.Dir(a.PureFTPConfig) + } + if _, err := os.Lstat(directory); errors.Is(err, os.ErrNotExist) { + return nil + } + if err := requirePhysicalDirectory(directory); err != nil { + return err + } + root, err := os.OpenRoot(directory) + if err != nil { + return err + } + defer root.Close() + info, err := root.Lstat("pureftpd.passwd") + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 { + return errors.New("unsafe FTP account database") + } + file, err := root.Open("pureftpd.passwd") + if err != nil { + return err + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, (16<<20)+1)) + if err != nil { + return err + } + if len(data) > 16<<20 { + return errors.New("FTP account database exceeds limit") + } + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, username+":") { + return a.command(ctx, binary, "usermod", username, "-r", "0.0.0.0", "-m") + } + } + return nil +} diff --git a/backend/internal/isolation/ftp_freeze_test.go b/backend/internal/isolation/ftp_freeze_test.go new file mode 100644 index 0000000..506b313 --- /dev/null +++ b/backend/internal/isolation/ftp_freeze_test.go @@ -0,0 +1,47 @@ +package isolation + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFTPFreezeOnlyChangesMatchingManagedAccount(t *testing.T) { + root := t.TempDir() + directory := filepath.Join(root, "etc") + if err := os.Mkdir(directory, 0700); err != nil { + t.Fatal(err) + } + file := filepath.Join(directory, "pureftpd.passwd") + if err := os.WriteFile(file, []byte("other-user:private-hash:1001\nsv0123456789:private-hash:1002\n"), 0600); err != nil { + t.Fatal(err) + } + var calls []string + a := Agent{PurePWBinary: filepath.Join(root, "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error { + calls = append(calls, strings.Join(args, " ")) + return nil + }} + if err := a.freezeFTPLogin(context.Background(), "sv0123456789"); err != nil { + t.Fatal(err) + } + if len(calls) != 1 || calls[0] != "usermod sv0123456789 -r 0.0.0.0 -m" { + t.Fatalf("unexpected FTP changes: %v", calls) + } + if err := a.freezeFTPLogin(context.Background(), "sv1111111111"); err != nil { + t.Fatal(err) + } + if len(calls) != 1 { + t.Fatal("missing account changed unrelated FTP resources") + } + if err := os.Remove(file); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(root, "outside"), file); err != nil { + t.Skip("symlink unavailable") + } + if err := a.freezeFTPLogin(context.Background(), "sv0123456789"); err == nil { + t.Fatal("symlink account database accepted") + } +} diff --git a/backend/internal/isolation/ftp_identity.go b/backend/internal/isolation/ftp_identity.go new file mode 100644 index 0000000..a0f33ca --- /dev/null +++ b/backend/internal/isolation/ftp_identity.go @@ -0,0 +1,43 @@ +package isolation + +import ( + "context" + "encoding/json" + "io" + "net/http" + "path/filepath" + "strings" + "time" +) + +func (a Agent) configureFTPIdentity(w http.ResponseWriter, r *http.Request) { + var spec FTPIdentitySpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !safeName.MatchString(spec.Project.HostName) || spec.Username != spec.Project.HostName || + spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + projectRoot, err := a.projectPath(spec.Project) + if err != nil || requirePhysicalDirectory(projectRoot) != nil { + http.Error(w, "project root unavailable", http.StatusPreconditionFailed) + return + } + binary := strings.TrimSpace(a.PurePWBinary) + if binary == "" { + binary = "/www/server/pure-ftpd/bin/pure-pw" + } + if !filepath.IsAbs(binary) || filepath.Base(binary) != "pure-pw" { + http.Error(w, "invalid Pure-FTPd identity tool", http.StatusInternalServerError) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + if err = a.command(ctx, binary, "usermod", spec.Username, "-u", spec.Project.HostName, "-g", spec.Project.HostName, "-d", projectRoot, "-m"); err != nil { + http.Error(w, "cannot bind FTP account to isolated identity", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} diff --git a/backend/internal/isolation/ftp_management.go b/backend/internal/isolation/ftp_management.go new file mode 100644 index 0000000..971b80b --- /dev/null +++ b/backend/internal/isolation/ftp_management.go @@ -0,0 +1,6 @@ +package isolation +import("context";"net/http") +type FTPManager interface{DisconnectFTP(context.Context,ProjectSpec)error} +func(c *Client)DisconnectFTP(ctx context.Context,p ProjectSpec)error{return c.request(ctx,"/v1/ftp/disconnect",p,nil)} +func(Mock)DisconnectFTP(context.Context,ProjectSpec)error{return nil} +func(a Agent)disconnectFTP(w http.ResponseWriter,r *http.Request){p,ok:=a.decode(w,r);if !ok{return};root,e:=a.projectPath(p);if e!=nil||!managedWebHostPattern.MatchString(p.HostName)||requirePhysicalDirectory(root)!=nil{http.Error(w,"invalid managed identity",412);return};if e=disconnectFTPSessions(r.Context(),p.HostName);e!=nil{http.Error(w,"cannot disconnect FTP",422);return};w.WriteHeader(200)} diff --git a/backend/internal/isolation/ftp_tls.go b/backend/internal/isolation/ftp_tls.go new file mode 100644 index 0000000..8cd178a --- /dev/null +++ b/backend/internal/isolation/ftp_tls.go @@ -0,0 +1,187 @@ +package isolation + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "time" +) + +var pureFTPTLSLine = regexp.MustCompile(`(?m)^[ \t]*TLS[ \t]+[0-9]+[ \t]*\r?$`) +var pureFTPCertFileLine = regexp.MustCompile(`(?m)^[ \t]*CertFile[ \t]+[^\r\n]+\r?$`) + +func (a Agent) configureFTPTLS(w http.ResponseWriter, r *http.Request) { + var input struct { + Domain string `json:"domain"` + } + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + input.Domain = strings.ToLower(strings.TrimSpace(input.Domain)) + if !webDomainPattern.MatchString(input.Domain) { + http.Error(w, "invalid FTP domain", http.StatusBadRequest) + return + } + policy, err := a.applyFTPTLSPolicy(r.Context(), input.Domain) + if err != nil { + http.Error(w, "cannot configure FTP TLS", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{"policy": policy}) +} + +func (a Agent) applyFTPTLSPolicy(ctx context.Context, domain string) (string, error) { + certRoot := a.CertificateRoot + if certRoot == "" { + certRoot = "/www/server/panel/vhost/cert" + } + configPath := a.PureFTPConfig + if configPath == "" { + configPath = "/www/server/pure-ftpd/etc/pure-ftpd.conf" + } + pemPath := a.PureFTPPem + if pemPath == "" { + pemPath = "/www/server/pure-ftpd/etc/pure-ftpd.pem" + } + certPath := filepath.Join(certRoot, domain, "fullchain.pem") + keyPath := filepath.Join(certRoot, domain, "privkey.pem") + certInfo, certErr := os.Lstat(certPath) + keyInfo, keyErr := os.Lstat(keyPath) + hasCert := certErr == nil && keyErr == nil + if (certErr == nil) != (keyErr == nil) || (certErr != nil && !errors.Is(certErr, os.ErrNotExist)) || (keyErr != nil && !errors.Is(keyErr, os.ErrNotExist)) { + return "", errors.New("incomplete FTP certificate") + } + if hasCert && (!certInfo.Mode().IsRegular() || certInfo.Mode()&os.ModeSymlink != 0 || !keyInfo.Mode().IsRegular() || keyInfo.Mode()&os.ModeSymlink != 0) { + return "", errors.New("unsafe FTP certificate") + } + configInfo, err := os.Lstat(configPath) + if err != nil || !configInfo.Mode().IsRegular() || configInfo.Mode()&os.ModeSymlink != 0 { + return "", errors.New("unsafe Pure-FTPd configuration") + } + config, err := os.ReadFile(configPath) + if err != nil { + return "", err + } + wantedTLS := "TLS 0" + policy := "plain_allowed_no_certificate" + changed := false + if hasCert { + pair, pairErr := tls.LoadX509KeyPair(certPath, keyPath) + if pairErr != nil || len(pair.Certificate) == 0 { + return "", errors.New("invalid FTP certificate pair") + } + leaf, parseErr := x509.ParseCertificate(pair.Certificate[0]) + if parseErr != nil || time.Now().Before(leaf.NotBefore) || !time.Now().Before(leaf.NotAfter) { + return "", errors.New("FTP certificate is not currently valid") + } + if err = leaf.VerifyHostname(domain); err != nil { + return "", errors.New("FTP certificate does not match the configured domain") + } + certPEM, readCertErr := os.ReadFile(certPath) + keyPEM, readKeyErr := os.ReadFile(keyPath) + if readCertErr != nil || readKeyErr != nil { + return "", errors.Join(readCertErr, readKeyErr) + } + combined := append(bytes.TrimSpace(certPEM), '\n') + combined = append(combined, bytes.TrimSpace(keyPEM)...) + combined = append(combined, '\n') + existing, _ := os.ReadFile(pemPath) + if !bytes.Equal(existing, combined) { + if err = writeSecureFile(pemPath, combined, 0600); err != nil { + return "", err + } + changed = true + } + wantedTLS = "TLS 2" + policy = "explicit_tls_required" + } + directiveCount := 0 + updated := pureFTPTLSLine.ReplaceAllFunc(config, func([]byte) []byte { + directiveCount++ + if directiveCount == 1 { + return []byte(wantedTLS) + } + return nil + }) + if directiveCount == 0 { + updated = append(bytes.TrimRight(config, "\r\n"), []byte("\n"+wantedTLS+"\n")...) + } + if hasCert { + wantedCertFile := []byte("CertFile " + pemPath) + certFileCount := 0 + updated = pureFTPCertFileLine.ReplaceAllFunc(updated, func([]byte) []byte { + certFileCount++ + if certFileCount == 1 { + return wantedCertFile + } + return nil + }) + if certFileCount == 0 { + updated = append(bytes.TrimRight(updated, "\r\n"), '\n') + updated = append(updated, wantedCertFile...) + updated = append(updated, '\n') + } + } + if !bytes.Equal(updated, config) { + if err = writeSecureFile(configPath, updated, configInfo.Mode().Perm()); err != nil { + return "", err + } + changed = true + } + if changed { + // Pure-FTPd turns the configuration into daemon command-line flags at + // process start. A SysV-generated unit may report a successful reload + // without replacing those flags, so TLS policy changes require a full + // restart rather than reload-or-restart. + if err = a.restartPureFTP(ctx, configPath); err != nil { + return "", err + } + } + return policy, nil +} + +func (a Agent) restartPureFTP(ctx context.Context, configPath string) error { + if err := a.command(ctx, "systemctl", "stop", "pure-ftpd.service"); err != nil { + return err + } + binaryPath := filepath.Join(filepath.Dir(filepath.Dir(configPath)), "sbin", "pure-ftpd") + if err := terminatePureFTPDaemons(ctx, binaryPath); err != nil { + return err + } + return a.command(ctx, "systemctl", "start", "pure-ftpd.service") +} + +func writeSecureFile(path string, data []byte, mode os.FileMode) error { + temporary, err := os.CreateTemp(filepath.Dir(path), ".sea-vhost-*.tmp") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err = temporary.Chmod(mode); err == nil { + _, err = temporary.Write(data) + } + if err == nil { + err = temporary.Sync() + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return os.Rename(temporaryPath, path) +} diff --git a/backend/internal/isolation/ftp_tls_test.go b/backend/internal/isolation/ftp_tls_test.go new file mode 100644 index 0000000..b8f2f0d --- /dev/null +++ b/backend/internal/isolation/ftp_tls_test.go @@ -0,0 +1,129 @@ +package isolation + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestApplyFTPTLSPolicyRejectsCertificateForAnotherDomain(t *testing.T) { + root := t.TempDir() + certRoot := filepath.Join(root, "cert") + domain := "ftp.example.com" + certDir := filepath.Join(certRoot, domain) + if err := os.MkdirAll(certDir, 0700); err != nil { + t.Fatal(err) + } + certificate, privateKey := ftpTestCertificatePair(t, "other.example.com") + if err := os.WriteFile(filepath.Join(certDir, "fullchain.pem"), certificate, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(certDir, "privkey.pem"), privateKey, 0600); err != nil { + t.Fatal(err) + } + configPath := filepath.Join(root, "pure-ftpd.conf") + if err := os.WriteFile(configPath, []byte("TLS 0\n"), 0600); err != nil { + t.Fatal(err) + } + pemPath := filepath.Join(root, "pure-ftpd.pem") + agent := Agent{ + CertificateRoot: certRoot, + PureFTPConfig: configPath, + PureFTPPem: pemPath, + runCommand: func(context.Context, string, ...string) error { + t.Fatal("service restart must not run for a mismatched certificate") + return nil + }, + } + _, err := agent.applyFTPTLSPolicy(context.Background(), domain) + if err == nil || !strings.Contains(err.Error(), "does not match") { + t.Fatalf("mismatched certificate error = %v", err) + } + if _, statErr := os.Stat(pemPath); !os.IsNotExist(statErr) { + t.Fatalf("FTP PEM was written for a mismatched certificate: %v", statErr) + } + config, readErr := os.ReadFile(configPath) + if readErr != nil || string(config) != "TLS 0\n" { + t.Fatalf("FTP config changed after rejection: %q, %v", config, readErr) + } +} + +func TestApplyFTPTLSPolicyNormalizesTLSAndRestartsDaemon(t *testing.T) { + root := t.TempDir() + certRoot := filepath.Join(root, "cert") + domain := "ftp.example.com" + certDir := filepath.Join(certRoot, domain) + if err := os.MkdirAll(certDir, 0700); err != nil { + t.Fatal(err) + } + certificate, privateKey := ftpTestCertificatePair(t, domain) + if err := os.WriteFile(filepath.Join(certDir, "fullchain.pem"), certificate, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(certDir, "privkey.pem"), privateKey, 0600); err != nil { + t.Fatal(err) + } + configPath := filepath.Join(root, "pure-ftpd.conf") + if err := os.WriteFile(configPath, []byte("NoAnonymous yes\r\nTLS 1\r\nTLS 0\n"), 0600); err != nil { + t.Fatal(err) + } + commands := make([]string, 0, 1) + agent := Agent{ + CertificateRoot: certRoot, PureFTPConfig: configPath, PureFTPPem: filepath.Join(root, "pure-ftpd.pem"), + runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return nil + }, + } + policy, err := agent.applyFTPTLSPolicy(context.Background(), domain) + if err != nil || policy != "explicit_tls_required" { + t.Fatalf("policy = %q, error = %v", policy, err) + } + config, err := os.ReadFile(configPath) + if err != nil { + t.Fatal(err) + } + matches := pureFTPTLSLine.FindAll(config, -1) + if strings.Count(string(config), "TLS 2") != 1 || len(matches) != 1 { + t.Fatalf("TLS directives were not normalized: %q", config) + } + wantedCertFile := "CertFile " + filepath.Join(root, "pure-ftpd.pem") + if strings.Count(string(config), wantedCertFile) != 1 || len(pureFTPCertFileLine.FindAll(config, -1)) != 1 { + t.Fatalf("certificate file directive was not normalized: %q", config) + } + if len(commands) != 2 || commands[0] != "systemctl stop pure-ftpd.service" || commands[1] != "systemctl start pure-ftpd.service" { + t.Fatalf("Pure-FTPd was not fully restarted: %#v", commands) + } +} + +func ftpTestCertificatePair(t *testing.T, domain string) ([]byte, []byte) { + t.Helper() + publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: domain}, DNSNames: []string{domain}, + NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey) + if err != nil { + t.Fatal(err) + } + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) +} diff --git a/backend/internal/isolation/ftp_usage.go b/backend/internal/isolation/ftp_usage.go new file mode 100644 index 0000000..bd6993e --- /dev/null +++ b/backend/internal/isolation/ftp_usage.go @@ -0,0 +1,59 @@ +package isolation + +import ( + "errors" + "path/filepath" + "strconv" + "strings" + "time" +) + +// Pure-FTPd's documented stats format: +// epoch session username ip U|D bytes duration filename (last field unquoted). +func parseFTPStats(line, username, month string, location *time.Location) (uint64, bool) { + fields := strings.Fields(line) + if len(fields) < 8 || fields[2] != username || (fields[4] != "U" && fields[4] != "D") { + return 0, false + } + epoch, err := strconv.ParseInt(fields[0], 10, 64) + if err != nil || epoch <= 0 || time.Unix(epoch, 0).In(location).Format("2006-01") != month { + return 0, false + } + bytes, err := strconv.ParseUint(fields[5], 10, 64) + return bytes, err == nil +} + +func (a Agent) measureFTPBandwidth(username string, now time.Time) (uint64, error) { + if !managedWebHostPattern.MatchString(username) { + return 0, errors.New("invalid FTP usage identity") + } + trafficStateMu.Lock() + defer trafficStateMu.Unlock() + statePath := a.UsageStatePath + if statePath == "" { + statePath = "/var/lib/sea-vhost-agent/traffic.json" + } + if !filepath.IsAbs(statePath) { + return 0, errors.New("invalid traffic state path") + } + state, err := loadTrafficState(statePath) + if err != nil { + return 0, err + } + key := "ftp:" + username + cursor := state.Domains[key] + month := now.Format("2006-01") + if cursor.Month != month { + cursor.Month = month + cursor.Bytes = 0 + } + cursor, err = measureTransferLog(a.ftpTransferLogPath(), cursor, month, func(line string) (uint64, bool) { return parseFTPStats(line, username, month, now.Location()) }) + if err != nil { + return 0, err + } + state.Domains[key] = cursor + if err = saveTrafficState(statePath, state); err != nil { + return 0, err + } + return cursor.Bytes, nil +} diff --git a/backend/internal/isolation/ftp_usage_test.go b/backend/internal/isolation/ftp_usage_test.go new file mode 100644 index 0000000..d20fa77 --- /dev/null +++ b/backend/internal/isolation/ftp_usage_test.go @@ -0,0 +1,52 @@ +package isolation + +import ( + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +func TestFTPMeterCountsBothDirectionsWithRotationAndPartialLines(t *testing.T) { + dir := t.TempDir() + log := filepath.Join(dir, "ftp.log") + now := time.Date(2026, 10, 25, 10, 0, 0, 0, time.UTC) + agent := Agent{UsageStatePath: filepath.Join(dir, "traffic.json"), FTPLogPath: log} + line := func(name, direction string, size int) string { + return fmt.Sprintf("%d session %s 127.0.0.1 %s %d 0.5 file with spaces.txt\n", now.Unix(), name, direction, size) + } + partial := line("sv0123456789", "D", 17) + data := line("sv0123456789", "U", 101) + line("sv0123456789", "D", 202) + line("sv9876543210", "D", 999) + partial[:len(partial)-1] + if err := os.WriteFile(log, []byte(data), 0600); err != nil { + t.Fatal(err) + } + check := func(want uint64) { + t.Helper() + got, err := agent.measureFTPBandwidth("sv0123456789", now) + if err != nil || got != want { + t.Fatalf("bytes=%d want=%d error=%v", got, want, err) + } + } + check(303) + check(303) + file, err := os.OpenFile(log, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + t.Fatal(err) + } + _, _ = file.WriteString("\n") + file.Close() + check(320) + if err = os.Rename(log, log+".1"); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(log, []byte(line("sv0123456789", "U", 23)), 0600); err != nil { + t.Fatal(err) + } + check(343) + next := now.AddDate(0, 1, 0) + got, err := agent.measureFTPBandwidth("sv0123456789", next) + if err != nil || got != 0 { + t.Fatalf("month reset=%d error=%v", got, err) + } +} diff --git a/backend/internal/isolation/isolation.go b/backend/internal/isolation/isolation.go new file mode 100644 index 0000000..995a202 --- /dev/null +++ b/backend/internal/isolation/isolation.go @@ -0,0 +1,169 @@ +package isolation + +import "context" + +type ProjectSpec struct { + TenantID uint64 `json:"tenantId"` + HostName string `json:"hostName"` + RunPath string `json:"runPath"` + StorageBytes uint64 `json:"storageBytes"` + ProcessLimit uint32 `json:"processLimit"` + Databases []string `json:"databases,omitempty"` +} + +type DatabaseAccessSpec struct { + Project ProjectSpec `json:"project"` + Database string `json:"database"` + ReadOnly bool `json:"readOnly"` + BlockCleanup bool `json:"blockCleanup,omitempty"` +} + +type TrafficLimitSpec struct { + Project ProjectSpec `json:"project"` + Domains []string `json:"domains"` + Mbps uint32 `json:"mbps"` +} + +type Prepared struct { + RootPath string `json:"rootPath"` + RunUser string `json:"runUser"` +} + +type FTPIdentitySpec struct { + Project ProjectSpec `json:"project"` + Username string `json:"username"` +} + +type PHPIdentitySpec struct { + Project ProjectSpec `json:"project"` + SiteName string `json:"siteName"` + Domain string `json:"domain"` + Version string `json:"version"` + ProcessLimit uint32 `json:"processLimit"` +} + +type WebProtectionSpec struct { + Project ProjectSpec `json:"project"` + Domain string `json:"domain"` +} + +type ExecutableSpec struct { + Project ProjectSpec `json:"project"` + RelativePath string `json:"relativePath"` +} + +type PanelRuntimeSpec struct { + Project ProjectSpec `json:"project"` + Runtime string `json:"runtime"` + Version string `json:"version,omitempty"` + ProjectName string `json:"projectName,omitempty"` +} + +type PythonRuntimeInstallSpec struct { + Version string `json:"version"` +} + +type RuntimeProcessSpec struct { + Project ProjectSpec `json:"project"` +} + +type ResourceUsageSpec struct { + Project ProjectSpec `json:"project"` + Domains []string `json:"domains"` +} + +type ResourceUsage struct { + MemoryBytes uint64 `json:"memoryBytes"` + CPUTicks uint64 `json:"cpuTicks"` + StorageBytes uint64 `json:"storageBytes"` + BandwidthBytes uint64 `json:"bandwidthBytes"` + ProcessCount uint32 `json:"processCount"` +} + +type NginxNetworkSpec struct { + Project ProjectSpec `json:"project"` + Domain string `json:"domain"` + IPAddress string `json:"ipAddress"` + Dedicated bool `json:"dedicated"` + HTTPPort int `json:"httpPort"` + HTTPSPort int `json:"httpsPort"` +} + +type ProjectBackup struct { + TenantID uint64 `json:"tenantId"` + HostName string `json:"hostName"` + ArchivePath string `json:"archivePath,omitempty"` + SizeBytes uint64 `json:"sizeBytes,omitempty"` + DatabaseCount int `json:"databaseCount"` +} + +type LegacyImportSpec struct { + Project ProjectSpec `json:"project"` + SourcePath string `json:"sourcePath"` +} + +type Interface interface { + Prepare(context.Context, ProjectSpec) (Prepared, error) + Quarantine(context.Context, ProjectSpec) error + ApplyWebProtection(context.Context, WebProtectionSpec) error + RemoveWebProtection(context.Context, WebProtectionSpec) error + PrepareExecutable(context.Context, ExecutableSpec) error + PreparePanelRuntime(context.Context, PanelRuntimeSpec) error + InstallPythonRuntime(context.Context, string) error + TerminateRuntime(context.Context, RuntimeProcessSpec) error + ReleaseRunPath(context.Context, ProjectSpec) error + PrepareTrash(context.Context, ProjectSpec) error + ConfigureFTPIdentity(context.Context, FTPIdentitySpec) error + ConfigurePHPIdentity(context.Context, PHPIdentitySpec) error + SetPHPIdentityState(context.Context, PHPIdentitySpec, bool) error + RemovePHPIdentity(context.Context, PHPIdentitySpec) error + ResourceUsage(context.Context, ResourceUsageSpec) (ResourceUsage, error) + TerminateProcesses(context.Context, ProjectSpec) error + FreezeWrites(context.Context, ProjectSpec) error + ConfigureDatabaseAccess(context.Context, DatabaseAccessSpec) error + ConfigureTrafficLimits(context.Context, TrafficLimitSpec) error + ConfigureFTPTLS(context.Context, string) (string, error) + ConfigureNginxNetwork(context.Context, NginxNetworkSpec) error + CreateProjectBackup(context.Context, ProjectSpec) (ProjectBackup, error) + DeleteProjectBackup(context.Context, ProjectBackup) error + VerifyProjectBackup(context.Context, ProjectBackup) error + PurgeProject(context.Context, ProjectSpec) error + ImportLegacyProject(context.Context, LegacyImportSpec) error +} + +type Mock struct{ Root string } + +func (m Mock) Prepare(_ context.Context, spec ProjectSpec) (Prepared, error) { + return Prepared{RootPath: m.Root + "/" + spec.HostName, RunUser: spec.HostName}, nil +} +func (Mock) Quarantine(context.Context, ProjectSpec) error { return nil } +func (Mock) ApplyWebProtection(context.Context, WebProtectionSpec) error { return nil } +func (Mock) RemoveWebProtection(context.Context, WebProtectionSpec) error { return nil } +func (Mock) PrepareExecutable(context.Context, ExecutableSpec) error { return nil } +func (Mock) PreparePanelRuntime(context.Context, PanelRuntimeSpec) error { return nil } +func (Mock) InstallPythonRuntime(context.Context, string) error { return nil } +func (Mock) TerminateRuntime(context.Context, RuntimeProcessSpec) error { return nil } +func (Mock) ReleaseRunPath(context.Context, ProjectSpec) error { return nil } +func (Mock) PrepareTrash(context.Context, ProjectSpec) error { return nil } +func (Mock) ConfigureFTPIdentity(context.Context, FTPIdentitySpec) error { return nil } +func (Mock) ConfigurePHPIdentity(context.Context, PHPIdentitySpec) error { return nil } +func (Mock) SetPHPIdentityState(context.Context, PHPIdentitySpec, bool) error { return nil } +func (Mock) RemovePHPIdentity(context.Context, PHPIdentitySpec) error { return nil } +func (Mock) ResourceUsage(context.Context, ResourceUsageSpec) (ResourceUsage, error) { + return ResourceUsage{}, nil +} +func (Mock) TerminateProcesses(context.Context, ProjectSpec) error { return nil } +func (Mock) FreezeWrites(context.Context, ProjectSpec) error { return nil } +func (Mock) ConfigureDatabaseAccess(context.Context, DatabaseAccessSpec) error { return nil } +func (Mock) ConfigureTrafficLimits(context.Context, TrafficLimitSpec) error { return nil } +func (Mock) ConfigureFTPTLS(context.Context, string) (string, error) { + return "plain_allowed_no_certificate", nil +} +func (Mock) ConfigureNginxNetwork(context.Context, NginxNetworkSpec) error { return nil } +func (Mock) CreateProjectBackup(_ context.Context, spec ProjectSpec) (ProjectBackup, error) { + return ProjectBackup{TenantID: spec.TenantID, HostName: spec.HostName, ArchivePath: "/tmp/sea-vhost-backup.full.tar.gz", DatabaseCount: len(spec.Databases)}, nil +} +func (Mock) DeleteProjectBackup(context.Context, ProjectBackup) error { return nil } +func (Mock) VerifyProjectBackup(context.Context, ProjectBackup) error { return nil } +func (Mock) PurgeProject(context.Context, ProjectSpec) error { return nil } +func (Mock) ImportLegacyProject(context.Context, LegacyImportSpec) error { return nil } diff --git a/backend/internal/isolation/legacy_import.go b/backend/internal/isolation/legacy_import.go new file mode 100644 index 0000000..4f29daf --- /dev/null +++ b/backend/internal/isolation/legacy_import.go @@ -0,0 +1,148 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "io" + "io/fs" + "net/http" + "os" + "path/filepath" + "strings" +) + +func (a Agent) importLegacyProject(w http.ResponseWriter, r *http.Request) { + var input LegacyImportSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if decoder.Decode(&input) != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(input.Project.HostName) || input.Project.TenantID == 0 || !validProjectRunPath(input.Project.RunPath) { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + target, err := a.projectPath(input.Project) + if err != nil || requirePhysicalDirectory(target) != nil { + http.Error(w, "unsafe target directory", http.StatusPreconditionFailed) + return + } + legacyRoot := strings.TrimSpace(a.LegacyRoot) + if legacyRoot == "" { + legacyRoot = "/www/wwwroot" + } + legacyRoot = filepath.Clean(legacyRoot) + source := filepath.Clean(strings.TrimSpace(input.SourcePath)) + managedRoot := filepath.Clean(a.Root) + if !filepath.IsAbs(source) || source == legacyRoot || !strings.HasPrefix(source+string(filepath.Separator), legacyRoot+string(filepath.Separator)) || strings.HasPrefix(source+string(filepath.Separator), managedRoot+string(filepath.Separator)) || requirePhysicalDirectory(source) != nil { + http.Error(w, "legacy source is outside import boundary", http.StatusBadRequest) + return + } + empty, err := importTargetEmpty(target, input.Project.RunPath) + if err != nil || !empty { + http.Error(w, "target directory is not empty", http.StatusConflict) + return + } + if err = copyLegacyTree(r.Context(), source, target); err != nil { + _ = removeImportedContents(target) + http.Error(w, "cannot import legacy project", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func importTargetEmpty(root, runPath string) (bool, error) { + // Prepare creates the selected run-directory chain before importing. Only + // those empty directories may pre-exist; never overwrite files or siblings. + runRoot := filepath.Clean(filepath.Join(root, strings.TrimPrefix(runPath, "/"))) + empty := true + err := filepath.WalkDir(root, func(current string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if current == root { + return nil + } + if !entry.IsDir() || (current != runRoot && !strings.HasPrefix(runRoot+string(filepath.Separator), current+string(filepath.Separator))) { + empty = false + return fs.SkipAll + } + return nil + }) + return empty, err +} + +func copyLegacyTree(ctx context.Context, source, target string) error { + sourceRoot, err := os.OpenRoot(source) + if err != nil { + return err + } + defer sourceRoot.Close() + return filepath.WalkDir(source, func(current string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + relative, err := filepath.Rel(source, current) + if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { + return errors.New("legacy import escaped source") + } + if relative == "." { + return nil + } + destination := filepath.Join(target, relative) + info, err := entry.Info() + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 || !(info.IsDir() || info.Mode().IsRegular()) { + return errors.New("legacy project contains unsupported links or special files") + } + if info.IsDir() { + if err := os.Mkdir(destination, info.Mode().Perm()|0700); err != nil { + if !errors.Is(err, os.ErrExist) { + return err + } + return requirePhysicalDirectory(destination) + } + return nil + } + return copyLegacyFile(sourceRoot, relative, destination, info.Mode().Perm()) + }) +} + +func copyLegacyFile(sourceRoot *os.Root, relative, target string, mode os.FileMode) error { + input, err := sourceRoot.Open(relative) + if err != nil { + return err + } + defer input.Close() + info, err := input.Stat() + if err != nil || !info.Mode().IsRegular() { + return errors.New("legacy source is not a regular file") + } + output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode|0600) + if err != nil { + return err + } + _, copyErr := io.Copy(output, input) + closeErr := output.Close() + if copyErr != nil { + return copyErr + } + return closeErr +} + +func removeImportedContents(root string) error { + entries, err := os.ReadDir(root) + if err != nil { + return err + } + var result error + for _, entry := range entries { + result = errors.Join(result, os.RemoveAll(filepath.Join(root, entry.Name()))) + } + return result +} diff --git a/backend/internal/isolation/legacy_import_test.go b/backend/internal/isolation/legacy_import_test.go new file mode 100644 index 0000000..dbc137e --- /dev/null +++ b/backend/internal/isolation/legacy_import_test.go @@ -0,0 +1,59 @@ +package isolation + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func TestLegacyImportAcceptsOnlyPreparedEmptyRunDirectories(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "apps", "public"), 0750); err != nil { + t.Fatal(err) + } + if empty, err := importTargetEmpty(root, "/apps/public"); err != nil || !empty { + t.Fatalf("prepared directory refused: %v", err) + } + file := filepath.Join(root, "apps", "public", "existing.txt") + if err := os.WriteFile(file, []byte("do not overwrite"), 0600); err != nil { + t.Fatal(err) + } + if empty, err := importTargetEmpty(root, "/apps/public"); err != nil || empty { + t.Fatal("nonempty directory accepted") + } + if err := os.Remove(file); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(root, "unrelated"), 0750); err != nil { + t.Fatal(err) + } + if empty, err := importTargetEmpty(root, "/apps/public"); err != nil || empty { + t.Fatal("unrelated directory accepted") + } +} + +func TestLegacyCopyPreservesSourceAndPreparedDirectories(t *testing.T) { + source, target := t.TempDir(), t.TempDir() + for _, root := range []string{source, target} { + if err := os.Mkdir(filepath.Join(root, "public"), 0750); err != nil { + t.Fatal(err) + } + } + original := filepath.Join(source, "public", "index.php") + if err := os.WriteFile(original, []byte("source marker"), 0600); err != nil { + t.Fatal(err) + } + if err := copyLegacyTree(context.Background(), source, target); err != nil { + t.Fatal(err) + } + for _, name := range []string{original, filepath.Join(target, "public", "index.php")} { + data, err := os.ReadFile(name) + if err != nil || string(data) != "source marker" { + t.Fatalf("copy changed data: %v", err) + } + } + if err := copyLegacyTree(context.Background(), source, target); err == nil { + t.Fatal("existing file overwritten") + } +} diff --git a/backend/internal/isolation/lifecycle.go b/backend/internal/isolation/lifecycle.go new file mode 100644 index 0000000..028b8e9 --- /dev/null +++ b/backend/internal/isolation/lifecycle.go @@ -0,0 +1,347 @@ +package isolation + +import ( + "archive/tar" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +func (a Agent) backupDirectory(tenantID uint64) (string, error) { + root := strings.TrimSpace(a.BackupRoot) + if root == "" { + root = "/www/backup/sea-vhost" + } + if !filepath.IsAbs(root) || tenantID == 0 { + return "", errors.New("invalid backup root") + } + return filepath.Join(filepath.Clean(root), strconv.FormatUint(tenantID, 10)), nil +} + +func (a Agent) createProjectBackup(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil || requirePhysicalDirectory(projectRoot) != nil { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + if len(spec.Databases) > 1 || (len(spec.Databases) == 1 && (spec.Databases[0] != spec.HostName || !managedWebHostPattern.MatchString(spec.HostName))) { + http.Error(w, "invalid backup database ownership", 400) + return + } + backupDir, err := a.backupDirectory(spec.TenantID) + if err != nil || os.MkdirAll(backupDir, 0700) != nil || os.Chmod(backupDir, 0700) != nil { + http.Error(w, "cannot prepare backup directory", http.StatusInternalServerError) + return + } + stamp := time.Now().UTC().Format("20060102T150405.000000000Z") + finalPath := filepath.Join(backupDir, spec.HostName+"-"+stamp+".tar.gz") + temporary, err := os.CreateTemp(backupDir, "."+spec.HostName+"-*.tmp") + if err != nil { + http.Error(w, "cannot create backup", http.StatusInternalServerError) + return + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + _ = temporary.Chmod(0600) + var dumps []backupDatabaseFile + for _, name := range spec.Databases { + dump, dumpErr := a.dumpDatabase(r.Context(), backupDir, name) + if dumpErr != nil { + temporary.Close() + http.Error(w, "cannot archive customer database", 500) + return + } + defer os.Remove(dump.path) + dumps = append(dumps, dump) + } + err = writeTarGzipDatabase(r.Context(), temporary, projectRoot, spec.HostName, dumps) + if err == nil { + err = temporary.Sync() + } + closeErr := temporary.Close() + if err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(temporaryPath, finalPath) + } + if err == nil && runtime.GOOS != "windows" { + directory, openErr := os.Open(backupDir) + if openErr != nil { + err = openErr + } else { + err = directory.Sync() + directory.Close() + } + } + if err != nil { + http.Error(w, "cannot archive project", http.StatusInternalServerError) + return + } + info, err := os.Stat(finalPath) + if err != nil { + http.Error(w, "cannot inspect backup", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + _ = json.NewEncoder(w).Encode(ProjectBackup{TenantID: spec.TenantID, HostName: spec.HostName, ArchivePath: finalPath, SizeBytes: uint64(info.Size()), DatabaseCount: len(dumps)}) +} + +func writeTarGzip(ctx context.Context, output io.Writer, root, hostName string) error { + return writeTarGzipDatabase(ctx, output, root, hostName, nil) +} + +type backupDatabaseFile struct { + name, path string + size int64 + digest string +} + +func (a Agent) dumpDatabase(ctx context.Context, directory, name string) (backupDatabaseFile, error) { + if !managedWebHostPattern.MatchString(name) { + return backupDatabaseFile{}, errors.New("invalid managed database name") + } + cfg, err := a.mysqlConfig(ctx) + if err != nil { + return backupDatabaseFile{}, err + } + options, err := os.CreateTemp(directory, ".mysql-options-*") + if err != nil { + return backupDatabaseFile{}, err + } + defer os.Remove(options.Name()) + _ = options.Chmod(0600) + if cfg.Net == "unix" { + _, err = fmt.Fprintf(options, "[client]\nuser=%s\npassword=%s\nsocket=%s\nprotocol=SOCKET\n", mysqlOptionValue(cfg.User), mysqlOptionValue(cfg.Passwd), mysqlOptionValue(cfg.Addr)) + } else { + _, err = fmt.Fprintf(options, "[client]\nuser=%s\npassword=%s\nhost=127.0.0.1\nport=%s\nprotocol=TCP\n", mysqlOptionValue(cfg.User), mysqlOptionValue(cfg.Passwd), strings.TrimPrefix(cfg.Addr, "127.0.0.1:")) + } + closeErr := options.Close() + if err == nil { + err = closeErr + } + if err != nil { + return backupDatabaseFile{}, err + } + file, err := os.CreateTemp(directory, ".database-*.sql") + if err != nil { + return backupDatabaseFile{}, err + } + _ = file.Chmod(0600) + cleanup := func() { file.Close(); os.Remove(file.Name()) } + command := exec.CommandContext(ctx, "/www/server/mysql/bin/mysqldump", "--defaults-extra-file="+options.Name(), "--single-transaction", "--quick", "--routines", "--events", "--triggers", "--hex-blob", "--no-tablespaces", "--set-gtid-purged=OFF", "--databases", name) + hash := sha256.New() + command.Stdout = io.MultiWriter(file, hash) + if command.Run() != nil { + cleanup() + return backupDatabaseFile{}, errors.New("customer database dump failed") + } + info, err := file.Stat() + if err != nil || info.Size() == 0 { + cleanup() + return backupDatabaseFile{}, errors.New("empty customer database dump") + } + if err = file.Close(); err != nil { + os.Remove(file.Name()) + return backupDatabaseFile{}, err + } + return backupDatabaseFile{name: name, path: file.Name(), size: info.Size(), digest: fmt.Sprintf("%x", hash.Sum(nil))}, nil +} + +func writeTarGzipDatabase(ctx context.Context, output io.Writer, root, hostName string, dumps []backupDatabaseFile) error { + archiveRoot, openErr := os.OpenRoot(root) + if openErr != nil { + return openErr + } + defer archiveRoot.Close() + gzipWriter := gzip.NewWriter(output) + tarWriter := tar.NewWriter(gzipWriter) + err := filepath.WalkDir(root, func(current string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + info, err := entry.Info() + if err != nil { + return err + } + if !(info.Mode().IsRegular() || info.IsDir() || info.Mode()&os.ModeSymlink != 0) { + return nil + } + relative, err := filepath.Rel(root, current) + if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { + return errors.New("backup path escaped project root") + } + link := "" + if info.Mode()&os.ModeSymlink != 0 { + link, err = os.Readlink(current) + if err != nil { + return err + } + } + header, err := tar.FileInfoHeader(info, link) + if err != nil { + return err + } + header.Name = filepath.ToSlash(filepath.Join(hostName, relative)) + if err = tarWriter.WriteHeader(header); err != nil || !info.Mode().IsRegular() { + return err + } + file, err := archiveRoot.Open(relative) + if err != nil { + return err + } + _, copyErr := io.Copy(tarWriter, file) + closeErr := file.Close() + if copyErr != nil { + return copyErr + } + return closeErr + }) + manifest := map[string]any{"format": 2, "hostName": hostName, "createdAt": time.Now().UTC(), "databases": []map[string]any{}} + entries := []map[string]any{} + for _, dump := range dumps { + if err != nil { + break + } + if ctx.Err() != nil { + err = ctx.Err() + break + } + name := ".sea-vhost-backup/databases/" + dump.name + ".sql" + if err = tarWriter.WriteHeader(&tar.Header{Name: name, Mode: 0600, Size: dump.size, ModTime: time.Now().UTC()}); err != nil { + break + } + file, openErr := os.Open(dump.path) + if openErr != nil { + err = openErr + break + } + _, err = io.Copy(tarWriter, file) + closeErr := file.Close() + if err == nil { + err = closeErr + } + entries = append(entries, map[string]any{"name": dump.name, "path": name, "bytes": dump.size, "sha256": dump.digest}) + } + manifest["databases"] = entries + if err == nil { + data, marshalErr := json.Marshal(manifest) + if marshalErr != nil { + err = marshalErr + } else { + err = tarWriter.WriteHeader(&tar.Header{Name: ".sea-vhost-backup/manifest.json", Mode: 0600, Size: int64(len(data)), ModTime: time.Now().UTC()}) + if err == nil { + _, err = tarWriter.Write(data) + } + } + } + if closeErr := tarWriter.Close(); err == nil { + err = closeErr + } + if closeErr := gzipWriter.Close(); err == nil { + err = closeErr + } + return err +} + +func (a Agent) deleteProjectBackup(w http.ResponseWriter, r *http.Request) { + var backup ProjectBackup + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if decoder.Decode(&backup) != nil || !safeName.MatchString(backup.HostName) || backup.TenantID == 0 { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + directory, err := a.backupDirectory(backup.TenantID) + cleaned := filepath.Clean(backup.ArchivePath) + if err != nil || filepath.Dir(cleaned) != directory || !strings.HasPrefix(filepath.Base(cleaned), backup.HostName+"-") || !strings.HasSuffix(cleaned, ".tar.gz") { + http.Error(w, "unsafe backup path", http.StatusBadRequest) + return + } + info, err := os.Lstat(cleaned) + if errors.Is(err, os.ErrNotExist) { + w.WriteHeader(http.StatusOK) + return + } + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + http.Error(w, "unsafe backup file", http.StatusPreconditionFailed) + return + } + if err = os.Remove(cleaned); err != nil { + http.Error(w, "cannot delete backup", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) purgeProject(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + physicalErr := requirePhysicalDirectory(projectRoot) + if physicalErr == nil { + files, findErr := findProjectUserINIFiles(projectRoot, 512) + if findErr != nil { + http.Error(w, "unsafe PHP isolation file", http.StatusPreconditionFailed) + return + } + for _, file := range files { + if err = a.removeUserINI(r.Context(), file); err != nil { + http.Error(w, "cannot release PHP isolation file", http.StatusInternalServerError) + return + } + } + if err = os.RemoveAll(projectRoot); err != nil { + http.Error(w, "cannot purge project", http.StatusInternalServerError) + return + } + } else if !errors.Is(physicalErr, os.ErrNotExist) { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + // Probe identities first so retries are idempotent without depending on + // distribution-specific userdel/groupdel error text. + if a.command(ctx, "id", "-u", spec.HostName) == nil { + if err = a.command(ctx, "userdel", spec.HostName); err != nil { + http.Error(w, "cannot remove project identity", http.StatusInternalServerError) + return + } + } + if a.command(ctx, "getent", "group", spec.HostName) == nil { + if err = a.command(ctx, "groupdel", spec.HostName); err != nil { + http.Error(w, "cannot remove project group", http.StatusInternalServerError) + return + } + } + w.WriteHeader(http.StatusOK) +} diff --git a/backend/internal/isolation/nginx_network.go b/backend/internal/isolation/nginx_network.go new file mode 100644 index 0000000..8c542e5 --- /dev/null +++ b/backend/internal/isolation/nginx_network.go @@ -0,0 +1,112 @@ +package isolation + +import ( + "context" + "encoding/json" + "io" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" +) + +var nginxListenLine = regexp.MustCompile(`(?m)^(\s*)listen\s+(?:\[[0-9A-Fa-f:]+\]|[0-9.]+)?(?::)?([0-9]{1,5})([^;]*);\s*$`) + +func (a Agent) configureNginxNetwork(w http.ResponseWriter, r *http.Request) { + var spec NginxNetworkSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !managedWebHostPattern.MatchString(spec.Project.HostName) || !webDomainPattern.MatchString(spec.Domain) || + spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 || + spec.HTTPPort < 1 || spec.HTTPPort > 65535 || spec.HTTPSPort < 1 || spec.HTTPSPort > 65535 || spec.HTTPPort == spec.HTTPSPort { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + if spec.Dedicated && net.ParseIP(spec.IPAddress) == nil { + http.Error(w, "invalid dedicated ip", http.StatusBadRequest) + return + } + if !spec.Dedicated && strings.TrimSpace(spec.IPAddress) != "" { + http.Error(w, "shared mode cannot bind an ip", http.StatusBadRequest) + return + } + vhostRoot, err := filepath.Abs(a.NginxVhostRoot) + if err != nil || !filepath.IsAbs(vhostRoot) || requirePhysicalDirectory(vhostRoot) != nil { + http.Error(w, "nginx vhost root is unavailable", http.StatusPreconditionFailed) + return + } + configPath := filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf") + info, err := os.Lstat(configPath) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 2<<20 { + http.Error(w, "unsafe nginx site configuration", http.StatusPreconditionFailed) + return + } + content, err := os.ReadFile(configPath) + if err != nil { + http.Error(w, "cannot read nginx site configuration", http.StatusInternalServerError) + return + } + matched := 0 + updated := nginxListenLine.ReplaceAllStringFunc(string(content), func(line string) string { + parts := nginxListenLine.FindStringSubmatch(line) + if len(parts) != 4 { + return line + } + port, parseErr := strconv.Atoi(parts[2]) + if parseErr != nil { + return line + } + suffix := parts[3] + isTLS := strings.Contains(strings.ToLower(suffix), "ssl") || port == 443 + wanted := spec.HTTPPort + if isTLS { + wanted = spec.HTTPSPort + } + address := "" + if spec.Dedicated { + address = spec.IPAddress + if strings.Contains(address, ":") { + address = "[" + address + "]" + } + address += ":" + } + matched++ + return parts[1] + "listen " + address + strconv.Itoa(wanted) + suffix + ";" + }) + if matched == 0 { + http.Error(w, "nginx listen directives were not found", http.StatusPreconditionFailed) + return + } + if updated == string(content) { + w.WriteHeader(http.StatusOK) + return + } + restore, err := writeManagedFile(configPath, []byte(updated)) + if err != nil { + http.Error(w, "cannot write nginx site configuration", http.StatusInternalServerError) + return + } + ctx, cancel := contextWithNetworkTimeout(r) + defer cancel() + rollback := func() { _ = restore(); _ = a.runNginx(ctx, "-t"); _ = a.runNginx(ctx, "-s", "reload") } + if err = a.runNginx(ctx, "-t"); err != nil { + rollback() + http.Error(w, "nginx rejected network configuration", http.StatusPreconditionFailed) + return + } + if err = a.runNginx(ctx, "-s", "reload"); err != nil { + rollback() + http.Error(w, "cannot reload nginx", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func contextWithNetworkTimeout(r *http.Request) (context.Context, context.CancelFunc) { + return context.WithTimeout(r.Context(), 20*time.Second) +} diff --git a/backend/internal/isolation/nginx_network_test.go b/backend/internal/isolation/nginx_network_test.go new file mode 100644 index 0000000..b7aa9e7 --- /dev/null +++ b/backend/internal/isolation/nginx_network_test.go @@ -0,0 +1,40 @@ +package isolation + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestRepeatedCustomNetworkPortIsIdempotent(t *testing.T) { + root := t.TempDir() + domain := "sv0123456789.hosts.example.test" + file := filepath.Join(root, domain+".conf") + if err := os.WriteFile(file, []byte("server {\n listen 80;\n server_name "+domain+";\n}\n"), 0600); err != nil { + t.Fatal(err) + } + commands := 0 + a := Agent{NginxVhostRoot: root, NginxBinary: filepath.Join(root, "nginx"), runCommand: func(context.Context, string, ...string) error { commands++; return nil }} + spec := NginxNetworkSpec{Project: ProjectSpec{TenantID: 1, HostName: "sv0123456789", StorageBytes: 1, ProcessLimit: 1}, Domain: domain, HTTPPort: 18080, HTTPSPort: 18443} + data, _ := json.Marshal(spec) + for i := 0; i < 2; i++ { + response := httptest.NewRecorder() + a.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/nginx/network", bytes.NewReader(data))) + if response.Code != http.StatusOK { + t.Fatalf("request %d: %d %s", i, response.Code, response.Body.String()) + } + } + if commands != 2 { + t.Fatalf("repeated request unnecessarily reloaded Nginx: %d", commands) + } + content, err := os.ReadFile(file) + if err != nil || !strings.Contains(string(content), "listen 18080;") { + t.Fatal("custom port was not retained") + } +} diff --git a/backend/internal/isolation/panel_runtime.go b/backend/internal/isolation/panel_runtime.go new file mode 100644 index 0000000..26028b8 --- /dev/null +++ b/backend/internal/isolation/panel_runtime.go @@ -0,0 +1,249 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "os/user" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" +) + +const defaultNodePIDRoot = "/www/server/nodejs/vhost/pids" + +var ( + pythonManagerVersionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`) + panelProjectNamePattern = regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`) +) + +// preparePanelRuntime applies only the narrowly-scoped host-side state that +// aaPanel's free language modules require. Project creation and lifecycle stay +// behind the panel broker; this endpoint never grants a tenant access to the +// panel installation as a whole. +func (a Agent) preparePanelRuntime(w http.ResponseWriter, r *http.Request) { + var input PanelRuntimeSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) || + input.Project.TenantID == 0 || input.Project.TenantID > 9_999_999_999 || + input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 || input.Project.ProcessLimit > 100_000 { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + projectRoot, err := a.projectPath(input.Project) + if err != nil || requirePhysicalDirectory(projectRoot) != nil { + http.Error(w, "unsafe project directory", http.StatusPreconditionFailed) + return + } + uid, err := a.hostUID(input.Project.HostName) + if err != nil { + http.Error(w, "isolated project identity is unavailable", http.StatusPreconditionFailed) + return + } + switch input.Runtime { + case "Node.js": + if err = a.prepareNodePIDAccess(r.Context(), input.Project.HostName); err != nil { + http.Error(w, "cannot prepare isolated Node.js PID access", http.StatusPreconditionFailed) + return + } + case "Python": + // aaPanel's current Python manager lists only root and identities from + // the normal UID range. Detect legacy Sea vHost system UIDs before the + // panel can create an untracked partial project. + if uid < 1000 { + http.Error(w, "legacy host UID is incompatible with the aaPanel Python project manager", http.StatusPreconditionFailed) + return + } + if !pythonManagerVersionPattern.MatchString(input.Version) || !panelProjectNamePattern.MatchString(input.ProjectName) { + http.Error(w, "invalid Python runtime specification", http.StatusBadRequest) + return + } + if err = a.preparePythonVirtualEnvironment(r.Context(), projectRoot, input); err != nil { + http.Error(w, "cannot prepare isolated Python environment", http.StatusPreconditionFailed) + return + } + default: + http.Error(w, "unsupported panel runtime", http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) preparePythonVirtualEnvironment(ctx context.Context, projectRoot string, input PanelRuntimeSpec) error { + managerRoot := a.PythonManagerRoot + if managerRoot == "" { + managerRoot = "/www/server/python_manager/versions" + } + baseRoot := filepath.Join(managerRoot, input.Version) + resolvedBase, err := filepath.EvalSymlinks(baseRoot) + if err != nil || filepath.Clean(resolvedBase) != filepath.Clean(baseRoot) { + return errors.New("Python manager version path is unavailable") + } + if err = a.repairManagedPythonAccess(ctx, baseRoot, input.Version); err != nil { + return err + } + basePython := filepath.Join(baseRoot, "bin", "python3") + resolvedPython, err := filepath.EvalSymlinks(basePython) + if err != nil || !strings.HasPrefix(filepath.Clean(resolvedPython)+string(os.PathSeparator), filepath.Clean(baseRoot)+string(os.PathSeparator)) { + return errors.New("Python manager interpreter escaped its version directory") + } + info, err := os.Stat(resolvedPython) + if err != nil || !runtimeExecutable(info) { + return errors.New("Python manager interpreter is not executable") + } + runtimeRelative := filepath.ToSlash(filepath.Join(strings.TrimPrefix(input.Project.RunPath, "/"), ".sea-runtime", "python")) + if !strings.HasPrefix(runtimeRelative, "/") { + runtimeRelative = "/" + runtimeRelative + } + if err = ensureProjectRunDirectory(projectRoot, runtimeRelative); err != nil { + return err + } + runtimeParent, err := physicalRunDirectory(projectRoot, runtimeRelative) + if err != nil { + return err + } + runtimeRoot := filepath.Dir(runtimeParent) + if err = requirePhysicalDirectory(runtimeRoot); err != nil { + return err + } + fileOwner := a.FileOwner + if fileOwner == "" { + fileOwner = "sea-vhost" + } + if err = a.command(ctx, "chown", fileOwner+":"+input.Project.HostName, runtimeRoot, runtimeParent); err != nil { + return err + } + if err = a.command(ctx, "chmod", "2770", runtimeRoot, runtimeParent); err != nil { + return err + } + venvPath := filepath.Join(runtimeParent, input.ProjectName+"-"+input.Version) + if venvInfo, statErr := os.Lstat(venvPath); statErr == nil { + if !venvInfo.IsDir() || venvInfo.Mode()&os.ModeSymlink != 0 { + return errors.New("Python virtual environment path is unsafe") + } + venvPython := filepath.Join(venvPath, "bin", "python3") + if existing, existingErr := os.Stat(venvPython); existingErr == nil && runtimeExecutable(existing) { + return a.securePythonRuntimeACL(ctx, runtimeRoot) + } + return errors.New("Python virtual environment is incomplete") + } else if !errors.Is(statErr, os.ErrNotExist) { + return statErr + } + if err = a.command(ctx, "runuser", "-u", input.Project.HostName, "--", basePython, "-m", "venv", "--system-site-packages", venvPath); err != nil { + return err + } + venvInfo, err := os.Lstat(venvPath) + if err != nil || !venvInfo.IsDir() || venvInfo.Mode()&os.ModeSymlink != 0 { + return errors.New("Python virtual environment was not created safely") + } + venvPython, err := os.Stat(filepath.Join(venvPath, "bin", "python3")) + if err != nil || !runtimeExecutable(venvPython) { + return errors.New("Python virtual environment interpreter is unavailable") + } + return a.securePythonRuntimeACL(ctx, runtimeRoot) +} + +// The agent's restrictive umask must not make shared standard libraries or +// pip metadata unreadable to isolated UIDs. Only the fixed interpreter tree +// is normalized; tenant venvs keep their private ACLs. +func (a Agent) normalizeSharedPythonAccess(ctx context.Context, root string) error { + if requirePhysicalDirectory(root) != nil { + return errors.New("unsafe shared Python installation") + } + if err := a.command(ctx, "chown", "-hR", "root:root", root); err != nil { + return err + } + if err := a.command(ctx, "find", root, "-xdev", "-type", "d", "-exec", "chmod", "a+rx,go-w", "{}", "+"); err != nil { + return err + } + return a.command(ctx, "find", root, "-xdev", "-type", "f", "-exec", "chmod", "a+rX,go-w", "{}", "+") +} + +func (a Agent) repairManagedPythonAccess(ctx context.Context, root, version string) error { + marker := filepath.Join(root, ".sea-vhost-runtime") + info, err := os.Lstat(marker) + if errors.Is(err, os.ErrNotExist) { + return nil + } // Do not rewrite administrator-managed installations. + if err != nil || !info.Mode().IsRegular() { + return errors.New("invalid managed Python marker") + } + data, err := os.ReadFile(marker) + if err != nil || strings.TrimSpace(string(data)) != version { + return errors.New("managed Python version marker mismatch") + } + return a.normalizeSharedPythonAccess(ctx, root) +} + +func runtimeExecutable(info os.FileInfo) bool { + return info.Mode().IsRegular() && (runtime.GOOS == "windows" || info.Mode()&0111 != 0) +} + +func (a Agent) securePythonRuntimeACL(ctx context.Context, runtimeRoot string) error { + // Do not pass venv symlinks to setfacl: Python intentionally links its + // executable back to the server-owned base interpreter, and setfacl follows + // those links. The private parent directory already prevents www from + // traversing the links; only real directories and files need explicit ACLs. + if err := a.command(ctx, "find", runtimeRoot, "-xdev", "(", "-type", "d", "-o", "-type", "f", ")", "-exec", "setfacl", "-m", "u:www:---", "{}", "+"); err != nil { + return err + } + return a.command(ctx, "find", runtimeRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", "d:u:www:---", "{}", "+") +} + +func (a Agent) hostUID(name string) (uint64, error) { + if a.lookupUID != nil { + return a.lookupUID(name) + } + account, err := user.Lookup(name) + if err != nil { + return 0, err + } + return strconv.ParseUint(account.Uid, 10, 64) +} + +func (a Agent) nodePIDDirectory() (string, error) { + root := a.NodePIDRoot + if root == "" { + root = defaultNodePIDRoot + } + if !filepath.IsAbs(root) || root != filepath.Clean(root) { + return "", errors.New("invalid Node.js PID directory") + } + if err := requirePhysicalDirectory(root); err != nil { + return "", err + } + resolved, err := filepath.EvalSymlinks(root) + if err != nil || filepath.Clean(resolved) != root { + return "", errors.New("Node.js PID directory contains a symbolic link") + } + return root, nil +} + +func (a Agent) prepareNodePIDAccess(ctx context.Context, hostName string) error { + root, err := a.nodePIDDirectory() + if err != nil { + return err + } + if err = a.command(ctx, "chmod", "+t", root); err != nil { + return err + } + return a.command(ctx, "setfacl", "-m", "u:"+hostName+":rwx,m::rwx", root) +} + +func (a Agent) revokeNodePIDAccess(ctx context.Context, hostName string) error { + root, err := a.nodePIDDirectory() + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + return a.command(ctx, "setfacl", "-x", "u:"+hostName, root) +} diff --git a/backend/internal/isolation/php_identity.go b/backend/internal/isolation/php_identity.go new file mode 100644 index 0000000..783eee5 --- /dev/null +++ b/backend/internal/isolation/php_identity.go @@ -0,0 +1,483 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" +) + +var ( + phpSiteNamePattern = regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`) + phpVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]$`) +) + +type phpIdentityPaths struct { + config, pid, socket, nginx string +} + +func (a Agent) decodePHPIdentity(w http.ResponseWriter, r *http.Request) (PHPIdentitySpec, bool) { + var spec PHPIdentitySpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !safeName.MatchString(spec.Project.HostName) || !phpSiteNamePattern.MatchString(spec.SiteName) || + !webDomainPattern.MatchString(spec.Domain) || !phpVersionPattern.MatchString(spec.Version) || + !validProjectRunPath(spec.Project.RunPath) || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || + spec.Project.ProcessLimit == 0 || spec.ProcessLimit == 0 || spec.ProcessLimit > 100_000 { + http.Error(w, "invalid request", http.StatusBadRequest) + return PHPIdentitySpec{}, false + } + return spec, true +} + +func (a Agent) configurePHPIdentity(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decodePHPIdentity(w, r) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + paths, binary, projectRoot, err := a.phpIdentityEnvironment(spec) + if err != nil { + http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) + return + } + tempRoot, err := a.preparePHPTempDirectory(ctx, projectRoot, spec.Project.HostName) + if err != nil { + http.Error(w, "cannot prepare isolated PHP temporary directory", http.StatusInternalServerError) + return + } + content := renderPHPIdentityConfig(spec, projectRoot, tempRoot, paths) + if err = writePrivateFile(paths.config, []byte(content)); err != nil { + http.Error(w, "cannot write PHP identity configuration", http.StatusInternalServerError) + return + } + if err = a.command(ctx, "chown", "root:"+spec.Project.HostName, paths.config); err != nil || + a.command(ctx, "chmod", "0640", paths.config) != nil { + http.Error(w, "cannot secure PHP identity configuration", http.StatusInternalServerError) + return + } + // Validate as the tenant identity, not as root. PHP-FPM opens its configured + // error log even during `-t`; a root validation would leave a root-owned + // file in the tenant runtime directory and can also follow a tenant-created + // symlink with root privileges. + if err = testPHPAsIdentity(ctx, binary, paths.config, spec.Project.HostName); err != nil { + slog.Error("PHP-FPM rejected isolated pool configuration", "site", spec.SiteName, "error", err) + http.Error(w, "PHP-FPM rejected isolated pool configuration", http.StatusPreconditionFailed) + return + } + _ = a.stopPHPIdentityProcess(ctx, paths) + if err = a.startPHPIdentityProcess(ctx, binary, paths, spec.Project.HostName); err != nil { + slog.Error("cannot start isolated PHP-FPM pool", "site", spec.SiteName, "identity", spec.Project.HostName, "error", err) + http.Error(w, "cannot start isolated PHP-FPM pool", http.StatusInternalServerError) + return + } + nginxContent := []byte(renderPHPNginxAdapter(paths.socket)) + restore, err := writeManagedFile(paths.nginx, nginxContent) + if err != nil { + _ = a.stopPHPIdentityProcess(ctx, paths) + http.Error(w, "cannot write isolated PHP adapter", http.StatusInternalServerError) + return + } + rollback := func() { + _ = restore() + _ = a.runNginx(ctx, "-t") + _ = a.runNginx(ctx, "-s", "reload") + _ = a.stopPHPIdentityProcess(ctx, paths) + } + if err = a.runNginx(ctx, "-t"); err != nil { + slog.Error("nginx rejected isolated PHP adapter", "site", spec.SiteName, "domain", spec.Domain, "error", err) + rollback() + http.Error(w, "Nginx rejected isolated PHP adapter", http.StatusPreconditionFailed) + return + } + if err = a.runNginx(ctx, "-s", "reload"); err != nil { + rollback() + http.Error(w, "cannot reload Nginx for isolated PHP pool", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) startPHPIdentity(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decodePHPIdentity(w, r) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + paths, binary, _, err := a.phpIdentityEnvironment(spec) + if err != nil { + http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) + return + } + if _, err = os.Stat(paths.config); err != nil { + http.Error(w, "PHP identity has not been configured", http.StatusPreconditionFailed) + return + } + if err = a.startPHPIdentityProcess(ctx, binary, paths, spec.Project.HostName); err != nil { + slog.Error("cannot start isolated PHP-FPM pool", "site", spec.SiteName, "identity", spec.Project.HostName, "error", err) + http.Error(w, "cannot start isolated PHP-FPM pool", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) stopPHPIdentity(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decodePHPIdentity(w, r) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + paths, _, _, err := a.phpIdentityEnvironment(spec) + if err != nil { + http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) + return + } + if err = a.stopPHPIdentityProcess(ctx, paths); err != nil { + http.Error(w, "cannot stop isolated PHP-FPM pool", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) removePHPIdentity(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decodePHPIdentity(w, r) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) + defer cancel() + paths, siteConfig, err := a.phpIdentityRemovalPaths(spec) + if err != nil { + http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) + return + } + if err = a.stopPHPIdentityProcess(ctx, paths); err != nil { + http.Error(w, "cannot stop isolated PHP-FPM pool", http.StatusInternalServerError) + return + } + var oldNginx []byte + if oldNginx, err = os.ReadFile(paths.nginx); err != nil && !errors.Is(err, os.ErrNotExist) { + http.Error(w, "cannot read isolated PHP adapter", http.StatusInternalServerError) + return + } + if err == nil { + if err = os.Remove(paths.nginx); err != nil { + http.Error(w, "cannot remove isolated PHP adapter", http.StatusInternalServerError) + return + } + if _, statErr := os.Stat(siteConfig); statErr == nil { + if err = a.runNginx(ctx, "-t"); err != nil { + _, _ = writeManagedFile(paths.nginx, oldNginx) + http.Error(w, "Nginx rejected isolated PHP adapter removal", http.StatusPreconditionFailed) + return + } + if err = a.runNginx(ctx, "-s", "reload"); err != nil { + _, _ = writeManagedFile(paths.nginx, oldNginx) + _ = a.runNginx(ctx, "-t") + _ = a.runNginx(ctx, "-s", "reload") + http.Error(w, "cannot reload Nginx after PHP adapter removal", http.StatusInternalServerError) + return + } + } + } + for _, target := range []string{paths.config, paths.pid, paths.socket} { + if info, statErr := os.Lstat(target); statErr == nil { + if !info.Mode().IsRegular() && info.Mode()&os.ModeSocket == 0 { + http.Error(w, "unsafe PHP identity state", http.StatusPreconditionFailed) + return + } + _ = os.Remove(target) + } + } + _ = os.Remove(filepath.Dir(paths.pid)) + w.WriteHeader(http.StatusOK) +} + +func (a Agent) phpIdentityEnvironment(spec PHPIdentitySpec) (phpIdentityPaths, string, string, error) { + projectRoot, err := a.projectPath(spec.Project) + if err != nil || requirePhysicalDirectory(projectRoot) != nil { + return phpIdentityPaths{}, "", "", errors.New("project root unavailable") + } + if _, err = physicalRunDirectory(projectRoot, spec.Project.RunPath); err != nil { + return phpIdentityPaths{}, "", "", err + } + stateRoot := strings.TrimSpace(a.PHPStateRoot) + if stateRoot == "" { + stateRoot = "/var/lib/sea-vhost-agent/php" + } + runRoot := strings.TrimSpace(a.PHPRunRoot) + if runRoot == "" { + runRoot = "/run/sea-vhost-php" + } + if !filepath.IsAbs(stateRoot) || !filepath.IsAbs(runRoot) { + return phpIdentityPaths{}, "", "", errors.New("invalid PHP identity root") + } + if err = ensurePhysicalDirectory(stateRoot, 0700); err != nil { + return phpIdentityPaths{}, "", "", err + } + if err = os.Chmod(stateRoot, 0711); err != nil { + return phpIdentityPaths{}, "", "", err + } + if err = ensurePhysicalDirectory(runRoot, 0755); err != nil { + return phpIdentityPaths{}, "", "", err + } + version := strings.ReplaceAll(spec.Version, ".", "") + binary := filepath.Join("/www/server/php", version, "sbin/php-fpm") + info, err := os.Lstat(binary) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode()&0111 == 0 { + return phpIdentityPaths{}, "", "", errors.New("PHP-FPM binary unavailable") + } + webPaths, err := a.webProtectionPaths(WebProtectionSpec{Project: spec.Project, Domain: spec.Domain}) + if err != nil || verifySiteExtensionInclude(webPaths.siteConfig, webPaths.siteExtension) != nil { + return phpIdentityPaths{}, "", "", errors.New("managed Nginx site unavailable") + } + key := spec.SiteName + instanceRunRoot := filepath.Join(runRoot, key) + permissionCtx, cancelPermissions := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelPermissions() + if err = ensurePhysicalDirectory(instanceRunRoot, 0770); err != nil || + a.command(permissionCtx, "chown", "root:"+spec.Project.HostName, instanceRunRoot) != nil || + a.command(permissionCtx, "chmod", "0770", instanceRunRoot) != nil || + a.command(permissionCtx, "setfacl", "-m", "u:www:--x,m::rwx,o::---", instanceRunRoot) != nil { + return phpIdentityPaths{}, "", "", errors.New("cannot prepare PHP identity runtime directory") + } + for _, legacyPath := range []string{filepath.Join(runRoot, key+".pid"), filepath.Join(runRoot, key+".sock")} { + if legacyInfo, legacyErr := os.Lstat(legacyPath); legacyErr == nil && + (legacyInfo.Mode().IsRegular() || legacyInfo.Mode()&os.ModeSocket != 0) { + _ = os.Remove(legacyPath) + } + } + paths := phpIdentityPaths{ + config: filepath.Join(stateRoot, key+".conf"), + pid: filepath.Join(instanceRunRoot, "php-fpm.pid"), + socket: filepath.Join(instanceRunRoot, "php-fpm.sock"), + nginx: filepath.Join(filepath.Dir(webPaths.siteExtension), "sea-vhost-php.conf"), + } + return paths, binary, projectRoot, nil +} + +func (a Agent) phpIdentityRemovalPaths(spec PHPIdentitySpec) (phpIdentityPaths, string, error) { + stateRoot := strings.TrimSpace(a.PHPStateRoot) + if stateRoot == "" { + stateRoot = "/var/lib/sea-vhost-agent/php" + } + runRoot := strings.TrimSpace(a.PHPRunRoot) + if runRoot == "" { + runRoot = "/run/sea-vhost-php" + } + vhostRoot, err := filepath.Abs(a.NginxVhostRoot) + if err != nil || !filepath.IsAbs(stateRoot) || !filepath.IsAbs(runRoot) || !filepath.IsAbs(vhostRoot) { + return phpIdentityPaths{}, "", errors.New("invalid PHP identity path") + } + for _, root := range []string{stateRoot, runRoot, vhostRoot} { + if err = requirePhysicalDirectory(root); err != nil { + return phpIdentityPaths{}, "", err + } + } + extensionRoot := filepath.Join(vhostRoot, "extension", strings.ToLower(spec.Domain)) + if err = requirePhysicalDirectory(extensionRoot); err != nil && !errors.Is(err, os.ErrNotExist) { + return phpIdentityPaths{}, "", err + } + paths := phpIdentityPaths{ + config: filepath.Join(stateRoot, spec.SiteName+".conf"), + pid: filepath.Join(runRoot, spec.SiteName, "php-fpm.pid"), + socket: filepath.Join(runRoot, spec.SiteName, "php-fpm.sock"), + nginx: filepath.Join(extensionRoot, "sea-vhost-php.conf"), + } + return paths, filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf"), nil +} + +func (a Agent) preparePHPTempDirectory(ctx context.Context, projectRoot, hostName string) (string, error) { + if err := ensureProjectRunDirectory(projectRoot, "/.sea-runtime/php"); err != nil { + return "", err + } + tempRoot, err := physicalRunDirectory(projectRoot, "/.sea-runtime/php") + if err != nil { + return "", err + } + fileOwner := strings.TrimSpace(a.FileOwner) + if fileOwner == "" { + fileOwner = "sea-vhost" + } + if err = a.command(ctx, "chown", fileOwner+":"+hostName, tempRoot); err != nil { + return "", err + } + if err = a.command(ctx, "chmod", "0770", tempRoot); err != nil { + return "", err + } + if err = a.command(ctx, "setfacl", "-m", "u:www:---,m::rwx,o::---", tempRoot); err != nil { + return "", err + } + return filepath.ToSlash(tempRoot), nil +} + +func renderPHPIdentityConfig(spec PHPIdentitySpec, projectRoot, tempRoot string, paths phpIdentityPaths) string { + children := int(spec.ProcessLimit) + if children > 50 { + children = 50 + } + if children < 1 { + children = 1 + } + return fmt.Sprintf(`[global] +pid = %s +error_log = %s +daemonize = yes + +[%s] +user = %s +group = %s +listen = %s +listen.mode = 0660 +pm = ondemand +pm.max_children = %d +pm.process_idle_timeout = 15s +pm.max_requests = 500 +request_terminate_timeout = 120s +catch_workers_output = yes +clear_env = no +php_admin_value[pcre.jit] = 0 +security.limit_extensions = .php +php_admin_value[open_basedir] = %s/ +php_admin_value[sys_temp_dir] = %s +php_admin_value[upload_tmp_dir] = %s +php_admin_value[session.save_path] = %s +`, paths.pid, filepath.ToSlash(filepath.Join(tempRoot, "fpm-error.log")), spec.SiteName, spec.Project.HostName, spec.Project.HostName, paths.socket, children, projectRoot, tempRoot, tempRoot, tempRoot) +} + +func renderPHPNginxAdapter(socket string) string { + return fmt.Sprintf(`# Managed by Sea vHost. Local changes will be replaced. +# aaPanel's shared PHP include declares its own regex location later in the +# server block. This equivalent, deliberately distinct expression is loaded +# first from the site's extension directory and therefore selects the private +# per-host socket without creating a duplicate Nginx location. +location ~ ^.+\.php(?:/|$) +{ + try_files $uri =404; + fastcgi_pass unix:%s; + fastcgi_index index.php; + include fastcgi.conf; + include pathinfo.conf; +} +`, filepath.ToSlash(socket)) +} + +func (a Agent) startPHPIdentityProcess(ctx context.Context, binary string, paths phpIdentityPaths, identity string) error { + if a.phpIdentityRunning(ctx, paths) { + return nil + } + _ = os.Remove(paths.pid) + _ = os.Remove(paths.socket) + if err := startPHPAsIdentity(ctx, binary, paths.config, identity); err != nil { + return err + } + for attempt := 0; attempt < 40; attempt++ { + if a.phpIdentityRunning(ctx, paths) { + if info, err := os.Lstat(paths.socket); err == nil && info.Mode()&os.ModeSocket != 0 { + if err = a.command(ctx, "chown", identity+":www", paths.socket); err != nil || + a.command(ctx, "chmod", "0660", paths.socket) != nil { + return errors.New("cannot publish PHP-FPM socket") + } + return nil + } + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(100 * time.Millisecond): + } + } + return errors.New("PHP-FPM pool did not become ready") +} + +func (a Agent) stopPHPIdentityProcess(ctx context.Context, paths phpIdentityPaths) error { + pid, err := readPID(paths.pid) + if errors.Is(err, os.ErrNotExist) { + _ = os.Remove(paths.socket) + return nil + } + if err != nil { + return err + } + if err = a.signalPHPProcess(ctx, paths, "TERM", pid); err != nil && a.signalPHPProcess(ctx, paths, "0", pid) == nil { + return err + } + for attempt := 0; attempt < 50; attempt++ { + if a.signalPHPProcess(ctx, paths, "0", pid) != nil { + _ = os.Remove(paths.pid) + _ = os.Remove(paths.socket) + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(100 * time.Millisecond): + } + } + return errors.New("PHP-FPM pool did not stop") +} + +func (a Agent) phpIdentityRunning(ctx context.Context, paths phpIdentityPaths) bool { + pid, err := readPID(paths.pid) + return err == nil && a.signalPHPProcess(ctx, paths, "0", pid) == nil +} +func (a Agent) signalPHPProcess(ctx context.Context, paths phpIdentityPaths, signal string, pid int) error { + if a.runCommand != nil { + return a.command(ctx, "kill", "-"+signal, strconv.Itoa(pid)) + } + return signalPHPAsIdentity(ctx, paths.config, signal, pid) +} + +func readPID(path string) (int, error) { + data, err := os.ReadFile(path) + if err != nil { + return 0, err + } + pid, err := strconv.Atoi(strings.TrimSpace(string(data))) + if err != nil || pid < 2 { + return 0, errors.New("invalid PHP-FPM pid") + } + return pid, nil +} + +func writePrivateFile(path string, content []byte) error { + if len(content) > 128<<10 { + return errors.New("private managed file is too large") + } + directory := filepath.Dir(path) + if err := requirePhysicalDirectory(directory); err != nil { + return err + } + temporary, err := os.CreateTemp(directory, ".sea-vhost-php-*") + if err != nil { + return err + } + name := temporary.Name() + defer os.Remove(name) + if err = temporary.Chmod(0600); err == nil { + _, err = temporary.Write(content) + } + if syncErr := temporary.Sync(); err == nil { + err = syncErr + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return os.Rename(name, path) +} diff --git a/backend/internal/isolation/php_process_linux.go b/backend/internal/isolation/php_process_linux.go new file mode 100644 index 0000000..10f6862 --- /dev/null +++ b/backend/internal/isolation/php_process_linux.go @@ -0,0 +1,89 @@ +//go:build linux + +package isolation + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "os/user" + "path/filepath" + "sea-vhost/internal/hosting" + "strconv" + "strings" + "syscall" +) + +// PID files are written by the unprivileged FPM master. Never send a root +// signal to a PID taken from that file: a host could substitute another PID. +func signalPHPAsIdentity(ctx context.Context, config, signal string, pid int) error { + identity := "" + name := strings.TrimSuffix(filepath.Base(config), ".conf") + if phpSiteNamePattern.MatchString(name) { + identity = strings.Split(name, "_")[0] + } else if config == filepath.Join(pmaStateRoot, "php-fpm.conf") { + identity = pmaIdentity + } + if identity == "" || pid < 2 || (signal != "0" && signal != "TERM") { + return fmt.Errorf("invalid PHP signal identity") + } + out, e := runScheduledIdentity(ctx, identity, "/bin/kill", []string{"-" + signal, strconv.Itoa(pid)}, "/", nil) + if e != nil { + return e + } + if out.ExitCode != 0 { + return fmt.Errorf("PHP process unavailable to its identity") + } + return nil +} + +// startPHPAsIdentity changes credentials in the forked child before exec. +// Linux clears the child's ambient capabilities when its UID changes from +// root, so the PHP-FPM master and every worker run without agent privileges. +func startPHPAsIdentity(ctx context.Context, binary, config, identity string) error { + return runPHPAsIdentity(ctx, binary, identity, "--fpm-config", config) +} + +func testPHPAsIdentity(ctx context.Context, binary, config, identity string) error { + return runPHPAsIdentity(ctx, binary, identity, "-t", "--fpm-config", config) +} + +func runPHPAsIdentity(ctx context.Context, binary, identity string, args ...string) error { + account, err := user.Lookup(identity) + if err != nil { + return fmt.Errorf("lookup PHP identity: %w", err) + } + uid, err := strconv.ParseUint(account.Uid, 10, 32) + if err != nil || uid == 0 { + return fmt.Errorf("invalid PHP identity uid") + } + gid, err := strconv.ParseUint(account.Gid, 10, 32) + if err != nil || gid == 0 { + return fmt.Errorf("invalid PHP identity gid") + } + command := exec.CommandContext(ctx, binary, args...) + command.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} + if len(args) > 0 { + key := strings.TrimSuffix(filepath.Base(args[len(args)-1]), ".conf") + if phpSiteNamePattern.MatchString(key) { + if raw, e := os.ReadFile(filepath.Join(startupStateRoot, key+".json")); e == nil { + var state hosting.RunnerConfig + if json.Unmarshal(raw, &state) == nil && state.UID == uint32(uid) { + for name, value := range state.Environment { + command.Env = append(command.Env, name+"="+value) + } + } + } + } + } + command.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{ + Uid: uint32(uid), Gid: uint32(gid), Groups: []uint32{uint32(gid)}, + }} + output, err := command.CombinedOutput() + if err != nil { + return fmt.Errorf("run PHP-FPM as isolated identity: %w: %s", err, strings.TrimSpace(string(output))) + } + return nil +} diff --git a/backend/internal/isolation/php_process_other.go b/backend/internal/isolation/php_process_other.go new file mode 100644 index 0000000..7aa2883 --- /dev/null +++ b/backend/internal/isolation/php_process_other.go @@ -0,0 +1,20 @@ +//go:build !linux + +package isolation + +import ( + "context" + "errors" +) + +func signalPHPAsIdentity(context.Context, string, string, int) error { + return errors.New("isolated PHP signals require Linux") +} + +func startPHPAsIdentity(context.Context, string, string, string) error { + return errors.New("isolated PHP identities require Linux") +} + +func testPHPAsIdentity(context.Context, string, string, string) error { + return errors.New("isolated PHP identities require Linux") +} diff --git a/backend/internal/isolation/phpmyadmin.go b/backend/internal/isolation/phpmyadmin.go new file mode 100644 index 0000000..8e1588e --- /dev/null +++ b/backend/internal/isolation/phpmyadmin.go @@ -0,0 +1,387 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "mime" + "net" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "sync" + "time" +) + +const pmaStateRoot = "/var/lib/sea-vhost-agent/phpmyadmin" +const pmaIdentity = "sea-vhost-pma" + +var pmaSetupMu sync.Mutex + +type PHPMyAdminRequest struct { + Project ProjectSpec `json:"project"` + Method string `json:"method"` + Path string `json:"path"` + Query string `json:"query"` + Body []byte `json:"body"` + Cookie string `json:"cookie"` + ContentType string `json:"contentType"` + Username string `json:"username"` + Password string `json:"password"` + BaseURI string `json:"baseURI"` +} +type PHPMyAdminResponse struct { + Status int `json:"status"` + Header http.Header `json:"header"` + Body []byte `json:"body"` +} +type PHPMyAdminProxy interface { + PHPMyAdmin(context.Context, PHPMyAdminRequest) (PHPMyAdminResponse, error) +} + +func (c *Client) PHPMyAdmin(ctx context.Context, v PHPMyAdminRequest) (PHPMyAdminResponse, error) { + var out PHPMyAdminResponse + e := c.requestLong(ctx, "/v1/database/phpmyadmin", v, &out) + return out, e +} +func (Mock) PHPMyAdmin(context.Context, PHPMyAdminRequest) (PHPMyAdminResponse, error) { + return PHPMyAdminResponse{Status: 200, Header: http.Header{"Content-Type": {"text/html"}}, Body: []byte("phpMyAdmin test")}, nil +} +func validPMAPath(name string) bool { + if name == "" { + return true + } + if path.Clean(name) != name || strings.HasPrefix(name, "/") || strings.ContainsAny(name, "\\\x00") || strings.Contains(name, "..") || len(name) > 255 { + return false + } + if name == "index.php" || name == "url.php" || name == "js/messages.php" { + return true + } + if strings.HasSuffix(strings.ToLower(name), ".php") { + return false + } + first := strings.Split(name, "/")[0] + ext := strings.ToLower(path.Ext(name)) + return (first == "themes" || first == "js" || first == "vendor" || first == "favicon.ico") && map[string]bool{".css": true, ".js": true, ".map": true, ".png": true, ".gif": true, ".jpg": true, ".svg": true, ".ico": true, ".woff": true, ".woff2": true, ".ttf": true}[ext] +} +func (a Agent) phpMyAdmin(w http.ResponseWriter, r *http.Request) { + var q PHPMyAdminRequest + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if d.Decode(&q) != nil || d.Decode(&struct{}{}) != io.EOF || !validUsageSpec(ResourceUsageSpec{Project: q.Project}) || q.Username != q.Project.HostName || len(q.Password) < 1 || len(q.Password) > 256 || !validPMAPath(q.Path) || (q.Method != "GET" && q.Method != "POST" && q.Method != "HEAD") || len(q.Body) > 2<<20 || len(q.Cookie) > 16384 || len(q.Query) > 16384 || strings.ContainsAny(q.ContentType, "\r\n\x00") { + http.Error(w, "invalid database administration request", 400) + return + } + base, e := url.Parse(q.BaseURI) + if e != nil || base.Scheme != "https" || !webDomainPattern.MatchString(base.Hostname()) || base.User != nil || base.RawQuery != "" || base.Fragment != "" || !regexp.MustCompile(`^/api/v1/projects/[1-9][0-9]*/database-admin/$`).MatchString(base.Path) { + http.Error(w, "invalid database administration origin", 400) + return + } + if _, e = a.projectPath(q.Project); e != nil { + http.Error(w, "host unavailable", 412) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 120*time.Second) + defer cancel() + app, socket, e := a.preparePHPMyAdmin(ctx) + if e != nil { + http.Error(w, "phpMyAdmin unavailable; install phpMyAdmin and PHP in aaPanel", 503) + return + } + name := q.Path + if name == "" { + name = "index.php" + } + var out PHPMyAdminResponse + if !strings.HasSuffix(name, ".php") { + root, e := os.OpenRoot(app) + if e != nil { + http.Error(w, "phpMyAdmin unavailable", 503) + return + } + defer root.Close() + file, e := root.Open(name) + if e != nil { + http.NotFound(w, r) + return + } + defer file.Close() + data, e := io.ReadAll(io.LimitReader(file, (2<<20)+1)) + if e != nil || len(data) > 2<<20 { + http.Error(w, "asset exceeds limit", 413) + return + } + out = PHPMyAdminResponse{Status: 200, Header: http.Header{"Content-Type": {mime.TypeByExtension(path.Ext(name))}}, Body: data} + } else { + uri := base.Path + name + if q.Query != "" { + uri += "?" + q.Query + } + params := map[string]string{"GATEWAY_INTERFACE": "CGI/1.1", "SERVER_SOFTWARE": "Sea-vHost", "SERVER_PROTOCOL": "HTTP/1.1", "REQUEST_METHOD": q.Method, "SCRIPT_FILENAME": filepath.Join(app, name), "SCRIPT_NAME": base.Path + name, "DOCUMENT_ROOT": app, "REQUEST_URI": uri, "QUERY_STRING": q.Query, "HTTPS": "on", "SERVER_NAME": base.Hostname(), "SERVER_PORT": "443", "HTTP_HOST": base.Host, "REMOTE_ADDR": "127.0.0.1", "CONTENT_TYPE": q.ContentType, "CONTENT_LENGTH": fmt.Sprint(len(q.Body)), "HTTP_COOKIE": q.Cookie, "SVH_DB_USER": q.Username, "SVH_DB_PASSWORD": q.Password, "SVH_PMA_URI": q.BaseURI} + status, header, body, e := callFastCGI(ctx, socket, params, q.Body) + if e != nil { + http.Error(w, "phpMyAdmin response failed or exceeded 2 MiB", 502) + return + } + out = PHPMyAdminResponse{status, header, body} + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(out) +} +func (a Agent) preparePHPMyAdmin(ctx context.Context) (string, string, error) { + pmaSetupMu.Lock() + defer pmaSetupMu.Unlock() + app := filepath.Join(pmaStateRoot, "app") + runRoot := "/run/sea-vhost-php/phpmyadmin" + socket := filepath.Join(runRoot, "php-fpm.sock") + if _, e := os.Stat(filepath.Join(app, ".sea-vhost-ready")); e == nil { + if e = securePMAReadPermissions(app); e != nil { + return "", "", e + } + } + if conn, e := (&net.Dialer{Timeout: time.Second}).DialContext(ctx, "unix", socket); e == nil { + conn.Close() + return app, socket, nil + } + if e := ensurePhysicalDirectory(pmaStateRoot, 0711); e != nil { + return "", "", e + } + if e := os.Chmod(pmaStateRoot, 0711); e != nil { + return "", "", e + } + if _, e := os.Stat(filepath.Join(app, ".sea-vhost-ready")); errors.Is(e, fs.ErrNotExist) { + candidates, _ := filepath.Glob("/www/server/phpmyadmin/phpmyadmin_*") + source := "" + for _, candidate := range candidates { + if i, e := os.Lstat(filepath.Join(candidate, "index.php")); e == nil && i.Mode().IsRegular() { + source = candidate + break + } + } + if source == "" { + return "", "", errors.New("phpMyAdmin not installed") + } + staging, e := os.MkdirTemp(pmaStateRoot, ".install-") + if e != nil { + return "", "", e + } + defer os.RemoveAll(staging) + e = filepath.WalkDir(source, func(name string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + relative, e := filepath.Rel(source, name) + if e != nil { + return e + } + if relative == "." { + return nil + } + first := strings.Split(filepath.ToSlash(relative), "/")[0] + if map[string]bool{"setup": true, "examples": true, "tmp": true, ".git": true}[first] { + if entry.IsDir() { + return fs.SkipDir + } + return nil + } + if (filepath.Dir(relative) == "." && strings.HasPrefix(entry.Name(), "config.")) || entry.Type()&os.ModeSymlink != 0 { + return nil + } + dest := filepath.Join(staging, relative) + if entry.IsDir() { + if e = os.Mkdir(dest, 0755); e != nil { + return e + } + return os.Chmod(dest, 0755) + } + info, e := entry.Info() + if e != nil || !info.Mode().IsRegular() { + return errors.New("invalid phpMyAdmin source") + } + if info.Size() > 16<<20 { + return errors.New("phpMyAdmin source file too large") + } + in, e := os.Open(name) + if e != nil { + return e + } + defer in.Close() + out, e := os.OpenFile(dest, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) + if e != nil { + return e + } + _, e = io.Copy(out, in) + if e == nil { + e = out.Chmod(0644) + } + ce := out.Close() + if e != nil { + return e + } + return ce + }) + if e != nil { + return "", "", e + } + if e = os.WriteFile(filepath.Join(staging, "config.inc.php"), []byte(pmaPHPConfig), 0644); e != nil { + return "", "", e + } + if e = os.WriteFile(filepath.Join(staging, "sea-signon.php"), []byte(pmaSignonPHP), 0644); e != nil { + return "", "", e + } + if e = os.WriteFile(filepath.Join(staging, ".sea-vhost-ready"), []byte("1"), 0644); e != nil { + return "", "", e + } + if e = os.Chmod(staging, 0755); e != nil { + return "", "", e + } + if e = os.Rename(staging, app); e != nil { + return "", "", e + } + if e = securePMAReadPermissions(app); e != nil { + return "", "", e + } + } + if e := a.command(ctx, "id", "-u", pmaIdentity); e != nil { + if e = a.command(ctx, "useradd", "--system", "--user-group", "--no-create-home", "--home-dir", "/nonexistent", "--shell", "/usr/sbin/nologin", pmaIdentity); e != nil { + return "", "", e + } + } + for _, dir := range []string{filepath.Join(pmaStateRoot, "sessions"), filepath.Join(pmaStateRoot, "tmp"), runRoot} { + if e := ensurePhysicalDirectory(dir, 0700); e != nil { + return "", "", e + } + if e := a.command(ctx, "chown", pmaIdentity+":"+pmaIdentity, dir); e != nil { + return "", "", e + } + } + binary := "" + for _, branch := range []string{"82", "83", "84", "81", "80"} { + candidate := filepath.Join("/www/server/php", branch, "sbin/php-fpm") + if i, e := os.Stat(candidate); e == nil && i.Mode().IsRegular() { + binary = candidate + break + } + } + if binary == "" { + return "", "", errors.New("PHP unavailable") + } + conf := filepath.Join(pmaStateRoot, "php-fpm.conf") + content := fmt.Sprintf(`[global] +pid = %s/php-fpm.pid +error_log = %s/fpm-error.log +daemonize = yes +[phpmyadmin] +user = %s +group = %s +listen = %s +listen.mode = 0600 +pm = ondemand +pm.max_children = 4 +pm.process_idle_timeout = 15s +pm.max_requests = 200 +request_terminate_timeout = 120s +catch_workers_output = yes +clear_env = yes +security.limit_extensions = .php +php_admin_value[open_basedir] = %s/:/www/server/php/ +php_admin_value[session.save_path] = %s/sessions +php_admin_value[upload_tmp_dir] = %s/tmp +php_admin_value[sys_temp_dir] = %s/tmp +php_admin_value[upload_max_filesize] = 2M +php_admin_value[post_max_size] = 2M +php_admin_value[memory_limit] = 256M +php_admin_flag[display_errors] = off +php_admin_flag[log_errors] = on +php_admin_value[pcre.jit] = 0 +php_admin_value[error_log] = %s/php-error.log +`, runRoot, runRoot, pmaIdentity, pmaIdentity, socket, pmaStateRoot, pmaStateRoot, pmaStateRoot, pmaStateRoot, runRoot) + if e := writePrivateFile(conf, []byte(content)); e != nil { + return "", "", e + } + if e := a.command(ctx, "chown", "root:"+pmaIdentity, conf); e != nil { + return "", "", e + } + if e := os.Chmod(conf, 0640); e != nil { + return "", "", e + } + if e := testPHPAsIdentity(ctx, binary, conf, pmaIdentity); e != nil { + return "", "", e + } + if e := startPHPAsIdentity(ctx, binary, conf, pmaIdentity); e != nil { + return "", "", e + } + return app, socket, nil +} + +// The agent's restrictive umask must not hide root-owned vendor files from +// the dedicated, unprivileged phpMyAdmin process. Credentials are never files +// in this directory; they are supplied only in private FastCGI parameters. +func securePMAReadPermissions(app string) error { + marker := filepath.Join(app, ".sea-vhost-readable-v2") + if raw, e := os.ReadFile(marker); e == nil && string(raw) == "2" { + return nil + } + if e := requirePhysicalDirectory(app); e != nil { + return e + } + e := filepath.WalkDir(app, func(name string, entry fs.DirEntry, e error) error { + if e != nil { + return e + } + if entry.Type()&os.ModeSymlink != 0 { + return errors.New("phpMyAdmin tree contains a symlink") + } + if entry.IsDir() { + return os.Chmod(name, 0755) + } + info, e := entry.Info() + if e != nil { + return e + } + if !info.Mode().IsRegular() { + return errors.New("invalid phpMyAdmin vendor file") + } + return os.Chmod(name, 0644) + }) + if e != nil { + return e + } + return os.WriteFile(marker, []byte("2"), 0644) +} + +const pmaPHPConfig = ` 0 { + memory += uint64(rss) * uint64(os.Getpagesize()) + } + } + return memory, ticks, nil +} diff --git a/backend/internal/isolation/process_metrics_other.go b/backend/internal/isolation/process_metrics_other.go new file mode 100644 index 0000000..e88b990 --- /dev/null +++ b/backend/internal/isolation/process_metrics_other.go @@ -0,0 +1,5 @@ +//go:build !linux + +package isolation + +func identityMetrics(string) (uint64, uint64, error) { return 0, 0, nil } diff --git a/backend/internal/isolation/process_usage_linux.go b/backend/internal/isolation/process_usage_linux.go new file mode 100644 index 0000000..92295e5 --- /dev/null +++ b/backend/internal/isolation/process_usage_linux.go @@ -0,0 +1,172 @@ +//go:build linux + +package isolation + +import ( + "context" + "errors" + "os" + "os/user" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" +) + +func identityUID(identity string) (uint32, error) { + account, err := user.Lookup(identity) + if err != nil { + return 0, err + } + uid, err := strconv.ParseUint(account.Uid, 10, 32) + if err != nil || uid == 0 { + return 0, errors.New("invalid identity uid") + } + return uint32(uid), nil +} + +func identityPIDs(identity string) ([]int, error) { + uid, err := identityUID(identity) + if err != nil { + return nil, err + } + entries, err := os.ReadDir("/proc") + if err != nil { + return nil, err + } + pids := make([]int, 0) + for _, entry := range entries { + pid, parseErr := strconv.Atoi(entry.Name()) + if parseErr != nil || pid <= 1 { + continue + } + data, readErr := os.ReadFile("/proc/" + entry.Name() + "/status") + if readErr != nil { + continue + } + for _, line := range strings.Split(string(data), "\n") { + if !strings.HasPrefix(line, "Uid:") { + continue + } + fields := strings.Fields(line) + if len(fields) >= 2 { + value, _ := strconv.ParseUint(fields[1], 10, 32) + if uint32(value) == uid { + pids = append(pids, pid) + } + } + break + } + } + return pids, nil +} + +func countIdentityProcesses(identity string) (uint32, error) { + pids, err := identityPIDs(identity) + return uint32(len(pids)), err +} + +func terminateIdentityProcesses(ctx context.Context, identity string) error { + pids, err := identityPIDs(identity) + if err != nil { + return err + } + for _, pid := range pids { + _ = syscall.Kill(pid, syscall.SIGTERM) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(750 * time.Millisecond): + } + pids, err = identityPIDs(identity) + if err != nil { + return err + } + for _, pid := range pids { + if killErr := syscall.Kill(pid, syscall.SIGKILL); killErr != nil && !errors.Is(killErr, syscall.ESRCH) { + return killErr + } + } + return nil +} + +func runtimeDirectoryPIDs(ctx context.Context, identity, runtimeRoot string) ([]int, error) { + uid, err := identityUID(identity) + if err != nil { + return nil, err + } + runtimeRoot = filepath.Clean(runtimeRoot) + entries, err := os.ReadDir("/proc") + if err != nil { + return nil, err + } + pids := make([]int, 0) + for _, entry := range entries { + pid, parseErr := strconv.Atoi(entry.Name()) + if parseErr != nil || pid <= 1 || pid == os.Getpid() { + continue + } + status, readErr := os.ReadFile("/proc/" + entry.Name() + "/status") + if readErr != nil || !statusHasUID(status, uid) { + continue + } + output, readErr := tenantMaintenanceCommand(ctx, identity, "/usr/bin/readlink", "/proc/"+entry.Name()+"/cwd").Output() + if readErr != nil { + continue + } + cwd := filepath.Clean(strings.TrimSpace(string(output))) + if cwd == runtimeRoot || strings.HasPrefix(cwd, runtimeRoot+string(os.PathSeparator)) { + pids = append(pids, pid) + } + } + return pids, nil +} + +func statusHasUID(status []byte, uid uint32) bool { + for _, line := range strings.Split(string(status), "\n") { + if !strings.HasPrefix(line, "Uid:") { + continue + } + fields := strings.Fields(line) + if len(fields) < 2 { + return false + } + value, err := strconv.ParseUint(fields[1], 10, 32) + return err == nil && uint32(value) == uid + } + return false +} + +func terminateRuntimeDirectoryProcesses(ctx context.Context, identity, runtimeRoot string) error { + pids, err := runtimeDirectoryPIDs(ctx, identity, runtimeRoot) + if err != nil { + return err + } + for _, pid := range pids { + _ = syscall.Kill(pid, syscall.SIGTERM) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(750 * time.Millisecond): + } + pids, err = runtimeDirectoryPIDs(ctx, identity, runtimeRoot) + if err != nil { + return err + } + for _, pid := range pids { + if killErr := syscall.Kill(pid, syscall.SIGKILL); killErr != nil && !errors.Is(killErr, syscall.ESRCH) { + return killErr + } + } + return nil +} + +func fileIdentity(info os.FileInfo) uint64 { + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + return stat.Ino + } + return uint64(info.ModTime().UnixNano()) +} diff --git a/backend/internal/isolation/process_usage_other.go b/backend/internal/isolation/process_usage_other.go new file mode 100644 index 0000000..f5da242 --- /dev/null +++ b/backend/internal/isolation/process_usage_other.go @@ -0,0 +1,20 @@ +//go:build !linux + +package isolation + +import ( + "context" + "errors" + "os" +) + +func countIdentityProcesses(string) (uint32, error) { + return 0, errors.New("process accounting requires Linux") +} +func terminateIdentityProcesses(context.Context, string) error { + return errors.New("process enforcement requires Linux") +} +func terminateRuntimeDirectoryProcesses(context.Context, string, string) error { + return errors.New("runtime process enforcement requires Linux") +} +func fileIdentity(os.FileInfo) uint64 { return 1 } diff --git a/backend/internal/isolation/pureftp_process_linux.go b/backend/internal/isolation/pureftp_process_linux.go new file mode 100644 index 0000000..583f788 --- /dev/null +++ b/backend/internal/isolation/pureftp_process_linux.go @@ -0,0 +1,63 @@ +//go:build linux + +package isolation + +import ( + "context" + "errors" + "os" + "path/filepath" + "strconv" + "syscall" + "time" +) + +func pureFTPDaemonPIDs(binaryPath string) ([]int, error) { + expected, err := filepath.EvalSymlinks(binaryPath) + if err != nil { + return nil, err + } + entries, err := os.ReadDir("/proc") + if err != nil { + return nil, err + } + pids := make([]int, 0, 2) + for _, entry := range entries { + pid, parseErr := strconv.Atoi(entry.Name()) + if parseErr != nil || pid <= 1 || pid == os.Getpid() { + continue + } + executable, readErr := os.Readlink("/proc/" + entry.Name() + "/exe") + if readErr == nil && filepath.Clean(executable) == filepath.Clean(expected) { + pids = append(pids, pid) + } + } + return pids, nil +} + +func terminatePureFTPDaemons(ctx context.Context, binaryPath string) error { + pids, err := pureFTPDaemonPIDs(binaryPath) + if err != nil { + return err + } + for _, pid := range pids { + _ = syscall.Kill(pid, syscall.SIGTERM) + } + if len(pids) > 0 { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(750 * time.Millisecond): + } + } + pids, err = pureFTPDaemonPIDs(binaryPath) + if err != nil { + return err + } + for _, pid := range pids { + if killErr := syscall.Kill(pid, syscall.SIGKILL); killErr != nil && !errors.Is(killErr, syscall.ESRCH) { + return killErr + } + } + return nil +} diff --git a/backend/internal/isolation/pureftp_process_other.go b/backend/internal/isolation/pureftp_process_other.go new file mode 100644 index 0000000..be17e85 --- /dev/null +++ b/backend/internal/isolation/pureftp_process_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package isolation + +import "context" + +func terminatePureFTPDaemons(context.Context, string) error { return nil } diff --git a/backend/internal/isolation/python_install.go b/backend/internal/isolation/python_install.go new file mode 100644 index 0000000..26e1110 --- /dev/null +++ b/backend/internal/isolation/python_install.go @@ -0,0 +1,324 @@ +package isolation + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +const maxPythonSourceBytes = 80 << 20 + +func (a Agent) installPythonRuntime(w http.ResponseWriter, r *http.Request) { + var input PythonRuntimeInstallSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !supportedPythonSourceVersion(input.Version) { + http.Error(w, "invalid Python version", http.StatusBadRequest) + return + } + if err := a.installPythonSource(r.Context(), input.Version); err != nil { + slog.Error("Python source installation failed", "version", input.Version, "error", err) + http.Error(w, "cannot install verified Python source: "+err.Error(), http.StatusPreconditionFailed) + return + } + w.WriteHeader(http.StatusOK) +} + +func supportedPythonSourceVersion(version string) bool { + if !pythonManagerVersionPattern.MatchString(version) { + return false + } + parts := strings.Split(version, ".") + minor, err := strconv.Atoi(parts[1]) + return err == nil && parts[0] == "3" && minor >= 10 && minor <= 99 +} + +func (a Agent) installPythonSource(ctx context.Context, version string) error { + managerRoot := a.PythonManagerRoot + if managerRoot == "" { + managerRoot = "/www/server/python_manager/versions" + } + if !filepath.IsAbs(managerRoot) || filepath.Clean(managerRoot) != managerRoot || requirePhysicalDirectory(managerRoot) != nil { + return errors.New("Python manager root is unavailable") + } + resolvedManager, err := filepath.EvalSymlinks(managerRoot) + if err != nil || filepath.Clean(resolvedManager) != managerRoot { + return errors.New("Python manager root contains a symbolic link") + } + finalRoot := filepath.Join(managerRoot, version) + if info, statErr := os.Lstat(finalRoot); statErr == nil { + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("Python version path is unsafe") + } + return a.validateInstalledPython(ctx, finalRoot) + } else if !errors.Is(statErr, os.ErrNotExist) { + return statErr + } + + buildRoot := a.PythonBuildRoot + if buildRoot == "" { + buildRoot = "/var/lib/sea-vhost-agent/python-builds" + } + if !filepath.IsAbs(buildRoot) || filepath.Clean(buildRoot) != buildRoot { + return errors.New("invalid Python build root") + } + if err = os.MkdirAll(buildRoot, 0700); err != nil { + return err + } + if err = requirePhysicalDirectory(buildRoot); err != nil { + return errors.New("Python build root contains a symbolic link") + } + releaseLock, err := acquirePythonInstallLock(buildRoot, version) + if err != nil { + return err + } + defer releaseLock() + // An earlier request may have finished between the initial existence check + // and lock acquisition. Do not rebuild or overwrite its completed version. + if info, statErr := os.Lstat(finalRoot); statErr == nil { + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("Python version path is unsafe") + } + return a.validateInstalledPython(ctx, finalRoot) + } else if !errors.Is(statErr, os.ErrNotExist) { + return statErr + } + + workRoot, err := os.MkdirTemp(buildRoot, "python-"+version+"-") + if err != nil { + return err + } + defer os.RemoveAll(workRoot) + // Check the destination before spending time compiling. On systemd hosts + // the versions directory must be prepared before the agent starts. + stageBase := filepath.Join(managerRoot, ".sea-vhost-stage-"+version+"-"+filepath.Base(workRoot)) + if err = os.Mkdir(stageBase, 0700); err != nil { + return fmt.Errorf("Python versions directory is not writable; rerun the node installer to prepare runtime mounts: %w", err) + } + defer os.RemoveAll(stageBase) + archivePath, err := a.downloadVerifiedPythonSource(ctx, workRoot, version) + if err != nil { + return err + } + if err = a.command(ctx, "tar", "-xJf", archivePath, "-C", workRoot); err != nil { + return err + } + sourceRoot := filepath.Join(workRoot, "Python-"+version) + configure := filepath.Join(sourceRoot, "configure") + if info, statErr := os.Stat(configure); statErr != nil || !runtimeExecutable(info) { + return errors.New("verified Python source archive has an invalid layout") + } + if err = a.commandAt(ctx, sourceRoot, configure, "--prefix="+finalRoot, "--with-ensurepip=install"); err != nil { + return err + } + jobs := runtime.NumCPU() + if jobs < 1 { + jobs = 1 + } else if jobs > 4 { + jobs = 4 + } + if err = a.command(ctx, "make", "-C", sourceRoot, "-j", strconv.Itoa(jobs)); err != nil { + return err + } + if err = a.command(ctx, "make", "-C", sourceRoot, "DESTDIR="+stageBase, "install"); err != nil { + return err + } + stagedRoot := stagedPythonInstallRoot(stageBase, finalRoot) + if info, statErr := os.Lstat(stagedRoot); statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("Python staged installation is invalid") + } + if err = a.normalizeSharedPythonAccess(ctx, stagedRoot); err != nil { + return err + } + if err = os.WriteFile(filepath.Join(stagedRoot, ".sea-vhost-runtime"), []byte(version+"\n"), 0600); err != nil { + return err + } + if err = os.Rename(stagedRoot, finalRoot); err != nil { + return err + } + if err = a.validateInstalledPython(ctx, finalRoot); err != nil { + marker, _ := os.ReadFile(filepath.Join(finalRoot, ".sea-vhost-runtime")) + if strings.TrimSpace(string(marker)) == version { + _ = os.RemoveAll(finalRoot) + } + return err + } + return nil +} + +func stagedPythonInstallRoot(stageBase, finalRoot string) string { + relative := strings.TrimPrefix(finalRoot, filepath.VolumeName(finalRoot)) + relative = strings.TrimLeft(relative, `/\\`) + return filepath.Join(stageBase, relative) +} + +func (a Agent) validateInstalledPython(ctx context.Context, root string) error { + python := filepath.Join(root, "bin", "python3") + resolved, err := filepath.EvalSymlinks(python) + if err != nil || !strings.HasPrefix(filepath.Clean(resolved)+string(os.PathSeparator), filepath.Clean(root)+string(os.PathSeparator)) { + return errors.New("Python interpreter escaped its installation root") + } + info, err := os.Stat(resolved) + if err != nil || !runtimeExecutable(info) { + return errors.New("Python interpreter is unavailable") + } + return a.command(ctx, python, "-c", "import ensurepip,ssl,sqlite3,venv") +} + +func (a Agent) downloadVerifiedPythonSource(ctx context.Context, workRoot, version string) (string, error) { + metadataBase := strings.TrimRight(a.PythonMetadataBaseURL, "/") + if metadataBase == "" { + metadataBase = "https://www.python.org/ftp/python" + } + fileName := "Python-" + version + ".tar.xz" + metadataURL := metadataBase + "/" + version + "/" + fileName + ".sigstore" + var bundleBytes []byte + var err error + trustedOfficial := metadataBase == "https://www.python.org/ftp/python" + if trustedOfficial { + bundleBytes, _ = a.readPythonMetadataCache(fileName + ".sigstore") + } + if len(bundleBytes) == 0 { + bundleBytes, err = fetchPythonURL(ctx, metadataURL, 1<<20) + } + if err != nil { + return "", fmt.Errorf("fetch official Python signature metadata: %w", err) + } + expectedDigest, err := pythonSourceDigest(bundleBytes) + if err != nil { + return "", err + } + if trustedOfficial { + a.cachePythonMetadata(fileName+".sigstore", bundleBytes) + if cached, cacheErr := a.readPythonVerificationCache(fileName, maxPythonSourceBytes); cacheErr == nil { + actual := sha256.Sum256(cached) + if subtle.ConstantTimeCompare(actual[:], expectedDigest) != 1 { + return "", errors.New("offline Python source digest mismatch") + } + archivePath := filepath.Join(workRoot, fileName) + if err = os.WriteFile(archivePath, cached, 0600); err != nil { + return "", err + } + return archivePath, nil + } + } + bases := a.PythonSourceBaseURLs + if len(bases) == 0 { + bases = []string{"https://mirrors.huaweicloud.com/python", "https://www.python.org/ftp/python"} + } + var failures []string + for _, base := range bases { + sourceURL := strings.TrimRight(base, "/") + "/" + version + "/" + fileName + archivePath := filepath.Join(workRoot, fileName) + actualDigest, downloadErr := downloadPythonArchive(ctx, sourceURL, archivePath) + if downloadErr == nil && subtle.ConstantTimeCompare(actualDigest, expectedDigest) == 1 { + return archivePath, nil + } + _ = os.Remove(archivePath) + if downloadErr != nil { + failures = append(failures, downloadErr.Error()) + } else { + failures = append(failures, "digest mismatch from "+sourceURL) + } + } + return "", fmt.Errorf("no verified Python source mirror succeeded: %s", strings.Join(failures, "; ")) +} + +func pythonSourceDigest(bundleBytes []byte) ([]byte, error) { + var bundle struct { + MessageSignature struct { + MessageDigest struct { + Algorithm string `json:"algorithm"` + Digest string `json:"digest"` + } `json:"messageDigest"` + } `json:"messageSignature"` + } + if json.Unmarshal(bundleBytes, &bundle) != nil || bundle.MessageSignature.MessageDigest.Algorithm != "SHA2_256" { + return nil, errors.New("official Python signature metadata is invalid") + } + expectedDigest, err := base64.StdEncoding.DecodeString(bundle.MessageSignature.MessageDigest.Digest) + if err != nil || len(expectedDigest) != sha256.Size { + return nil, errors.New("official Python source digest is invalid") + } + return expectedDigest, nil +} + +func fetchPythonURL(ctx context.Context, rawURL string, limit int64) ([]byte, error) { + parsed, err := url.Parse(rawURL) + if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || parsed.Host == "" { + return nil, errors.New("invalid source URL") + } + request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil) + if err != nil { + return nil, err + } + response, err := (&http.Client{Timeout: 2 * time.Minute}).Do(request) + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("source returned HTTP %d", response.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(response.Body, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, errors.New("source response exceeded size limit") + } + return data, nil +} + +func downloadPythonArchive(ctx context.Context, rawURL, destination string) ([]byte, error) { + parsed, err := url.Parse(rawURL) + if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || parsed.Host == "" { + return nil, errors.New("invalid source URL") + } + request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil) + if err != nil { + return nil, err + } + response, err := (&http.Client{Timeout: 15 * time.Minute}).Do(request) + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%s returned HTTP %d", parsed.Host, response.StatusCode) + } + file, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if err != nil { + return nil, err + } + hash := sha256.New() + written, copyErr := io.Copy(io.MultiWriter(file, hash), io.LimitReader(response.Body, maxPythonSourceBytes+1)) + closeErr := file.Close() + if copyErr != nil { + return nil, copyErr + } + if closeErr != nil { + return nil, closeErr + } + if written > maxPythonSourceBytes { + return nil, errors.New("Python source archive exceeded size limit") + } + digest := hash.Sum(nil) + slog.Info("downloaded Python source", "version", filepath.Base(destination), "host", parsed.Host, "sha256", hex.EncodeToString(digest)) + return digest, nil +} diff --git a/backend/internal/isolation/python_install_test.go b/backend/internal/isolation/python_install_test.go new file mode 100644 index 0000000..2d1feef --- /dev/null +++ b/backend/internal/isolation/python_install_test.go @@ -0,0 +1,122 @@ +package isolation + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestInstallPythonRuntimeUsesVerifiedMirrorAndAtomicDestination(t *testing.T) { + const version = "3.12.15" + archive := []byte("verified CPython test archive") + digest := sha256.Sum256(archive) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/" + version + "/Python-" + version + ".tar.xz.sigstore": + _ = json.NewEncoder(w).Encode(map[string]any{"messageSignature": map[string]any{"messageDigest": map[string]any{"algorithm": "SHA2_256", "digest": base64.StdEncoding.EncodeToString(digest[:])}}}) + case "/" + version + "/Python-" + version + ".tar.xz": + _, _ = w.Write(archive) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + managerRoot := filepath.Join(t.TempDir(), "versions") + buildRoot := filepath.Join(t.TempDir(), "builds") + if err := os.MkdirAll(managerRoot, 0755); err != nil { + t.Fatal(err) + } + finalRoot := filepath.Join(managerRoot, version) + commands := make([]string, 0, 5) + agent := Agent{ + PythonManagerRoot: managerRoot, PythonBuildRoot: buildRoot, + PythonMetadataBaseURL: server.URL, PythonSourceBaseURLs: []string{server.URL}, + runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + switch name { + case "tar": + sourceRoot := filepath.Join(args[len(args)-1], "Python-"+version) + if err := os.MkdirAll(sourceRoot, 0700); err != nil { + return err + } + return os.WriteFile(filepath.Join(sourceRoot, "configure"), []byte("test"), 0755) + case "make": + for _, argument := range args { + if strings.HasPrefix(argument, "DESTDIR=") { + stageBase := strings.TrimPrefix(argument, "DESTDIR=") + python := filepath.Join(stagedPythonInstallRoot(stageBase, finalRoot), "bin", "python3") + if err := os.MkdirAll(filepath.Dir(python), 0755); err != nil { + return err + } + return os.WriteFile(python, []byte("test"), 0755) + } + } + } + return nil + }, + } + body, _ := json.Marshal(PythonRuntimeInstallSpec{Version: version}) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/python/install", bytes.NewReader(body))) + if response.Code != http.StatusOK { + t.Fatalf("install status = %d, body = %s", response.Code, response.Body.String()) + } + if _, err := os.Stat(filepath.Join(finalRoot, "bin", "python3")); err != nil { + t.Fatal(err) + } + joined := strings.Join(commands, "\n") + if !strings.Contains(joined, "--prefix="+finalRoot) || !strings.Contains(joined, "DESTDIR="+managerRoot) { + t.Fatalf("Python build was not confined to managed paths:\n%s", joined) + } +} + +func TestInstallPythonRuntimeRejectsUnsupportedBranch(t *testing.T) { + agent := Agent{} + body, _ := json.Marshal(PythonRuntimeInstallSpec{Version: "3.9.25"}) + response := httptest.NewRecorder() + agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/python/install", bytes.NewReader(body))) + if response.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", response.Code) + } +} + +func TestPythonSourceDigestMismatchCannotReachExtraction(t *testing.T) { + const version = "3.12.15" + digest := sha256.Sum256([]byte("official source")) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, ".sigstore") { + _ = json.NewEncoder(w).Encode(map[string]any{"messageSignature": map[string]any{"messageDigest": map[string]any{"algorithm": "SHA2_256", "digest": base64.StdEncoding.EncodeToString(digest[:])}}}) + return + } + _, _ = w.Write([]byte("tampered source")) + })) + defer server.Close() + managerRoot, buildRoot := t.TempDir(), t.TempDir() + called := false + agent := Agent{ + PythonManagerRoot: managerRoot, PythonBuildRoot: buildRoot, + PythonMetadataBaseURL: server.URL, PythonSourceBaseURLs: []string{server.URL}, + runCommand: func(context.Context, string, ...string) error { called = true; return nil }, + } + if err := agent.installPythonSource(context.Background(), version); err == nil || !strings.Contains(err.Error(), "digest mismatch") { + t.Fatalf("mismatched archive result = %v", err) + } + if called { + t.Fatal("unverified source reached extraction or compilation") + } + if _, err := os.Stat(filepath.Join(managerRoot, version)); !os.IsNotExist(err) { + t.Fatal("unverified source created an installed version") + } + if _, err := os.Stat(filepath.Join(buildRoot, "Python-"+version+".tar.xz")); !os.IsNotExist(err) { + t.Fatal("unverified archive was retained") + } +} diff --git a/backend/internal/isolation/python_lock_linux.go b/backend/internal/isolation/python_lock_linux.go new file mode 100644 index 0000000..2188bcf --- /dev/null +++ b/backend/internal/isolation/python_lock_linux.go @@ -0,0 +1,35 @@ +//go:build linux + +package isolation + +import ( + "errors" + "os" + "path/filepath" + "syscall" +) + +// The kernel releases flock when the agent exits, including on a crash. Keep +// the file on disk: unlinking a locked inode would let another request open a +// different inode and acquire a second lock for the same version. +func acquirePythonInstallLock(buildRoot, version string) (func(), error) { + lockPath := filepath.Join(buildRoot, ".install-"+version+".flock") + fd, err := syscall.Open(lockPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0600) + if err != nil { + return nil, err + } + file := os.NewFile(uintptr(fd), lockPath) + info, err := file.Stat() + if err != nil || !info.Mode().IsRegular() { + _ = file.Close() + return nil, errors.New("Python installation lock path is unsafe") + } + if err = syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + _ = file.Close() + if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) { + return nil, errors.New("Python version installation is already running") + } + return nil, err + } + return func() { _ = file.Close() }, nil +} diff --git a/backend/internal/isolation/python_lock_linux_test.go b/backend/internal/isolation/python_lock_linux_test.go new file mode 100644 index 0000000..a5fa823 --- /dev/null +++ b/backend/internal/isolation/python_lock_linux_test.go @@ -0,0 +1,70 @@ +//go:build linux + +package isolation + +import ( + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestPythonInstallLockExcludesConcurrentRequests(t *testing.T) { + root := t.TempDir() + release, err := acquirePythonInstallLock(root, "3.12.15") + if err != nil { + t.Fatal(err) + } + t.Cleanup(release) + if second, err := acquirePythonInstallLock(root, "3.12.15"); err == nil { + second() + t.Fatal("a concurrent installation acquired the same version lock") + } + release() + second, err := acquirePythonInstallLock(root, "3.12.15") + if err != nil { + t.Fatalf("released lock could not be reacquired: %v", err) + } + defer second() +} + +func TestPythonInstallLockReleasedAfterProcessExit(t *testing.T) { + if root := os.Getenv("SEA_PYTHON_LOCK_TEST_ROOT"); root != "" { + _, err := acquirePythonInstallLock(root, "3.12.15") + if err != nil { + os.Exit(2) + } + // Deliberately skip cleanup to simulate an agent crash. + os.Exit(0) + } + root := t.TempDir() + child := exec.Command(os.Args[0], "-test.run=^TestPythonInstallLockReleasedAfterProcessExit$") + child.Env = append(os.Environ(), "SEA_PYTHON_LOCK_TEST_ROOT="+root) + if output, err := child.CombinedOutput(); err != nil { + t.Fatalf("lock owner failed: %v: %s", err, output) + } + release, err := acquirePythonInstallLock(root, "3.12.15") + if err != nil { + t.Fatalf("exited process left a stale lock: %v", err) + } + defer release() +} + +func TestPythonInstallLockRejectsSymlink(t *testing.T) { + root := t.TempDir() + target := filepath.Join(root, "unrelated") + if err := os.WriteFile(target, []byte("untouched"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, filepath.Join(root, ".install-3.12.15.flock")); err != nil { + t.Fatal(err) + } + if release, err := acquirePythonInstallLock(root, "3.12.15"); err == nil { + release() + t.Fatal("symbolic link was accepted as a lock file") + } + data, err := os.ReadFile(target) + if err != nil || string(data) != "untouched" { + t.Fatal("lock acquisition modified the symlink target") + } +} diff --git a/backend/internal/isolation/python_lock_other.go b/backend/internal/isolation/python_lock_other.go new file mode 100644 index 0000000..a27c850 --- /dev/null +++ b/backend/internal/isolation/python_lock_other.go @@ -0,0 +1,20 @@ +//go:build !linux + +package isolation + +import ( + "errors" + "os" + "path/filepath" +) + +func acquirePythonInstallLock(buildRoot, version string) (func(), error) { + lockPath := filepath.Join(buildRoot, ".install-"+version+".lock") + if err := os.Mkdir(lockPath, 0700); err != nil { + if errors.Is(err, os.ErrExist) { + return nil, errors.New("Python version installation is already running") + } + return nil, err + } + return func() { _ = os.Remove(lockPath) }, nil +} diff --git a/backend/internal/isolation/python_metadata_cache.go b/backend/internal/isolation/python_metadata_cache.go new file mode 100644 index 0000000..1144c69 --- /dev/null +++ b/backend/internal/isolation/python_metadata_cache.go @@ -0,0 +1,94 @@ +package isolation + +import ( + "errors" + "io" + "os" + "path/filepath" +) + +func (a Agent) pythonMetadataDirectory() string { + if a.PythonMetadataCacheRoot != "" { + return a.PythonMetadataCacheRoot + } + return "/var/lib/sea-vhost-agent/python-metadata" +} + +// A cache is software verification material, not a node-side platform ledger. +// It can only be supplied by root (including an offline import of the official +// .sigstore file); unprivileged users and symlinks cannot establish trust. +func (a Agent) readPythonMetadataCache(name string) ([]byte, error) { + data, err := a.readPythonVerificationCache(name, 1<<20) + if err != nil { + return nil, err + } + if _, err = pythonSourceDigest(data); err != nil { + return nil, err + } + return data, nil +} + +func (a Agent) readPythonVerificationCache(name string, limit int64) ([]byte, error) { + directory := a.pythonMetadataDirectory() + if filepath.Base(name) != name || requirePhysicalDirectory(directory) != nil { + return nil, errors.New("unsafe metadata cache") + } + info, err := os.Lstat(directory) + if err != nil || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 { + return nil, errors.New("untrusted metadata cache directory") + } + root, err := os.OpenRoot(directory) + if err != nil { + return nil, err + } + defer root.Close() + info, err = root.Lstat(name) + if err != nil || !info.Mode().IsRegular() || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 || info.Size() > limit { + return nil, errors.New("untrusted metadata cache file") + } + file, err := root.Open(name) + if err != nil { + return nil, err + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, errors.New("metadata cache exceeds limit") + } + return data, nil +} + +func (a Agent) cachePythonMetadata(name string, data []byte) { + if !canWritePythonMetadataCache() || filepath.Base(name) != name { + return + } + directory := a.pythonMetadataDirectory() + if os.MkdirAll(directory, 0700) != nil || requirePhysicalDirectory(directory) != nil { + return + } + info, err := os.Lstat(directory) + if err != nil || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 { + return + } + file, err := os.CreateTemp(directory, ".metadata-") + if err != nil { + return + } + temporary := file.Name() + defer os.Remove(temporary) + if file.Chmod(0600) != nil { + file.Close() + return + } + if _, err = file.Write(data); err != nil { + file.Close() + return + } + if file.Close() != nil { + return + } + _ = os.Rename(temporary, filepath.Join(directory, name)) +} diff --git a/backend/internal/isolation/python_metadata_cache_linux.go b/backend/internal/isolation/python_metadata_cache_linux.go new file mode 100644 index 0000000..0ad472d --- /dev/null +++ b/backend/internal/isolation/python_metadata_cache_linux.go @@ -0,0 +1,14 @@ +//go:build linux + +package isolation + +import ( + "os" + "syscall" +) + +func rootOwnedPythonMetadata(info os.FileInfo) bool { + s, ok := info.Sys().(*syscall.Stat_t) + return ok && s.Uid == 0 +} +func canWritePythonMetadataCache() bool { return os.Geteuid() == 0 } diff --git a/backend/internal/isolation/python_metadata_cache_linux_test.go b/backend/internal/isolation/python_metadata_cache_linux_test.go new file mode 100644 index 0000000..fb50a51 --- /dev/null +++ b/backend/internal/isolation/python_metadata_cache_linux_test.go @@ -0,0 +1,85 @@ +//go:build linux + +package isolation + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "fmt" + "os" + "path/filepath" + "testing" +) + +func TestOfflinePythonSourceCacheRequiresOfficialDigest(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("root-owned offline source test") + } + root := t.TempDir() + a := Agent{PythonMetadataCacheRoot: root} + const name = "Python-3.12.15.tar.xz" + source := []byte("verified offline source") + digest := sha256.Sum256(source) + bundle := []byte(fmt.Sprintf(`{"messageSignature":{"messageDigest":{"algorithm":"SHA2_256","digest":%q}}}`, base64.StdEncoding.EncodeToString(digest[:]))) + a.cachePythonMetadata(name+".sigstore", bundle) + if err := os.WriteFile(filepath.Join(root, name), source, 0600); err != nil { + t.Fatal(err) + } + archive, err := a.downloadVerifiedPythonSource(context.Background(), t.TempDir(), "3.12.15") + if err != nil { + t.Fatal(err) + } + actual, err := os.ReadFile(archive) + if err != nil || string(actual) != string(source) { + t.Fatal("verified offline source was not staged") + } + if err = os.WriteFile(filepath.Join(root, name), []byte("tampered"), 0600); err != nil { + t.Fatal(err) + } + if _, err = a.downloadVerifiedPythonSource(context.Background(), t.TempDir(), "3.12.15"); err == nil { + t.Fatal("tampered offline source trusted") + } +} + +func TestPythonMetadataCacheOnlyAcceptsRootProtectedFiles(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("root-owned offline metadata test") + } + root := t.TempDir() + a := Agent{PythonMetadataCacheRoot: root} + const name = "Python-3.12.15.tar.xz.sigstore" + data := []byte(`{"messageSignature":{"messageDigest":{"algorithm":"SHA2_256","digest":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}}}`) + a.cachePythonMetadata(name, data) + if _, err := a.readPythonMetadataCache(name); err != nil { + t.Fatal(err) + } + if err := os.Chmod(filepath.Join(root, name), 0666); err != nil { + t.Fatal(err) + } + if _, err := a.readPythonMetadataCache(name); err == nil { + t.Fatal("world-writable cache trusted") + } + if err := os.Chmod(filepath.Join(root, name), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chown(filepath.Join(root, name), 65534, 65534); err != nil { + t.Fatal(err) + } + if _, err := a.readPythonMetadataCache(name); err == nil { + t.Fatal("non-root cache trusted") + } + if err := os.Remove(filepath.Join(root, name)); err != nil { + t.Fatal(err) + } + target := filepath.Join(t.TempDir(), "public") + if err := os.WriteFile(target, data, 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, filepath.Join(root, name)); err != nil { + t.Fatal(err) + } + if _, err := a.readPythonMetadataCache(name); err == nil { + t.Fatal("symlink cache trusted") + } +} diff --git a/backend/internal/isolation/python_metadata_cache_other.go b/backend/internal/isolation/python_metadata_cache_other.go new file mode 100644 index 0000000..88b76f2 --- /dev/null +++ b/backend/internal/isolation/python_metadata_cache_other.go @@ -0,0 +1,8 @@ +//go:build !linux + +package isolation + +import "os" + +func rootOwnedPythonMetadata(os.FileInfo) bool { return false } +func canWritePythonMetadataCache() bool { return false } diff --git a/backend/internal/isolation/resource_usage.go b/backend/internal/isolation/resource_usage.go new file mode 100644 index 0000000..bb535f0 --- /dev/null +++ b/backend/internal/isolation/resource_usage.go @@ -0,0 +1,347 @@ +package isolation + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "time" +) + +type trafficCursor struct { + Month string `json:"month"` + FileID uint64 `json:"fileId"` + Offset int64 `json:"offset"` + Bytes uint64 `json:"bytes"` +} + +type trafficState struct { + Version int `json:"version"` + Domains map[string]trafficCursor `json:"domains"` +} + +var ( + trafficStateMu sync.Mutex + nginxBytesPattern = regexp.MustCompile(`"\s+[0-9]{3}\s+([0-9]+|-)\s`) + nginxDatePattern = regexp.MustCompile(`\[([0-9]{2})/([A-Za-z]{3})/([0-9]{4}):`) +) + +func (a Agent) resourceUsage(w http.ResponseWriter, r *http.Request) { + var spec ResourceUsageSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !validUsageSpec(spec) || len(spec.Domains) > 100 { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + projectRoot, err := a.projectPath(spec.Project) + if err != nil || requirePhysicalDirectory(projectRoot) != nil { + http.Error(w, "project root unavailable", http.StatusPreconditionFailed) + return + } + storage, err := measureProjectStorage(projectRoot) + if err != nil { + http.Error(w, "cannot measure project storage", http.StatusInternalServerError) + return + } + processes, err := countIdentityProcesses(spec.Project.HostName) + if err != nil { + http.Error(w, "cannot count isolated processes", http.StatusInternalServerError) + return + } + bandwidth, err := a.measureBandwidth(spec.Domains, time.Now()) + if err != nil { + http.Error(w, "cannot measure site bandwidth", http.StatusInternalServerError) + return + } + ftpBytes, err := a.measureFTPBandwidth(spec.Project.HostName, time.Now()) + if err != nil || ftpBytes > math.MaxUint64-bandwidth { + http.Error(w, "cannot measure FTP bandwidth", 500) + return + } + bandwidth += ftpBytes + memory, ticks, err := identityMetrics(spec.Project.HostName) + if err != nil { + http.Error(w, "cannot read process metrics", 412) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(ResourceUsage{StorageBytes: storage, BandwidthBytes: bandwidth, ProcessCount: processes, MemoryBytes: memory, CPUTicks: ticks}) +} + +// measureProjectStorage runs only in the root isolation agent. The API service +// deliberately cannot traverse private runtime directories owned by a host +// identity, so measuring there would let a tenant make quota refresh fail with +// chmod(000). WalkDir does not follow symlinks; only logical entry sizes below +// the already validated physical project root are counted. +func measureProjectStorage(projectRoot string) (uint64, error) { + if err := requirePhysicalDirectory(projectRoot); err != nil { + return 0, err + } + var total uint64 + err := filepath.WalkDir(projectRoot, func(_ string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() { + return nil + } + info, err := entry.Info() + if err != nil { + return err + } + size := info.Size() + if size < 0 || uint64(size) > math.MaxUint64-total { + return errors.New("storage usage overflow") + } + total += uint64(size) + return nil + }) + if err != nil { + return 0, err + } + return total, nil +} + +func (a Agent) terminateProcesses(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decode(w, r) + if !ok { + return + } + projectRoot, err := a.projectPath(spec) + if err != nil || requirePhysicalDirectory(projectRoot) != nil { + http.Error(w, "project root unavailable", http.StatusPreconditionFailed) + return + } + if err = terminateIdentityProcesses(r.Context(), spec.HostName); err != nil { + http.Error(w, "cannot terminate isolated processes", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func (a Agent) terminateRuntime(w http.ResponseWriter, r *http.Request) { + var input RuntimeProcessSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) || + input.Project.TenantID == 0 || input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 { + http.Error(w, "invalid request", http.StatusBadRequest) + return + } + projectRoot, err := a.projectPath(input.Project) + if err != nil { + http.Error(w, "invalid path", http.StatusBadRequest) + return + } + runtimeRoot, err := physicalRunDirectory(projectRoot, input.Project.RunPath) + if err != nil { + http.Error(w, "unsafe runtime directory", http.StatusPreconditionFailed) + return + } + if err = terminateRuntimeDirectoryProcesses(r.Context(), input.Project.HostName, runtimeRoot); err != nil { + http.Error(w, "cannot terminate isolated runtime processes", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func validUsageSpec(spec ResourceUsageSpec) bool { + if !safeName.MatchString(spec.Project.HostName) || spec.Project.TenantID == 0 || + spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 || !validProjectRunPath(spec.Project.RunPath) { + return false + } + seen := make(map[string]bool, len(spec.Domains)) + for index, domain := range spec.Domains { + domain = strings.ToLower(strings.TrimSpace(domain)) + if !webDomainPattern.MatchString(domain) || seen[domain] { + return false + } + seen[domain] = true + spec.Domains[index] = domain + } + return true +} + +func (a Agent) measureBandwidth(domains []string, now time.Time) (uint64, error) { + trafficStateMu.Lock() + defer trafficStateMu.Unlock() + statePath := a.UsageStatePath + if statePath == "" { + statePath = "/var/lib/sea-vhost-agent/traffic.json" + } + logRoot := a.NginxLogRoot + if logRoot == "" { + logRoot = "/www/wwwlogs" + } + state, err := loadTrafficState(statePath) + if err != nil { + return 0, err + } + month := now.Format("2006-01") + var total uint64 + for _, rawDomain := range domains { + domain := strings.ToLower(strings.TrimSpace(rawDomain)) + cursor := state.Domains[domain] + if cursor.Month != month { + cursor.Month = month + cursor.Bytes = 0 + } + cursor, err = measureDomainLog(filepath.Join(logRoot, domain+".log"), cursor, month) + if err != nil { + return 0, fmt.Errorf("measure %s: %w", domain, err) + } + state.Domains[domain] = cursor + if cursor.Bytes > math.MaxUint64-total { + return 0, errors.New("bandwidth usage overflow") + } + total += cursor.Bytes + } + if err = saveTrafficState(statePath, state); err != nil { + return 0, err + } + return total, nil +} + +func loadTrafficState(path string) (trafficState, error) { + state := trafficState{Version: 1, Domains: map[string]trafficCursor{}} + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return state, nil + } + if err != nil { + return state, err + } + if err = json.Unmarshal(data, &state); err != nil || state.Version != 1 || state.Domains == nil { + return trafficState{}, errors.New("invalid traffic state") + } + return state, nil +} + +func saveTrafficState(path string, state trafficState) error { + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return err + } + data, err := json.Marshal(state) + if err != nil { + return err + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".traffic-*.tmp") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err = temporary.Chmod(0600); err == nil { + _, err = temporary.Write(append(data, '\n')) + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return os.Rename(temporaryPath, path) +} + +func measureDomainLog(path string, cursor trafficCursor, month string) (trafficCursor, error) { + return measureTransferLog(path, cursor, month, nil) +} + +func measureTransferLog(path string, cursor trafficCursor, month string, parse func(string) (uint64, bool)) (trafficCursor, error) { + info, err := os.Stat(path) + if errors.Is(err, os.ErrNotExist) { + return cursor, nil + } + if err != nil || !info.Mode().IsRegular() { + return cursor, errors.New("site log is not a regular file") + } + currentID := fileIdentity(info) + if cursor.FileID != 0 && cursor.FileID != currentID { + rotated := path + ".1" + if rotatedInfo, statErr := os.Stat(rotated); statErr == nil && rotatedInfo.Mode().IsRegular() && fileIdentity(rotatedInfo) == cursor.FileID { + if err = accumulateTransferLog(rotated, cursor.Offset, month, &cursor, parse); err != nil { + return cursor, err + } + } + cursor.Offset = 0 + } + if cursor.FileID == currentID && info.Size() < cursor.Offset { + cursor.Offset = 0 // copytruncate rotation + } + cursor.FileID = currentID + if err = accumulateTransferLog(path, cursor.Offset, month, &cursor, parse); err != nil { + return cursor, err + } + return cursor, nil +} + +func accumulateLog(path string, offset int64, month string, cursor *trafficCursor) error { + return accumulateTransferLog(path, offset, month, cursor, nil) +} + +func accumulateTransferLog(path string, offset int64, month string, cursor *trafficCursor, parse func(string) (uint64, bool)) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + if _, err = file.Seek(offset, io.SeekStart); err != nil { + return err + } + reader := bufio.NewReaderSize(file, 64<<10) + for { + line, readErr := reader.ReadString('\n') + if errors.Is(readErr, io.EOF) && len(line) > 0 && !strings.HasSuffix(line, "\n") { + // Nginx may still be writing this record. Re-read it from the same + // offset next cycle instead of permanently skipping a partial line. + return nil + } + if len(line) > 0 { + cursor.Offset += int64(len(line)) + if parse != nil { + if value, ok := parse(line); ok { + if value > math.MaxUint64-cursor.Bytes { + return errors.New("FTP bandwidth usage overflow") + } + cursor.Bytes += value + } + } else if lineMonth(line) == month { + match := nginxBytesPattern.FindStringSubmatch(line) + if match != nil && match[1] != "-" { + value, parseErr := strconv.ParseUint(match[1], 10, 64) + if parseErr != nil || value > math.MaxUint64-cursor.Bytes { + return errors.New("bandwidth usage overflow") + } + cursor.Bytes += value + } + } + } + if errors.Is(readErr, io.EOF) { + return nil + } + if readErr != nil { + return readErr + } + } +} + +func lineMonth(line string) string { + match := nginxDatePattern.FindStringSubmatch(line) + if match == nil { + return "" + } + months := map[string]string{"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"} + return match[3] + "-" + months[match[2]] +} diff --git a/backend/internal/isolation/runtime_maintenance.go b/backend/internal/isolation/runtime_maintenance.go new file mode 100644 index 0000000..68de52b --- /dev/null +++ b/backend/internal/isolation/runtime_maintenance.go @@ -0,0 +1,517 @@ +package isolation + +import ( + "context" + "debug/buildinfo" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "time" +) + +type RuntimeProbeSpec struct { + Project ProjectSpec `json:"project"` + Runtime string `json:"runtime"` + Version string `json:"version"` + ProjectName string `json:"projectName"` + EntryFile string `json:"entryFile,omitempty"` + Running bool `json:"running"` +} +type RuntimeObservation struct { + InstalledVersion string `json:"installedVersion"` + RunningVersion string `json:"runningVersion,omitempty"` + Healthy bool `json:"healthy"` + Detail string `json:"detail,omitempty"` +} +type PHPMaintenanceSpec struct { + Branch string `json:"branch"` + JobID uint64 `json:"jobId"` + Action string `json:"action"` +} +type PHPState struct { + Version string `json:"version"` + Extensions []string `json:"extensions"` + BackupPath string `json:"backupPath,omitempty"` +} +type RuntimeMaintenance interface { + ProbeRuntime(context.Context, RuntimeProbeSpec) (RuntimeObservation, error) + MaintainPHP(context.Context, PHPMaintenanceSpec) (PHPState, error) + CopyPythonDependencies(context.Context, PanelRuntimeSpec, string) error +} + +func (c *Client) ProbeRuntime(ctx context.Context, spec RuntimeProbeSpec) (RuntimeObservation, error) { + var result RuntimeObservation + err := c.request(ctx, "/v1/runtime/probe", spec, &result) + return result, err +} +func (c *Client) MaintainPHP(ctx context.Context, spec PHPMaintenanceSpec) (PHPState, error) { + var result PHPState + err := c.requestLong(ctx, "/v1/runtime/php/maintenance", spec, &result) + return result, err +} +func (c *Client) CopyPythonDependencies(ctx context.Context, spec PanelRuntimeSpec, old string) error { + return c.requestLong(ctx, "/v1/runtime/python/dependencies", struct { + Spec PanelRuntimeSpec `json:"spec"` + Previous string `json:"previous"` + }{spec, old}, nil) +} + +var exactPHPVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]\.[0-9]{1,4}$`) +var maintenanceHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`) + +func maintenanceProjectMatches(host, name string) bool { + return maintenanceHostPattern.MatchString(host) && panelProjectNamePattern.MatchString(name) && (name == host || strings.HasPrefix(name, host+"_")) +} + +func phpInstallationState(ctx context.Context, branch string) (PHPState, error) { + if !phpVersionPattern.MatchString(branch) { + return PHPState{}, errors.New("invalid PHP branch") + } + root := filepath.Join("/www/server/php", strings.ReplaceAll(branch, ".", "")) + if requirePhysicalDirectory(root) != nil { + return PHPState{}, errors.New("PHP branch is not installed") + } + cmd := exec.CommandContext(ctx, filepath.Join(root, "bin/php"), "-r", `echo json_encode(["version"=>PHP_VERSION,"extensions"=>get_loaded_extensions()]);`) + cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C"} + data, err := cmd.Output() + if err != nil { + return PHPState{}, fmt.Errorf("read PHP version: %w", err) + } + var state PHPState + if json.Unmarshal(data, &state) != nil || !exactPHPVersionPattern.MatchString(state.Version) || !strings.HasPrefix(state.Version, branch+".") { + return state, errors.New("PHP returned invalid version metadata") + } + slices.Sort(state.Extensions) + return state, nil +} + +func (a Agent) maintainPHP(w http.ResponseWriter, r *http.Request) { + var spec PHPMaintenanceSpec + if decodeMaintenance(r, &spec) != nil || !phpVersionPattern.MatchString(spec.Branch) || !slices.Contains([]string{"inspect", "backup", "restore", "complete"}, spec.Action) || (spec.Action != "inspect" && spec.JobID == 0) { + http.Error(w, "invalid PHP maintenance request", 400) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute) + defer cancel() + state, err := a.maintainPHPBranch(ctx, spec) + if err != nil { + http.Error(w, err.Error(), 412) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(state) +} +func decodeMaintenance(r *http.Request, out any) error { + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(out); err != nil { + return err + } + if err := decoder.Decode(&struct{}{}); err != io.EOF { + return errors.New("unexpected trailing JSON") + } + return nil +} + +func (a Agent) maintainPHPBranch(ctx context.Context, spec PHPMaintenanceSpec) (PHPState, error) { + if spec.Action == "inspect" { + return phpInstallationState(ctx, spec.Branch) + } + base := a.BackupRoot + if base == "" { + base = "/www/backup/sea-vhost" + } + if !filepath.IsAbs(base) || filepath.Clean(base) != base { + return PHPState{}, errors.New("invalid backup root") + } + branch := strings.ReplaceAll(spec.Branch, ".", "") + root := filepath.Join("/www/server/php", branch) + backup := filepath.Join(base, "runtime", "php", branch, strconv.FormatUint(spec.JobID, 10)) + if err := os.MkdirAll(filepath.Dir(backup), 0700); err != nil { + return PHPState{}, err + } + if spec.Action == "backup" { + if info, err := os.Lstat(backup); err == nil { + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return PHPState{}, errors.New("unsafe PHP backup") + } + return readPHPSnapshot(backup, spec.Branch) + } + state, err := phpInstallationState(ctx, spec.Branch) + if err != nil { + return state, err + } + stage, err := os.MkdirTemp(filepath.Dir(backup), ".snapshot-") + if err != nil { + return state, err + } + defer os.RemoveAll(stage) + if err = a.command(ctx, "cp", "-a", "--", root, filepath.Join(stage, "installation")); err != nil { + return state, err + } + state.BackupPath = backup + data, _ := json.Marshal(state) + if err = os.WriteFile(filepath.Join(stage, "manifest.json"), data, 0600); err != nil { + return state, err + } + if err = os.Rename(stage, backup); err != nil { + return state, err + } + return state, nil + } + saved, err := readPHPSnapshot(backup, spec.Branch) + if err != nil { + return saved, err + } + if spec.Action == "complete" { + if err = os.WriteFile(filepath.Join(backup, "retention-start"), []byte(time.Now().UTC().Format(time.RFC3339)), 0600); err != nil { + return saved, err + } + a.prunePHPSnapshots(filepath.Join(base, "runtime", "php")) + return saved, nil + } + if requirePhysicalDirectory(filepath.Join(backup, "installation")) != nil { + return saved, errors.New("PHP snapshot installation unavailable") + } + stage, err := os.MkdirTemp("/www/server/php", ".sea-restore-") + if err != nil { + return saved, err + } + defer os.RemoveAll(stage) + if err = a.command(ctx, "cp", "-a", "--", filepath.Join(backup, "installation"), filepath.Join(stage, "installation")); err != nil { + return saved, err + } + if err = a.command(ctx, "/etc/init.d/php-fpm-"+branch, "stop"); err != nil { + return saved, err + } + if requirePhysicalDirectory(root) != nil { + return saved, errors.New("unsafe PHP restore destination") + } + failed := filepath.Join(stage, "replaced") + if err = os.Rename(root, failed); err != nil { + return saved, err + } + if err = os.Rename(filepath.Join(stage, "installation"), root); err != nil { + _ = os.Rename(failed, root) + return saved, err + } + if err = a.command(ctx, "/etc/init.d/php-fpm-"+branch, "start"); err != nil { + return saved, err + } + return phpInstallationState(ctx, spec.Branch) +} + +// Only finalized Sea vHost snapshots expire. An interrupted task keeps its +// unsealed backup until an administrator resolves that task. +func (a Agent) prunePHPSnapshots(base string) { + branches, err := os.ReadDir(base) + if err != nil { + return + } + for _, branch := range branches { + if !branch.IsDir() || !regexp.MustCompile("^[5-9][0-9]$").MatchString(branch.Name()) { + continue + } + root := filepath.Join(base, branch.Name()) + if requirePhysicalDirectory(root) != nil { + continue + } + jobs, err := os.ReadDir(root) + if err != nil { + continue + } + for _, job := range jobs { + if _, err = strconv.ParseUint(job.Name(), 10, 64); err != nil || !job.IsDir() { + continue + } + path := filepath.Join(root, job.Name()) + if _, err = readPHPSnapshot(path, branch.Name()[:1]+"."+branch.Name()[1:]); err != nil { + continue + } + info, err := os.Lstat(filepath.Join(path, "retention-start")) + if err != nil || !info.Mode().IsRegular() || time.Since(info.ModTime()) < 14*24*time.Hour { + continue + } + _ = os.RemoveAll(path) + } + } +} + +// Expiry runs independently of future updates; unresolved snapshots are never +// sealed and therefore remain available for administrator recovery. +func (a Agent) RunRuntimeBackupExpiry(ctx context.Context) { + base := a.BackupRoot + if base == "" { + base = "/www/backup/sea-vhost" + } + if !filepath.IsAbs(base) || filepath.Clean(base) != base { + return + } + prune := func() { a.prunePHPSnapshots(filepath.Join(base, "runtime", "php")) } + prune() + ticker := time.NewTicker(time.Hour) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + prune() + } + } +} +func readPHPSnapshot(backup, branch string) (PHPState, error) { + if requirePhysicalDirectory(backup) != nil { + return PHPState{}, errors.New("PHP snapshot unavailable") + } + data, err := os.ReadFile(filepath.Join(backup, "manifest.json")) + if err != nil { + return PHPState{}, err + } + var state PHPState + if json.Unmarshal(data, &state) != nil || !exactPHPVersionPattern.MatchString(state.Version) || !strings.HasPrefix(state.Version, branch+".") || state.BackupPath != backup { + return state, errors.New("invalid PHP snapshot manifest") + } + return state, nil +} + +func (a Agent) probeRuntime(w http.ResponseWriter, r *http.Request) { + var spec RuntimeProbeSpec + if decodeMaintenance(r, &spec) != nil || !maintenanceProjectMatches(spec.Project.HostName, spec.ProjectName) || !validProjectRunPath(spec.Project.RunPath) || spec.Project.TenantID == 0 { + http.Error(w, "invalid runtime probe", 400) + return + } + result, err := a.probeRuntimeState(r.Context(), spec) + if err != nil { + http.Error(w, err.Error(), 412) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(result) +} +func (a Agent) probeRuntimeState(ctx context.Context, spec RuntimeProbeSpec) (RuntimeObservation, error) { + root, err := a.projectPath(spec.Project) + if err != nil { + return RuntimeObservation{}, err + } + working, err := physicalRunDirectory(root, spec.Project.RunPath) + if err != nil { + return RuntimeObservation{}, err + } + result := RuntimeObservation{} + var executable string + switch spec.Runtime { + case "PHP": + state, err := phpInstallationState(ctx, spec.Version) + if err != nil { + return result, err + } + result.InstalledVersion = state.Version + executable = filepath.Join("/www/server/php", strings.ReplaceAll(spec.Version, ".", ""), "sbin/php-fpm") + if !spec.Running { + result.Detail = "站点已停止,等待启动验证" + return result, nil + } + // Probe the private PID/socket directly; no Nginx config is modified. + runRoot := a.PHPRunRoot + if runRoot == "" { + runRoot = "/run/sea-vhost-php" + } + pid, err := readPID(filepath.Join(runRoot, spec.ProjectName, "php-fpm.pid")) + if err != nil { + return result, err + } + if !processUsesExecutable(ctx, pid, spec.Project.HostName, executable, working, false) { + result.Detail = "PHP-FPM 仍在使用旧程序或进程身份不匹配" + return result, nil + } + conn, err := net.DialTimeout("unix", filepath.Join(runRoot, spec.ProjectName, "php-fpm.sock"), time.Second) + if err != nil { + return result, err + } + _ = conn.Close() + result.RunningVersion = state.Version + result.Healthy = true + return result, nil + case "Python": + if !supportedPythonSourceVersion(spec.Version) { + return result, errors.New("invalid Python version") + } + manager := a.PythonManagerRoot + if manager == "" { + manager = "/www/server/python_manager/versions" + } + executable = filepath.Join(manager, spec.Version, "bin/python3") + result.InstalledVersion = spec.Version + case "Node.js": + if !regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+$`).MatchString(spec.Version) { + return result, errors.New("invalid Node version") + } + executable = filepath.Join("/www/server/nodejs", spec.Version, "bin/node") + result.InstalledVersion = spec.Version + case "Java": + if !regexp.MustCompile(`^(?:jdk-)?[0-9]+(?:\.[0-9]+){0,3}(?:_[0-9]+)?$`).MatchString(spec.Version) { + return result, errors.New("invalid JDK version") + } + executable = filepath.Join("/www/server/java", spec.Version, "bin/java") + if info, err := os.Stat(filepath.Join("/www/server/java", spec.Version)); err == nil && info.Mode().IsRegular() { + executable = filepath.Join("/www/server/java", spec.Version) + } + result.InstalledVersion = spec.Version + case "Go": + if !validExecutablePath(spec.EntryFile) { + return result, errors.New("invalid Go entry") + } + executable = filepath.Join(working, spec.EntryFile) + guard, err := os.OpenRoot(working) + if err != nil { + return result, err + } + defer guard.Close() + entry, err := guard.Open(spec.EntryFile) + if err != nil { + return result, err + } + defer entry.Close() + info, err := buildinfo.Read(entry) + if err != nil { + return result, errors.New("无法读取 Go 二进制编译版本,请上传带有 Go 构建信息的程序") + } + result.InstalledVersion = info.GoVersion + if info.GoVersion != spec.Version { + result.Detail = "二进制尚未使用目标 Go 版本重新编译" + return result, nil + } + default: + return result, errors.New("unsupported runtime probe") + } + if _, err = os.Stat(executable); err != nil { + return result, errors.New("runtime executable unavailable") + } + if !spec.Running { + result.Detail = "站点已停止,等待启动验证" + return result, nil + } + pids, err := identityPIDsForRuntimeProbe(spec.Project.HostName) + if err != nil { + return result, err + } + for _, pid := range pids { + if processUsesExecutable(ctx, pid, spec.Project.HostName, executable, working, true) { + result.RunningVersion = result.InstalledVersion + result.Healthy = true + return result, nil + } + } + result.Detail = "未找到使用目标版本的站点进程" + return result, nil +} + +func (a Agent) copyPythonDependencies(w http.ResponseWriter, r *http.Request) { + var input struct { + Spec PanelRuntimeSpec `json:"spec"` + Previous string `json:"previous"` + } + if decodeMaintenance(r, &input) != nil || input.Spec.Runtime != "Python" || !supportedPythonSourceVersion(input.Previous) || !supportedPythonSourceVersion(input.Spec.Version) || !maintenanceProjectMatches(input.Spec.Project.HostName, input.Spec.ProjectName) || input.Spec.Project.TenantID == 0 { + http.Error(w, "invalid Python migration", 400) + return + } + root, err := a.projectPath(input.Spec.Project) + if err != nil { + http.Error(w, "invalid project", 412) + return + } + working, err := physicalRunDirectory(root, input.Spec.Project.RunPath) + if err != nil { + http.Error(w, "unsafe run directory", 412) + return + } + parent := filepath.Join(working, ".sea-runtime/python") + oldPython := filepath.Join(parent, input.Spec.ProjectName+"-"+input.Previous, "bin/python3") + newPython := filepath.Join(parent, input.Spec.ProjectName+"-"+input.Spec.Version, "bin/python3") + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute) + defer cancel() + manager := a.PythonManagerRoot + if manager == "" { + manager = "/www/server/python_manager/versions" + } + if err = a.repairManagedPythonAccess(ctx, filepath.Join(manager, input.Previous), input.Previous); err != nil { + http.Error(w, "previous shared Python installation is unavailable", 412) + return + } + // Both commands drop UID before executing tenant-controlled venv content. + cmd := tenantMaintenanceCommand(ctx, input.Spec.Project.HostName, oldPython, "-m", "pip", "freeze") + var dependencies cappedDependencyBuffer + cmd.Stdout = &dependencies + err = cmd.Run() + if err != nil { + http.Error(w, "cannot export previous Python dependencies", 412) + return + } + if dependencies.exceeded { + http.Error(w, "Python dependency list too large", 412) + return + } + data := dependencies.data + if strings.TrimSpace(string(data)) != "" { + cmd = pythonDependencyRestoreCommand(ctx, input.Spec.Project.HostName, newPython) + cmd.Stdin = strings.NewReader(string(data)) + cmd.Stdout, cmd.Stderr = io.Discard, io.Discard + if installErr := cmd.Run(); installErr != nil { + http.Error(w, "Python dependency restore failed; previous environment retained", 412) + return + } + } + w.WriteHeader(200) +} + +const pythonDependencyRestore = `import os,sys,tempfile,subprocess +with tempfile.TemporaryDirectory(prefix=".sea-migrate-",dir=sys.argv[1]) as directory: + requirements=os.path.join(directory,"requirements.txt") + fd=os.open(requirements,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) + with os.fdopen(fd,"wb") as output: + output.write(sys.stdin.buffer.read(1048577)) + result=subprocess.run([sys.executable,"-m","pip","install","--disable-pip-version-check","-r",requirements],stdin=subprocess.DEVNULL) + sys.exit(result.returncode) +` + +func pythonDependencyRestoreCommand(ctx context.Context, identity, python string) *exec.Cmd { + // A root-created stdin pipe can be read via inherited FD 0, but reopening + // /dev/stdin after dropping UID can fail its inode permission check. Create + // a private requirements file as the tenant instead, and always remove it. + return tenantMaintenanceCommand(ctx, identity, python, "-c", pythonDependencyRestore, filepath.Dir(filepath.Dir(python))) +} + +func tenantMaintenanceCommand(ctx context.Context, identity string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "/usr/sbin/runuser", append([]string{"-u", identity, "--"}, args...)...) + // runuser does not remove every inherited environment variable. Never let + // an own-UID helper or tenant-controlled Python read the agent's token. + cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "LANG=C", "PIP_NO_CACHE_DIR=1"} + return cmd +} + +type cappedDependencyBuffer struct { + data []byte + exceeded bool +} + +func (b *cappedDependencyBuffer) Write(p []byte) (int, error) { + n := len(p) + remaining := (1 << 20) - len(b.data) + if n > remaining { + b.exceeded = true + p = p[:remaining] + } + b.data = append(b.data, p...) + return n, nil +} diff --git a/backend/internal/isolation/runtime_maintenance_test.go b/backend/internal/isolation/runtime_maintenance_test.go new file mode 100644 index 0000000..f62a769 --- /dev/null +++ b/backend/internal/isolation/runtime_maintenance_test.go @@ -0,0 +1,176 @@ +package isolation + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestRuntimeMaintenanceRejectsUntrustedInputs(t *testing.T) { + agent := Agent{InternalToken: "internal-test-token"} + for _, test := range []struct { + route, body string + status int + }{ + {"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"inspect"}`, 401}, + {"/v1/runtime/php/maintenance", `{"branch":"../../etc","action":"restore","jobId":1}`, 400}, + {"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"restore","jobId":0}`, 400}, + {"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"shell","jobId":1}`, 400}, + {"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"inspect"}{}`, 400}, + {"/v1/runtime/probe", `{"project":{"hostName":"root","tenantId":1,"runPath":"/"},"projectName":"sv0123456789","runtime":"PHP","version":"8.4"}`, 400}, + {"/v1/runtime/python/dependencies", `{"spec":{"project":{"hostName":"sv0123456789"},"runtime":"Python","projectName":"../../etc","version":"3.12.15"},"previous":"3.12.0"}`, 400}, + } { + r := httptest.NewRequest(http.MethodPost, test.route, bytes.NewBufferString(test.body)) + if test.status != 401 { + r.Header.Set("Authorization", "Bearer internal-test-token") + } + w := httptest.NewRecorder() + agent.Handler().ServeHTTP(w, r) + if w.Code != test.status { + t.Fatalf("%s got %d: %s", test.route, w.Code, w.Body.String()) + } + } +} + +func TestDependencyExportRemainsBounded(t *testing.T) { + var buffer cappedDependencyBuffer + payload := bytes.Repeat([]byte("x"), (1<<20)+100) + n, err := buffer.Write(payload) + if err != nil || n != len(payload) || len(buffer.data) != 1<<20 || !buffer.exceeded { + t.Fatal("untrusted dependency export was not bounded") + } + _, _ = buffer.Write(payload) + if len(buffer.data) != 1<<20 { + t.Fatal("buffer grew beyond its limit") + } +} + +func TestTenantMaintenanceDoesNotInheritAgentSecrets(t *testing.T) { + t.Setenv("SEA_INTERNAL_AUTH_TOKEN", "canary-not-for-tenant") + t.Setenv("SEA_PANEL_API_KEY", "canary-not-for-tenant") + cmd := tenantMaintenanceCommand(context.Background(), "sv0123456789", "/usr/bin/stat", "/proc/123/exe") + if len(cmd.Env) == 0 || strings.Contains(strings.Join(cmd.Env, "\n"), "canary") || strings.Contains(strings.Join(cmd.Env, "\n"), "SEA_") { + t.Fatal("tenant command inherited privileged environment") + } + if !strings.Contains(strings.Join(cmd.Args, " "), "-u sv0123456789 -- /usr/bin/stat") { + t.Fatal("tenant command did not drop UID") + } +} + +func TestDependencyRestoreDoesNotReopenPrivilegedStdin(t *testing.T) { + cmd := pythonDependencyRestoreCommand(context.Background(), "sv0123456789", "/host/private/venv/bin/python3") + joined := strings.Join(cmd.Args, " ") + if strings.Contains(joined, "/dev/stdin") || !strings.Contains(joined, "sys.stdin.buffer.read") || !strings.Contains(joined, "0o600") || cmd.Args[len(cmd.Args)-1] != filepath.Dir(filepath.Dir("/host/private/venv/bin/python3")) { + t.Fatal("dependency restore must create an own-UID private requirements file") + } +} + +func TestProjectACLProtectsNestedRuntimeDirectories(t *testing.T) { + root := t.TempDir() + paths := []string{filepath.Join(root, "public", ".sea-runtime"), filepath.Join(root, "apps", "web", ".sea-runtime")} + for _, path := range paths { + if err := os.MkdirAll(path, 0700); err != nil { + t.Fatal(err) + } + } + var commands []string + agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return nil + }} + if err := agent.applyProjectACL(context.Background(), root, "sea-vhost"); err != nil { + t.Fatal(err) + } + if !strings.Contains(strings.Join(commands, "\n"), "-type f -perm /111 -exec setfacl -m u:www:r--,m::rwx,o::---") { + t.Fatal("ACL repair would revoke execution from tenant binaries") + } + for _, path := range paths { + if !strings.Contains(strings.Join(commands, "\n"), "find "+path+" -xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") { + t.Fatalf("nested runtime was not protected: %s", path) + } + } +} + +func TestSharedPythonModesAreReadableButNotTenantWritable(t *testing.T) { + root := t.TempDir() + var commands []string + agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error { + commands = append(commands, name+" "+strings.Join(args, " ")) + return nil + }} + if err := agent.normalizeSharedPythonAccess(context.Background(), root); err != nil { + t.Fatal(err) + } + joined := strings.Join(commands, "\n") + for _, expected := range []string{"chown -hR root:root " + root, "-type d -exec chmod a+rx,go-w", "-type f -exec chmod a+rX,go-w"} { + if !strings.Contains(joined, expected) { + t.Fatalf("shared interpreter access missing %s", expected) + } + } + if strings.Contains(joined, "chmod -R") || strings.Contains(joined, "find -L") { + t.Fatal("shared interpreter repair must not follow symlinks") + } +} + +func TestPythonRepairDoesNotRewriteUnmanagedInstallations(t *testing.T) { + root := t.TempDir() + calls := 0 + agent := Agent{runCommand: func(context.Context, string, ...string) error { calls++; return nil }} + if err := agent.repairManagedPythonAccess(context.Background(), root, "3.12.15"); err != nil || calls != 0 { + t.Fatal("unmanaged interpreter was modified") + } + if err := os.WriteFile(filepath.Join(root, ".sea-vhost-runtime"), []byte("3.12.0"), 0600); err != nil { + t.Fatal(err) + } + if err := agent.repairManagedPythonAccess(context.Background(), root, "3.12.15"); err == nil || calls != 0 { + t.Fatal("mismatched marker accepted") + } +} + +func TestSnapshotExpiryPreservesUnresolvedAndRecentBackups(t *testing.T) { + base := t.TempDir() + old := time.Now().Add(-15 * 24 * time.Hour) + for _, test := range []struct { + id string + sealed, stale bool + }{{"1", true, true}, {"2", false, true}, {"3", true, false}} { + root := filepath.Join(base, "runtime", "php", "84", test.id) + if err := os.MkdirAll(root, 0700); err != nil { + t.Fatal(err) + } + manifest, _ := json.Marshal(PHPState{Version: "8.4.25", BackupPath: root}) + if err := os.WriteFile(filepath.Join(root, "manifest.json"), manifest, 0600); err != nil { + t.Fatal(err) + } + if test.sealed { + marker := filepath.Join(root, "retention-start") + if err := os.WriteFile(marker, []byte("completed"), 0600); err != nil { + t.Fatal(err) + } + if test.stale { + if err := os.Chtimes(marker, old, old); err != nil { + t.Fatal(err) + } + } + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + Agent{BackupRoot: base}.RunRuntimeBackupExpiry(ctx) + for _, test := range []struct { + id string + removed bool + }{{"1", true}, {"2", false}, {"3", false}} { + _, err := os.Stat(filepath.Join(base, "runtime", "php", "84", test.id)) + if os.IsNotExist(err) != test.removed { + t.Fatalf("snapshot %s expiry mismatch: %v", test.id, err) + } + } +} diff --git a/backend/internal/isolation/runtime_probe_linux.go b/backend/internal/isolation/runtime_probe_linux.go new file mode 100644 index 0000000..df26c99 --- /dev/null +++ b/backend/internal/isolation/runtime_probe_linux.go @@ -0,0 +1,55 @@ +//go:build linux + +package isolation + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +func identityPIDsForRuntimeProbe(identity string) ([]int, error) { return identityPIDs(identity) } +func processUsesExecutable(ctx context.Context, pid int, identity, executable, working string, checkCWD bool) bool { + uid, err := identityUID(identity) + if err != nil { + return false + } + proc := filepath.Join("/proc", strconv.Itoa(pid)) + info, err := os.Stat(proc) + if err != nil { + return false + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok || stat.Uid != uid { + return false + } + expected, err := os.Stat(executable) + if err != nil { + return false + } + expectedStat, ok := expected.Sys().(*syscall.Stat_t) + if !ok { + return false + } + // A restricted root agent intentionally lacks CAP_SYS_PTRACE. Inspect the + // process as its own UID, without adding broad process-reading privileges. + actual, err := tenantMaintenanceCommand(ctx, identity, "/usr/bin/stat", "-Lc", "%d:%i", filepath.Join(proc, "exe")).Output() + if err != nil || strings.TrimSpace(string(actual)) != fmt.Sprintf("%d:%d", expectedStat.Dev, expectedStat.Ino) { + return false + } + if checkCWD { + output, err := tenantMaintenanceCommand(ctx, identity, "/usr/bin/readlink", filepath.Join(proc, "cwd")).Output() + if err != nil { + return false + } + cwd := strings.TrimSpace(string(output)) + if filepath.Clean(cwd) != filepath.Clean(working) && !strings.HasPrefix(filepath.Clean(cwd)+"/", filepath.Clean(working)+"/") { + return false + } + } + return true +} diff --git a/backend/internal/isolation/runtime_probe_other.go b/backend/internal/isolation/runtime_probe_other.go new file mode 100644 index 0000000..127c347 --- /dev/null +++ b/backend/internal/isolation/runtime_probe_other.go @@ -0,0 +1,13 @@ +//go:build !linux + +package isolation + +import ( + "context" + "errors" +) + +func identityPIDsForRuntimeProbe(string) ([]int, error) { + return nil, errors.New("runtime process verification requires Linux") +} +func processUsesExecutable(context.Context, int, string, string, string, bool) bool { return false } diff --git a/backend/internal/isolation/runtime_prune.go b/backend/internal/isolation/runtime_prune.go new file mode 100644 index 0000000..f13e727 --- /dev/null +++ b/backend/internal/isolation/runtime_prune.go @@ -0,0 +1,33 @@ +package isolation + +import ( + "context" + "encoding/json" + "io" + "net/http" + "path/filepath" +) + +func (c *Client) PruneRuntimeBackups(ctx context.Context) error { + return c.requestLong(ctx, "/v1/runtime/backups/prune", struct{}{}, nil) +} +func (a Agent) pruneRuntimeBackups(w http.ResponseWriter, r *http.Request) { + var input struct{} + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if decoder.Decode(&input) != nil || decoder.Decode(&struct{}{}) != io.EOF { + http.Error(w, "invalid prune request", 400) + return + } + base := a.BackupRoot + if base == "" { + base = "/www/backup/sea-vhost" + } + if !filepath.IsAbs(base) || filepath.Clean(base) != base { + http.Error(w, "invalid backup root", 500) + return + } + a.prunePHPSnapshots(filepath.Join(base, "runtime", "php")) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"status":"ok"}`)) +} diff --git a/backend/internal/isolation/schedule_execution.go b/backend/internal/isolation/schedule_execution.go new file mode 100644 index 0000000..208c236 --- /dev/null +++ b/backend/internal/isolation/schedule_execution.go @@ -0,0 +1,165 @@ +package isolation + +import ( + "context" + "crypto/tls" + "encoding/json" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "sea-vhost/internal/hosting" + "strconv" + "strings" + "time" +) + +type ScheduleExecutionSpec struct { + Project ProjectSpec `json:"project"` + SiteName string `json:"siteName"` + Kind string `json:"kind"` + Version string `json:"version"` + Target string `json:"target"` + Arguments []string `json:"arguments"` + Environment map[string]string `json:"environment"` + Domain string `json:"domain"` + Port int `json:"port"` + UseHTTPS bool `json:"useHTTPS"` +} +type ScheduleOutput struct { + ExitCode int `json:"exitCode"` + Output string `json:"output"` + Truncated bool `json:"truncated"` +} +type ScheduleExecutor interface { + ExecuteSchedule(context.Context, ScheduleExecutionSpec) (ScheduleOutput, error) +} + +func (c *Client) ExecuteSchedule(ctx context.Context, v ScheduleExecutionSpec) (ScheduleOutput, error) { + var out ScheduleOutput + e := c.requestLong(ctx, "/v1/schedule/execute", v, &out) + return out, e +} +func (Mock) ExecuteSchedule(context.Context, ScheduleExecutionSpec) (ScheduleOutput, error) { + return ScheduleOutput{Output: "test task completed"}, nil +} +func (a Agent) executeSchedule(w http.ResponseWriter, r *http.Request) { + var v ScheduleExecutionSpec + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + check := hosting.Startup{} + if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(v.Project.HostName) || !phpSiteNamePattern.MatchString(v.SiteName) || !(v.SiteName == v.Project.HostName || strings.HasPrefix(v.SiteName, v.Project.HostName+"_")) || !validUsageSpec(ResourceUsageSpec{Project: v.Project}) { + http.Error(w, "invalid scheduled task", 400) + return + } + check.Arguments = v.Arguments + check.Environment = v.Environment + delete(check.Environment, "PORT") + if check.Validate() != nil { + http.Error(w, "invalid task parameters", 400) + return + } + root, e := a.projectPath(v.Project) + if e != nil { + http.Error(w, "invalid host root", 412) + return + } + working, e := physicalRunDirectory(root, v.Project.RunPath) + if e != nil { + http.Error(w, "website directory unavailable", 412) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 300*time.Second) + defer cancel() + var out ScheduleOutput + if v.Kind == "url" { + uri, e := url.ParseRequestURI(v.Target) + if e != nil || uri.IsAbs() || uri.Host != "" || !strings.HasPrefix(v.Target, "/") || strings.HasPrefix(v.Target, "//") || !webDomainPattern.MatchString(v.Domain) || v.Port < 1 || v.Port > 65535 { + http.Error(w, "only this website URL is allowed", 400) + return + } + scheme := "http" + if v.UseHTTPS { + scheme = "https" + } + transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(v.Port))) + }, TLSClientConfig: &tls.Config{ServerName: v.Domain, MinVersion: tls.VersionTLS12}} + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport, Timeout: 300 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + request, e := http.NewRequestWithContext(ctx, "GET", scheme+"://"+v.Domain+v.Target, nil) + if e != nil { + http.Error(w, "invalid task URL", 400) + return + } + response, e := client.Do(request) + if e != nil { + out.ExitCode = 1 + out.Output = "请求本站失败" + } else { + body, e := io.ReadAll(io.LimitReader(response.Body, 65537)) + response.Body.Close() + out.ExitCode = 0 + if e != nil || response.StatusCode < 200 || response.StatusCode >= 300 { + out.ExitCode = 1 + } + out.Truncated = len(body) > 65536 + if out.Truncated { + body = body[:65536] + } + out.Output = "HTTP " + strconv.Itoa(response.StatusCode) + "\n" + strings.ToValidUTF8(string(body), "�") + } + } else { + if !hosting.ValidRelative(v.Target) || !validScheduleVersion(v.Kind, v.Version) { + http.Error(w, "invalid task script", 400) + return + } + binary := "" + switch v.Kind { + case "php": + binary = filepath.Join("/www/server/php", strings.ReplaceAll(v.Version, ".", ""), "bin/php") + case "python": + binary = filepath.Join("/www/server/python_manager/versions", v.Version, "bin/python3") + case "node": + binary = filepath.Join("/www/server/nodejs", v.Version, "bin/node") + default: + http.Error(w, "unsupported task kind", 400) + return + } + guard, e := os.OpenRoot(working) + if e != nil { + http.Error(w, "task directory unavailable", 412) + return + } + i, e := guard.Lstat(v.Target) + guard.Close() + if e != nil || !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 { + http.Error(w, "script must be a regular website file", 412) + return + } + args := append([]string{filepath.Join(working, v.Target)}, v.Arguments...) + if v.Kind == "php" { + args = append([]string{"-d", "pcre.jit=0", "-d", "opcache.jit=0"}, args...) + } else if v.Kind == "node" { + args = append([]string{"--jitless"}, args...) + } + out, e = runScheduledIdentity(ctx, v.Project.HostName, binary, args, working, v.Environment) + if e != nil { + http.Error(w, "cannot start isolated task", 422) + return + } + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(out) +} + +func validScheduleVersion(kind, version string) bool { + pattern := `^v?[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,4}$` + if kind == "php" { + pattern = `^[0-9]{1,2}\.[0-9]{1,2}$` + } + return regexp.MustCompile(pattern).MatchString(version) +} diff --git a/backend/internal/isolation/schedule_execution_linux.go b/backend/internal/isolation/schedule_execution_linux.go new file mode 100644 index 0000000..7b20074 --- /dev/null +++ b/backend/internal/isolation/schedule_execution_linux.go @@ -0,0 +1,72 @@ +//go:build linux + +package isolation + +import ( + "context" + "os/exec" + "os/user" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" +) + +func runScheduledIdentity(ctx context.Context, identity, binary string, args []string, cwd string, env map[string]string) (ScheduleOutput, error) { + account, e := user.Lookup(identity) + if e != nil { + return ScheduleOutput{}, e + } + uid, e := strconv.ParseUint(account.Uid, 10, 32) + if e != nil || uid == 0 { + return ScheduleOutput{}, syscall.EPERM + } + gid, e := strconv.ParseUint(account.Gid, 10, 32) + if e != nil || gid == 0 { + return ScheduleOutput{}, syscall.EPERM + } + cmd := exec.CommandContext(ctx, binary, args...) + cmd.Dir = cwd + cmd.Env = []string{"PATH=" + filepath.Dir(binary) + ":/usr/bin:/bin", "HOME=/nonexistent", "LANG=C.UTF-8"} + for k, v := range env { + cmd.Env = append(cmd.Env, k+"="+v) + } + cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid), Groups: []uint32{uint32(gid)}}, Setpgid: true, Pdeathsig: syscall.SIGKILL} + cmd.Cancel = func() error { + if cmd.Process != nil { + return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } + return nil + } + cmd.WaitDelay = 3 * time.Second + buffer := &scheduleBuffer{} + cmd.Stdout = buffer + cmd.Stderr = buffer + e = cmd.Run() + out := ScheduleOutput{Output: strings.ToValidUTF8(string(buffer.data), "�"), Truncated: buffer.truncated} + if e != nil { + out.ExitCode = 1 + if exit, ok := e.(*exec.ExitError); ok { + out.ExitCode = exit.ExitCode() + } else { + return out, e + } + } + return out, nil +} + +type scheduleBuffer struct { + data []byte + truncated bool +} + +func (b *scheduleBuffer) Write(p []byte) (int, error) { + n := len(p) + if len(b.data)+n > 65536 { + b.truncated = true + p = p[:max(0, 65536-len(b.data))] + } + b.data = append(b.data, p...) + return n, nil +} diff --git a/backend/internal/isolation/schedule_execution_other.go b/backend/internal/isolation/schedule_execution_other.go new file mode 100644 index 0000000..a08f6af --- /dev/null +++ b/backend/internal/isolation/schedule_execution_other.go @@ -0,0 +1,12 @@ +//go:build !linux + +package isolation + +import ( + "context" + "errors" +) + +func runScheduledIdentity(context.Context, string, string, []string, string, map[string]string) (ScheduleOutput, error) { + return ScheduleOutput{}, errors.New("requires Linux") +} diff --git a/backend/internal/isolation/schedule_native_linux_test.go b/backend/internal/isolation/schedule_native_linux_test.go new file mode 100644 index 0000000..0f776c9 --- /dev/null +++ b/backend/internal/isolation/schedule_native_linux_test.go @@ -0,0 +1,13 @@ +//go:build linux + +package isolation +import("context";"fmt";"os";"os/user";"path/filepath";"strconv";"strings";"testing";"time") +func TestScheduledIdentityAndForeignPIDProtection(t *testing.T){ + identity:=os.Getenv("SEA_QA_HOST_IDENTITY");if identity==""{t.Skip("managed disposable identity not supplied")};if os.Geteuid()!=0||!managedWebHostPattern.MatchString(identity){t.Fatal("root test with a managed identity required")};account,e:=user.Lookup(identity);if e!=nil{t.Fatal(e)};uid,_:=strconv.Atoi(account.Uid);gid,_:=strconv.Atoi(account.Gid);if uid==0||gid==0{t.Fatal("refusing privileged identity")} + root,e:=os.MkdirTemp("/tmp","sea-vhost-schedule-native-");if e!=nil{t.Fatal(e)};defer os.RemoveAll(root);if e=os.Chown(root,uid,gid);e!=nil{t.Fatal(e)} + out,e:=runScheduledIdentity(context.Background(),identity,"/usr/bin/id",[]string{"-u"},root,nil);if e!=nil||strings.TrimSpace(out.Output)!=account.Uid{t.Fatal("scheduled task did not drop UID",e)} + marker:="$(touch "+filepath.Join(root,"injected")+")";out,e=runScheduledIdentity(context.Background(),identity,"/bin/sh",[]string{"-c",`printf '%s' "$QA_MARKER"`},root,map[string]string{"QA_MARKER":marker});if e!=nil||out.Output!=marker{t.Fatal("environment was not passed literally",e)};if _,e=os.Stat(filepath.Join(root,"injected"));!os.IsNotExist(e){t.Fatal("environment executed as shell")} + ctx,cancel:=context.WithTimeout(context.Background(),100*time.Millisecond);defer cancel();_,_=runScheduledIdentity(ctx,identity,"/bin/sh",[]string{"-c",`(sleep 1; echo escaped > escaped) & wait`},root,nil);time.Sleep(1300*time.Millisecond);if _,e=os.Stat(filepath.Join(root,"escaped"));!os.IsNotExist(e){t.Fatal("timed-out task left a normal descendant running")} + config:="/var/lib/sea-vhost-agent/php/"+identity+".conf";if e=signalPHPAsIdentity(context.Background(),config,"TERM",os.Getpid());e==nil{t.Fatal("unprivileged FPM identity signaled the root test runner")} + fmt.Println("isolated UID, literal environment, process-group timeout and foreign root PID protection passed") +} diff --git a/backend/internal/isolation/scheduler_bridge.go b/backend/internal/isolation/scheduler_bridge.go new file mode 100644 index 0000000..ba8482f --- /dev/null +++ b/backend/internal/isolation/scheduler_bridge.go @@ -0,0 +1,43 @@ +package isolation + +import ( + "context" + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "sea-vhost/internal/schedulerbridge" +) + +type SchedulerBridge interface { + ConfigureSchedulerBridge(context.Context, schedulerbridge.Config) error +} + +func (c *Client) ConfigureSchedulerBridge(ctx context.Context, v schedulerbridge.Config) error { + return c.request(ctx, "/v1/scheduler/configure", v, nil) +} +func (Mock) ConfigureSchedulerBridge(context.Context, schedulerbridge.Config) error { return nil } +func (a Agent) configureSchedulerBridge(w http.ResponseWriter, r *http.Request) { + var v schedulerbridge.Config + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || v.Validate() != nil { + http.Error(w, "invalid scheduler identity", 400) + return + } + if e := ensurePhysicalDirectory(filepath.Dir(schedulerbridge.ConfigPath), 0700); e != nil { + http.Error(w, "scheduler directory unavailable", 422) + return + } + raw, _ := json.Marshal(v) + if e := writePrivateFile(schedulerbridge.ConfigPath, raw); e != nil { + http.Error(w, "cannot save scheduler identity", 422) + return + } + if e := os.Chmod(schedulerbridge.ConfigPath, 0600); e != nil { + http.Error(w, "cannot secure scheduler identity", 422) + return + } + w.WriteHeader(200) +} diff --git a/backend/internal/isolation/site_operations.go b/backend/internal/isolation/site_operations.go new file mode 100644 index 0000000..adacb9b --- /dev/null +++ b/backend/internal/isolation/site_operations.go @@ -0,0 +1,229 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "regexp" + "sea-vhost/internal/hosting" + "strings" + "time" +) + +type WebsiteSpec struct { + Project ProjectSpec `json:"project"` + SiteName string `json:"siteName"` + Domain string `json:"domain"` + Runtime string `json:"runtime"` + Settings hosting.WebsiteSettings `json:"settings"` +} +type SiteLogSpec struct { + Project ProjectSpec `json:"project"` + SiteName string `json:"siteName"` + Domain string `json:"domain"` + Kind string `json:"kind"` + Lines int `json:"lines"` + Search string `json:"search"` +} +type SiteLog struct { + Available bool `json:"available"` + Lines []string `json:"lines"` + Truncated bool `json:"truncated"` +} +type SiteOperations interface { + ConfigureWebsite(context.Context, WebsiteSpec) error + ReadSiteLog(context.Context, SiteLogSpec) (SiteLog, error) +} + +func (c *Client) ConfigureWebsite(ctx context.Context, v WebsiteSpec) error { + return c.request(ctx, "/v1/site/settings", v, nil) +} +func (c *Client) ReadSiteLog(ctx context.Context, v SiteLogSpec) (SiteLog, error) { + var out SiteLog + e := c.request(ctx, "/v1/site/log", v, &out) + return out, e +} +func (Mock) ConfigureWebsite(context.Context, WebsiteSpec) error { return nil } +func (Mock) ReadSiteLog(context.Context, SiteLogSpec) (SiteLog, error) { + return SiteLog{Available: true, Lines: []string{}}, nil +} +func (a Agent) configureWebsite(w http.ResponseWriter, r *http.Request) { + var v WebsiteSpec + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || !webDomainPattern.MatchString(v.Domain) || v.Settings.Validate() != nil { + http.Error(w, "invalid website settings", 400) + return + } + if v.Runtime != "PHP" && v.Settings.Rewrite != "none" { + http.Error(w, "rewrite templates require PHP", 422) + return + } + paths, e := a.webProtectionPaths(WebProtectionSpec{Project: v.Project, Domain: v.Domain}) + if e != nil || verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension) != nil { + http.Error(w, "managed site unavailable", 412) + return + } + raw, e := os.ReadFile(paths.siteConfig) + root, _ := a.projectPath(v.Project) + if e != nil || !strings.Contains(string(raw), root) { + http.Error(w, "website does not match host root", 412) + return + } + content := regexp.MustCompile(`(?m)^[ \t]*index\s+[^;\n]+;[ \t]*\r?\n?`).ReplaceAllString(string(raw), "") + content = regexp.MustCompile(`(?m)^[ \t]*error_page\s+(?:404|503)\s+[^;\n]+;[ \t]*\r?\n?`).ReplaceAllString(content, "") + restoreMain, e := writeManagedFile(paths.siteConfig, []byte(content)) + if e != nil { + http.Error(w, "cannot stage website config", 412) + return + } + restoreSettings, e := writeManagedFile(filepath.Join(filepath.Dir(paths.siteExtension), "sea-vhost-site.conf"), []byte(renderWebsite(v.Settings))) + if e != nil { + restoreMain() + http.Error(w, "cannot stage settings", 412) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + if a.runNginx(ctx, "-t") != nil || a.runNginx(ctx, "-s", "reload") != nil { + restoreSettings() + restoreMain() + _ = a.runNginx(ctx, "-t") + _ = a.runNginx(ctx, "-s", "reload") + http.Error(w, "Nginx rejected settings; previous config restored", 422) + return + } + w.WriteHeader(200) +} +func renderWebsite(v hosting.WebsiteSettings) string { + var b strings.Builder + b.WriteString("# Managed by Sea vHost\nindex " + strings.Join(v.Index, " ") + ";\n") + if v.Error404 != "" { + fmt.Fprintf(&b, "error_page 404 /%s;\n", v.Error404) + } + if v.Error503 != "" { + fmt.Fprintf(&b, "error_page 503 /%s;\n", v.Error503) + } + if v.ForceHTTPS { + b.WriteString("set $svh_https_redirect 0;\nif ($scheme = http) { set $svh_https_redirect 1; }\nif ($uri ~ ^/\\.well-known/acme-challenge/) { set $svh_https_redirect 0; }\nif ($svh_https_redirect = 1) { return 301 https://$host$request_uri; }\n") + } + if v.Maintenance { + exclude := "^/(?:\\.well-known/acme-challenge/" + if v.Error503 != "" { + exclude += "|" + regexp.QuoteMeta(v.Error503) + "$" + } + exclude += ")" + fmt.Fprintf(&b, "if ($uri !~ %s) { return 503; }\n", exclude) + } + if v.RedirectURL != "" { + fmt.Fprintf(&b, "if ($uri !~ ^/\\.well-known/acme-challenge/) { return %d %s; }\n", v.RedirectCode, v.RedirectURL) + } + switch v.Rewrite { + case "wordpress", "laravel": + b.WriteString("location / { try_files $uri $uri/ /index.php?$query_string; }\n") + case "thinkphp": + b.WriteString("location / { try_files $uri $uri/ /index.php?s=$uri&$args; }\n") + case "spa": + b.WriteString("location / { try_files $uri $uri/ /index.html; }\n") + } + return b.String() +} + +var logBearer = regexp.MustCompile(`(?i)(authorization["' :=]+)(?:bearer|basic) +[^\s,;"']+`) +var logSecret = regexp.MustCompile(`(?i)(password|passwd|secret|token|authorization)(["' :=]+)([^\s&,;"']+)`) + +func (a Agent) readSiteLog(w http.ResponseWriter, r *http.Request) { + var v SiteLogSpec + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || !webDomainPattern.MatchString(v.Domain) || len(v.Search) > 200 { + http.Error(w, "invalid log request", 400) + return + } + root, e := a.projectPath(v.Project) + if e != nil || requirePhysicalDirectory(root) != nil { + http.Error(w, "host unavailable", 412) + return + } + dir := a.NginxLogRoot + if dir == "" { + dir = "/www/wwwlogs" + } + name := v.Domain + ".log" + switch v.Kind { + case "access": + case "error": + name = v.Domain + ".error.log" + case "runtime": + dir = root + name = ".sea-runtime/logs/" + v.SiteName + ".log" + case "php": + dir = root + name = ".sea-runtime/php/fpm-error.log" + default: + http.Error(w, "invalid log kind", 400) + return + } + result, e := tailSiteLog(dir, name, v.Lines, v.Search) + if e != nil { + http.Error(w, "cannot safely read site log", 422) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(result) +} +func tailSiteLog(dir, name string, lines int, search string) (SiteLog, error) { + out := SiteLog{Lines: []string{}} + if lines < 1 || lines > 1000 { + lines = 200 + } + root, e := os.OpenRoot(dir) + if e != nil { + return out, e + } + defer root.Close() + i, e := root.Lstat(name) + if errors.Is(e, os.ErrNotExist) { + return out, nil + } + if e != nil || !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 { + return out, errors.New("unsafe log") + } + f, e := root.Open(name) + if e != nil { + return out, e + } + defer f.Close() + size := i.Size() + offset := int64(0) + if size > 256<<10 { + offset = size - (256 << 10) + out.Truncated = true + } + f.Seek(offset, io.SeekStart) + raw, e := io.ReadAll(io.LimitReader(f, 256<<10)) + if e != nil { + return out, e + } + text := strings.ToValidUTF8(string(raw), "�") + all := strings.Split(strings.TrimSuffix(text, "\n"), "\n") + if offset > 0 && len(all) > 0 { + all = all[1:] + } + for _, line := range all { + if search == "" || strings.Contains(strings.ToLower(line), strings.ToLower(search)) { + out.Lines = append(out.Lines, logSecret.ReplaceAllString(logBearer.ReplaceAllString(line, "${1}[REDACTED]"), "${1}${2}[REDACTED]")) + } + } + if len(out.Lines) > lines { + out.Lines = out.Lines[len(out.Lines)-lines:] + out.Truncated = true + } + out.Available = true + return out, nil +} diff --git a/backend/internal/isolation/startup.go b/backend/internal/isolation/startup.go new file mode 100644 index 0000000..f9ba289 --- /dev/null +++ b/backend/internal/isolation/startup.go @@ -0,0 +1,143 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "os/user" + "path/filepath" + "regexp" + "sea-vhost/internal/hosting" + "strconv" + "strings" +) + +const startupStateRoot = "/var/lib/sea-vhost-agent/startup" + +type StartupSpec struct { + Project ProjectSpec `json:"project"` + SiteName string `json:"siteName"` + Runtime string `json:"runtime"` + Version string `json:"version"` + Port int `json:"port"` + Config hosting.Startup `json:"config"` +} +type StartupManager interface { + ConfigureStartup(context.Context, StartupSpec) error +} + +func (c *Client) ConfigureStartup(ctx context.Context, v StartupSpec) error { + return c.request(ctx, "/v1/site/startup", v, nil) +} +func (Mock) ConfigureStartup(context.Context, StartupSpec) error { return nil } +func (a Agent) configureStartup(w http.ResponseWriter, r *http.Request) { + var v StartupSpec + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || v.Config.Validate() != nil || !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$`).MatchString(v.Version) { + http.Error(w, "invalid startup settings", 400) + return + } + if e := a.prepareStartup(r.Context(), v); e != nil { + http.Error(w, "cannot prepare safe application launcher", 422) + return + } + w.WriteHeader(200) +} +func (a Agent) prepareStartup(ctx context.Context, v StartupSpec) error { + if v.SiteName != v.Project.HostName && !strings.HasPrefix(v.SiteName, v.Project.HostName+"_") { + return errors.New("site identity mismatch") + } + root, e := a.projectPath(v.Project) + if e != nil { + return e + } + working, e := physicalRunDirectory(root, v.Project.RunPath) + if e != nil { + return e + } + cwd := working + if v.Config.WorkDir != "." && v.Config.WorkDir != "" { + cwd, e = physicalRunDirectory(root, filepath.ToSlash(filepath.Join(v.Project.RunPath, v.Config.WorkDir))) + if e != nil { + return e + } + } + account, e := user.Lookup(v.Project.HostName) + if e != nil { + return e + } + uid, e := strconv.ParseUint(account.Uid, 10, 32) + if e != nil || uid == 0 { + return errors.New("invalid uid") + } + entry := filepath.Join(working, v.Config.EntryFile) + var binary string + var args []string + switch v.Runtime { + case "PHP": + binary = filepath.Join("/www/server/php", strings.ReplaceAll(v.Version, ".", ""), "bin/php") + case "Node.js": + binary = filepath.Join("/www/server/nodejs", v.Version, "bin/npm") + args = []string{"run", "start", "--"} + case "Python": + binary = filepath.Join(working, ".sea-runtime/python", v.SiteName+"-"+v.Version, "bin/python3") + args = []string{entry} + case "Go": + binary = entry + case "Java": + binary = filepath.Join("/www/server/java", v.Version, "bin/java") + args = []string{"-jar", entry, "--server.port=" + strconv.Itoa(v.Port)} + default: + return errors.New("invalid runtime") + } + if i, e := os.Stat(binary); e != nil || !i.Mode().IsRegular() || i.Mode()&0111 == 0 { + return errors.New("runtime executable not found") + } + args = append(args, v.Config.Arguments...) + if e = ensureProjectRunDirectory(root, "/.sea-runtime/logs"); e != nil { + return e + } + logdir, e := physicalRunDirectory(root, "/.sea-runtime/logs") + if e != nil { + return e + } + if e = a.command(ctx, "chown", a.fileServiceOwner()+":"+v.Project.HostName, logdir); e != nil { + return e + } + if e = a.command(ctx, "chmod", "0770", logdir); e != nil { + return e + } + if e = a.command(ctx, "setfacl", "-m", "u:www:---,m::rwx,o::---", logdir); e != nil { + return e + } + if e = ensurePhysicalDirectory(startupStateRoot, 0711); e != nil { + return e + } + if e = os.Chmod(startupStateRoot, 0711); e != nil { + return e + } + config := hosting.RunnerConfig{UID: uint32(uid), HostName: v.Project.HostName, Binary: binary, Arguments: args, Environment: v.Config.Environment, WorkDir: cwd, LogDir: logdir, SiteName: v.SiteName} + if config.Environment == nil { + config.Environment = map[string]string{} + } + config.Environment["PORT"] = strconv.Itoa(v.Port) + raw, _ := json.Marshal(config) + file := filepath.Join(startupStateRoot, v.SiteName+".json") + if e = writePrivateFile(file, raw); e != nil { + return e + } + if e = a.command(ctx, "chown", "root:"+v.Project.HostName, file); e != nil { + return e + } + return a.command(ctx, "chmod", "0640", file) +} +func (a Agent) fileServiceOwner() string { + if a.FileOwner != "" { + return a.FileOwner + } + return "sea-vhost" +} diff --git a/backend/internal/isolation/traffic_limits.go b/backend/internal/isolation/traffic_limits.go new file mode 100644 index 0000000..35cce3d --- /dev/null +++ b/backend/internal/isolation/traffic_limits.go @@ -0,0 +1,203 @@ +package isolation + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "time" +) + +var trafficPolicyMu sync.Mutex +var ftpAltLogLine = regexp.MustCompile(`(?mi)^\s*AltLog\s+[^\r\n]*`) + +func (a Agent) configureTrafficLimits(w http.ResponseWriter, r *http.Request) { + var spec TrafficLimitSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Mbps > 10000 || !validUsageSpec(ResourceUsageSpec{Project: spec.Project, Domains: spec.Domains}) || len(spec.Domains) > 100 { + http.Error(w, "invalid traffic policy", 400) + return + } + root, err := a.projectPath(spec.Project) + if err != nil || requirePhysicalDirectory(root) != nil { + http.Error(w, "managed project root unavailable", 412) + return + } + trafficPolicyMu.Lock() + defer trafficPolicyMu.Unlock() + ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) + defer cancel() + if err = a.applyTrafficLimits(ctx, spec); err != nil { + http.Error(w, "cannot enforce traffic policy: "+err.Error(), 412) + return + } + w.WriteHeader(200) +} + +func (a Agent) trafficLimitStatePath(host string) (string, error) { + path := a.UsageStatePath + if path == "" { + path = "/var/lib/sea-vhost-agent/traffic.json" + } + dir := filepath.Join(filepath.Dir(path), "limits") + if err := os.MkdirAll(dir, 0700); err != nil { + return "", err + } + if err := requirePhysicalDirectory(dir); err != nil { + return "", err + } + return filepath.Join(dir, host+".json"), nil +} + +func (a Agent) applyTrafficLimits(ctx context.Context, spec TrafficLimitSpec) error { + var restore []func() error + changed := false + rollback := func() { + for _, f := range restore { + _ = f() + } + _ = a.runNginx(ctx, "-t") + _ = a.runNginx(ctx, "-s", "reload") + } + for _, domain := range spec.Domains { + paths, err := a.webProtectionPaths(WebProtectionSpec{Project: spec.Project, Domain: domain}) + if err != nil { + rollback() + return err + } + if err = verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension); err != nil { + rollback() + return err + } + target := filepath.Join(filepath.Dir(paths.siteExtension), "sea-vhost-rate.conf") + content := []byte("# Managed Sea vHost HTTP rate: per request, not aggregate host speed.\nlimit_rate " + strconv.FormatUint(uint64(spec.Mbps)*125000, 10) + ";\nlimit_rate_after 0;\nproxy_ignore_headers X-Accel-Limit-Rate;\nfastcgi_ignore_headers X-Accel-Limit-Rate;\n") + old, err := os.ReadFile(target) + if err == nil && bytes.Equal(old, content) { + continue + } + undo, err := writeManagedFile(target, content) + if err != nil { + rollback() + return err + } + restore = append(restore, undo) + changed = true + } + if changed { + if err := a.runNginx(ctx, "-t"); err != nil { + rollback() + return errors.New("Nginx rejected bandwidth limit") + } + if err := a.runNginx(ctx, "-s", "reload"); err != nil { + rollback() + return err + } + } + statePath, err := a.trafficLimitStatePath(spec.Project.HostName) + if err != nil { + return err + } + var previous struct { + Mbps uint32 `json:"mbps"` + Applied bool `json:"applied"` + } + if info, err := os.Lstat(statePath); err == nil { + if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("unsafe traffic policy state") + } + data, err := os.ReadFile(statePath) + if err != nil { + return err + } + _ = json.Unmarshal(data, &previous) + } + if !previous.Applied || previous.Mbps != spec.Mbps { + binary := a.PurePWBinary + if binary == "" { + binary = "/www/server/pure-ftpd/bin/pure-pw" + } + rate := "" + if spec.Mbps > 0 { + rate = strconv.FormatUint(uint64(spec.Mbps)*125000/1024, 10) + } + if err = a.command(ctx, binary, "usermod", spec.Project.HostName, "-t", rate, "-T", rate, "-m"); err != nil { + return errors.New("cannot set FTP account transfer limit") + } + data, _ := json.Marshal(map[string]any{"mbps": spec.Mbps, "applied": true}) + if err = writeSecureFile(statePath, data, 0600); err != nil { + return err + } + } + return a.ensureFTPTransferLog(ctx) +} + +func (a Agent) ftpTransferLogPath() string { + if a.FTPLogPath != "" { + return a.FTPLogPath + } + return "/www/wwwlogs/sea-vhost-ftp.log" +} + +func (a Agent) ensureFTPTransferLog(ctx context.Context) error { + configPath := a.PureFTPConfig + if configPath == "" { + configPath = "/www/server/pure-ftpd/etc/pure-ftpd.conf" + } + info, err := os.Lstat(configPath) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("unsafe FTP configuration") + } + content, err := os.ReadFile(configPath) + if err != nil { + return err + } + logPath := a.ftpTransferLogPath() + if !filepath.IsAbs(logPath) || strings.ContainsAny(logPath, "\r\n\x00 ") { + return errors.New("invalid FTP transfer log path") + } + wanted := []byte("AltLog stats:" + logPath) + matches := ftpAltLogLine.FindAll(content, -1) + if len(matches) == 1 && bytes.Equal(bytes.TrimSpace(matches[0]), wanted) { + return nil + } + if requirePhysicalDirectory(filepath.Dir(logPath)) != nil { + return errors.New("FTP log directory unavailable") + } + if existing, err := os.Lstat(logPath); err == nil { + if !existing.Mode().IsRegular() || existing.Mode()&os.ModeSymlink != 0 { + return errors.New("unsafe FTP log") + } + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + if len(matches) > 0 { + backup := configPath + ".sea-vhost-before-stats" + if _, err = os.Lstat(backup); errors.Is(err, os.ErrNotExist) { + if err = writeSecureFile(backup, content, 0600); err != nil { + return err + } + } + } + updated := ftpAltLogLine.ReplaceAll(content, nil) + updated = append(bytes.TrimRight(updated, "\r\n"), '\n') + updated = append(updated, wanted...) + updated = append(updated, '\n') + if err = writeSecureFile(configPath, updated, info.Mode().Perm()); err != nil { + return err + } + if err = a.restartPureFTP(ctx, configPath); err != nil { + _ = writeSecureFile(configPath, content, info.Mode().Perm()) + _ = a.restartPureFTP(ctx, configPath) + return errors.New("cannot activate FTP transfer log") + } + return nil +} diff --git a/backend/internal/isolation/web_protection.go b/backend/internal/isolation/web_protection.go new file mode 100644 index 0000000..ac1fa3e --- /dev/null +++ b/backend/internal/isolation/web_protection.go @@ -0,0 +1,360 @@ +package isolation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "time" +) + +const globalWebProtectionConfig = `# Managed by Sea vHost. Local changes will be replaced. +limit_req_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip:10m rate=20r/s; +limit_conn_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip_conn:10m; +` + +const siteWebProtectionConfig = `# Managed by Sea vHost. Local changes will be replaced. +limit_req zone=sea_vhost_per_ip burst=60 nodelay; +limit_req_status 429; +limit_conn sea_vhost_per_ip_conn 40; +limit_conn_status 429; +client_max_body_size 64m; +client_body_timeout 30s; +client_header_timeout 15s; +send_timeout 60s; +disable_symlinks if_not_owner from=$document_root; + +add_header X-Content-Type-Options "nosniff" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; + +if ($request_method ~* ^(TRACE|TRACK)$) { return 405; } +location ~* "(^|/)\.(?!well-known(?:/|$))" { return 404; } +location ~* "\.(?:env|ini|log|sql|sqlite|bak|old|orig|swp)$" { return 404; } +location ~* "(^|/)(?:composer\.(?:json|lock)|package(?:-lock)?\.json|yarn\.lock|pnpm-lock\.yaml|requirements(?:-[^/]+)?\.txt|Pipfile(?:\.lock)?|go\.(?:mod|sum)|pom\.xml|build\.gradle(?:\.kts)?)$" { return 404; } +` + +var ( + managedWebHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`) + webDomainPattern = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)$`) +) + +type managedFileSnapshot struct { + existed bool + content []byte +} + +func (a Agent) decodeWebProtection(w http.ResponseWriter, r *http.Request) (WebProtectionSpec, bool) { + var spec WebProtectionSpec + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || + !managedWebHostPattern.MatchString(spec.Project.HostName) || !webDomainPattern.MatchString(spec.Domain) || + spec.Project.TenantID == 0 || spec.Project.TenantID > 9_999_999_999 || spec.Project.StorageBytes == 0 || + spec.Project.ProcessLimit == 0 || spec.Project.ProcessLimit > 100_000 { + http.Error(w, "invalid request", http.StatusBadRequest) + return WebProtectionSpec{}, false + } + return spec, true +} + +func (a Agent) applyWebProtection(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decodeWebProtection(w, r) + if !ok { + return + } + paths, err := a.webProtectionPaths(spec) + if err != nil { + http.Error(w, "web protection path is unavailable", http.StatusPreconditionFailed) + return + } + if err = verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension); err != nil { + http.Error(w, "aaPanel site extension include is unavailable", http.StatusPreconditionFailed) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + if err = verifyGlobalWebProtection(paths.globalConfig); err != nil { + http.Error(w, "global web protection is missing or invalid", http.StatusPreconditionFailed) + return + } + challenge, err := httpChallengeConfig(paths.challengeRoot) + if err != nil { + http.Error(w, "invalid challenge root", http.StatusPreconditionFailed) + return + } + restoreSite, err := writeManagedFile(paths.siteExtension, []byte(siteWebProtectionConfig+challenge)) + if err != nil { + http.Error(w, "cannot write site web protection", http.StatusInternalServerError) + return + } + rollback := func() { + _ = restoreSite() + _ = a.runNginx(ctx, "-t") + _ = a.runNginx(ctx, "-s", "reload") + } + if err = a.runNginx(ctx, "-t"); err != nil { + slog.Error("nginx rejected site web protection", "domain", spec.Domain, "error", err) + rollback() + http.Error(w, "nginx rejected web protection configuration", http.StatusPreconditionFailed) + return + } + if err = a.runNginx(ctx, "-s", "reload"); err != nil { + rollback() + http.Error(w, "cannot reload nginx", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +func verifyGlobalWebProtection(path string) error { + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 128<<10 { + return errors.New("unsafe global web protection file") + } + content, err := os.ReadFile(path) + if err != nil { + return err + } + normalized := strings.ReplaceAll(string(content), "\r\n", "\n") + if normalized != globalWebProtectionConfig { + return errors.New("global web protection content mismatch") + } + return nil +} + +func (a Agent) removeWebProtection(w http.ResponseWriter, r *http.Request) { + spec, ok := a.decodeWebProtection(w, r) + if !ok { + return + } + paths, err := a.webProtectionPaths(spec) + if err != nil { + http.Error(w, "web protection path is unavailable", http.StatusPreconditionFailed) + return + } + info, err := os.Lstat(paths.siteExtension) + if errors.Is(err, os.ErrNotExist) { + w.WriteHeader(http.StatusOK) + return + } + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + http.Error(w, "unsafe site web protection file", http.StatusPreconditionFailed) + return + } + content, err := os.ReadFile(paths.siteExtension) + if err != nil || len(content) > 128<<10 { + http.Error(w, "cannot read site web protection", http.StatusInternalServerError) + return + } + if err = os.Remove(paths.siteExtension); err != nil { + http.Error(w, "cannot remove site web protection", http.StatusInternalServerError) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + restore := func() { _, _ = writeManagedFile(paths.siteExtension, content) } + if err = a.runNginx(ctx, "-t"); err != nil { + restore() + http.Error(w, "nginx rejected protection removal", http.StatusPreconditionFailed) + return + } + if err = a.runNginx(ctx, "-s", "reload"); err != nil { + restore() + _ = a.runNginx(ctx, "-t") + _ = a.runNginx(ctx, "-s", "reload") + http.Error(w, "cannot reload nginx", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} + +type protectionPaths struct { + globalConfig, siteConfig, siteExtension, projectRoot, challengeRoot string +} + +func (a Agent) webProtectionPaths(spec WebProtectionSpec) (protectionPaths, error) { + projectRoot, err := a.projectPath(spec.Project) + if err != nil { + return protectionPaths{}, err + } + if err = requirePhysicalDirectory(projectRoot); err != nil { + return protectionPaths{}, err + } + runPath := spec.Project.RunPath + if runPath == "" { + runPath = "/" + } + challengeRoot, err := physicalRunDirectory(projectRoot, runPath) + if err != nil { + return protectionPaths{}, err + } + vhostRoot, err := filepath.Abs(a.NginxVhostRoot) + if err != nil || !filepath.IsAbs(vhostRoot) { + return protectionPaths{}, errors.New("invalid nginx vhost root") + } + if err = requirePhysicalDirectory(vhostRoot); err != nil { + return protectionPaths{}, err + } + extensionRoot := filepath.Join(vhostRoot, "extension") + if err = ensurePhysicalDirectory(extensionRoot, 0755); err != nil { + return protectionPaths{}, err + } + domainRoot := filepath.Join(extensionRoot, strings.ToLower(spec.Domain)) + if err = ensurePhysicalDirectory(domainRoot, 0755); err != nil { + return protectionPaths{}, err + } + return protectionPaths{ + projectRoot: projectRoot, + challengeRoot: challengeRoot, + globalConfig: filepath.Join(vhostRoot, "sea-vhost-security-global.conf"), + siteConfig: filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf"), + siteExtension: filepath.Join(domainRoot, "sea-vhost-security.conf"), + }, nil +} + +func verifySiteExtensionInclude(siteConfig, extension string) error { + info, err := os.Lstat(siteConfig) + if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 2<<20 { + return errors.New("unsafe aaPanel site config") + } + content, err := os.ReadFile(siteConfig) + if err != nil { + return err + } + expected := filepath.ToSlash(filepath.Dir(extension)) + "/*.conf" + if !strings.Contains(filepath.ToSlash(string(content)), expected) { + return errors.New("site config does not include the managed extension directory") + } + return nil +} + +func ensurePhysicalDirectory(path string, mode os.FileMode) error { + if err := requirePhysicalDirectory(filepath.Dir(path)); err != nil { + return err + } + if err := os.Mkdir(path, mode); err != nil && !errors.Is(err, os.ErrExist) { + return err + } + return requirePhysicalDirectory(path) +} + +func requirePhysicalDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("path is not a physical directory") + } + return nil +} + +func writeManagedFile(path string, content []byte) (func() error, error) { + if len(content) > 128<<10 { + return nil, errors.New("managed file is too large") + } + snapshot := managedFileSnapshot{} + info, err := os.Lstat(path) + if err == nil { + if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 128<<10 { + return nil, errors.New("managed file target is unsafe") + } + snapshot.existed = true + snapshot.content, err = os.ReadFile(path) + if err != nil { + return nil, err + } + } else if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + directory := filepath.Dir(path) + if err = requirePhysicalDirectory(directory); err != nil { + return nil, err + } + temporary, err := os.CreateTemp(directory, ".sea-vhost-security-*") + if err != nil { + return nil, err + } + temporaryName := temporary.Name() + defer os.Remove(temporaryName) + if err = temporary.Chmod(0644); err == nil { + _, err = temporary.Write(content) + } + if syncErr := temporary.Sync(); err == nil { + err = syncErr + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err != nil { + return nil, err + } + if err = os.Rename(temporaryName, path); err != nil { + return nil, err + } + restore := func() error { + if !snapshot.existed { + return os.Remove(path) + } + _, restoreErr := writeManagedFileWithoutSnapshot(path, snapshot.content) + return restoreErr + } + return restore, nil +} + +func writeManagedFileWithoutSnapshot(path string, content []byte) (string, error) { + directory := filepath.Dir(path) + temporary, err := os.CreateTemp(directory, ".sea-vhost-restore-*") + if err != nil { + return "", err + } + name := temporary.Name() + defer os.Remove(name) + if err = temporary.Chmod(0644); err == nil { + _, err = temporary.Write(content) + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(name, path) + } + return path, err +} + +func (a Agent) runNginx(ctx context.Context, args ...string) error { + binary := strings.TrimSpace(a.NginxBinary) + if !filepath.IsAbs(binary) || filepath.Base(binary) != "nginx" { + return errors.New("invalid nginx binary") + } + if a.runCommand != nil { + return a.runCommand(ctx, binary, args...) + } + if err := command(ctx, binary, args...); err != nil { + return fmt.Errorf("nginx %s: %w", strings.Join(args, " "), err) + } + return nil +} + +func httpChallengeConfig(root string) (string, error) { + if !filepath.IsAbs(root) || strings.ContainsAny(filepath.ToSlash(root), "$;{}\r\n\x00\"\\") { + return "", errors.New("unsafe ACME root") + } + return fmt.Sprintf(` +# ACME tokens use the same physical run directory as aaPanel issuance and renewal, including proxied sites. +location ^~ /.well-known/acme-challenge/ { + root %q; + default_type text/plain; + disable_symlinks on; + limit_except GET { deny all; } + try_files $uri =404; +} +`, filepath.ToSlash(root)), nil +} diff --git a/backend/internal/migrations/001_initial.sql b/backend/internal/migrations/001_initial.sql new file mode 100644 index 0000000..bb95370 --- /dev/null +++ b/backend/internal/migrations/001_initial.sql @@ -0,0 +1,153 @@ +CREATE TABLE IF NOT EXISTS schema_migrations ( + version VARCHAR(64) PRIMARY KEY, + applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS plans ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(80) NOT NULL, + storage_bytes BIGINT UNSIGNED NOT NULL, + database_bytes BIGINT UNSIGNED NOT NULL, + monthly_bandwidth_bytes BIGINT UNSIGNED NOT NULL, + process_limit INT UNSIGNED NOT NULL, + ftp_limit INT UNSIGNED NOT NULL DEFAULT 1, + database_limit INT UNSIGNED NOT NULL DEFAULT 1, + project_limit INT UNSIGNED NOT NULL DEFAULT 10, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS tenants ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + slug VARCHAR(48) NOT NULL UNIQUE, + name VARCHAR(120) NOT NULL, + status ENUM('active','suspended') NOT NULL DEFAULT 'active', + plan_id BIGINT UNSIGNED NOT NULL, + expires_at DATETIME NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_tenants_plan FOREIGN KEY (plan_id) REFERENCES plans(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS users ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NULL, + email VARCHAR(190) NOT NULL UNIQUE, + display_name VARCHAR(80) NOT NULL, + password_hash VARCHAR(255) NOT NULL, + role ENUM('admin','tenant') NOT NULL, + status ENUM('active','disabled') NOT NULL DEFAULT 'active', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_users_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + INDEX idx_users_tenant (tenant_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS sessions ( + token_hash BINARY(32) PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL, + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_sessions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_sessions_expires (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS projects ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + slug VARCHAR(50) NOT NULL, + runtime ENUM('PHP','Node.js','Python','Go','Java') NOT NULL, + runtime_version VARCHAR(40) NOT NULL, + root_path VARCHAR(500) NOT NULL, + assigned_domain VARCHAR(253) NOT NULL UNIQUE, + panel_site_id BIGINT NULL, + backend_port INT UNSIGNED NULL, + process_limit INT UNSIGNED NOT NULL, + auto_ssl BOOLEAN NOT NULL DEFAULT TRUE, + ssl_status ENUM('off','pending','active','failed') NOT NULL DEFAULT 'pending', + status ENUM('provisioning','awaiting_upload','running','stopped','failed','quota_suspended') NOT NULL DEFAULT 'provisioning', + last_error VARCHAR(500) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_projects_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + UNIQUE KEY uk_projects_tenant_slug (tenant_id, slug), + INDEX idx_projects_tenant (tenant_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS domains ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NOT NULL, + domain VARCHAR(253) NOT NULL UNIQUE, + kind ENUM('assigned','custom') NOT NULL, + status ENUM('pending','approved','rejected') NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_domains_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + CONSTRAINT fk_domains_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE, + INDEX idx_domains_tenant (tenant_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS ftp_accounts ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NOT NULL UNIQUE, + panel_ftp_id BIGINT NULL, + username VARCHAR(64) NOT NULL UNIQUE, + password_ciphertext VARBINARY(1024) NULL, + root_path VARCHAR(500) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_ftp_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + CONSTRAINT fk_ftp_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `databases` ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NOT NULL UNIQUE, + panel_database_id BIGINT NULL, + name VARCHAR(64) NOT NULL UNIQUE, + username VARCHAR(64) NOT NULL UNIQUE, + password_ciphertext VARBINARY(1024) NULL, + size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + status ENUM('active','quota_suspended') NOT NULL DEFAULT 'active', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_databases_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + CONSTRAINT fk_databases_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS quota_usage ( + tenant_id BIGINT UNSIGNED PRIMARY KEY, + storage_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + database_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + bandwidth_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + process_count INT UNSIGNED NOT NULL DEFAULT 0, + period_start DATE NOT NULL, + measured_at DATETIME NOT NULL, + CONSTRAINT fk_usage_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS operation_logs ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NULL, + user_id BIGINT UNSIGNED NULL, + action VARCHAR(80) NOT NULL, + resource_type VARCHAR(40) NOT NULL, + resource_id VARCHAR(80) NULL, + ip_address VARCHAR(45) NULL, + success BOOLEAN NOT NULL, + detail VARCHAR(500) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_logs_tenant_created (tenant_id, created_at), + CONSTRAINT fk_logs_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE SET NULL, + CONSTRAINT fk_logs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS system_settings ( + setting_key VARCHAR(80) PRIMARY KEY, + setting_value VARCHAR(500) NOT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT INTO system_settings(setting_key, setting_value) VALUES ('domain_approval', 'true') +ON DUPLICATE KEY UPDATE setting_key=VALUES(setting_key); + +INSERT INTO plans (id, name, storage_bytes, database_bytes, monthly_bandwidth_bytes, process_limit, ftp_limit, database_limit, project_limit) +VALUES (1, '标准套餐', 53687091200, 21474836480, 536870912000, 100, 10, 10, 10) +ON DUPLICATE KEY UPDATE name=VALUES(name); diff --git a/backend/internal/migrations/002_remove_docker_runtime.sql b/backend/internal/migrations/002_remove_docker_runtime.sql new file mode 100644 index 0000000..9eb43c7 --- /dev/null +++ b/backend/internal/migrations/002_remove_docker_runtime.sql @@ -0,0 +1,2 @@ +ALTER TABLE projects + MODIFY COLUMN runtime ENUM('PHP','Node.js','Python','Go','Java') NOT NULL diff --git a/backend/internal/migrations/003_random_host_names.sql b/backend/internal/migrations/003_random_host_names.sql new file mode 100644 index 0000000..648be13 --- /dev/null +++ b/backend/internal/migrations/003_random_host_names.sql @@ -0,0 +1,7 @@ +ALTER TABLE projects ADD COLUMN host_name VARCHAR(24) NULL AFTER tenant_id; + +UPDATE projects SET host_name=CONCAT('sv', LPAD(RIGHT(LOWER(HEX(id)), 10), 10, '0')) WHERE host_name IS NULL; + +ALTER TABLE projects MODIFY COLUMN host_name VARCHAR(24) NOT NULL; + +ALTER TABLE projects ADD UNIQUE KEY uk_projects_host_name (host_name); diff --git a/backend/internal/migrations/004_project_run_path.sql b/backend/internal/migrations/004_project_run_path.sql new file mode 100644 index 0000000..83a9a7e --- /dev/null +++ b/backend/internal/migrations/004_project_run_path.sql @@ -0,0 +1 @@ +ALTER TABLE projects ADD COLUMN run_path VARCHAR(255) NOT NULL DEFAULT '/' AFTER root_path; diff --git a/backend/internal/migrations/005_host_accounts_and_sites.sql b/backend/internal/migrations/005_host_accounts_and_sites.sql new file mode 100644 index 0000000..3fc9e86 --- /dev/null +++ b/backend/internal/migrations/005_host_accounts_and_sites.sql @@ -0,0 +1,53 @@ +ALTER TABLE users MODIFY COLUMN role ENUM('admin','tenant','host') NOT NULL; + +ALTER TABLE users ADD COLUMN login_name VARCHAR(190) NULL AFTER tenant_id; + +ALTER TABLE users ADD COLUMN project_id BIGINT UNSIGNED NULL AFTER tenant_id; + +UPDATE users SET login_name=email WHERE login_name IS NULL; + +ALTER TABLE users ADD UNIQUE KEY uk_users_login_name (login_name); + +ALTER TABLE users ADD INDEX idx_users_project (project_id); + +ALTER TABLE users ADD CONSTRAINT fk_users_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE; + +CREATE TABLE IF NOT EXISTS sites ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NOT NULL, + slug VARCHAR(50) NOT NULL, + assigned_domain VARCHAR(253) NOT NULL UNIQUE, + run_path VARCHAR(255) NOT NULL DEFAULT '/', + runtime ENUM('PHP','Node.js','Python','Go','Java') NOT NULL, + runtime_version VARCHAR(40) NOT NULL, + panel_site_id BIGINT NULL, + backend_port INT UNSIGNED NULL, + process_limit INT UNSIGNED NOT NULL, + auto_ssl BOOLEAN NOT NULL DEFAULT TRUE, + ssl_status ENUM('off','pending','active','failed') NOT NULL DEFAULT 'pending', + status ENUM('provisioning','awaiting_upload','running','stopped','failed','quota_suspended') NOT NULL DEFAULT 'provisioning', + is_primary BOOLEAN NOT NULL DEFAULT FALSE, + last_error VARCHAR(500) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_sites_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + CONSTRAINT fk_sites_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE, + UNIQUE KEY uk_sites_project_slug (project_id, slug), + UNIQUE KEY uk_sites_panel_site (panel_site_id), + INDEX idx_sites_project (project_id), + INDEX idx_sites_tenant (tenant_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT INTO sites(tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,panel_site_id,backend_port,process_limit,auto_ssl,ssl_status,status,is_primary,created_at) +SELECT tenant_id,id,slug,assigned_domain,run_path,runtime,runtime_version,panel_site_id,backend_port,process_limit,auto_ssl,ssl_status,status,TRUE,created_at +FROM projects +WHERE panel_site_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sites WHERE sites.project_id=projects.id AND sites.is_primary=TRUE); + +ALTER TABLE domains ADD COLUMN site_id BIGINT UNSIGNED NULL AFTER project_id; + +UPDATE domains d JOIN sites s ON s.project_id=d.project_id AND s.is_primary=TRUE SET d.site_id=s.id WHERE d.site_id IS NULL; + +ALTER TABLE domains ADD INDEX idx_domains_site (site_id); + +ALTER TABLE domains ADD CONSTRAINT fk_domains_site FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE; diff --git a/backend/internal/migrations/006_account_security.sql b/backend/internal/migrations/006_account_security.sql new file mode 100644 index 0000000..1b70cbc --- /dev/null +++ b/backend/internal/migrations/006_account_security.sql @@ -0,0 +1,11 @@ +ALTER TABLE users ADD COLUMN totp_secret_ciphertext VARBINARY(1024) NULL AFTER password_hash; + +ALTER TABLE users ADD COLUMN totp_enabled BOOLEAN NOT NULL DEFAULT FALSE AFTER totp_secret_ciphertext; + +CREATE TABLE IF NOT EXISTS mfa_recovery_codes ( + user_id BIGINT UNSIGNED NOT NULL, + code_hash BINARY(32) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (user_id, code_hash), + CONSTRAINT fk_mfa_recovery_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/007_dns_certificates.sql b/backend/internal/migrations/007_dns_certificates.sql new file mode 100644 index 0000000..18960a2 --- /dev/null +++ b/backend/internal/migrations/007_dns_certificates.sql @@ -0,0 +1,37 @@ +CREATE TABLE IF NOT EXISTS dns_credentials ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + scope_key VARCHAR(64) NOT NULL, + tenant_id BIGINT UNSIGNED NULL, + secret_ref CHAR(32) NOT NULL UNIQUE, + label VARCHAR(80) NOT NULL, + provider ENUM('cloudflare','aliyun','tencent') NOT NULL, + zone_name VARCHAR(253) NOT NULL, + credential_ciphertext VARBINARY(4096) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_dns_credentials_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + UNIQUE KEY uk_dns_credentials_scope_zone (scope_key, zone_name), + INDEX idx_dns_credentials_tenant (tenant_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS system_secrets ( + secret_key VARCHAR(80) PRIMARY KEY, + secret_ciphertext VARBINARY(4096) NOT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS certificate_automations ( + site_id BIGINT UNSIGNED PRIMARY KEY, + mode ENUM('off','manual','http-01','dns-01') NOT NULL DEFAULT 'off', + expires_at DATETIME NULL, + last_attempt_at DATETIME NULL, + next_attempt_at DATETIME NULL, + last_error VARCHAR(500) NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_certificate_automations_site FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE, + INDEX idx_certificate_automations_due (mode, next_attempt_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT INTO certificate_automations(site_id,mode) +SELECT id,IF(auto_ssl,'http-01',IF(ssl_status='active','manual','off')) FROM sites +ON DUPLICATE KEY UPDATE site_id=VALUES(site_id); diff --git a/backend/internal/migrations/008_dns_credential_tests.sql b/backend/internal/migrations/008_dns_credential_tests.sql new file mode 100644 index 0000000..f742456 --- /dev/null +++ b/backend/internal/migrations/008_dns_credential_tests.sql @@ -0,0 +1,5 @@ +ALTER TABLE dns_credentials + ADD COLUMN last_tested_at DATETIME NULL AFTER credential_ciphertext, + ADD COLUMN test_status ENUM('untested','testing','passed','failed') NOT NULL DEFAULT 'untested' AFTER last_tested_at, + ADD COLUMN test_error VARCHAR(500) NULL AFTER test_status, + ADD INDEX idx_dns_credentials_test_status (test_status, last_tested_at); diff --git a/backend/internal/migrations/009_hosting_administration.sql b/backend/internal/migrations/009_hosting_administration.sql new file mode 100644 index 0000000..210325b --- /dev/null +++ b/backend/internal/migrations/009_hosting_administration.sql @@ -0,0 +1,70 @@ +ALTER TABLE system_settings MODIFY COLUMN setting_value MEDIUMTEXT NOT NULL; + +ALTER TABLE tenants ADD COLUMN lifecycle_state ENUM('active','grace','recycle') NOT NULL DEFAULT 'active' AFTER status; +ALTER TABLE tenants ADD COLUMN suspended_at DATETIME NULL AFTER expires_at; +ALTER TABLE tenants ADD COLUMN grace_until DATETIME NULL AFTER suspended_at; +ALTER TABLE tenants ADD COLUMN purge_after DATETIME NULL AFTER grace_until; +ALTER TABLE tenants ADD COLUMN backup_purge_after DATETIME NULL AFTER purge_after; + +ALTER TABLE domains ADD COLUMN resolution_mode ENUM('direct','cname','cdn') NOT NULL DEFAULT 'direct' AFTER status; +ALTER TABLE domains ADD COLUMN cname_target VARCHAR(253) NULL AFTER resolution_mode; +ALTER TABLE domains ADD COLUMN filing_status ENUM('exempt','pending','approved','rejected') NOT NULL DEFAULT 'exempt' AFTER cname_target; +ALTER TABLE domains ADD COLUMN filing_number VARCHAR(80) NULL AFTER filing_status; +ALTER TABLE domains ADD COLUMN filing_note VARCHAR(500) NULL AFTER filing_number; + +CREATE TABLE IF NOT EXISTS ip_pool ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + address VARCHAR(45) NOT NULL UNIQUE, + family ENUM('ipv4','ipv6') NOT NULL, + allocation_mode ENUM('shared','dedicated') NOT NULL DEFAULT 'shared', + label VARCHAR(80) NOT NULL DEFAULT '', + enabled BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS site_networks ( + site_id BIGINT UNSIGNED PRIMARY KEY, + ip_id BIGINT UNSIGNED NULL, + http_port INT UNSIGNED NOT NULL DEFAULT 80, + https_port INT UNSIGNED NOT NULL DEFAULT 443, + dedicated BOOLEAN NOT NULL DEFAULT FALSE, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_site_network_site FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE, + CONSTRAINT fk_site_network_ip FOREIGN KEY (ip_id) REFERENCES ip_pool(id) ON DELETE SET NULL, + INDEX idx_site_network_ip (ip_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT IGNORE INTO site_networks(site_id) SELECT id FROM sites; + +CREATE TABLE IF NOT EXISTS sso_identities ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL, + provider VARCHAR(40) NOT NULL, + subject VARCHAR(255) NOT NULL, + email VARCHAR(190) NOT NULL DEFAULT '', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_sso_identity_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + UNIQUE KEY uk_sso_provider_subject (provider,subject), + UNIQUE KEY uk_sso_user_provider (user_id,provider) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS admin_notifications ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + severity ENUM('info','warning','critical') NOT NULL DEFAULT 'info', + category VARCHAR(40) NOT NULL, + title VARCHAR(160) NOT NULL, + detail VARCHAR(1000) NOT NULL DEFAULT '', + delivered_at DATETIME NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_admin_notifications_created (created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +INSERT INTO system_settings(setting_key,setting_value) VALUES + ('filing_required','false'), + ('cdn_cname_target',''), + ('lifecycle_grace_days','3'), + ('lifecycle_recycle_days','7'), + ('backup_retention_days','14'), + ('smtp_config','{}'), + ('oidc_config','{}') +ON DUPLICATE KEY UPDATE setting_key=VALUES(setting_key); diff --git a/backend/internal/migrations/010_operational_completion.sql b/backend/internal/migrations/010_operational_completion.sql new file mode 100644 index 0000000..ba04896 --- /dev/null +++ b/backend/internal/migrations/010_operational_completion.sql @@ -0,0 +1,40 @@ +ALTER TABLE tenants MODIFY COLUMN lifecycle_state ENUM('active','grace','recycle','purged') NOT NULL DEFAULT 'active'; + +CREATE TABLE IF NOT EXISTS tenant_backups ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + tenant_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NULL, + host_name VARCHAR(50) NOT NULL, + archive_path VARCHAR(500) NOT NULL UNIQUE, + size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + expires_at DATETIME NOT NULL, + deleted_at DATETIME NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_tenant_backup_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, + UNIQUE KEY uk_tenant_backup_project (tenant_id,project_id), + INDEX idx_tenant_backups_expiry (expires_at,deleted_at), + INDEX idx_tenant_backups_tenant (tenant_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS oidc_states ( + state_hash BINARY(32) PRIMARY KEY, + user_id BIGINT UNSIGNED NULL, + mode ENUM('login','bind') NOT NULL, + verifier VARCHAR(128) NOT NULL, + nonce VARCHAR(128) NOT NULL, + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_oidc_state_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_oidc_states_expiry (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +ALTER TABLE admin_notifications ADD COLUMN attempts INT UNSIGNED NOT NULL DEFAULT 0 AFTER detail; +ALTER TABLE admin_notifications ADD COLUMN last_error VARCHAR(500) NULL AFTER attempts; +ALTER TABLE admin_notifications ADD COLUMN next_attempt_at DATETIME NULL AFTER last_error; + +ALTER TABLE domains ADD COLUMN dns_credential_id BIGINT UNSIGNED NULL AFTER cname_target; +ALTER TABLE domains ADD COLUMN dns_record_id VARCHAR(190) NULL AFTER dns_credential_id; +ALTER TABLE domains ADD COLUMN dns_record_type ENUM('A','AAAA','CNAME') NULL AFTER dns_record_id; +ALTER TABLE domains ADD COLUMN dns_last_error VARCHAR(500) NULL AFTER dns_record_type; +ALTER TABLE domains ADD CONSTRAINT fk_domain_dns_credential FOREIGN KEY (dns_credential_id) REFERENCES dns_credentials(id) ON DELETE SET NULL; +ALTER TABLE domains ADD INDEX idx_domains_dns_credential (dns_credential_id); diff --git a/backend/internal/migrations/011_runtime_maintenance.sql b/backend/internal/migrations/011_runtime_maintenance.sql new file mode 100644 index 0000000..dbaf8f1 --- /dev/null +++ b/backend/internal/migrations/011_runtime_maintenance.sql @@ -0,0 +1,34 @@ +CREATE TABLE IF NOT EXISTS runtime_maintenance_jobs ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + action VARCHAR(24) NOT NULL, + runtime VARCHAR(16) NOT NULL, + from_version VARCHAR(40) NOT NULL DEFAULT '', + target_version VARCHAR(40) NOT NULL, + entry_file VARCHAR(255) NOT NULL DEFAULT '', + site_id BIGINT UNSIGNED NULL, + status VARCHAR(24) NOT NULL DEFAULT 'queued', + phase VARCHAR(40) NOT NULL DEFAULT 'queued', + message TEXT NULL, + rollback_data MEDIUMTEXT NULL, + backup_available BOOLEAN NOT NULL DEFAULT FALSE, + active_key VARCHAR(64) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_runtime_maintenance_active(active_key), + INDEX idx_runtime_maintenance_status(status,id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS site_runtime_observations ( + site_id BIGINT UNSIGNED PRIMARY KEY, + installed_version VARCHAR(80) NOT NULL DEFAULT '', + running_version VARCHAR(80) NOT NULL DEFAULT '', + healthy BOOLEAN NOT NULL DEFAULT FALSE, + detail VARCHAR(500) NOT NULL DEFAULT '', + checked_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_runtime_observation_site FOREIGN KEY(site_id) REFERENCES sites(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS runtime_update_notices ( + release_key VARCHAR(190) PRIMARY KEY, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/backend/internal/migrations/012_control_nodes.sql b/backend/internal/migrations/012_control_nodes.sql new file mode 100644 index 0000000..90c3724 --- /dev/null +++ b/backend/internal/migrations/012_control_nodes.sql @@ -0,0 +1,77 @@ +CREATE TABLE control_nodes ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(80) NOT NULL, + transport ENUM('local','https') NOT NULL DEFAULT 'https', + endpoint VARCHAR(500) NOT NULL DEFAULT '', + root_domain VARCHAR(253) NOT NULL DEFAULT '', + tenant_root VARCHAR(500) NOT NULL DEFAULT '/www/wwwroot/seavHost/vHost', + ftp_certificate_domain VARCHAR(253) NOT NULL DEFAULT '', + enabled BOOLEAN NOT NULL DEFAULT TRUE, + credentials LONGBLOB NULL, + registry_json MEDIUMTEXT NOT NULL, + registry_revision BIGINT UNSIGNED NOT NULL DEFAULT 0, + last_seen_at DATETIME NULL, + last_error VARCHAR(500) NOT NULL DEFAULT '', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_control_node_endpoint(endpoint) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +INSERT IGNORE INTO control_nodes(id,name,transport,endpoint,registry_json) VALUES(1,'本机节点','local','local', '{"version":1,"sites":{},"ftp":{},"databases":{}}'); + +ALTER TABLE projects ADD COLUMN node_id BIGINT UNSIGNED NOT NULL DEFAULT 1 AFTER tenant_id; +ALTER TABLE projects ADD COLUMN plan_id BIGINT UNSIGNED NULL AFTER node_id; +UPDATE projects p JOIN tenants t ON t.id=p.tenant_id SET p.plan_id=t.plan_id WHERE p.plan_id IS NULL; +UPDATE projects p JOIN plans l ON l.id=p.plan_id SET p.process_limit=l.process_limit; +UPDATE sites s JOIN projects p ON p.id=s.project_id SET s.process_limit=p.process_limit; +ALTER TABLE projects ADD CONSTRAINT fk_project_node FOREIGN KEY(node_id) REFERENCES control_nodes(id); +ALTER TABLE projects ADD CONSTRAINT fk_project_plan FOREIGN KEY(plan_id) REFERENCES plans(id); +ALTER TABLE projects ADD UNIQUE KEY uk_project_id_node(id,node_id); +ALTER TABLE projects ADD COLUMN identity_verified BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE projects ADD COLUMN expires_at DATETIME NULL; +ALTER TABLE projects ADD COLUMN lifecycle_state ENUM('active','grace','recycle','purged') NOT NULL DEFAULT 'active'; +ALTER TABLE projects ADD COLUMN grace_until DATETIME NULL; +ALTER TABLE projects ADD COLUMN purge_after DATETIME NULL; +ALTER TABLE projects ADD COLUMN backup_purge_after DATETIME NULL; +UPDATE projects p JOIN tenants t ON t.id=p.tenant_id SET p.expires_at=COALESCE(p.expires_at,t.expires_at),p.lifecycle_state=IF(t.lifecycle_state IN ('grace','recycle','purged'),t.lifecycle_state,p.lifecycle_state),p.grace_until=COALESCE(p.grace_until,t.grace_until),p.purge_after=COALESCE(p.purge_after,t.purge_after),p.backup_purge_after=COALESCE(p.backup_purge_after,t.backup_purge_after); + +UPDATE tenants SET status='active',lifecycle_state='active',expires_at=NULL,suspended_at=NULL,grace_until=NULL,purge_after=NULL,backup_purge_after=NULL WHERE lifecycle_state IN ('grace','recycle'); +ALTER TABLE sites ADD COLUMN node_id BIGINT UNSIGNED NOT NULL DEFAULT 1 AFTER project_id; +ALTER TABLE sites DROP INDEX uk_sites_panel_site; +ALTER TABLE sites ADD UNIQUE KEY uk_sites_node_panel(node_id,panel_site_id); +ALTER TABLE sites ADD CONSTRAINT fk_site_project_node FOREIGN KEY(project_id,node_id) REFERENCES projects(id,node_id) ON DELETE CASCADE; + +CREATE TABLE project_quota_usage ( + project_id BIGINT UNSIGNED PRIMARY KEY, + storage_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + database_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + bandwidth_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + process_count INT UNSIGNED NOT NULL DEFAULT 0, + period_start DATE NOT NULL, + measured_at DATETIME NOT NULL, + CONSTRAINT fk_project_quota_project FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +ALTER TABLE runtime_maintenance_jobs ADD COLUMN node_id BIGINT UNSIGNED NOT NULL DEFAULT 1 AFTER id; +ALTER TABLE runtime_maintenance_jobs ADD CONSTRAINT fk_runtime_job_node FOREIGN KEY(node_id) REFERENCES control_nodes(id); +UPDATE runtime_maintenance_jobs SET active_key=CONCAT('node/',node_id) WHERE active_key IS NOT NULL; +ALTER TABLE runtime_update_notices ADD COLUMN node_id BIGINT UNSIGNED NOT NULL DEFAULT 1; +ALTER TABLE runtime_update_notices DROP PRIMARY KEY, ADD PRIMARY KEY(node_id,release_key); +ALTER TABLE ip_pool ADD COLUMN node_id BIGINT UNSIGNED NOT NULL DEFAULT 1; +ALTER TABLE ip_pool DROP INDEX address; +ALTER TABLE ip_pool ADD UNIQUE KEY uk_node_ip(node_id,address); +ALTER TABLE tenant_backups ADD COLUMN node_id BIGINT UNSIGNED NOT NULL DEFAULT 1; + +CREATE TABLE control_tasks ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + node_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NULL, + operation VARCHAR(80) NOT NULL, + state ENUM('running','succeeded','failed','uncertain') NOT NULL DEFAULT 'running', + request_id CHAR(32) NOT NULL UNIQUE, + detail VARCHAR(500) NOT NULL DEFAULT '', + started_at DATETIME NOT NULL, + finished_at DATETIME NULL, + CONSTRAINT fk_control_task_node FOREIGN KEY(node_id) REFERENCES control_nodes(id), + INDEX idx_control_task_node_state(node_id,state,id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/backend/internal/migrations/013_complete_backups.sql b/backend/internal/migrations/013_complete_backups.sql new file mode 100644 index 0000000..77faa9a --- /dev/null +++ b/backend/internal/migrations/013_complete_backups.sql @@ -0,0 +1 @@ +ALTER TABLE tenant_backups ADD COLUMN database_count INT UNSIGNED NOT NULL DEFAULT 0; diff --git a/backend/internal/migrations/014_bandwidth_limits.sql b/backend/internal/migrations/014_bandwidth_limits.sql new file mode 100644 index 0000000..76454a3 --- /dev/null +++ b/backend/internal/migrations/014_bandwidth_limits.sql @@ -0,0 +1 @@ +ALTER TABLE plans ADD COLUMN bandwidth_mbps INT UNSIGNED NOT NULL DEFAULT 0; diff --git a/backend/internal/migrations/015_host_operation_logs.sql b/backend/internal/migrations/015_host_operation_logs.sql new file mode 100644 index 0000000..591ba5e --- /dev/null +++ b/backend/internal/migrations/015_host_operation_logs.sql @@ -0,0 +1,21 @@ +ALTER TABLE operation_logs ADD COLUMN project_id BIGINT UNSIGNED NULL; +ALTER TABLE operation_logs ADD KEY idx_logs_tenant_project_id (tenant_id, project_id, id); + +UPDATE operation_logs l JOIN projects p ON BINARY l.resource_id=BINARY CAST(p.id AS CHAR) +SET l.project_id=p.id,l.tenant_id=p.tenant_id +WHERE l.project_id IS NULL AND (l.tenant_id=p.tenant_id OR l.tenant_id IS NULL) +AND l.success=TRUE AND l.resource_type IN ('project','run_path','host_password','project_network'); + +UPDATE operation_logs l JOIN sites s ON l.tenant_id=s.tenant_id AND BINARY l.resource_id=BINARY CAST(s.id AS CHAR) +SET l.project_id=s.project_id +WHERE l.project_id IS NULL AND l.success=TRUE +AND l.resource_type IN ('site','deployment','certificate','automatic_certificate','manual_certificate','dns_certificate'); + +UPDATE operation_logs l JOIN domains d ON l.tenant_id=d.tenant_id +AND ((l.resource_type='domain' AND (BINARY l.resource_id=BINARY d.domain OR BINARY l.resource_id=BINARY CAST(d.id AS CHAR))) +OR (l.resource_type='domain_dns' AND BINARY l.resource_id=BINARY CAST(d.id AS CHAR))) +SET l.project_id=d.project_id WHERE l.project_id IS NULL AND l.success=TRUE; + +UPDATE operation_logs l JOIN users u ON l.user_id=u.id AND l.tenant_id=u.tenant_id +SET l.project_id=u.project_id +WHERE l.project_id IS NULL AND u.role='host' AND u.project_id IS NOT NULL; diff --git a/backend/internal/migrations/016_administrator_impersonation.sql b/backend/internal/migrations/016_administrator_impersonation.sql new file mode 100644 index 0000000..338d163 --- /dev/null +++ b/backend/internal/migrations/016_administrator_impersonation.sql @@ -0,0 +1,17 @@ +ALTER TABLE operation_logs ADD COLUMN administrator_id BIGINT UNSIGNED NULL; +ALTER TABLE operation_logs ADD COLUMN impersonated_user_id BIGINT UNSIGNED NULL; +ALTER TABLE operation_logs ADD COLUMN admin_action BOOLEAN NOT NULL DEFAULT FALSE; +UPDATE operation_logs l JOIN users u ON u.id=l.user_id SET l.admin_action=TRUE,l.administrator_id=u.id WHERE u.role='admin'; +UPDATE operation_logs SET admin_action=TRUE WHERE resource_type IN ('plan','tenant','domain_approval','system_settings','project_network','host_subscription','panel_site','node','node_task','runtime_component','runtime_environment','runtime_maintenance','impersonation'); +CREATE TABLE impersonation_sessions ( + token_hash BINARY(32) PRIMARY KEY, + parent_session_hash BINARY(32) NOT NULL, + administrator_id BIGINT UNSIGNED NOT NULL, + target_user_id BIGINT UNSIGNED NOT NULL, + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_impersonation_target (target_user_id), + CONSTRAINT fk_impersonation_parent FOREIGN KEY (parent_session_hash) REFERENCES sessions(token_hash) ON DELETE CASCADE, + CONSTRAINT fk_impersonation_administrator FOREIGN KEY (administrator_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT fk_impersonation_target FOREIGN KEY (target_user_id) REFERENCES users(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/017_optional_host_ownership.sql b/backend/internal/migrations/017_optional_host_ownership.sql new file mode 100644 index 0000000..cd6a43a --- /dev/null +++ b/backend/internal/migrations/017_optional_host_ownership.sql @@ -0,0 +1,8 @@ +ALTER TABLE tenants ADD COLUMN resource_namespace BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE projects ADD COLUMN owner_tenant_id BIGINT UNSIGNED NULL; +ALTER TABLE projects ADD COLUMN ownership_initialized BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE projects ADD COLUMN management_locked BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE projects ADD COLUMN ownership_version BIGINT UNSIGNED NOT NULL DEFAULT 1; +ALTER TABLE projects ADD KEY idx_projects_owner (owner_tenant_id,id); +ALTER TABLE projects ADD CONSTRAINT fk_project_owner FOREIGN KEY(owner_tenant_id) REFERENCES tenants(id); +UPDATE projects SET owner_tenant_id=tenant_id,ownership_initialized=TRUE WHERE ownership_initialized=FALSE; diff --git a/backend/internal/migrations/018_admin_batches.sql b/backend/internal/migrations/018_admin_batches.sql new file mode 100644 index 0000000..bc86f4b --- /dev/null +++ b/backend/internal/migrations/018_admin_batches.sql @@ -0,0 +1,32 @@ +CREATE TABLE admin_batches ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + request_key CHAR(32) NOT NULL UNIQUE, + input_digest CHAR(64) NOT NULL, + administrator_id BIGINT UNSIGNED NOT NULL, + operation VARCHAR(40) NOT NULL, + state VARCHAR(24) NOT NULL DEFAULT 'queued', + total_count INT UNSIGNED NOT NULL, + secret_ref CHAR(32) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + finished_at DATETIME NULL, + secrets_expire_at DATETIME NULL, + INDEX idx_admin_batches_queue(state,id), + INDEX idx_admin_batches_secret_expiry(secrets_expire_at,id), + CONSTRAINT fk_admin_batch_administrator FOREIGN KEY(administrator_id) REFERENCES users(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE admin_batch_items ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + batch_id BIGINT UNSIGNED NOT NULL, + item_number INT UNSIGNED NOT NULL, + label VARCHAR(190) NOT NULL, + state VARCHAR(24) NOT NULL DEFAULT 'pending', + resource_id BIGINT UNSIGNED NULL, + input_cipher LONGBLOB NULL, + result_cipher LONGBLOB NULL, + detail VARCHAR(500) NOT NULL DEFAULT '', + started_at DATETIME NULL, + finished_at DATETIME NULL, + UNIQUE KEY uk_admin_batch_row(batch_id,item_number), + CONSTRAINT fk_admin_batch_item FOREIGN KEY(batch_id) REFERENCES admin_batches(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/019_host_ownership_changes.sql b/backend/internal/migrations/019_host_ownership_changes.sql new file mode 100644 index 0000000..b495a6a --- /dev/null +++ b/backend/internal/migrations/019_host_ownership_changes.sql @@ -0,0 +1,13 @@ +CREATE TABLE host_ownership_changes ( + project_id BIGINT UNSIGNED PRIMARY KEY, + source_owner_id BIGINT UNSIGNED NULL, + target_owner_id BIGINT UNSIGNED NULL, + expected_version BIGINT UNSIGNED NOT NULL, + credential_mode VARCHAR(16) NOT NULL, + stop_services BOOLEAN NOT NULL, + state VARCHAR(24) NOT NULL DEFAULT 'pending', + credentials_cipher LONGBLOB NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_host_ownership_project FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/020_hosting_features.sql b/backend/internal/migrations/020_hosting_features.sql new file mode 100644 index 0000000..5b7317e --- /dev/null +++ b/backend/internal/migrations/020_hosting_features.sql @@ -0,0 +1,22 @@ +ALTER TABLE ftp_accounts ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT TRUE; +CREATE TABLE site_preferences ( + site_id BIGINT UNSIGNED PRIMARY KEY, + website_json JSON NULL, + startup_cipher LONGBLOB NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT fk_site_preferences FOREIGN KEY(site_id) REFERENCES sites(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE host_metrics ( + project_id BIGINT UNSIGNED NOT NULL, + sampled_at DATETIME NOT NULL, + cpu_percent DOUBLE NOT NULL DEFAULT 0, + cpu_ticks BIGINT UNSIGNED NOT NULL DEFAULT 0, + memory_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + process_count INT UNSIGNED NOT NULL DEFAULT 0, + storage_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + database_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + bandwidth_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY(project_id,sampled_at), + INDEX idx_metric_retention(sampled_at), + CONSTRAINT fk_host_metric_project FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/021_user_schedules.sql b/backend/internal/migrations/021_user_schedules.sql new file mode 100644 index 0000000..2c46966 --- /dev/null +++ b/backend/internal/migrations/021_user_schedules.sql @@ -0,0 +1,49 @@ +CREATE TABLE user_schedules ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL, + account_id BIGINT UNSIGNED NOT NULL, + project_id BIGINT UNSIGNED NOT NULL, + site_id BIGINT UNSIGNED NOT NULL, + ownership_version BIGINT UNSIGNED NOT NULL, + name VARCHAR(120) NOT NULL, + cron_expression VARCHAR(120) NOT NULL, + timezone VARCHAR(80) NOT NULL, + kind VARCHAR(16) NOT NULL, + runtime_version VARCHAR(80) NOT NULL DEFAULT '', + target VARCHAR(512) NOT NULL, + arguments_json JSON NOT NULL, + secret_ref CHAR(32) NOT NULL, + config_cipher LONGBLOB NOT NULL, + use_https BOOLEAN NOT NULL DEFAULT FALSE, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + run_requested BOOLEAN NOT NULL DEFAULT FALSE, + next_run_at DATETIME NOT NULL, + running_until DATETIME NULL, + running_run_id BIGINT UNSIGNED NULL, + last_state VARCHAR(32) NOT NULL DEFAULT 'ready', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + INDEX idx_user_schedule_owner(user_id,id), + INDEX idx_user_schedule_due(next_run_at,enabled), + CONSTRAINT fk_user_schedule_user FOREIGN KEY(user_id) REFERENCES users(id), + CONSTRAINT fk_user_schedule_account FOREIGN KEY(account_id) REFERENCES tenants(id), + CONSTRAINT fk_user_schedule_project FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE, + CONSTRAINT fk_user_schedule_site FOREIGN KEY(site_id) REFERENCES sites(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE user_schedule_runs ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + schedule_id BIGINT UNSIGNED NOT NULL, + state VARCHAR(32) NOT NULL, + exit_code INT NULL, + output_cipher LONGBLOB NULL, + started_at DATETIME NOT NULL, + finished_at DATETIME NULL, + INDEX idx_schedule_run(schedule_id,id), + INDEX idx_schedule_run_retention(started_at), + CONSTRAINT fk_user_schedule_run FOREIGN KEY(schedule_id) REFERENCES user_schedules(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE scheduler_ticks ( + tick_minute DATETIME PRIMARY KEY, + node_id BIGINT UNSIGNED NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/022_integration_api.sql b/backend/internal/migrations/022_integration_api.sql new file mode 100644 index 0000000..95dc210 --- /dev/null +++ b/backend/internal/migrations/022_integration_api.sql @@ -0,0 +1,33 @@ +CREATE TABLE integration_keys ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + administrator_id BIGINT UNSIGNED NOT NULL, + name VARCHAR(120) NOT NULL, + token_hash CHAR(64) NOT NULL UNIQUE, + token_prefix VARCHAR(24) NOT NULL, + scopes_json JSON NOT NULL, + expires_at DATETIME NOT NULL, + revoked_at DATETIME NULL, + last_used_at DATETIME NULL, + webhook_url VARCHAR(2048) NOT NULL DEFAULT '', + webhook_secret_cipher LONGBLOB NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_integration_admin FOREIGN KEY(administrator_id) REFERENCES users(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +ALTER TABLE admin_batches ADD COLUMN integration_key_id BIGINT UNSIGNED NULL, + ADD CONSTRAINT fk_batch_integration_key FOREIGN KEY(integration_key_id) REFERENCES integration_keys(id); +CREATE TABLE integration_webhooks ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + event_id CHAR(32) NOT NULL UNIQUE, + key_id BIGINT UNSIGNED NOT NULL, + batch_id BIGINT UNSIGNED NOT NULL UNIQUE, + state VARCHAR(24) NOT NULL DEFAULT 'pending', + attempts INT UNSIGNED NOT NULL DEFAULT 0, + next_attempt_at DATETIME NOT NULL, + last_status INT NOT NULL DEFAULT 0, + last_error VARCHAR(120) NOT NULL DEFAULT '', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + delivered_at DATETIME NULL, + INDEX idx_webhook_due(state,next_attempt_at), + CONSTRAINT fk_webhook_key FOREIGN KEY(key_id) REFERENCES integration_keys(id), + CONSTRAINT fk_webhook_batch FOREIGN KEY(batch_id) REFERENCES admin_batches(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/backend/internal/migrations/023_resource_crud.sql b/backend/internal/migrations/023_resource_crud.sql new file mode 100644 index 0000000..f6b9e03 --- /dev/null +++ b/backend/internal/migrations/023_resource_crud.sql @@ -0,0 +1,4 @@ +ALTER TABLE tenants ADD COLUMN deleted_at DATETIME NULL; +ALTER TABLE control_nodes ADD COLUMN deleted_at DATETIME NULL; +ALTER TABLE projects ADD COLUMN manual_recycled_at DATETIME NULL; +ALTER TABLE projects ADD COLUMN recycle_error VARCHAR(500) NOT NULL DEFAULT ''; diff --git a/backend/internal/migrations/024_runtime_queue.sql b/backend/internal/migrations/024_runtime_queue.sql new file mode 100644 index 0000000..d0d764b --- /dev/null +++ b/backend/internal/migrations/024_runtime_queue.sql @@ -0,0 +1,4 @@ +ALTER TABLE runtime_maintenance_jobs MODIFY active_key VARCHAR(190) NULL; +UPDATE runtime_maintenance_jobs SET active_key=CASE WHEN site_id IS NOT NULL THEN CONCAT('site/',site_id) ELSE CONCAT('node/',node_id,'/',action,'/',runtime,'/',target_version,'/0') END WHERE active_key IS NOT NULL; +ALTER TABLE runtime_maintenance_jobs ADD COLUMN running_node_id BIGINT UNSIGNED GENERATED ALWAYS AS (CASE WHEN status IN ('running','interrupted') THEN node_id ELSE NULL END) STORED; +ALTER TABLE runtime_maintenance_jobs ADD UNIQUE KEY uk_runtime_running_node(running_node_id); diff --git a/backend/internal/migrations/025_host_runtime_policy.sql b/backend/internal/migrations/025_host_runtime_policy.sql new file mode 100644 index 0000000..bd7640b --- /dev/null +++ b/backend/internal/migrations/025_host_runtime_policy.sql @@ -0,0 +1,2 @@ +ALTER TABLE projects ADD COLUMN allow_runtime_change BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE runtime_maintenance_jobs ADD COLUMN ownership_version BIGINT UNSIGNED NULL; diff --git a/backend/internal/migrations/026_dns_providers.sql b/backend/internal/migrations/026_dns_providers.sql new file mode 100644 index 0000000..db35293 --- /dev/null +++ b/backend/internal/migrations/026_dns_providers.sql @@ -0,0 +1,2 @@ +ALTER TABLE dns_credentials MODIFY provider ENUM('cloudflare','aliyun','tencent','west','dnsmgr') NOT NULL; +ALTER TABLE domains MODIFY dns_record_id VARCHAR(768) NULL; diff --git a/backend/internal/migrations/027_runtime_host_recovery.sql b/backend/internal/migrations/027_runtime_host_recovery.sql new file mode 100644 index 0000000..8bd175d --- /dev/null +++ b/backend/internal/migrations/027_runtime_host_recovery.sql @@ -0,0 +1,4 @@ +ALTER TABLE runtime_maintenance_jobs DROP INDEX uk_runtime_running_node; +ALTER TABLE runtime_maintenance_jobs DROP COLUMN running_node_id; +ALTER TABLE runtime_maintenance_jobs ADD COLUMN running_node_id BIGINT UNSIGNED GENERATED ALWAYS AS (CASE WHEN status='running' OR (status='interrupted' AND action<>'runtime_change') THEN node_id ELSE NULL END) STORED; +ALTER TABLE runtime_maintenance_jobs ADD UNIQUE KEY uk_runtime_running_node(running_node_id); diff --git a/backend/internal/migrations/028_sso_login_policy.sql b/backend/internal/migrations/028_sso_login_policy.sql new file mode 100644 index 0000000..248c370 --- /dev/null +++ b/backend/internal/migrations/028_sso_login_policy.sql @@ -0,0 +1,17 @@ +-- Scope existing bindings to the issuer configured before this upgrade. +UPDATE sso_identities i JOIN system_settings s ON s.setting_key='oidc_config' +SET i.provider=CONCAT('oidc:',LEFT(SHA2(TRIM(TRAILING '/' FROM JSON_UNQUOTE(JSON_EXTRACT(s.setting_value,'$.issuer'))),256),32)) +WHERE i.provider='oidc' AND JSON_VALID(s.setting_value) AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(s.setting_value,'$.issuer')),'')<>''; +ALTER TABLE oidc_states ADD COLUMN provider_key VARCHAR(40) NOT NULL DEFAULT ''; +ALTER TABLE oidc_states ADD COLUMN session_token_hash BINARY(32) NULL; +CREATE TABLE IF NOT EXISTS oidc_pending_logins ( + token_hash BINARY(32) PRIMARY KEY, + provider VARCHAR(40) NOT NULL, + subject VARCHAR(255) COLLATE utf8mb4_bin NOT NULL, + email VARCHAR(190) NOT NULL DEFAULT '', + display_name VARCHAR(80) NOT NULL DEFAULT '', + email_verified BOOLEAN NOT NULL DEFAULT FALSE, + expires_at DATETIME NOT NULL, + KEY idx_oidc_pending_expires(expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +ALTER TABLE sso_identities MODIFY subject VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL; diff --git a/backend/internal/migrations/embed.go b/backend/internal/migrations/embed.go new file mode 100644 index 0000000..60104cb --- /dev/null +++ b/backend/internal/migrations/embed.go @@ -0,0 +1,8 @@ +package migrations + +import "embed" + +// Files contains ordered, idempotent schema migrations. +// +//go:embed *.sql +var Files embed.FS diff --git a/backend/internal/nodefiles/files.go b/backend/internal/nodefiles/files.go new file mode 100644 index 0000000..88e0214 --- /dev/null +++ b/backend/internal/nodefiles/files.go @@ -0,0 +1,356 @@ +// Package nodefiles provides bounded, rooted file operations. The node accepts +// a host identity and relative names, never a caller-supplied absolute root. +package nodefiles + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "time" +) + +const MaxFileBytes = 20 << 20 +const MaxMessageBytes = 30 << 20 + +type Info struct { + NameValue string `json:"name"` + SizeValue int64 `json:"size"` + ModeValue uint32 `json:"mode"` + Modified time.Time `json:"modified"` +} + +func (i Info) Name() string { return i.NameValue } +func (i Info) Size() int64 { return i.SizeValue } +func (i Info) Mode() fs.FileMode { return fs.FileMode(i.ModeValue) } +func (i Info) ModTime() time.Time { return i.Modified } +func (i Info) IsDir() bool { return i.Mode().IsDir() } +func (i Info) Sys() any { return nil } +func (i Info) Type() fs.FileMode { return i.Mode().Type() } +func (i Info) Info() (fs.FileInfo, error) { return i, nil } +func info(i fs.FileInfo) Info { return Info{i.Name(), i.Size(), uint32(i.Mode()), i.ModTime()} } + +type Request struct { + HostName string `json:"hostName"` + Operation string `json:"operation"` + Path string `json:"path"` + To string `json:"to,omitempty"` + Data []byte `json:"data,omitempty"` + Overwrite bool `json:"overwrite,omitempty"` + Mode uint32 `json:"mode,omitempty"` + Budget uint64 `json:"budget,omitempty"` +} +type Response struct { + Info Info `json:"info"` + Entries []Info `json:"entries,omitempty"` + Data []byte `json:"data,omitempty"` + Error string `json:"error,omitempty"` + Trash []TrashEntry `json:"trash,omitempty"` +} +type Call func(context.Context, Request) (Response, error) +type Root struct { + ctx context.Context + host string + call Call +} + +func New(ctx context.Context, host string, call Call) *Root { return &Root{ctx, host, call} } +func (r *Root) Close() error { return nil } +func (r *Root) Action(q Request) (Response, error) { return r.execute(q) } +func (r *Root) execute(q Request) (Response, error) { + q.HostName = r.host + out, err := r.call(r.ctx, q) + if err != nil { + return out, err + } + switch out.Error { + case "": + case "not_found": + err = fs.ErrNotExist + case "exists": + err = fs.ErrExist + case "denied": + err = fs.ErrPermission + default: + err = errors.New("文件操作失败") + } + return out, err +} +func (r *Root) Lstat(name string) (fs.FileInfo, error) { + out, err := r.execute(Request{Operation: "stat", Path: name}) + return out.Info, err +} +func (r *Root) Open(name string) (*File, error) { + out, err := r.execute(Request{Operation: "read", Path: name}) + if err != nil { + return nil, err + } + return &File{reader: bytes.NewReader(out.Data), info: out.Info, entries: out.Entries}, nil +} +func (r *Root) OpenFile(name string, flag int, mode fs.FileMode) (*File, error) { + if flag&os.O_WRONLY == 0 { + return nil, fs.ErrPermission + } + overwrite := flag&os.O_TRUNC != 0 + return &File{root: r, name: name, write: true, overwrite: overwrite, mode: mode}, nil +} +func (r *Root) MkdirAll(name string, mode fs.FileMode) error { + _, err := r.execute(Request{Operation: "mkdir", Path: name, Mode: uint32(mode.Perm())}) + return err +} +func (r *Root) Rename(from, to string) error { + _, err := r.execute(Request{Operation: "rename", Path: from, To: to}) + return err +} +func (r *Root) Remove(name string) error { + _, err := r.execute(Request{Operation: "remove", Path: name}) + return err +} +func (r *Root) RemoveAll(name string) error { + if name != ".sea-trash" { + return fs.ErrPermission + } + _, err := r.execute(Request{Operation: "empty_trash", Path: name}) + return err +} + +type File struct { + root *Root + name string + write, overwrite, closed bool + mode fs.FileMode + buffer bytes.Buffer + reader *bytes.Reader + info Info + entries []Info + closeErr error +} + +func (f *File) Abort() { f.closed = true; f.buffer.Reset() } +func (f *File) Stat() (fs.FileInfo, error) { return f.info, nil } +func (f *File) Read(b []byte) (int, error) { + if f.reader == nil { + return 0, fs.ErrPermission + } + return f.reader.Read(b) +} +func (f *File) Seek(offset int64, whence int) (int64, error) { + if f.reader == nil { + return 0, fs.ErrPermission + } + return f.reader.Seek(offset, whence) +} +func (f *File) Write(b []byte) (int, error) { + if f.closed || !f.write { + return 0, fs.ErrPermission + } + if len(b) > MaxFileBytes-f.buffer.Len() { + return 0, errors.New("文件超过20 MB") + } + return f.buffer.Write(b) +} +func (f *File) ReadDir(n int) ([]fs.DirEntry, error) { + if !f.info.IsDir() { + return nil, errors.New("不是目录") + } + take := len(f.entries) + if n > 0 && n < take { + take = n + } + out := make([]fs.DirEntry, take) + for i := range out { + out[i] = f.entries[i] + } + f.entries = f.entries[take:] + if take == 0 && n > 0 { + return out, io.EOF + } + return out, nil +} +func (f *File) Close() error { + if f.closed { + return f.closeErr + } + f.closed = true + if f.write { + _, f.closeErr = f.root.execute(Request{Operation: "write", Path: f.name, Data: f.buffer.Bytes(), Overwrite: f.overwrite, Mode: uint32(f.mode.Perm())}) + } + return f.closeErr +} + +func validName(name string) bool { + return name != "" && !strings.HasPrefix(name, "/") && !filepath.IsAbs(name) && !strings.ContainsAny(name, ":\\\x00\r\n") && name != ".." && !strings.HasPrefix(filepath.ToSlash(filepath.Clean(name)), "../") +} +func check(root *os.Root, name string) error { + if !validName(name) { + return fs.ErrPermission + } + parts := strings.Split(filepath.ToSlash(filepath.Clean(name)), "/") + p := "" + for _, part := range parts { + p = filepath.Join(p, part) + i, err := root.Lstat(p) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + if i.Mode()&fs.ModeSymlink != 0 { + return fs.ErrPermission + } + } + return nil +} +func Execute(rootPath string, q Request) (out Response) { + err := execute(rootPath, q, &out) + if err != nil { + switch { + case errors.Is(err, fs.ErrNotExist): + out.Error = "not_found" + case errors.Is(err, fs.ErrExist): + out.Error = "exists" + case errors.Is(err, fs.ErrPermission): + out.Error = "denied" + default: + out.Error = "failed" + } + } + return out +} +func execute(rootPath string, q Request, out *Response) error { + root, err := os.OpenRoot(rootPath) + if err != nil { + return err + } + defer root.Close() + if isAdvanced(q.Operation) { + return advanced(root, q, out) + } + if (IsProtectedPath(q.Path) && !(q.Operation == "empty_trash" && q.Path == ".sea-trash")) || (q.To != "" && IsProtectedPath(q.To)) { + return fs.ErrPermission + } + if err = check(root, q.Path); err != nil { + return err + } + switch q.Operation { + case "stat": + i, e := root.Lstat(q.Path) + if e == nil { + out.Info = info(i) + } + return e + case "read": + f, e := root.Open(q.Path) + if e != nil { + return e + } + defer f.Close() + i, e := f.Stat() + if e != nil { + return e + } + out.Info = info(i) + if i.IsDir() { + entries, e := f.ReadDir(10001) + if e != nil && e != io.EOF { + return e + } + if len(entries) > 10000 { + return errors.New("目录文件过多") + } + out.Entries = []Info{} + for _, entry := range entries { + v, e := entry.Info() + if e == nil { + out.Entries = append(out.Entries, info(v)) + } + } + return nil + } + if !i.Mode().IsRegular() || i.Size() > MaxFileBytes { + return fs.ErrPermission + } + out.Data, e = io.ReadAll(io.LimitReader(f, MaxFileBytes+1)) + if len(out.Data) > MaxFileBytes { + return fs.ErrPermission + } + return e + case "write": + if q.Path == "." || len(q.Data) > MaxFileBytes { + return fs.ErrPermission + } + if i, e := root.Lstat(q.Path); e == nil { + if !q.Overwrite { + return fs.ErrExist + } + if !i.Mode().IsRegular() { + return fs.ErrPermission + } + } else if !errors.Is(e, fs.ErrNotExist) { + return e + } + // Stage in the destination directory so interruptions preserve old contents. + random := make([]byte, 16) + if _, err = rand.Read(random); err != nil { + return err + } + temp := filepath.Join(filepath.Dir(q.Path), ".sea-upload-"+hex.EncodeToString(random)) + f, e := root.OpenFile(temp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660) + if e != nil { + return e + } + defer root.Remove(temp) + _, e = f.Write(q.Data) + if e == nil { + e = f.Sync() + } + closeErr := f.Close() + if e != nil { + return e + } + if closeErr != nil { + return closeErr + } + if !q.Overwrite { + if _, e = root.Lstat(q.Path); e == nil { + return fs.ErrExist + } + if !errors.Is(e, fs.ErrNotExist) { + return e + } + } + return root.Rename(temp, q.Path) + case "mkdir": + if q.Path == "." { + return nil + } + return root.MkdirAll(q.Path, 0770) + case "rename": + if q.Path == "." || !strings.HasPrefix(q.To, ".sea-trash/") { + return fs.ErrPermission + } + if err = check(root, q.To); err != nil { + return err + } + return root.Rename(q.Path, q.To) + case "remove": + if q.Path == "." { + return fs.ErrPermission + } + return root.Remove(q.Path) + case "empty_trash": + if q.Path != ".sea-trash" { + return fs.ErrPermission + } + return root.RemoveAll(q.Path) + default: + return fs.ErrPermission + } +} diff --git a/backend/internal/nodefiles/files_test.go b/backend/internal/nodefiles/files_test.go new file mode 100644 index 0000000..dc53a77 --- /dev/null +++ b/backend/internal/nodefiles/files_test.go @@ -0,0 +1,53 @@ +package nodefiles + +import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "testing" +) + +func TestBufferedWritesRequireSuccessfulCommit(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "index.txt") + if err := os.WriteFile(file, []byte("original"), 0660); err != nil { + t.Fatal(err) + } + root := New(context.Background(), "sv0123456789", func(_ context.Context, q Request) (Response, error) { return Execute(dir, q), nil }) + f, _ := root.OpenFile("index.txt", os.O_WRONLY|os.O_TRUNC, 0660) + _, _ = f.Write([]byte("partial")) + f.Abort() + _ = f.Close() + raw, _ := os.ReadFile(file) + if string(raw) != "original" { + t.Fatal("aborted upload changed original") + } + f, _ = root.OpenFile("index.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0660) + _, _ = f.Write([]byte("new")) + if err := f.Close(); !errors.Is(err, fs.ErrExist) { + t.Fatalf("exclusive write: %v", err) + } + f, _ = root.OpenFile("index.txt", os.O_WRONLY|os.O_TRUNC, 0660) + _, _ = f.Write([]byte("committed")) + if err := f.Close(); err != nil { + t.Fatal(err) + } + raw, _ = os.ReadFile(file) + if string(raw) != "committed" { + t.Fatal("successful commit missing") + } +} +func TestSymlinkEscapeDenied(t *testing.T) { + dir := t.TempDir() + outside := t.TempDir() + _ = os.WriteFile(filepath.Join(outside, "secret"), []byte("marker"), 0600) + if err := os.Symlink(outside, filepath.Join(dir, "escape")); err != nil { + t.Skip("symlinks unavailable") + } + out := Execute(dir, Request{Operation: "read", Path: "escape/secret"}) + if out.Error != "denied" || len(out.Data) != 0 { + t.Fatal("symlink escape read") + } +} diff --git a/backend/internal/nodefiles/operations.go b/backend/internal/nodefiles/operations.go new file mode 100644 index 0000000..7fcd6b0 --- /dev/null +++ b/backend/internal/nodefiles/operations.go @@ -0,0 +1,423 @@ +package nodefiles + +import ( + "archive/zip" + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "io" + "io/fs" + "os" + "path" + "strings" + "time" +) + +const maxExpanded = 256 << 20 + +type TrashEntry struct { + ID string `json:"id"` + OriginalPath string `json:"originalPath"` + Name string `json:"name"` + DeletedAt time.Time `json:"deletedAt"` + Size int64 `json:"size"` +} + +func isAdvanced(op string) bool { + switch op { + case "move", "copy", "zip", "extract", "trash", "trash_list", "restore": + return true + } + return false +} + +// IsProtectedPath identifies platform-owned configuration and runtime paths. +func IsProtectedPath(name string) bool { + return protected(path.Clean(strings.ReplaceAll(name, "\\", "/"))) +} + +func protected(name string) bool { + for _, v := range strings.Split(name, "/") { + if v == ".sea-runtime" || v == ".user.ini" || v == ".sea-trash" || strings.HasPrefix(v, ".sea-op-") { + return true + } + } + return false +} +func userPath(root *os.Root, name string) error { + if name == "." || path.Clean(name) != name || protected(name) { + return fs.ErrPermission + } + return check(root, name) +} +func absent(root *os.Root, name string) error { + if _, e := root.Lstat(name); e == nil { + return fs.ErrExist + } else if !errors.Is(e, fs.ErrNotExist) { + return e + } + return nil +} +func opID() (string, error) { + b := make([]byte, 16) + _, e := rand.Read(b) + return hex.EncodeToString(b), e +} +func advanced(root *os.Root, q Request, out *Response) error { + if q.Operation == "trash_list" { + return listTrash(root, out) + } + if q.Operation == "restore" { + if len(q.Path) != 32 || strings.Trim(q.Path, "0123456789abcdef") != "" { + return fs.ErrPermission + } + if e := userPath(root, q.To); e != nil { + return e + } + if e := absent(root, q.To); e != nil { + return e + } + from := ".sea-trash/" + q.Path + if e := check(root, from); e != nil { + return e + } + if e := root.MkdirAll(path.Dir(q.To), 0770); e != nil { + return e + } + if e := root.Rename(from, q.To); e != nil { + return e + } + _ = root.Remove(from + ".json") + return nil + } + if e := userPath(root, q.Path); e != nil { + return e + } + if q.Operation == "trash" { + id, e := opID() + if e != nil { + return e + } + if e = root.MkdirAll(".sea-trash", 0770); e != nil { + return e + } + if e = check(root, ".sea-trash"); e != nil { + return e + } + i, e := root.Lstat(q.Path) + if e != nil { + return e + } + entry := TrashEntry{ID: id, OriginalPath: q.Path, Name: path.Base(q.Path), DeletedAt: time.Now().UTC(), Size: i.Size()} + raw, _ := json.Marshal(entry) + f, e := root.OpenFile(".sea-trash/"+id+".json", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660) + if e != nil { + return e + } + _, e = f.Write(raw) + closeErr := f.Close() + if e == nil { + e = closeErr + } + if e == nil { + e = root.Rename(q.Path, ".sea-trash/"+id) + } + if e != nil { + root.Remove(".sea-trash/" + id + ".json") + } + return e + } + if e := userPath(root, q.To); e != nil { + return e + } + if e := absent(root, q.To); e != nil { + return e + } + if q.To == q.Path || strings.HasPrefix(q.To, q.Path+"/") { + return fs.ErrPermission + } + if q.Operation == "move" { + return root.Rename(q.Path, q.To) + } + budget := q.Budget + if budget > maxExpanded { + budget = maxExpanded + } + id, e := opID() + if e != nil { + return e + } + stage := path.Join(path.Dir(q.To), ".sea-op-"+id) + defer root.RemoveAll(stage) + switch q.Operation { + case "copy": + if e = copyTree(root, q.Path, stage, &budget, new(int)); e != nil { + return e + } + case "zip": + f, e := root.OpenFile(stage, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660) + if e != nil { + return e + } + z := zip.NewWriter(&budgetWriter{w: f, left: budget}) + e = zipTree(root, z, q.Path, path.Base(q.Path), new(int), newZipBudget()) + if closeErr := z.Close(); e == nil { + e = closeErr + } + if closeErr := f.Close(); e == nil { + e = closeErr + } + if e != nil { + return e + } + case "extract": + f, e := root.Open(q.Path) + if e != nil { + return e + } + i, e := f.Stat() + if e != nil || !i.Mode().IsRegular() || i.Size() > MaxFileBytes { + f.Close() + return fs.ErrPermission + } + data, e := io.ReadAll(io.LimitReader(f, MaxFileBytes+1)) + f.Close() + if e != nil || len(data) > MaxFileBytes { + return fs.ErrPermission + } + z, e := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if e != nil { + return e + } + if len(z.File) > 10000 { + return fs.ErrPermission + } + if e = root.Mkdir(stage, 0770); e != nil { + return e + } + seen := map[string]bool{} + for _, entry := range z.File { + name := strings.TrimSuffix(entry.Name, "/") + if name == "" || path.Clean(name) != name || !validName(name) || strings.HasPrefix(name, "/") || protected(name) || entry.Mode()&fs.ModeSymlink != 0 || (!entry.Mode().IsRegular() && !entry.FileInfo().IsDir()) || seen[name] { + return fs.ErrPermission + } + seen[name] = true + target := path.Join(stage, name) + if e = check(root, target); e != nil { + return e + } + if entry.FileInfo().IsDir() { + if e = root.MkdirAll(target, 0770); e != nil { + return e + } + continue + } + if entry.UncompressedSize64 > budget { + return fs.ErrPermission + } + if e = root.MkdirAll(path.Dir(target), 0770); e != nil { + return e + } + input, e := entry.Open() + if e != nil { + return e + } + output, e := root.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660) + if e != nil { + input.Close() + return e + } + n, e := io.Copy(output, io.LimitReader(input, int64(budget)+1)) + input.Close() + output.Close() + if e != nil || uint64(n) > budget { + return fs.ErrPermission + } + budget -= uint64(n) + } + default: + return fs.ErrPermission + } + if e = check(root, q.To); e != nil { + return e + } + if e = absent(root, q.To); e != nil { + return e + } + return root.Rename(stage, q.To) +} + +type budgetWriter struct { + w io.Writer + left uint64 +} + +func (w *budgetWriter) Write(b []byte) (int, error) { + if uint64(len(b)) > w.left { + return 0, fs.ErrPermission + } + n, e := w.w.Write(b) + w.left -= uint64(n) + return n, e +} +func copyTree(root *os.Root, from, to string, budget *uint64, count *int) error { + *count++ + if *count > 10000 { + return fs.ErrPermission + } + if e := check(root, from); e != nil { + return e + } + i, e := root.Lstat(from) + if e != nil { + return e + } + if i.IsDir() { + if e = root.Mkdir(to, 0770); e != nil { + return e + } + dir, e := root.Open(from) + if e != nil { + return e + } + entries, e := dir.ReadDir(10001) + dir.Close() + if e != nil && e != io.EOF { + return e + } + for _, entry := range entries { + source := path.Join(from, entry.Name()) + if protected(source) { + continue + } + if e = copyTree(root, source, path.Join(to, entry.Name()), budget, count); e != nil { + return e + } + } + return nil + } + if !i.Mode().IsRegular() || uint64(i.Size()) > *budget { + return fs.ErrPermission + } + input, e := root.Open(from) + if e != nil { + return e + } + defer input.Close() + output, e := root.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660) + if e != nil { + return e + } + n, e := io.Copy(output, io.LimitReader(input, int64(*budget)+1)) + output.Close() + if e != nil || uint64(n) > *budget { + return fs.ErrPermission + } + *budget -= uint64(n) + return nil +} +func zipTree(root *os.Root, z *zip.Writer, name, archiveName string, count *int, inputBudget *uint64) error { + *count++ + if *count > 10000 { + return fs.ErrPermission + } + if e := check(root, name); e != nil { + return e + } + i, e := root.Lstat(name) + if e != nil { + return e + } + if i.IsDir() { + dir, e := root.Open(name) + if e != nil { + return e + } + entries, e := dir.ReadDir(10001) + dir.Close() + if e != nil && e != io.EOF { + return e + } + for _, entry := range entries { + source := path.Join(name, entry.Name()) + if protected(source) { + continue + } + if e = zipTree(root, z, source, path.Join(archiveName, entry.Name()), count, inputBudget); e != nil { + return e + } + } + return nil + } + if !i.Mode().IsRegular() { + return fs.ErrPermission + } + if uint64(i.Size()) > *inputBudget { + return fs.ErrPermission + } + *inputBudget -= uint64(i.Size()) + header, e := zip.FileInfoHeader(i) + if e != nil { + return e + } + header.Name = archiveName + header.Method = zip.Deflate + dst, e := z.CreateHeader(header) + if e != nil { + return e + } + f, e := root.Open(name) + if e != nil { + return e + } + defer f.Close() + _, e = io.Copy(dst, io.LimitReader(f, maxExpanded+1)) + return e +} +func listTrash(root *os.Root, out *Response) error { + out.Trash = []TrashEntry{} + if e := check(root, ".sea-trash"); e != nil { + return e + } + dir, e := root.Open(".sea-trash") + if errors.Is(e, fs.ErrNotExist) { + return nil + } + if e != nil { + return e + } + entries, e := dir.ReadDir(10001) + dir.Close() + if e != nil && e != io.EOF { + return e + } + if len(entries) > 10000 { + return fs.ErrPermission + } + for _, entry := range entries { + if !strings.HasSuffix(entry.Name(), ".json") { + continue + } + name := ".sea-trash/" + entry.Name() + if check(root, name) != nil { + continue + } + f, e := root.Open(name) + if e != nil { + continue + } + var v TrashEntry + e = json.NewDecoder(io.LimitReader(f, 4096)).Decode(&v) + f.Close() + if e == nil && len(v.ID) == 32 && strings.Trim(v.ID, "0123456789abcdef") == "" && entry.Name() == v.ID+".json" && userPath(root, v.OriginalPath) == nil { + if _, e = root.Lstat(".sea-trash/" + v.ID); e == nil { + out.Trash = append(out.Trash, v) + } + } + } + return nil +} + +func newZipBudget() *uint64 { v := uint64(maxExpanded); return &v } diff --git a/backend/internal/nodefiles/operations_test.go b/backend/internal/nodefiles/operations_test.go new file mode 100644 index 0000000..51932da --- /dev/null +++ b/backend/internal/nodefiles/operations_test.go @@ -0,0 +1,77 @@ +package nodefiles + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "testing" +) + +func TestFileOperationsRoundTripAndQuota(t *testing.T) { + dir := t.TempDir() + os.Mkdir(filepath.Join(dir, "source"), 0770) + os.WriteFile(filepath.Join(dir, "source", "hello.txt"), []byte("security-marker"), 0660) + call := func(q Request) Response { return Execute(dir, q) } + if v := call(Request{Operation: "copy", Path: "source", To: "too-small", Budget: 2}); v.Error == "" { + t.Fatal("copy ignored remaining quota") + } + if _, e := os.Stat(filepath.Join(dir, "too-small")); !os.IsNotExist(e) { + t.Fatal("failed copy left target") + } + for _, q := range []Request{{Operation: "copy", Path: "source", To: "copy", Budget: 1024}, {Operation: "move", Path: "copy", To: "moved"}, {Operation: "zip", Path: "source", To: "source.zip", Budget: 4096}, {Operation: "extract", Path: "source.zip", To: "expanded", Budget: 4096}, {Operation: "trash", Path: "moved"}} { + if v := call(q); v.Error != "" { + t.Fatalf("%s: %s", q.Operation, v.Error) + } + } + list := call(Request{Operation: "trash_list"}) + if list.Error != "" || len(list.Trash) != 1 || list.Trash[0].OriginalPath != "moved" { + t.Fatalf("trash %+v", list) + } + if v := call(Request{Operation: "restore", Path: list.Trash[0].ID, To: "restored"}); v.Error != "" { + t.Fatal(v.Error) + } + raw, e := os.ReadFile(filepath.Join(dir, "restored", "hello.txt")) + if e != nil || string(raw) != "security-marker" { + t.Fatal("restoration lost content") + } + if v := call(Request{Operation: "copy", Path: "source", To: "source/nested", Budget: 100}); v.Error == "" { + t.Fatal("recursive copy accepted") + } + for _, name := range []string{".sea-runtime", ".user.ini", ".sea-trash/abc", "../outside", "/etc/passwd"} { + if v := call(Request{Operation: "copy", Path: "source", To: name, Budget: 4096}); v.Error == "" { + t.Fatalf("reserved destination %s accepted", name) + } + } +} +func TestExtractRejectsZipSlipSymlinksAndBombs(t *testing.T) { + for _, test := range []struct { + name string + mode os.FileMode + data string + budget uint64 + }{{"../escape", 0660, "x", 1024}, {"/escape", 0660, "x", 1024}, {".sea-runtime/secret", 0660, "x", 1024}, {"link", os.ModeSymlink | 0777, "/etc/passwd", 1024}, {"large.txt", 0660, "xxxxxxxxxxxxxxxxxxxxxxxxx", 2}} { + t.Run(test.name, func(t *testing.T) { + dir := t.TempDir() + var buf bytes.Buffer + z := zip.NewWriter(&buf) + header := &zip.FileHeader{Name: test.name, Method: zip.Deflate} + header.SetMode(test.mode) + f, _ := z.CreateHeader(header) + f.Write([]byte(test.data)) + z.Close() + os.WriteFile(filepath.Join(dir, "bad.zip"), buf.Bytes(), 0660) + v := Execute(dir, Request{Operation: "extract", Path: "bad.zip", To: "target", Budget: test.budget}) + if v.Error == "" { + t.Fatal("unsafe archive accepted") + } + if _, e := os.Stat(filepath.Join(dir, "target")); !os.IsNotExist(e) { + t.Fatal("failed extraction published target") + } + stages, _ := filepath.Glob(filepath.Join(dir, ".sea-op-*")) + if len(stages) > 0 { + t.Fatal("failed extraction left staging files") + } + }) + } +} diff --git a/backend/internal/nodefiles/protected_paths_test.go b/backend/internal/nodefiles/protected_paths_test.go new file mode 100644 index 0000000..e4719f0 --- /dev/null +++ b/backend/internal/nodefiles/protected_paths_test.go @@ -0,0 +1,50 @@ +package nodefiles + +import ( + "os" + "path/filepath" + "testing" +) + +func TestPlatformConfigurationCannotBeReadOrReplaced(t *testing.T) { + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, ".sea-runtime"), 0700); err != nil { + t.Fatal(err) + } + original := []byte("PLATFORM_CONFIGURATION_SENTINEL") + for _, name := range []string{".user.ini", ".sea-runtime/launch.env"} { + if err := os.WriteFile(filepath.Join(root, name), original, 0600); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(root, "ordinary.txt"), []byte("ordinary"), 0600); err != nil { + t.Fatal(err) + } + for _, name := range []string{".user.ini", ".sea-runtime/launch.env", "new/../.sea-runtime/launch.env"} { + for _, operation := range []string{"read", "stat", "write", "remove", "mkdir"} { + out := Execute(root, Request{Operation: operation, Path: name, Data: []byte("replaced"), Overwrite: true}) + if out.Error != "denied" { + t.Fatalf("%s %s: %+v", operation, name, out) + } + } + } + if out := Execute(root, Request{Operation: "rename", Path: "ordinary.txt", To: ".user.ini"}); out.Error != "denied" { + t.Fatalf("rename onto protected file accepted: %+v", out) + } + for _, name := range []string{".user.ini", ".sea-runtime/launch.env"} { + content, err := os.ReadFile(filepath.Join(root, name)) + if err != nil || string(content) != string(original) { + t.Fatal("platform file changed", name, err) + } + } + if out := Execute(root, Request{Operation: "read", Path: "ordinary.txt"}); out.Error != "" || string(out.Data) != "ordinary" { + t.Fatal("ordinary file read blocked", out.Error) + } + // Trash is still accessible only through its dedicated API, including emptying. + if err := os.Mkdir(filepath.Join(root, ".sea-trash"), 0700); err != nil { + t.Fatal(err) + } + if out := Execute(root, Request{Operation: "empty_trash", Path: ".sea-trash"}); out.Error != "" { + t.Fatal("dedicated trash cleanup blocked", out.Error) + } +} diff --git a/backend/internal/notify/smtp.go b/backend/internal/notify/smtp.go new file mode 100644 index 0000000..00ad945 --- /dev/null +++ b/backend/internal/notify/smtp.go @@ -0,0 +1,244 @@ +package notify + +import ( + "bufio" + "context" + "crypto/tls" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "mime" + "net" + "net/mail" + "net/smtp" + "strconv" + "strings" + "time" + + "sea-vhost/internal/secrets" + "sea-vhost/internal/store" +) + +type smtpConfig struct { + Host string `json:"host"` + Port int `json:"port"` + Username string `json:"username"` + Secret string `json:"secret"` + From string `json:"from"` + AdminRecipients string `json:"adminRecipients"` + StartTLS bool `json:"startTls"` + Enabled bool `json:"enabled"` +} + +type Dispatcher struct { + store *store.Store + box *secrets.Box +} + +func New(database *store.Store, secret string) *Dispatcher { + return &Dispatcher{store: database, box: secrets.New(secret)} +} + +func (d *Dispatcher) Run(ctx context.Context, interval time.Duration) { + if interval <= 0 { + interval = time.Minute + } + d.dispatch(ctx) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + d.dispatch(ctx) + } + } +} + +func (d *Dispatcher) dispatch(ctx context.Context) { + cfg, err := d.config(ctx) + if err != nil || !cfg.Enabled { + return + } + items, err := d.store.PendingAdminNotifications(ctx, time.Now(), 25) + if err != nil { + return + } + for _, item := range items { + operation, cancel := context.WithTimeout(ctx, 30*time.Second) + err = send(operation, cfg, item) + cancel() + if err == nil { + _ = d.store.CompleteAdminNotification(context.WithoutCancel(ctx), item.ID) + continue + } + delay := time.Duration(1< 65535 { + return errors.New("invalid SMTP port") + } + from, err := mail.ParseAddress(cfg.From) + if err != nil || from.Address != cfg.From { + return errors.New("invalid SMTP sender") + } + if len(recipients(cfg.AdminRecipients)) == 0 { + return errors.New("SMTP recipients are empty") + } + if cfg.Username != "" && cfg.Secret == "" { + return errors.New("SMTP password is empty") + } + return nil +} + +func send(ctx context.Context, cfg smtpConfig, item store.AdminNotification) error { + address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)) + dialer := &net.Dialer{Timeout: 10 * time.Second} + var connection net.Conn + var err error + implicitTLS := cfg.Port == 465 + if implicitTLS { + connection, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{MinVersion: tls.VersionTLS12, ServerName: cfg.Host}) + } else { + connection, err = dialer.DialContext(ctx, "tcp", address) + } + if err != nil { + return fmt.Errorf("connect SMTP: %w", err) + } + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(25 * time.Second)) + client, err := smtp.NewClient(connection, cfg.Host) + if err != nil { + return err + } + defer client.Close() + secure := implicitTLS + if !implicitTLS && cfg.StartTLS { + if ok, _ := client.Extension("STARTTLS"); !ok { + return errors.New("SMTP server does not support STARTTLS") + } + if err = client.StartTLS(&tls.Config{MinVersion: tls.VersionTLS12, ServerName: cfg.Host}); err != nil { + return err + } + secure = true + } + if cfg.Username != "" { + if !secure { + return errors.New("SMTP authentication requires TLS") + } + if err = client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Secret, cfg.Host)); err != nil { + return err + } + } + if err = client.Mail(cfg.From); err != nil { + return err + } + to := recipients(cfg.AdminRecipients) + for _, recipient := range to { + if err = client.Rcpt(recipient); err != nil { + return err + } + } + writer, err := client.Data() + if err != nil { + return err + } + buffer := bufio.NewWriter(writer) + subject := "[Sea vHost][" + strings.ToUpper(item.Severity) + "] " + sanitizeHeader(item.Title) + headers := []string{ + "From: " + cfg.From, + "To: " + strings.Join(to, ", "), + "Subject: " + mime.QEncoding.Encode("UTF-8", subject), + "Date: " + time.Now().Format(time.RFC1123Z), + "MIME-Version: 1.0", + "Content-Type: text/plain; charset=UTF-8", + "Content-Transfer-Encoding: base64", + "", + } + for _, header := range headers { + if _, err = buffer.WriteString(header + "\r\n"); err != nil { + return err + } + } + body := fmt.Sprintf("类型:%s\n级别:%s\n时间:%s\n\n%s\n", item.Category, item.Severity, time.Now().Format(time.RFC3339), item.Detail) + encoded := base64.StdEncoding.EncodeToString([]byte(body)) + for len(encoded) > 76 { + _, _ = buffer.WriteString(encoded[:76] + "\r\n") + encoded = encoded[76:] + } + _, _ = buffer.WriteString(encoded + "\r\n") + if err = buffer.Flush(); err != nil { + return err + } + if err = writer.Close(); err != nil { + return err + } + return client.Quit() +} + +func recipients(value string) []string { + fields := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' || r == '\n' }) + result := make([]string, 0, len(fields)) + seen := map[string]bool{} + for _, field := range fields { + address := strings.TrimSpace(field) + parsed, err := mail.ParseAddress(address) + if err == nil && parsed.Address == address && !seen[strings.ToLower(address)] { + seen[strings.ToLower(address)] = true + result = append(result, address) + } + } + return result +} + +func sanitizeHeader(value string) string { + return strings.ReplaceAll(strings.ReplaceAll(value, "\r", " "), "\n", " ") +} + +func validDNSName(value string) bool { + value = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), ".")) + if value == "" || len(value) > 253 { + return false + } + for _, label := range strings.Split(value, ".") { + if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { + return false + } + for _, character := range label { + if !(character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '-') { + return false + } + } + } + return true +} diff --git a/backend/internal/notify/smtp_test.go b/backend/internal/notify/smtp_test.go new file mode 100644 index 0000000..1dd056a --- /dev/null +++ b/backend/internal/notify/smtp_test.go @@ -0,0 +1,137 @@ +package notify + +import ( + "bufio" + "context" + "encoding/base64" + "fmt" + "mime" + "net" + "net/mail" + "strconv" + "strings" + "testing" + "time" + + "sea-vhost/internal/store" +) + +func TestSMTPDeliveryAndHeaderSafety(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + message := make(chan string, 1) + go func() { + connection, e := listener.Accept() + if e != nil { + return + } + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(10 * time.Second)) + reader := bufio.NewReader(connection) + fmt.Fprint(connection, "220 localhost test SMTP\r\n") + for { + line, e := reader.ReadString('\n') + if e != nil { + return + } + switch { + case strings.HasPrefix(line, "EHLO"): + fmt.Fprint(connection, "250 localhost\r\n") + case strings.HasPrefix(line, "MAIL FROM:"), strings.HasPrefix(line, "RCPT TO:"): + fmt.Fprint(connection, "250 accepted\r\n") + case strings.HasPrefix(line, "DATA"): + fmt.Fprint(connection, "354 continue\r\n") + var data strings.Builder + for { + line, e = reader.ReadString('\n') + if e != nil { + return + } + if line == ".\r\n" { + break + } + data.WriteString(line) + } + message <- data.String() + fmt.Fprint(connection, "250 queued\r\n") + case strings.HasPrefix(line, "QUIT"): + fmt.Fprint(connection, "221 bye\r\n") + return + default: + fmt.Fprint(connection, "500 unexpected\r\n") + } + } + }() + host, port, _ := net.SplitHostPort(listener.Addr().String()) + number, _ := strconv.Atoi(port) + err = send(context.Background(), smtpConfig{Host: host, Port: number, From: "sender@seavhost.test", AdminRecipients: "admin@seavhost.test"}, store.AdminNotification{Title: "主机超额\r\nBcc: attacker@example.test", Category: "quota", Severity: "critical", Detail: "仅本机测试字符串 SEA-SMTP-CANARY"}) + if err != nil { + t.Fatal(err) + } + select { + case raw := <-message: + parsed, e := mail.ReadMessage(strings.NewReader(raw)) + if e != nil { + t.Fatal(e) + } + if parsed.Header.Get("Bcc") != "" { + t.Fatal("header injection") + } + subject, e := new(mime.WordDecoder).DecodeHeader(parsed.Header.Get("Subject")) + if e != nil || !strings.Contains(subject, "主机超额") { + t.Fatalf("invalid Unicode subject: %v", e) + } + body := base64.NewDecoder(base64.StdEncoding, parsed.Body) + scanner := bufio.NewScanner(body) + var text strings.Builder + for scanner.Scan() { + text.WriteString(scanner.Text()) + } + if !strings.Contains(text.String(), "SEA-SMTP-CANARY") { + t.Fatal("notification body lost") + } + case <-time.After(5 * time.Second): + t.Fatal("message not delivered") + } +} + +func TestSMTPDoesNotSendCredentialsWithoutTLS(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + commands := make(chan string, 1) + go func() { + connection, e := listener.Accept() + if e != nil { + return + } + defer connection.Close() + _ = connection.SetDeadline(time.Now().Add(5 * time.Second)) + fmt.Fprint(connection, "220 local\r\n") + reader := bufio.NewReader(connection) + var all strings.Builder + for { + line, e := reader.ReadString('\n') + if e != nil { + commands <- all.String() + return + } + all.WriteString(line) + fmt.Fprint(connection, "250 localhost\r\n") + } + }() + host, port, _ := net.SplitHostPort(listener.Addr().String()) + number, _ := strconv.Atoi(port) + err = send(context.Background(), smtpConfig{Host: host, Port: number, Username: "test", Secret: "must-not-transmit"}, store.AdminNotification{}) + if err == nil || !strings.Contains(err.Error(), "requires TLS") { + t.Fatalf("insecure authentication allowed: %v", err) + } + if command := <-commands; strings.Contains(command, "AUTH") || strings.Contains(command, "must-not-transmit") { + t.Fatal("plaintext credential sent") + } +} diff --git a/backend/internal/panel/broker_client.go b/backend/internal/panel/broker_client.go new file mode 100644 index 0000000..4482d99 --- /dev/null +++ b/backend/internal/panel/broker_client.go @@ -0,0 +1,285 @@ +package panel + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "strings" + "time" +) + +type BrokerCredentials struct { + URL string `json:"url"` + APIKey string `json:"apiKey"` + TLSInsecure bool `json:"tlsInsecure"` +} + +type PanelInspection struct { + Versions RuntimeCatalog `json:"versions"` + Runtimes RuntimeCapabilities `json:"runtimes"` +} + +type BrokerClient struct { + http *http.Client + internalToken string +} + +func NewTransportClient(transport http.RoundTripper, timeout time.Duration) *BrokerClient { + return &BrokerClient{http: &http.Client{Transport: transport, Timeout: timeout}} +} + +type brokerRequest struct { + Operation string `json:"operation"` + Site *SiteSpec `json:"site,omitempty"` + Runtime *RuntimeSpec `json:"runtime,omitempty"` + ID int64 `json:"id,omitempty"` + SiteID int64 `json:"siteId,omitempty"` + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + Path string `json:"path,omitempty"` + Domain string `json:"domain,omitempty"` + MaxBytes int64 `json:"maxBytes,omitempty"` + Port int `json:"port,omitempty"` + Domains []string `json:"domains,omitempty"` + PrivateKey string `json:"privateKey,omitempty"` + Certificate string `json:"certificate,omitempty"` + Enabled bool `json:"enabled,omitempty"` + Credentials *BrokerCredentials `json:"credentials,omitempty"` + SourcePath string `json:"sourcePath,omitempty"` +} + +type brokerResponse struct { + Runtime *RuntimeSpec `json:"runtime,omitempty"` + Pending bool `json:"pending"` + ID int64 `json:"id,omitempty"` + Bytes uint64 `json:"bytes,omitempty"` + Catalog RuntimeCatalog `json:"catalog,omitempty"` + Capabilities RuntimeCapabilities `json:"capabilities,omitempty"` + Environments []RuntimeEnvironment `json:"environments,omitempty"` + Sites []ExistingSite `json:"sites,omitempty"` + Message string `json:"message,omitempty"` +} + +func NewBrokerClient(socket string, timeout time.Duration, internalToken ...string) *BrokerClient { + transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket) + }} + token := "" + if len(internalToken) > 0 { + token = strings.TrimSpace(internalToken[0]) + } + return &BrokerClient{http: &http.Client{Transport: transport, Timeout: timeout}, internalToken: token} +} + +func (c *BrokerClient) call(ctx context.Context, path, setupToken string, input any, output any) error { + body, err := json.Marshal(input) + if err != nil { + return err + } + request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://unix"+path, bytes.NewReader(body)) + if err != nil { + return err + } + request.Header.Set("Content-Type", "application/json") + if c.internalToken != "" { + request.Header.Set("Authorization", "Bearer "+c.internalToken) + } + if setupToken != "" { + request.Header.Set("X-Setup-Token", setupToken) + } + response, err := c.http.Do(request) + if err != nil { + return fmt.Errorf("panel broker: %w", err) + } + defer response.Body.Close() + data, err := io.ReadAll(io.LimitReader(response.Body, 128<<10)) + if err != nil { + return err + } + if response.StatusCode < 200 || response.StatusCode > 299 { + var payload struct { + Error struct { + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal(data, &payload) == nil && strings.TrimSpace(payload.Error.Message) != "" { + return errors.New(payload.Error.Message) + } + return fmt.Errorf("panel broker rejected request (%d)", response.StatusCode) + } + if output != nil && len(data) > 0 { + return json.Unmarshal(data, output) + } + return nil +} + +func (c *BrokerClient) TestCredentials(ctx context.Context, credentials BrokerCredentials, setupToken string) error { + _, err := c.InspectCredentials(ctx, credentials, setupToken) + return err +} + +func (c *BrokerClient) InspectCredentials(ctx context.Context, credentials BrokerCredentials, setupToken string) (PanelInspection, error) { + var inspection PanelInspection + err := c.call(ctx, "/v1/setup/test", setupToken, credentials, &inspection) + return inspection, err +} + +func (c *BrokerClient) Configure(ctx context.Context, credentials BrokerCredentials, setupToken string) error { + return c.call(ctx, "/v1/setup/configure", setupToken, credentials, nil) +} + +func (c *BrokerClient) operation(ctx context.Context, request brokerRequest) (brokerResponse, error) { + var response brokerResponse + err := c.call(ctx, "/v1/operations", "", request, &response) + return response, err +} + +func (c *BrokerClient) Ping(ctx context.Context) error { + _, err := c.operation(ctx, brokerRequest{Operation: "ping"}) + return err +} + +func (c *BrokerClient) RuntimeCatalog(ctx context.Context) (RuntimeCatalog, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "runtime_catalog"}) + return response.Catalog, err +} + +func (c *BrokerClient) RuntimeCapabilities(ctx context.Context) (RuntimeCapabilities, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "runtime_capabilities"}) + return response.Capabilities, err +} + +func (c *BrokerClient) RuntimeEnvironments(ctx context.Context) ([]RuntimeEnvironment, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "runtime_environments"}) + return response.Environments, err +} + +func (c *BrokerClient) InstallRuntimeComponent(ctx context.Context, runtimeName string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "install_runtime_component", Name: runtimeName}) + return err +} + +func (c *BrokerClient) InstallRuntimeEnvironment(ctx context.Context, runtimeName, version string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "install_runtime_environment", Name: runtimeName, Version: version}) + return err +} + +func (c *BrokerClient) CreateSite(ctx context.Context, spec SiteSpec) (int64, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "create_site", Site: &spec}) + return response.ID, err +} +func (c *BrokerClient) ListUnmanagedSites(ctx context.Context) ([]ExistingSite, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "list_unmanaged_sites"}) + return response.Sites, err +} +func (c *BrokerClient) AdoptSite(ctx context.Context, id int64, sourcePath string, spec SiteSpec) error { + _, err := c.operation(ctx, brokerRequest{Operation: "adopt_site", ID: id, SourcePath: sourcePath, Site: &spec}) + return err +} +func (c *BrokerClient) RollbackAdoption(ctx context.Context, id int64, name, sourcePath string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "rollback_adoption", ID: id, Name: name, SourcePath: sourcePath}) + return err +} +func (c *BrokerClient) SetSitePath(context.Context, int64, string) error { + return errors.New("site path changes are only available through managed adoption") +} + +func (c *BrokerClient) DeleteSite(ctx context.Context, id int64, name string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "delete_site", ID: id, Name: name}) + return err +} + +func (c *BrokerClient) AddDomain(ctx context.Context, siteID int64, siteName, domain string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "add_domain", SiteID: siteID, Name: siteName, Domain: domain}) + return err +} + +func (c *BrokerClient) DeleteDomain(ctx context.Context, siteID int64, siteName, domain string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "delete_domain", SiteID: siteID, Name: siteName, Domain: domain}) + return err +} + +func (c *BrokerClient) CreateFTP(ctx context.Context, username, password, path string, maxBytes int64) (int64, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "create_ftp", Username: username, Password: password, Path: path, MaxBytes: maxBytes}) + return response.ID, err +} + +func (c *BrokerClient) DeleteFTP(ctx context.Context, id int64, username string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "delete_ftp", ID: id, Username: username}) + return err +} +func (c *BrokerClient) SetFTPState(ctx context.Context, id int64, username string, enabled bool) error { + _, err := c.operation(ctx, brokerRequest{Operation: "set_ftp_state", ID: id, Username: username, Enabled: enabled}) + return err +} + +func (c *BrokerClient) CreateDatabase(ctx context.Context, name, username, password string, siteID int64) (int64, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "create_database", Name: name, Username: username, Password: password, SiteID: siteID}) + return response.ID, err +} + +func (c *BrokerClient) DeleteDatabase(ctx context.Context, id int64, name string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "delete_database", ID: id, Name: name}) + return err +} + +func (c *BrokerClient) DatabaseSize(ctx context.Context, id int64, name string) (uint64, error) { + response, err := c.operation(ctx, brokerRequest{Operation: "database_size", ID: id, Name: name}) + return response.Bytes, err +} + +func (c *BrokerClient) ConfigureRuntime(ctx context.Context, spec RuntimeSpec) error { + _, err := c.operation(ctx, brokerRequest{Operation: "configure_runtime", Runtime: &spec}) + return err +} + +func (c *BrokerClient) RemoveRuntime(ctx context.Context, spec RuntimeSpec) error { + _, err := c.operation(ctx, brokerRequest{Operation: "remove_runtime", Runtime: &spec}) + return err +} + +func (c *BrokerClient) SetRuntimeState(ctx context.Context, spec RuntimeSpec, enabled bool) error { + _, err := c.operation(ctx, brokerRequest{Operation: "set_runtime_state", Runtime: &spec, Enabled: enabled}) + return err +} + +func (c *BrokerClient) ConfigureProxy(ctx context.Context, siteID int64, domain string, port int) error { + _, err := c.operation(ctx, brokerRequest{Operation: "configure_proxy", SiteID: siteID, Domain: domain, Port: port}) + return err +} + +func (c *BrokerClient) RequestCertificate(ctx context.Context, siteID int64, path string, domains []string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "request_certificate", SiteID: siteID, Path: path, Domains: domains}) + return err +} + +func (c *BrokerClient) InstallCertificate(ctx context.Context, siteID int64, siteName, privateKey, certificate string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "install_certificate", SiteID: siteID, Name: siteName, PrivateKey: privateKey, Certificate: certificate}) + return err +} + +func (c *BrokerClient) DisableCertificate(ctx context.Context, siteID int64, siteName string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "disable_certificate", SiteID: siteID, Name: siteName}) + return err +} + +func (c *BrokerClient) SetSiteState(ctx context.Context, siteID int64, name string, enabled bool) error { + _, err := c.operation(ctx, brokerRequest{Operation: "set_site_state", SiteID: siteID, Name: name, Enabled: enabled}) + return err +} + +func (c *BrokerClient) SetSiteRunPath(ctx context.Context, siteID int64, runPath string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "set_site_run_path", SiteID: siteID, Path: runPath}) + return err +} +func (c *BrokerClient) MigrateRuntimeIdentity(ctx context.Context, siteID int64, runUser string, enabled bool) error { + _, err := c.operation(ctx, brokerRequest{Operation: "migrate_runtime_identity", SiteID: siteID, Username: runUser, Enabled: enabled}) + return err +} diff --git a/backend/internal/panel/broker_server.go b/backend/internal/panel/broker_server.go new file mode 100644 index 0000000..51ae2bb --- /dev/null +++ b/backend/internal/panel/broker_server.go @@ -0,0 +1,1235 @@ +package panel + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + pathpkg "path" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "time" +) + +var ( + errBrokerConfigured = errors.New("panel broker is already configured with different credentials") + errOutsideManaged = errors.New("resource is outside the Sea vHost managed set") + brokerHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`) + brokerProjectPattern = regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`) + brokerDomainPattern = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)$`) + brokerVersionPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,40}$`) + brokerRunUserPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`) +) + +type brokerCredentialFile struct { + Version int `json:"version"` + URL string `json:"url"` + APIKey string `json:"api_key"` + TLSInsecure bool `json:"tls_insecure"` +} + +type managedSite struct { + ACMEOrder string `json:"acme_order,omitempty"` + Name string `json:"name"` + Domain string `json:"domain"` + Path string `json:"path"` + RunPath string `json:"run_path"` + RunUser string `json:"run_user"` + ResourceName string `json:"resource_name"` + Port int `json:"port"` + ProcessLimit int `json:"process_limit"` + Domains map[string]bool `json:"domains"` + Runtime *RuntimeSpec `json:"runtime,omitempty"` + ProxyReady bool `json:"proxy_ready,omitempty"` +} + +type brokerRegistry struct { + Version int `json:"version"` + Sites map[int64]*managedSite `json:"sites"` + FTP map[int64]string `json:"ftp"` + Databases map[int64]string `json:"databases"` +} + +type BrokerServer struct { + stateless bool + mu sync.Mutex + stateDir string + tenantRoot string + setupToken string + internalToken string + setupOpen bool + direct Interface + registry brokerRegistry + runtimeJobs map[string]bool + newPanel func(BrokerCredentials) Interface +} + +func NewBrokerServer(stateDir, tenantRoot, setupToken string, internalToken ...string) (*BrokerServer, error) { + return newBrokerServer(stateDir, tenantRoot, setupToken, func(credentials BrokerCredentials) Interface { + return NewClient(credentials.URL, credentials.APIKey, credentials.TLSInsecure, 30*time.Minute) + }, internalToken...) +} + +func newBrokerServer(stateDir, tenantRoot, setupToken string, factory func(BrokerCredentials) Interface, internalToken ...string) (*BrokerServer, error) { + setupToken = strings.TrimSpace(setupToken) + if err := os.MkdirAll(stateDir, 0700); err != nil { + return nil, err + } + server := &BrokerServer{ + stateDir: stateDir, tenantRoot: tenantRoot, setupToken: setupToken, newPanel: factory, + registry: brokerRegistry{Version: 1, Sites: map[int64]*managedSite{}, FTP: map[int64]string{}, Databases: map[int64]string{}}, + runtimeJobs: map[string]bool{}, + } + if len(internalToken) > 0 { + server.internalToken = strings.TrimSpace(internalToken[0]) + } + if err := server.loadRegistry(); err != nil { + return nil, err + } + credentials, err := server.loadCredentials() + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + if err == nil { + server.direct = factory(credentials) + } else if len(setupToken) < 24 { + return nil, errors.New("SEA_SETUP_TOKEN must contain at least 24 characters before panel broker configuration") + } + server.setupOpen = server.direct == nil && len(setupToken) >= 24 + return server, nil +} + +func (s *BrokerServer) Handler() http.Handler { + mux := http.NewServeMux() + if s.stateless { + mux.HandleFunc("POST /v1/scoped-operations", s.authorizeInternal(s.scopedOperations)) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { + brokerWriteJSON(w, 200, map[string]any{"status": "ok", "stateless": true}) + }) + return mux + } + mux.HandleFunc("GET /healthz", s.health) + if s.setupOpen { + mux.HandleFunc("POST /v1/setup/test", s.authorizeSetup(s.testCredentials)) + mux.HandleFunc("POST /v1/setup/configure", s.authorizeSetup(s.configure)) + } + mux.HandleFunc("POST /v1/operations", s.authorizeInternal(s.operations)) + return http.MaxBytesHandler(mux, 256<<10) +} + +func (s *BrokerServer) authorizeInternal(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if s.internalToken != "" { + supplied := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if len(supplied) != len(s.internalToken) || subtle.ConstantTimeCompare([]byte(supplied), []byte(s.internalToken)) != 1 { + brokerWriteError(w, http.StatusUnauthorized, "内部调用鉴权失败") + return + } + } + next(w, r) + } +} + +func (s *BrokerServer) health(w http.ResponseWriter, _ *http.Request) { + s.mu.Lock() + configured := s.direct != nil + s.mu.Unlock() + status := "unconfigured" + if configured { + status = "ok" + } + brokerWriteJSON(w, http.StatusOK, map[string]string{"status": status}) +} + +func (s *BrokerServer) authorizeSetup(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + setupOpen := s.setupOpen + s.mu.Unlock() + if !setupOpen { + brokerWriteError(w, http.StatusNotFound, "安装接口已关闭") + return + } + supplied := r.Header.Get("X-Setup-Token") + if len(supplied) != len(s.setupToken) || subtle.ConstantTimeCompare([]byte(supplied), []byte(s.setupToken)) != 1 { + brokerWriteError(w, http.StatusUnauthorized, "安装令牌无效") + return + } + next(w, r) + } +} + +func (s *BrokerServer) testCredentials(w http.ResponseWriter, r *http.Request) { + var credentials BrokerCredentials + if !brokerDecode(w, r, &credentials) { + return + } + credentials = normalizeBrokerCredentials(credentials) + if err := validateBrokerCredentials(credentials); err != nil { + brokerWriteError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + direct := s.newPanel(credentials) + if err := direct.Ping(ctx); err != nil { + brokerWriteError(w, http.StatusUnprocessableEntity, safeBrokerError("宝塔连接失败", err)) + return + } + capabilities, err := direct.RuntimeCapabilities(ctx) + if err != nil { + brokerWriteError(w, http.StatusUnprocessableEntity, safeBrokerError("运行环境检查失败", err)) + return + } + brokerWriteJSON(w, http.StatusOK, inspectionFromCapabilities(capabilities)) +} + +func (s *BrokerServer) configure(w http.ResponseWriter, r *http.Request) { + var credentials BrokerCredentials + if !brokerDecode(w, r, &credentials) { + return + } + credentials = normalizeBrokerCredentials(credentials) + if err := validateBrokerCredentials(credentials); err != nil { + brokerWriteError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + direct := s.newPanel(credentials) + if err := direct.Ping(ctx); err != nil { + brokerWriteError(w, http.StatusUnprocessableEntity, safeBrokerError("宝塔连接失败", err)) + return + } + if _, err := direct.RuntimeCapabilities(ctx); err != nil { + brokerWriteError(w, http.StatusUnprocessableEntity, safeBrokerError("运行环境检查失败", err)) + return + } + s.mu.Lock() + defer s.mu.Unlock() + stored, err := s.loadCredentials() + if err == nil { + if sameBrokerCredentials(stored, credentials) { + s.direct = direct + brokerWriteJSON(w, http.StatusOK, map[string]bool{"ok": true}) + return + } + brokerWriteError(w, http.StatusConflict, errBrokerConfigured.Error()) + return + } + if !errors.Is(err, os.ErrNotExist) { + brokerWriteError(w, http.StatusInternalServerError, "无法读取面板代理配置") + return + } + if err := s.saveCredentials(credentials); err != nil { + brokerWriteError(w, http.StatusInternalServerError, "无法保存面板代理配置") + return + } + s.direct = direct + brokerWriteJSON(w, http.StatusCreated, map[string]bool{"ok": true}) +} + +func inspectionFromCapabilities(capabilities RuntimeCapabilities) PanelInspection { + versions := make(RuntimeCatalog, len(capabilities)) + for runtime, capability := range capabilities { + versions[runtime] = capability.Versions + } + return PanelInspection{Versions: versions, Runtimes: capabilities} +} + +func (s *BrokerServer) operations(w http.ResponseWriter, r *http.Request) { + var request brokerRequest + if !brokerDecode(w, r, &request) { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if s.direct == nil { + brokerWriteError(w, http.StatusServiceUnavailable, "面板代理尚未配置") + return + } + response, err := s.execute(r.Context(), request) + if err != nil { + status := http.StatusUnprocessableEntity + if errors.Is(err, errOutsideManaged) { + status = http.StatusForbidden + } + brokerWriteError(w, status, safeBrokerError("面板操作失败", err)) + return + } + brokerWriteJSON(w, http.StatusOK, response) +} + +func (s *BrokerServer) execute(ctx context.Context, request brokerRequest) (brokerResponse, error) { + if request.Operation == "ensure_scheduler" { + manager, ok := s.direct.(SystemScheduler) + if !ok { + return brokerResponse{}, errors.New("面板不支持系统调度器") + } + id, e := manager.EnsureSystemScheduler(ctx) + return brokerResponse{ID: id}, e + } + if request.Operation == "ping" { + return brokerResponse{}, s.direct.Ping(ctx) + } + if request.Operation == "runtime_catalog" { + catalog, err := s.direct.RuntimeCatalog(ctx) + return brokerResponse{Catalog: catalog}, err + } + if request.Operation == "runtime_capabilities" { + capabilities, err := s.direct.RuntimeCapabilities(ctx) + return brokerResponse{Capabilities: capabilities}, err + } + if request.Operation == "runtime_environments" { + environments, err := s.direct.RuntimeEnvironments(ctx) + if err == nil { + for index := range environments { + for key := range s.runtimeJobs { + prefix := environments[index].Name + "/" + if strings.HasPrefix(key, prefix) { + environments[index].Installing = append(environments[index].Installing, strings.TrimPrefix(key, prefix)) + } + } + environments[index].Installing = cleanVersions(environments[index].Installing) + } + } + return brokerResponse{Environments: environments}, err + } + if request.Operation == "list_unmanaged_sites" { + items, err := s.direct.ListUnmanagedSites(ctx) + if err != nil { + return brokerResponse{}, err + } + available := make([]ExistingSite, 0, len(items)) + for _, item := range items { + if _, managed := s.registry.Sites[item.ID]; managed { + continue + } + cleaned := pathpkg.Clean(item.Path) + if !pathpkg.IsAbs(cleaned) || !strings.HasPrefix(cleaned+"/", "/www/wwwroot/") || strings.HasPrefix(cleaned+"/", pathpkg.Clean(s.tenantRoot)+"/") { + continue + } + item.Path = cleaned + available = append(available, item) + } + return brokerResponse{Sites: available}, nil + } + if request.Operation == "managed_runtime" { + site, ok := s.registry.Sites[request.SiteID] + if !ok || site.Runtime == nil { + return brokerResponse{}, errOutsideManaged + } + copy := *site.Runtime + return brokerResponse{Runtime: ©}, nil + } + if request.Operation == "php_update_pending" { + maintenance, ok := s.direct.(RuntimeMaintenance) + if !ok { + return brokerResponse{}, errors.New("PHP maintenance adapter unavailable") + } + pending, err := maintenance.PHPRuntimeUpdatePending(ctx, request.Name) + return brokerResponse{Pending: pending}, err + } + // Confirm the private state directory is writable before any panel mutation. + if err := s.saveRegistry(); err != nil { + return brokerResponse{}, fmt.Errorf("managed resource registry unavailable: %w", err) + } + switch request.Operation { + case "update_php_runtime": + maintenance, ok := s.direct.(RuntimeMaintenance) + if !ok { + return brokerResponse{}, errors.New("PHP update adapter unavailable") + } + return brokerResponse{}, maintenance.UpdatePHPRuntime(ctx, request.Name, request.Version) + case "replace_runtime": + site, ok := s.registry.Sites[request.SiteID] + if !ok || site.Runtime == nil || request.Runtime == nil { + return brokerResponse{}, errOutsideManaged + } + old := *site.Runtime + next := old + next.Version = request.Runtime.Version + if (request.Runtime.EntryFile != old.EntryFile || request.Runtime.Runner) && !validRuntimeEntry(old.Runtime, request.Runtime.EntryFile) { + return brokerResponse{}, errors.New("invalid managed runtime entry") + } + next.EntryFile = request.Runtime.EntryFile + next.Runner = request.Runtime.Runner + + if next != *request.Runtime || !brokerVersionPattern.MatchString(next.Version) { + return brokerResponse{}, errors.New("only managed runtime version changes are allowed") + } + inventory, err := s.direct.RuntimeEnvironments(ctx) + if err != nil { + return brokerResponse{}, err + } + installed := false + for _, item := range inventory { + if item.Name == next.Runtime && slices.Contains(item.Installed, next.Version) { + installed = true + } + } + if !installed { + return brokerResponse{}, errors.New("target runtime version is not installed") + } + if err = s.direct.SetRuntimeState(ctx, old, false); err != nil { + return brokerResponse{}, err + } + if err = s.direct.RemoveRuntime(ctx, old); err != nil { + return brokerResponse{}, err + } + if err = s.direct.ConfigureRuntime(ctx, next); err != nil { + if restoreErr := s.direct.ConfigureRuntime(context.WithoutCancel(ctx), old); restoreErr != nil { + return brokerResponse{}, fmt.Errorf("runtime migration failed: %v; rollback failed: %w", err, restoreErr) + } + return brokerResponse{}, err + } + site.Runtime = &next + if err = s.saveRegistry(); err != nil { + _ = s.direct.RemoveRuntime(context.WithoutCancel(ctx), next) + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), old) + site.Runtime = &old + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "install_runtime_component": + if !slices.Contains([]string{"Node.js", "Python"}, request.Name) { + return brokerResponse{}, errors.New("unsupported runtime component") + } + return brokerResponse{}, s.direct.InstallRuntimeComponent(ctx, request.Name) + case "install_runtime_environment": + if !slices.Contains([]string{"Node.js", "Python", "Go", "Java"}, request.Name) || !brokerVersionPattern.MatchString(request.Version) { + return brokerResponse{}, errors.New("invalid runtime environment installation") + } + if request.Name == "Python" { + return brokerResponse{}, errors.New("Python source installation is handled by the isolation service") + } + return brokerResponse{}, s.direct.InstallRuntimeEnvironment(ctx, request.Name, request.Version) + case "create_site": + if request.Site == nil { + return brokerResponse{}, errors.New("site specification is required") + } + if request.Site.RunPath == "" { + request.Site.RunPath = "/" + } + if err := s.validateSite(*request.Site); err != nil { + return brokerResponse{}, err + } + id, err := s.direct.CreateSite(ctx, *request.Site) + if err != nil { + return brokerResponse{}, err + } + if id <= 0 { + return brokerResponse{}, errors.New("panel returned an invalid site id") + } + hostName, _ := s.pathIdentity(request.Site.Path) + resourceName := hostName + s.registry.Sites[id] = &managedSite{Name: request.Site.Name, Domain: request.Site.Domain, Path: request.Site.Path, RunPath: request.Site.RunPath, RunUser: request.Site.RunUser, ResourceName: resourceName, Port: request.Site.Port, ProcessLimit: request.Site.ProcessLimit, Domains: map[string]bool{strings.ToLower(request.Site.Domain): true}} + if err := s.saveRegistry(); err != nil { + delete(s.registry.Sites, id) + _ = s.direct.DeleteSite(context.WithoutCancel(ctx), id, request.Site.Domain) + return brokerResponse{}, err + } + return brokerResponse{ID: id}, nil + case "adopt_site": + if request.Site == nil || request.ID <= 0 || strings.TrimSpace(request.SourcePath) == "" { + return brokerResponse{}, errors.New("adoption specification is required") + } + if _, exists := s.registry.Sites[request.ID]; exists { + return brokerResponse{}, errors.New("panel site is already managed") + } + if request.Site.RunPath == "" { + request.Site.RunPath = "/" + } + if err := s.validateSite(*request.Site); err != nil { + return brokerResponse{}, err + } + sourcePath := pathpkg.Clean(request.SourcePath) + if !pathpkg.IsAbs(sourcePath) || !strings.HasPrefix(sourcePath+"/", "/www/wwwroot/") || strings.HasPrefix(sourcePath+"/", pathpkg.Clean(s.tenantRoot)+"/") { + return brokerResponse{}, errors.New("legacy site path is outside the import boundary") + } + if err := s.direct.AdoptSite(ctx, request.ID, sourcePath, *request.Site); err != nil { + return brokerResponse{}, err + } + hostName, _ := s.pathIdentity(request.Site.Path) + s.registry.Sites[request.ID] = &managedSite{Name: request.Site.Name, Domain: request.Site.Domain, Path: request.Site.Path, RunPath: request.Site.RunPath, RunUser: request.Site.RunUser, ResourceName: hostName, Port: request.Site.Port, ProcessLimit: request.Site.ProcessLimit, Domains: map[string]bool{strings.ToLower(request.Site.Domain): true}} + if err := s.saveRegistry(); err != nil { + delete(s.registry.Sites, request.ID) + _ = s.direct.SetSitePath(context.WithoutCancel(ctx), request.ID, sourcePath) + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "rollback_adoption": + site, ok := s.registry.Sites[request.ID] + if !ok || site.Domain != request.Name { + return brokerResponse{}, errOutsideManaged + } + sourcePath := pathpkg.Clean(request.SourcePath) + if !pathpkg.IsAbs(sourcePath) || !strings.HasPrefix(sourcePath+"/", "/www/wwwroot/") || strings.HasPrefix(sourcePath+"/", pathpkg.Clean(s.tenantRoot)+"/") { + return brokerResponse{}, errors.New("legacy site path is outside the import boundary") + } + if err := s.direct.SetSitePath(ctx, request.ID, sourcePath); err != nil { + return brokerResponse{}, err + } + delete(s.registry.Sites, request.ID) + if err := s.saveRegistry(); err != nil { + s.registry.Sites[request.ID] = site + _ = s.direct.SetSitePath(context.WithoutCancel(ctx), request.ID, site.Path) + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "delete_site": + site, ok := s.registry.Sites[request.ID] + if !ok || site.Domain != request.Name { + return brokerResponse{}, errOutsideManaged + } + if site.Runtime != nil { + if err := s.direct.RemoveRuntime(ctx, *site.Runtime); err != nil { + return brokerResponse{}, fmt.Errorf("remove managed runtime: %w", err) + } + } + delete(s.registry.Sites, request.ID) + if err := s.saveRegistry(); err != nil { + s.registry.Sites[request.ID] = site + if site.Runtime != nil { + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), *site.Runtime) + } + return brokerResponse{}, err + } + if err := s.direct.DeleteSite(ctx, request.ID, request.Name); err != nil { + s.registry.Sites[request.ID] = site + _ = s.saveRegistry() + if site.Runtime != nil { + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), *site.Runtime) + } + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "add_domain": + site, err := s.managedSite(request.SiteID, request.Name) + if err != nil || !brokerDomainPattern.MatchString(request.Domain) { + return brokerResponse{}, errors.Join(errOutsideManaged, err) + } + if err := s.direct.AddDomain(ctx, request.SiteID, request.Name, request.Domain); err != nil { + return brokerResponse{}, err + } + site.Domains[strings.ToLower(request.Domain)] = true + return brokerResponse{}, s.saveRegistry() + case "delete_domain": + site, err := s.managedSite(request.SiteID, request.Name) + if err != nil || !brokerDomainPattern.MatchString(request.Domain) || strings.EqualFold(request.Domain, request.Name) { + return brokerResponse{}, errOutsideManaged + } + domain := strings.ToLower(request.Domain) + // Pending/rejected domains may never have reached the panel. Only tracked + // bindings can be removed; the primary name is always protected above. + if !site.Domains[domain] { + return brokerResponse{}, nil + } + if err := s.direct.DeleteDomain(ctx, request.SiteID, request.Name, request.Domain); err != nil { + return brokerResponse{}, err + } + delete(site.Domains, domain) + if err := s.saveRegistry(); err != nil { + site.Domains[domain] = true + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "create_ftp": + site := s.siteByPath(request.Path) + if site == nil || request.Username != site.ResourceName || !brokerHostPattern.MatchString(request.Username) || len(request.Password) < 16 || len(request.Password) > 256 || request.MaxBytes <= 0 { + return brokerResponse{}, errors.New("invalid or unmanaged FTP specification") + } + id, err := s.direct.CreateFTP(ctx, request.Username, request.Password, request.Path, request.MaxBytes) + if err != nil { + return brokerResponse{}, err + } + if id <= 0 { + return brokerResponse{}, errors.New("panel returned an invalid FTP id") + } + s.registry.FTP[id] = request.Username + if err := s.saveRegistry(); err != nil { + delete(s.registry.FTP, id) + _ = s.direct.DeleteFTP(context.WithoutCancel(ctx), id, request.Username) + return brokerResponse{}, err + } + return brokerResponse{ID: id}, nil + case "delete_ftp": + username, ok := s.registry.FTP[request.ID] + if !ok || username != request.Username { + return brokerResponse{}, errOutsideManaged + } + delete(s.registry.FTP, request.ID) + if err := s.saveRegistry(); err != nil { + s.registry.FTP[request.ID] = username + return brokerResponse{}, err + } + if err := s.direct.DeleteFTP(ctx, request.ID, request.Username); err != nil { + s.registry.FTP[request.ID] = username + _ = s.saveRegistry() + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "set_ftp_state": + username, ok := s.registry.FTP[request.ID] + if !ok || username != request.Username { + return brokerResponse{}, errOutsideManaged + } + return brokerResponse{}, s.direct.SetFTPState(ctx, request.ID, request.Username, request.Enabled) + case "set_ftp_password", "set_database_password": + name := request.Username + registry := s.registry.FTP + if request.Operation == "set_database_password" { + name = request.Name + registry = s.registry.Databases + } + if registered, ok := registry[request.ID]; !ok || registered != name || !brokerHostPattern.MatchString(name) || !managedPasswordPattern.MatchString(request.Password) { + return brokerResponse{}, errOutsideManaged + } + manager, ok := s.direct.(CredentialManager) + if !ok { + return brokerResponse{}, errors.New("credential reset adapter unavailable") + } + if request.Operation == "set_ftp_password" { + return brokerResponse{}, manager.SetFTPPassword(ctx, request.ID, name, request.Password) + } + return brokerResponse{}, manager.SetDatabasePassword(ctx, request.ID, name, request.Password) + case "create_database": + site, ok := s.registry.Sites[request.SiteID] + if !ok || request.Name != site.ResourceName || !brokerHostPattern.MatchString(request.Name) || request.Username != request.Name || len(request.Password) < 16 || len(request.Password) > 256 { + return brokerResponse{}, errors.New("invalid or unmanaged database specification") + } + id, err := s.direct.CreateDatabase(ctx, request.Name, request.Username, request.Password, request.SiteID) + if err != nil { + return brokerResponse{}, err + } + if id <= 0 { + return brokerResponse{}, errors.New("panel returned an invalid database id") + } + s.registry.Databases[id] = request.Name + if err := s.saveRegistry(); err != nil { + delete(s.registry.Databases, id) + _ = s.direct.DeleteDatabase(context.WithoutCancel(ctx), id, request.Name) + return brokerResponse{}, err + } + return brokerResponse{ID: id}, nil + case "delete_database": + name, ok := s.registry.Databases[request.ID] + if !ok || name != request.Name { + return brokerResponse{}, errOutsideManaged + } + delete(s.registry.Databases, request.ID) + if err := s.saveRegistry(); err != nil { + s.registry.Databases[request.ID] = name + return brokerResponse{}, err + } + if err := s.direct.DeleteDatabase(ctx, request.ID, request.Name); err != nil { + s.registry.Databases[request.ID] = name + _ = s.saveRegistry() + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "database_size": + name, ok := s.registry.Databases[request.ID] + if !ok || name != request.Name { + return brokerResponse{}, errOutsideManaged + } + size, err := s.direct.DatabaseSize(ctx, request.ID, request.Name) + return brokerResponse{Bytes: size}, err + case "configure_runtime": + if request.Runtime == nil || !s.runtimeIsManaged(*request.Runtime) { + return brokerResponse{}, errOutsideManaged + } + site := s.siteForRuntime(*request.Runtime) + if site == nil { + return brokerResponse{}, errOutsideManaged + } + if site.Runtime != nil { + if *site.Runtime == *request.Runtime { + return brokerResponse{}, nil + } + return brokerResponse{}, errors.New("site already has a different managed runtime") + } + if err := s.direct.ConfigureRuntime(ctx, *request.Runtime); err != nil { + return brokerResponse{}, err + } + runtimeSpec := *request.Runtime + site.Runtime = &runtimeSpec + if err := s.saveRegistry(); err != nil { + site.Runtime = nil + _ = s.direct.RemoveRuntime(context.WithoutCancel(ctx), runtimeSpec) + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "reset_managed_runtime": + site, err := s.managedSite(request.SiteID, request.Name) + if err != nil { + return brokerResponse{}, err + } + // Only this fixed, broker-owned proxy can be removed. Never accept a proxy name. + remover, ok := s.direct.(interface { + RemoveManagedProxy(context.Context, string) error + }) + if !ok { + return brokerResponse{}, errors.New("managed proxy removal unavailable") + } + saved := site.Runtime + if saved != nil { + if err = s.direct.SetRuntimeState(ctx, *saved, false); err != nil { + return brokerResponse{}, err + } + } + if site.ProxyReady { + if err = remover.RemoveManagedProxy(ctx, site.Domain); err != nil { + return brokerResponse{}, err + } + } + if saved != nil { + if err = s.direct.RemoveRuntime(ctx, *saved); err != nil { + if site.ProxyReady { + _ = s.direct.ConfigureProxy(context.WithoutCancel(ctx), request.SiteID, site.Domain, site.Port) + } + return brokerResponse{}, err + } + } + site.Runtime = nil + site.ProxyReady = false + if err = s.saveRegistry(); err != nil { + site.Runtime = saved + if saved != nil { + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), *saved) + _ = s.direct.SetRuntimeState(context.WithoutCancel(ctx), *saved, false) + } + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "remove_runtime": + if request.Runtime == nil { + return brokerResponse{}, errOutsideManaged + } + site := s.siteForRuntime(*request.Runtime) + if site == nil || site.Runtime == nil || *site.Runtime != *request.Runtime { + return brokerResponse{}, errOutsideManaged + } + if err := s.direct.RemoveRuntime(ctx, *request.Runtime); err != nil { + return brokerResponse{}, err + } + saved := site.Runtime + site.Runtime = nil + site.ProxyReady = false + if err := s.saveRegistry(); err != nil { + site.Runtime = saved + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), *saved) + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "set_runtime_state": + if request.Runtime == nil { + return brokerResponse{}, errOutsideManaged + } + site := s.siteForRuntime(*request.Runtime) + if site == nil || site.Runtime == nil || *site.Runtime != *request.Runtime { + return brokerResponse{}, errOutsideManaged + } + return brokerResponse{}, s.direct.SetRuntimeState(ctx, *request.Runtime, request.Enabled) + case "configure_proxy": + site, ok := s.registry.Sites[request.SiteID] + if !ok || site.Runtime == nil || !site.Domains[strings.ToLower(request.Domain)] || request.Port != site.Port { + return brokerResponse{}, errOutsideManaged + } + if site.ProxyReady { + return brokerResponse{}, nil + } + if err := s.direct.ConfigureProxy(ctx, request.SiteID, request.Domain, request.Port); err != nil { + return brokerResponse{}, err + } + site.ProxyReady = true + return brokerResponse{}, s.saveRegistry() + case "request_certificate": + site, ok := s.registry.Sites[request.SiteID] + if !ok || site.Path != request.Path || len(request.Domains) == 0 { + return brokerResponse{}, errOutsideManaged + } + for _, domain := range request.Domains { + if !site.Domains[strings.ToLower(domain)] { + return brokerResponse{}, errOutsideManaged + } + } + var order string + var err error + if issuer, ok := s.direct.(ManagedCertificateIssuer); ok { + order, err = issuer.IssueManagedCertificate(ctx, request.SiteID, request.Path, request.Domains) + } else { + err = s.direct.RequestCertificate(ctx, request.SiteID, request.Path, request.Domains) + } + if err != nil { + return brokerResponse{}, err + } + site.ACMEOrder = order + return brokerResponse{}, s.saveRegistry() + + case "install_certificate": + site, err := s.managedSite(request.SiteID, request.Name) + if err != nil || len(request.PrivateKey) == 0 || len(request.PrivateKey) > 32<<10 || len(request.Certificate) == 0 || len(request.Certificate) > 96<<10 { + return brokerResponse{}, errors.Join(errOutsideManaged, err) + } + if err = s.direct.InstallCertificate(ctx, request.SiteID, request.Name, request.PrivateKey, request.Certificate); err != nil { + return brokerResponse{}, err + } + if err = s.clearSiteACMEOrder(ctx, site); err != nil { + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "disable_certificate": + site, err := s.managedSite(request.SiteID, request.Name) + if err != nil { + return brokerResponse{}, err + } + if err = s.direct.DisableCertificate(ctx, request.SiteID, request.Name); err != nil { + return brokerResponse{}, err + } + if err = s.clearSiteACMEOrder(ctx, site); err != nil { + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "set_site_state": + site, err := s.managedSite(request.SiteID, request.Name) + if err != nil { + return brokerResponse{}, err + } + if site.Runtime == nil { + return brokerResponse{}, s.direct.SetSiteState(ctx, request.SiteID, request.Name, request.Enabled) + } + if request.Enabled { + if err := s.direct.SetSiteState(ctx, request.SiteID, request.Name, true); err != nil { + return brokerResponse{}, err + } + if err := s.direct.SetRuntimeState(ctx, *site.Runtime, true); err != nil { + _ = s.direct.SetSiteState(context.WithoutCancel(ctx), request.SiteID, request.Name, false) + return brokerResponse{}, err + } + return brokerResponse{}, nil + } + if err := s.direct.SetRuntimeState(ctx, *site.Runtime, false); err != nil { + return brokerResponse{}, err + } + if err := s.direct.SetSiteState(ctx, request.SiteID, request.Name, false); err != nil { + _ = s.direct.SetRuntimeState(context.WithoutCancel(ctx), *site.Runtime, true) + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "set_site_run_path": + site, ok := s.registry.Sites[request.SiteID] + if !ok || site.Runtime != nil || !validRunPath(request.Path) { + return brokerResponse{}, errOutsideManaged + } + previous := site.RunPath + if previous == "" { + previous = "/" + } + if err := s.direct.SetSiteRunPath(ctx, request.SiteID, request.Path); err != nil { + return brokerResponse{}, err + } + site.RunPath = request.Path + if err := s.saveRegistry(); err != nil { + site.RunPath = previous + _ = s.direct.SetSiteRunPath(context.WithoutCancel(ctx), request.SiteID, previous) + return brokerResponse{}, err + } + return brokerResponse{}, nil + case "migrate_runtime_identity": + site, ok := s.registry.Sites[request.SiteID] + if !ok { + return brokerResponse{}, errOutsideManaged + } + hostName, pathOK := s.pathIdentity(site.Path) + if !pathOK || request.Username != hostName || !brokerRunUserPattern.MatchString(request.Username) { + return brokerResponse{}, errOutsideManaged + } + if site.RunUser == request.Username { + return brokerResponse{}, nil + } + if site.RunUser != "www" { + return brokerResponse{}, errors.New("managed site has an unexpected legacy run user") + } + previousUser := site.RunUser + if site.Runtime != nil { + previousRuntime := *site.Runtime + if err := s.direct.RemoveRuntime(ctx, previousRuntime); err != nil { + return brokerResponse{}, err + } + migrated := previousRuntime + migrated.RunUser = request.Username + if err := s.direct.ConfigureRuntime(ctx, migrated); err != nil { + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), previousRuntime) + return brokerResponse{}, err + } + if !request.Enabled { + if err := s.direct.SetRuntimeState(ctx, migrated, false); err != nil { + _ = s.direct.RemoveRuntime(context.WithoutCancel(ctx), migrated) + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), previousRuntime) + return brokerResponse{}, err + } + } + site.Runtime = &migrated + } + site.RunUser = request.Username + if err := s.saveRegistry(); err != nil { + if site.Runtime != nil { + migrated := *site.Runtime + previousRuntime := migrated + previousRuntime.RunUser = previousUser + _ = s.direct.RemoveRuntime(context.WithoutCancel(ctx), migrated) + _ = s.direct.ConfigureRuntime(context.WithoutCancel(ctx), previousRuntime) + site.Runtime = &previousRuntime + } + site.RunUser = previousUser + return brokerResponse{}, err + } + return brokerResponse{}, nil + default: + return brokerResponse{}, errors.New("unsupported panel operation") + } +} + +func (s *BrokerServer) validateSite(spec SiteSpec) error { + hostName, pathOK := s.pathIdentity(spec.Path) + if !brokerHostPattern.MatchString(spec.Name) || spec.Name != hostName || !pathOK { + return errors.New("site path or host name is outside the managed host tree") + } + if !brokerDomainPattern.MatchString(spec.Domain) { + return errors.New("invalid site domain") + } + if !brokerVersionPattern.MatchString(spec.Version) { + return errors.New("invalid runtime version") + } + if !brokerRunUserPattern.MatchString(spec.RunUser) { + return errors.New("invalid tenant run user") + } + if spec.RunUser != hostName { + return errors.New("tenant run user does not match the managed host") + } + if !validRunPath(spec.RunPath) { + return errors.New("invalid site run path") + } + if spec.Port < 20000 || spec.Port > 39999 || spec.ProcessLimit < 1 || spec.ProcessLimit > 100000 { + return errors.New("invalid port or process limit") + } + if !slices.Contains([]string{"PHP", "Node.js", "Python", "Go", "Java"}, spec.Runtime) { + return errors.New("unsupported runtime") + } + for _, site := range s.registry.Sites { + if site.Domain == spec.Domain || site.Port == spec.Port || (site.Path == spec.Path && site.RunPath == spec.RunPath) { + return errors.New("site is already managed") + } + } + return nil +} + +func validRunPath(value string) bool { + if value == "/" { + return true + } + if len(value) < 2 || len(value) > 255 || !strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || pathpkg.Clean(value) != value { + return false + } + for _, segment := range strings.Split(strings.TrimPrefix(value, "/"), "/") { + if segment == "" || segment == "." || segment == ".." || len(segment) > 80 { + return false + } + for _, character := range segment { + if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) { + return false + } + } + } + return true +} + +func (s *BrokerServer) managedSite(id int64, name string) (*managedSite, error) { + site, ok := s.registry.Sites[id] + if !ok || site.Domain != name { + return nil, errOutsideManaged + } + if site.Domains == nil { + site.Domains = map[string]bool{strings.ToLower(site.Domain): true} + } + return site, nil +} + +func (s *BrokerServer) siteByPath(path string) *managedSite { + for _, site := range s.registry.Sites { + if site.Path == path { + return site + } + } + return nil +} + +func (s *BrokerServer) runtimeIsManaged(spec RuntimeSpec) bool { + if !brokerProjectPattern.MatchString(spec.ProjectName) || !brokerVersionPattern.MatchString(spec.Version) || spec.ProcessLimit < 1 || spec.ProcessLimit > 100000 || spec.Port < 20000 || spec.Port > 39999 || !brokerRunUserPattern.MatchString(spec.RunUser) || !validRunPath(spec.RunPath) || !validRuntimeEntry(spec.Runtime, spec.EntryFile) { + return false + } + for _, site := range s.registry.Sites { + nameOK := spec.ProjectName == site.ResourceName || strings.HasPrefix(spec.ProjectName, site.ResourceName+"_") + if site.Path == spec.Path && site.Domain == spec.Domain && site.RunPath == spec.RunPath && nameOK && site.RunUser == spec.RunUser && site.Port == spec.Port && site.ProcessLimit == spec.ProcessLimit { + return true + } + } + return false +} + +func (s *BrokerServer) siteForRuntime(spec RuntimeSpec) *managedSite { + for _, site := range s.registry.Sites { + if site.Path == spec.Path && site.Domain == spec.Domain && site.Port == spec.Port && site.RunPath == spec.RunPath { + return site + } + } + return nil +} + +func validRuntimeEntry(runtimeName, entry string) bool { + if entry == "" || len(entry) > 255 || strings.HasPrefix(entry, "/") || strings.Contains(entry, "\\") || pathpkg.Clean(entry) != entry || entry == "." || entry == ".." || strings.HasPrefix(entry, "../") { + return false + } + for _, segment := range strings.Split(entry, "/") { + if segment == "" || segment == "." || segment == ".." || len(segment) > 100 { + return false + } + for _, character := range segment { + if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) { + return false + } + } + } + switch runtimeName { + case "Node.js": + return pathpkg.Base(entry) == "package.json" + case "Python": + return pathpkg.Ext(entry) == ".py" + case "Go": + return pathpkg.Ext(entry) == "" + case "Java": + return pathpkg.Ext(entry) == ".jar" + default: + return false + } +} + +func (s *BrokerServer) pathIdentity(target string) (hostName string, ok bool) { + root, err := filepath.Abs(s.tenantRoot) + if err != nil { + return "", false + } + absolute, err := filepath.Abs(target) + if err != nil { + return "", false + } + relative, err := filepath.Rel(root, absolute) + if err != nil || relative == "." || relative == ".." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) { + return "", false + } + parts := strings.Split(filepath.ToSlash(relative), "/") + if len(parts) != 1 || !brokerHostPattern.MatchString(parts[0]) { + return "", false + } + // The broker must validate identity without gaining access to tenant + // contents. Host directories are intentionally owned by sea-vhost and the + // per-host group, while + // sea-vhost-panel belongs to neither identity. lstat only needs traversal + // on the 0755 managed root and still rejects a symlinked host directory. + info, err := os.Lstat(absolute) + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", false + } + return parts[0], true +} + +func (s *BrokerServer) credentialsPath() string { return filepath.Join(s.stateDir, "credentials.json") } +func (s *BrokerServer) registryPath() string { return filepath.Join(s.stateDir, "resources.json") } + +func (s *BrokerServer) loadCredentials() (BrokerCredentials, error) { + data, err := os.ReadFile(s.credentialsPath()) + if err != nil { + return BrokerCredentials{}, err + } + var stored brokerCredentialFile + if err := json.Unmarshal(data, &stored); err != nil { + return BrokerCredentials{}, err + } + return BrokerCredentials{URL: stored.URL, APIKey: stored.APIKey, TLSInsecure: stored.TLSInsecure}, nil +} + +func (s *BrokerServer) saveCredentials(credentials BrokerCredentials) error { + data, err := json.MarshalIndent(brokerCredentialFile{Version: 1, URL: credentials.URL, APIKey: credentials.APIKey, TLSInsecure: credentials.TLSInsecure}, "", " ") + if err != nil { + return err + } + return writeExclusiveFile(s.credentialsPath(), append(data, '\n')) +} + +func (s *BrokerServer) loadRegistry() error { + data, err := os.ReadFile(s.registryPath()) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + if err := json.Unmarshal(data, &s.registry); err != nil { + return err + } + if s.registry.Sites == nil { + s.registry.Sites = map[int64]*managedSite{} + } + if s.registry.FTP == nil { + s.registry.FTP = map[int64]string{} + } + if s.registry.Databases == nil { + s.registry.Databases = map[int64]string{} + } + return nil +} + +func (s *BrokerServer) saveRegistry() error { + if s.stateless { + return nil + } + data, err := json.MarshalIndent(s.registry, "", " ") + if err != nil { + return err + } + return writeAtomicFile(s.registryPath(), append(data, '\n')) +} + +func writeExclusiveFile(path string, data []byte) error { + temporary, err := os.CreateTemp(filepath.Dir(path), ".credentials-*.tmp") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err = temporary.Chmod(0600); err == nil { + _, err = temporary.Write(data) + } + if err == nil { + err = temporary.Sync() + } + closeErr := temporary.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return os.Link(temporaryPath, path) +} + +func writeAtomicFile(path string, data []byte) error { + temporary, err := os.CreateTemp(filepath.Dir(path), ".resources-*.tmp") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err = temporary.Chmod(0600); err == nil { + _, err = temporary.Write(data) + } + if err == nil { + err = temporary.Sync() + } + closeErr := temporary.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + return os.Rename(temporaryPath, path) +} + +func validateBrokerCredentials(credentials BrokerCredentials) error { + parsed, err := url.Parse(credentials.URL) + if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.User != nil || !brokerLoopback(parsed.Hostname()) { + return errors.New("宝塔面板必须使用本机 HTTP(S) 回环地址") + } + if len(credentials.APIKey) < 16 || len(credentials.APIKey) > 512 { + return errors.New("宝塔 API 密钥无效") + } + return nil +} + +func brokerLoopback(host string) bool { + host = strings.Trim(strings.ToLower(strings.TrimSpace(host)), "[]") + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func normalizeBrokerCredentials(credentials BrokerCredentials) BrokerCredentials { + credentials.URL = strings.TrimRight(strings.TrimSpace(credentials.URL), "/") + credentials.APIKey = strings.TrimSpace(credentials.APIKey) + return credentials +} + +func sameBrokerCredentials(left, right BrokerCredentials) bool { + return left.URL == right.URL && left.TLSInsecure == right.TLSInsecure && len(left.APIKey) == len(right.APIKey) && subtle.ConstantTimeCompare([]byte(left.APIKey), []byte(right.APIKey)) == 1 +} + +func brokerDecode(w http.ResponseWriter, r *http.Request, target any) bool { + decoder := json.NewDecoder(io.LimitReader(r.Body, 128<<10)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + brokerWriteError(w, http.StatusBadRequest, "请求内容无效") + return false + } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + brokerWriteError(w, http.StatusBadRequest, "请求只能包含一个 JSON 对象") + return false + } + return true +} + +func safeBrokerError(prefix string, err error) string { + message := strings.ReplaceAll(err.Error(), "\n", " ") + if len(message) > 180 { + message = message[:180] + } + return prefix + ":" + message +} + +func brokerWriteJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func brokerWriteError(w http.ResponseWriter, status int, message string) { + brokerWriteJSON(w, status, map[string]any{"error": map[string]string{"message": message}}) +} + +func (s *BrokerServer) clearSiteACMEOrder(ctx context.Context, site *managedSite) error { + if site.ACMEOrder == "" { + return nil + } + issuer, ok := s.direct.(ManagedCertificateIssuer) + if !ok { + return errors.New("managed certificate renewal adapter unavailable") + } + if err := issuer.ClearManagedCertificateOrder(ctx, site.ACMEOrder); err != nil { + return err + } + site.ACMEOrder = "" + return s.saveRegistry() +} diff --git a/backend/internal/panel/broker_server_test.go b/backend/internal/panel/broker_server_test.go new file mode 100644 index 0000000..2d70e72 --- /dev/null +++ b/backend/internal/panel/broker_server_test.go @@ -0,0 +1,237 @@ +package panel + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +type trackingPanel struct { + Interface + deletedSites int + installedCertificates int + disabledCertificates int + clearedOrders []string +} + +func (p *trackingPanel) DeleteSite(ctx context.Context, id int64, name string) error { + p.deletedSites++ + return p.Interface.DeleteSite(ctx, id, name) +} + +func (p *trackingPanel) InstallCertificate(ctx context.Context, id int64, name, privateKey, certificate string) error { + p.installedCertificates++ + return p.Interface.InstallCertificate(ctx, id, name, privateKey, certificate) +} + +func (p *trackingPanel) DisableCertificate(ctx context.Context, id int64, name string) error { + p.disabledCertificates++ + return p.Interface.DisableCertificate(ctx, id, name) +} + +func (p *trackingPanel) IssueManagedCertificate(ctx context.Context, id int64, path string, domains []string) (string, error) { + return "owned-order", p.Interface.RequestCertificate(ctx, id, path, domains) +} +func (p *trackingPanel) ClearManagedCertificateOrder(_ context.Context, index string) error { + p.clearedOrders = append(p.clearedOrders, index) + return nil +} + +func TestBrokerConfigAndManagedResourceBoundary(t *testing.T) { + stateDir := filepath.Join(t.TempDir(), "broker") + tenantRoot := filepath.Join(t.TempDir(), "tenants") + token := strings.Repeat("t", 32) + direct := &trackingPanel{Interface: NewMock()} + server, err := newBrokerServer(stateDir, tenantRoot, token, func(BrokerCredentials) Interface { return direct }) + if err != nil { + t.Fatal(err) + } + credentials := BrokerCredentials{URL: "https://127.0.0.1:8888", APIKey: strings.Repeat("k", 32), TLSInsecure: true} + body, _ := json.Marshal(credentials) + request := httptest.NewRequest(http.MethodPost, "/v1/setup/configure", strings.NewReader(string(body))) + request.Header.Set("X-Setup-Token", token) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusCreated { + t.Fatalf("configure status = %d, body = %s", response.Code, response.Body.String()) + } + info, err := os.Stat(filepath.Join(stateDir, "credentials.json")) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0600 { + t.Fatalf("credential mode = %o, want 600", info.Mode().Perm()) + } + catalogResponse, err := server.execute(context.Background(), brokerRequest{Operation: "runtime_catalog"}) + if err != nil || len(catalogResponse.Catalog["PHP"]) == 0 { + t.Fatalf("runtime catalog unavailable through broker: catalog=%v err=%v", catalogResponse.Catalog, err) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_runtime_component", Name: "Python"}); err != nil { + t.Fatalf("broker rejected the official Python component: %v", err) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_runtime_component", Name: "Go"}); err == nil { + t.Fatal("broker accepted a runtime without an installable manager component") + } + + hostName := "sv0123456789" + sitePath := filepath.Join(tenantRoot, hostName) + if err := os.MkdirAll(sitePath, 0750); err != nil { + t.Fatal(err) + } + if err = server.validateSite(SiteSpec{Name: hostName, Domain: hostName + ".hosts.example.com", Path: sitePath, Runtime: "Docker", Version: "Compose-v2", RunUser: hostName, Port: 20020, ProcessLimit: 10}); err == nil { + t.Fatal("broker accepted the removed Docker runtime") + } + if err = server.validateSite(SiteSpec{Name: hostName, Domain: hostName + ".hosts.example.com", Path: sitePath, RunPath: "/../etc", Runtime: "PHP", Version: "8.3", RunUser: hostName, Port: 20020, ProcessLimit: 10}); err == nil { + t.Fatal("broker accepted an escaping run path") + } + created, err := server.execute(context.Background(), brokerRequest{Operation: "create_site", Site: &SiteSpec{Name: hostName, Domain: hostName + ".hosts.example.com", Path: sitePath, RunPath: "/public", Runtime: "PHP", Version: "8.3", RunUser: hostName, Port: 20020, ProcessLimit: 10}}) + if err != nil { + t.Fatal(err) + } + if created.ID <= 0 { + t.Fatal("broker did not return a managed site id") + } + primary := hostName + ".hosts.example.com" + if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_domain", SiteID: created.ID, Name: primary, Domain: primary}); !errors.Is(err, errOutsideManaged) { + t.Fatal("primary domain removal allowed") + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "add_domain", SiteID: created.ID, Name: primary, Domain: "custom.example.com"}); err != nil { + t.Fatal(err) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_domain", SiteID: created.ID, Name: primary, Domain: "custom.example.com"}); err != nil { + t.Fatal(err) + } + if server.registry.Sites[created.ID].Domains["custom.example.com"] { + t.Fatal("removed binding still registered") + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_domain", SiteID: created.ID, Name: primary, Domain: "custom.example.com"}); err != nil { + t.Fatal("removal retry failed", err) + } + second, err := server.execute(context.Background(), brokerRequest{Operation: "create_site", Site: &SiteSpec{Name: hostName, Domain: hostName + "-docs.hosts.example.com", Path: sitePath, RunPath: "/docs", Runtime: "Node.js", Version: "v24.21.0", RunUser: hostName, Port: 20021, ProcessLimit: 10}}) + if err != nil || second.ID <= 0 { + t.Fatalf("broker rejected a second website inside the same managed host: id=%d err=%v", second.ID, err) + } + if err = server.validateSite(SiteSpec{Name: hostName, Domain: hostName + "-duplicate.hosts.example.com", Path: sitePath, RunPath: "/docs", Runtime: "PHP", Version: "8.3", RunUser: hostName, Port: 20022, ProcessLimit: 10}); err == nil { + t.Fatal("broker accepted two websites with the same host-relative run path") + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "set_site_run_path", SiteID: created.ID, Path: "/apps/web/public"}); err != nil { + t.Fatalf("managed run path update failed: %v", err) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "configure_proxy", SiteID: created.ID, Domain: hostName + ".hosts.example.com", Port: 20040}); !errors.Is(err, errOutsideManaged) { + t.Fatalf("broker accepted a port not bound to the managed site: %v", err) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_certificate", SiteID: created.ID + 100, Name: "outside.example.com", PrivateKey: "key", Certificate: "cert"}); !errors.Is(err, errOutsideManaged) || direct.installedCertificates != 0 { + t.Fatalf("unmanaged certificate install reached panel: err=%v installs=%d", err, direct.installedCertificates) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "request_certificate", SiteID: created.ID, Path: sitePath, Domains: []string{primary}}); err != nil { + t.Fatal(err) + } + if server.registry.Sites[created.ID].ACMEOrder != "owned-order" { + t.Fatal("issued renewal order not recorded") + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "install_certificate", SiteID: created.ID, Name: hostName + ".hosts.example.com", PrivateKey: "key", Certificate: "cert"}); err != nil { + t.Fatalf("managed certificate install failed: %v", err) + } + if len(direct.clearedOrders) != 1 || direct.clearedOrders[0] != "owned-order" || server.registry.Sites[created.ID].ACMEOrder != "" { + t.Fatal("manual certificate did not clear only its tracked renewal") + } + server.registry.Sites[created.ID].ACMEOrder = "second-owned-order" + if direct.installedCertificates != 1 { + t.Fatalf("managed certificate install count = %d, want 1", direct.installedCertificates) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "disable_certificate", SiteID: created.ID + 100, Name: "outside.example.com"}); !errors.Is(err, errOutsideManaged) || direct.disabledCertificates != 0 { + t.Fatalf("unmanaged certificate disable reached panel: err=%v disables=%d", err, direct.disabledCertificates) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "disable_certificate", SiteID: created.ID, Name: hostName + ".hosts.example.com"}); err != nil { + t.Fatalf("managed certificate disable failed: %v", err) + } + if len(direct.clearedOrders) != 2 || direct.clearedOrders[1] != "second-owned-order" || server.registry.Sites[created.ID].ACMEOrder != "" { + t.Fatal("SSL disable did not cancel tracked renewal") + } + if direct.disabledCertificates != 1 { + t.Fatalf("managed certificate disable count = %d, want 1", direct.disabledCertificates) + } + wrongRuntime := RuntimeSpec{ProjectName: hostName, Runtime: "Java", Version: "21", Path: sitePath, Domain: hostName + ".hosts.example.com", RunUser: "root", Port: 20020, ProcessLimit: 10} + if _, err = server.execute(context.Background(), brokerRequest{Operation: "configure_runtime", Runtime: &wrongRuntime}); !errors.Is(err, errOutsideManaged) { + t.Fatalf("broker accepted another tenant run user: %v", err) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "create_ftp", Username: "sv_other_project", Password: strings.Repeat("p", 24), Path: sitePath, MaxBytes: 1024}); err == nil { + t.Fatal("broker accepted an FTP account not bound to the managed site") + } + _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_site", ID: created.ID + 100, Name: "outside.example.com"}) + if !errors.Is(err, errOutsideManaged) || direct.deletedSites != 0 { + t.Fatalf("unmanaged delete reached panel: err=%v deletes=%d", err, direct.deletedSites) + } + if _, err = server.execute(context.Background(), brokerRequest{Operation: "delete_site", ID: created.ID, Name: hostName + ".hosts.example.com"}); err != nil { + t.Fatal(err) + } + if direct.deletedSites != 1 { + t.Fatalf("managed delete count = %d, want 1", direct.deletedSites) + } + restarted, err := newBrokerServer(stateDir, tenantRoot, "", func(BrokerCredentials) Interface { return direct }) + if err != nil { + t.Fatalf("configured broker should restart without the one-time setup token: %v", err) + } + request = httptest.NewRequest(http.MethodPost, "/v1/setup/test", strings.NewReader(string(body))) + response = httptest.NewRecorder() + restarted.Handler().ServeHTTP(response, request) + if response.Code != http.StatusNotFound { + t.Fatalf("setup endpoint remained registered after restart: status=%d", response.Code) + } +} + +func TestBrokerSetupRequiresToken(t *testing.T) { + server, err := newBrokerServer(t.TempDir(), t.TempDir(), strings.Repeat("t", 32), func(BrokerCredentials) Interface { return NewMock() }) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "/v1/setup/test", strings.NewReader(`{}`)) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401", response.Code) + } +} + +func TestBrokerOperationsRequireInternalToken(t *testing.T) { + server, err := newBrokerServer(t.TempDir(), t.TempDir(), strings.Repeat("t", 32), func(BrokerCredentials) Interface { return NewMock() }, strings.Repeat("i", 32)) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "/v1/operations", strings.NewReader(`{"operation":"ping"}`)) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated operation status = %d, want 401", response.Code) + } +} + +func TestBrokerSetupInspectionReturnsRuntimeVersions(t *testing.T) { + token := strings.Repeat("t", 32) + server, err := newBrokerServer(t.TempDir(), t.TempDir(), token, func(BrokerCredentials) Interface { return NewMock() }) + if err != nil { + t.Fatal(err) + } + body, _ := json.Marshal(BrokerCredentials{URL: "https://127.0.0.1:8888", APIKey: strings.Repeat("k", 32), TLSInsecure: true}) + request := httptest.NewRequest(http.MethodPost, "/v1/setup/test", strings.NewReader(string(body))) + request.Header.Set("X-Setup-Token", token) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"PHP"`) || !strings.Contains(response.Body.String(), `"Node.js"`) { + t.Fatalf("inspection status = %d, body = %s", response.Code, response.Body.String()) + } +} + +func TestUnconfiguredBrokerRejectsMissingSetupToken(t *testing.T) { + _, err := newBrokerServer(t.TempDir(), t.TempDir(), "", func(BrokerCredentials) Interface { return NewMock() }) + if err == nil { + t.Fatal("unconfigured broker started without a setup token") + } +} diff --git a/backend/internal/panel/certificate_inline_test.go b/backend/internal/panel/certificate_inline_test.go new file mode 100644 index 0000000..0dae14f --- /dev/null +++ b/backend/internal/panel/certificate_inline_test.go @@ -0,0 +1,69 @@ +package panel + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/json" + "encoding/pem" + "math/big" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestSynchronousHTTPCertificateIsValidatedAndInstalledWithoutOrderIndex(t *testing.T) { + key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if e != nil { + t.Fatal(e) + } + cert := &x509.Certificate{SerialNumber: big.NewInt(42), Subject: pkix.Name{CommonName: "host.example.com"}, DNSNames: []string{"host.example.com"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(90 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature} + der, e := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key) + if e != nil { + t.Fatal(e) + } + rawKey, e := x509.MarshalPKCS8PrivateKey(key) + if e != nil { + t.Fatal(e) + } + chain := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) + private := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: rawKey})) + installed := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + switch r.Form.Get("action") { + case "apply_cert_api": + if r.Form.Get("auth_to") != "7" { + t.Error("issuance must resolve the site's current run directory") + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "申请成功", "cert": chain, "root": "", "private_key": private}) + case "SetSSL": + installed++ + if r.Form.Get("siteName") != "host.example.com" || r.Form.Get("key") != private || r.Form.Get("csr") == "" { + t.Error("invalid fixed-site installation") + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + default: + t.Error("unexpected certificate operation", r.Form.Get("action")) + w.WriteHeader(404) + } + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, 5*time.Second) + if e = client.RequestCertificate(context.Background(), 7, "/www/example", []string{"host.example.com"}); e != nil { + t.Fatal(e) + } + if installed != 1 { + t.Fatal("inline certificate was not installed") + } + if e = client.RequestCertificate(context.Background(), 7, "/www/example", []string{"outside.example.net"}); e == nil { + t.Fatal("certificate outside requested domains accepted") + } + if installed != 1 { + t.Fatal("invalid certificate reached panel installation") + } +} diff --git a/backend/internal/panel/certificate_orders.go b/backend/internal/panel/certificate_orders.go new file mode 100644 index 0000000..4cc8ac6 --- /dev/null +++ b/backend/internal/panel/certificate_orders.go @@ -0,0 +1,61 @@ +package panel + +import ( + "context" + "crypto/md5" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/url" + "strings" +) + +// aaPanel indexes orders with the MD5 of Python's JSON identifiers array. +func managedACMEIndex(domains []string) string { + parts := make([]string, 0, len(domains)) + for _, domain := range domains { + raw, _ := json.Marshal(domain) + parts = append(parts, `{"type": "dns", "value": `+string(raw)+`}`) + } + sum := md5.Sum([]byte("[" + strings.Join(parts, ", ") + "]")) + return hex.EncodeToString(sum[:]) +} +func sameDomainSet(a, b []string) bool { + if len(a) != len(b) { + return false + } + set := map[string]bool{} + for _, v := range b { + set[strings.ToLower(v)] = true + } + for _, v := range a { + key := strings.ToLower(v) + if !set[key] { + return false + } + delete(set, key) + } + return len(set) == 0 +} +func (c *Client) ClearManagedCertificateOrder(ctx context.Context, index string) error { + if !validIdentifierForOrder(index) { + return errors.New("invalid managed certificate order") + } + _, err := c.call(ctx, http.MethodPost, "/acme", url.Values{"action": {"remove_order"}, "index": {index}}) + if err != nil && strings.Contains(err.Error(), "指定订单不存在") { + return nil + } + return err +} +func validIdentifierForOrder(v string) bool { + if len(v) < 1 || len(v) > 128 { + return false + } + for _, c := range v { + if !(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && c != '-' && c != '_' { + return false + } + } + return true +} diff --git a/backend/internal/panel/certificate_orders_test.go b/backend/internal/panel/certificate_orders_test.go new file mode 100644 index 0000000..c0dd7f1 --- /dev/null +++ b/backend/internal/panel/certificate_orders_test.go @@ -0,0 +1,40 @@ +package panel + +import ( + "context" + "crypto/md5" + "encoding/hex" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestManagedACMEIndexUsesNativePythonJSON(t *testing.T) { + raw := `[{"type": "dns", "value": "a.example.com"}, {"type": "dns", "value": "b.example.com"}]` + sum := md5.Sum([]byte(raw)) + if got := managedACMEIndex([]string{"a.example.com", "b.example.com"}); got != hex.EncodeToString(sum[:]) { + t.Fatal("native order index mismatch", got) + } +} + +func TestClearManagedCertificateOrderIsScopedAndIdempotent(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + calls++ + if r.URL.Path != "/acme" || r.Form.Get("action") != "remove_order" || r.Form.Get("index") != "owned-order" { + t.Error("unexpected order mutation") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"status":false,"msg":"指定订单不存在!"}`)) + })) + defer server.Close() + c := NewClient(server.URL, "test-key", false, time.Second) + if err := c.ClearManagedCertificateOrder(context.Background(), "../foreign"); err == nil || calls != 0 { + t.Fatal("invalid index reached panel") + } + if err := c.ClearManagedCertificateOrder(context.Background(), "owned-order"); err != nil || calls != 1 { + t.Fatal("missing owned order retry failed", err) + } +} diff --git a/backend/internal/panel/client.go b/backend/internal/panel/client.go new file mode 100644 index 0000000..23b811c --- /dev/null +++ b/backend/internal/panel/client.go @@ -0,0 +1,1878 @@ +package panel + +import ( + "context" + "crypto/md5" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net" + "net/http" + "net/url" + pathpkg "path" + "regexp" + "sea-vhost/internal/schedulerbridge" + "slices" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +type Client struct { + baseURL string + apiKey string + http *http.Client + goMetadataMu sync.Mutex + goRefreshAfter time.Time + goLastGood []byte + goLastGoodAt time.Time +} + +type apiResponse struct { + Status any `json:"status"` + Msg string `json:"msg"` + Message string `json:"message"` + ErrorMsg string `json:"error_msg"` + Index string `json:"index"` + SiteID int64 `json:"siteId"` + ID int64 `json:"id"` +} + +type javaInstallation struct { + Name string `json:"name"` + Path string `json:"path"` + Operation int `json:"operation"` +} + +type pythonInstallation struct { + Version string `json:"version"` + PythonPath string `json:"python_path"` +} + +type runtimeSDK struct { + Version string `json:"version"` + Installed any `json:"installed"` + Installing any `json:"is_install"` +} + +type runtimePluginInfo struct { + Name string `json:"name"` + Title string `json:"title"` + Price any `json:"price"` + PanelFree any `json:"panel_free"` + Setup any `json:"setup"` + MVersion string `json:"m_version"` + MinVersion string `json:"version"` + Versions []runtimePluginRelease `json:"versions"` +} + +type runtimePluginRelease struct { + MVersion string `json:"m_version"` + Version string `json:"version"` + Beta int `json:"beta"` +} + +type runtimePluginPreparation struct { + Status any `json:"status"` + Msg string `json:"msg"` + Message string `json:"message"` + ErrorMsg string `json:"error_msg"` + Name string `json:"name"` + TmpPath string `json:"tmp_path"` + InstallOpt string `json:"install_opt"` +} + +var runtimeVersionPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$`) +var stablePythonVersionPattern = regexp.MustCompile(`^3\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`) + +// freePanelRequestPolicy is deliberately explicit. Sea vHost must not grow +// accidental dependencies on aaPanel Professional/Enterprise plugins through +// a generic request helper. +var freePanelRequestPolicy = map[string]map[string]bool{ + "POST /crontab": {"GetCrontab": true, "AddCrontab": true, "set_cron_status": true}, + "POST /system": {"GetSystemTotal": true}, + "POST /site": { + "GetPHPVersion": true, "AddSite": true, "multiple_basedir": true, + "DeleteSite": true, "AddDomain": true, "DelDomain": true, "CreateProxy": true, "GetProxyList": true, "RemoveProxy": true, "SetSiteRunPath": true, "SetPath": true, + "SiteStart": true, "SiteStop": true, "SetSSL": true, "CloseSSLConf": true, + }, + "POST /ftp": {"AddUser": true, "DeleteUser": true, "SetStatus": true, "SetUserPassword": true}, + "POST /database": {"AddDatabase": true, "DeleteDatabase": true, "GetInfo": true, "ResDatabasePassword": true}, + "POST /data": {"getData": true}, + "POST /acme": {"apply_cert_api": true, "get_order_find": true, "SetCertToSite": true, "remove_order": true}, + "POST /project/nodejs/get_nodejs_version/stype": {"": true}, + "POST /project/nodejs/is_install_nodejs/stype": {"": true}, + "POST /project/nodejs/get_project_list/stype": {"": true}, + "POST /project/nodejs/create_project/stype": {"": true}, + "POST /project/nodejs/start_project/stype": {"": true}, + "POST /project/nodejs/stop_project/stype": {"": true}, + "POST /project/nodejs/remove_project/stype": {"": true}, + "POST /project/python/list_py_version/stype": {"": true}, + "POST /project/python/GetProjectList/stype": {"": true}, + "POST /mod/python/environment/add_environment/stype": {"": true}, + // The trailing /stype path argument overwrites the Python create form's + // stype=command value on aaPanel 12.0.0. Use the equivalent route without + // that optional router argument for creation only. + "POST /project/python/CreateProject": {"": true}, + "POST /project/python/StartProject/stype": {"": true}, + "POST /project/python/StopProject/stype": {"": true}, + "POST /project/python/RemoveProject/stype": {"": true}, + "POST /project/go/list_go_sdk/stype": {"": true}, + "POST /project/go/install_go_sdk/stype": {"": true}, + "POST /project/go/get_project_list/stype": {"": true}, + "POST /project/go/create_project/stype": {"": true}, + "POST /project/go/start_project/stype": {"": true}, + "POST /project/go/stop_project/stype": {"": true}, + "POST /project/go/remove_project/stype": {"": true}, + "GET /mod/java/project/get_system_info/stype": {"": true}, + "POST /mod/java/project/install_jdk_new/stype": {"": true}, + "POST /mod/java/project/create_spring_boot_project/stype": {"": true}, + "POST /mod/java/project/project_list/stype": {"": true}, + "POST /mod/java/project/start_project/stype": {"": true}, + "POST /mod/java/project/stop_project/stype": {"": true}, + "POST /mod/java/project/remove_project/stype": {"": true}, + "POST /plugin": { + "get_soft_find": true, "install_plugin": true, "upgrade_plugin": true, "input_package": true, "a": true, + }, +} + +func NewClient(baseURL, apiKey string, insecureTLS bool, timeout time.Duration) *Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecureTLS} // #nosec G402 -- explicit operator setting for a loopback/self-signed panel only. + return &Client{baseURL: strings.TrimRight(baseURL, "/"), apiKey: apiKey, http: &http.Client{Timeout: timeout, Transport: transport}} +} + +func Signature(apiKey string, timestamp int64) string { + inner := md5.Sum([]byte(apiKey)) // The panel protocol requires double MD5; this is not password hashing. + outer := md5.Sum([]byte(strconv.FormatInt(timestamp, 10) + hex.EncodeToString(inner[:]))) + return hex.EncodeToString(outer[:]) +} + +func (c *Client) request(ctx context.Context, method, path string, values url.Values) ([]byte, error) { + if err := validateFreePanelRequest(method, path, values); err != nil { + return nil, err + } + if values == nil { + values = make(url.Values) + } else { + values = cloneValues(values) + } + now := time.Now().Unix() + values.Set("request_time", strconv.FormatInt(now, 10)) + values.Set("request_token", Signature(c.apiKey, now)) + var request *http.Request + var err error + if method == http.MethodGet { + endpoint := c.baseURL + path + "?" + values.Encode() + request, err = http.NewRequestWithContext(ctx, method, endpoint, nil) + } else { + request, err = http.NewRequestWithContext(ctx, method, c.baseURL+path, strings.NewReader(values.Encode())) + if request != nil { + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + } + if err != nil { + return nil, err + } + response, err := c.http.Do(request) + if err != nil { + return nil, fmt.Errorf("panel request: %w", err) + } + defer response.Body.Close() + body, err := io.ReadAll(io.LimitReader(response.Body, (2<<20)+1)) + if err != nil { + return nil, err + } + if len(body) > 2<<20 { + return nil, errors.New("panel response exceeded size limit") + } + if response.StatusCode < 200 || response.StatusCode > 299 { + return nil, fmt.Errorf("panel HTTP %d", response.StatusCode) + } + return body, nil +} + +func validateFreePanelRequest(method, path string, values url.Values) error { + actions, ok := freePanelRequestPolicy[method+" "+path] + if !ok || !actions[values.Get("action")] { + return errors.New("panel operation is outside the free-core allowlist") + } + if path == "/site" && (values.Get("action") == "GetProxyList" || values.Get("action") == "RemoveProxy") { + if !brokerDomainPattern.MatchString(values.Get("sitename")) || (values.Get("action") == "RemoveProxy" && values.Get("proxyname") != "sea-vhost-runtime") { + return errors.New("only the fixed managed runtime proxy is allowed") + } + } + if path == "/crontab" { + switch values.Get("action") { + case "GetCrontab": + if values.Get("search") != schedulerbridge.CronName { + return errors.New("only the Sea vHost system cron can be queried") + } + case "AddCrontab": + if values.Get("name") != schedulerbridge.CronName || values.Get("sBody") != schedulerbridge.Command || values.Get("type") != "minute-n" || values.Get("where1") != "1" || values.Get("sType") != "toShell" || values.Get("user") != "root" { + return errors.New("only the fixed Sea vHost scheduler command is allowed") + } + case "set_cron_status": + id, e := strconv.ParseUint(values.Get("id"), 10, 64) + if e != nil || id == 0 { + return errors.New("invalid system cron identifier") + } + } + } + if path == "/mod/python/environment/add_environment/stype" { + if values.Get("add_type") != "system" || !regexp.MustCompile(`^/www/server/python_manager/versions/3\.[0-9]+\.[0-9]+/bin/python3\.[0-9]+$`).MatchString(values.Get("path")) { + return errors.New("only the managed Python SDK can be registered") + } + } + if path == "/data" { + table := values.Get("table") + if table != "ftps" && table != "databases" && table != "sites" && table != "tasks" && table != "domain" { + return errors.New("panel data table is outside the managed-resource allowlist") + } + if table == "domain" { + id, err := strconv.ParseUint(values.Get("search"), 10, 64) + if err != nil || id == 0 || values.Get("list") != "true" { + return errors.New("domain queries require an exact site identifier") + } + } + if table == "tasks" && values.Get("search") != "execshell" { + return errors.New("only software execution task queries are allowed") + } + } + if path == "/plugin" { + switch values.Get("action") { + case "get_soft_find": + if !slices.Contains([]string{"nodejs", "pythonmamager"}, values.Get("sName")) && !phpSoftwarePattern.MatchString(values.Get("sName")) { + return errors.New("panel plugin is outside the free runtime-component allowlist") + } + case "install_plugin": + if phpSoftwarePattern.MatchString(values.Get("sName")) { + if values.Get("type") != "0" || values.Get("upgrade") != "1" || values.Get("sName") != "php-"+values.Get("version") || !phpPatchNumberPattern.MatchString(values.Get("min_version")) { + return errors.New("PHP update is outside the fixed-branch allowlist") + } + return nil + } + if !slices.Contains([]string{"nodejs", "pythonmamager"}, values.Get("sName")) || values.Get("type") != "0" || !runtimeVersionPattern.MatchString(values.Get("version")) || !runtimeVersionPattern.MatchString(values.Get("min_version")) { + return errors.New("panel plugin installation is outside the free runtime-component allowlist") + } + case "upgrade_plugin": + if !slices.Contains([]string{"nodejs", "pythonmamager"}, values.Get("plugin_name")) || !runtimeVersionPattern.MatchString(values.Get("version")) || !runtimeVersionPattern.MatchString(values.Get("min_version")) { + return errors.New("panel plugin update is outside the free runtime-component allowlist") + } + case "input_package": + pluginName := values.Get("plugin_name") + if !slices.Contains([]string{"nodejs", "pythonmamager"}, pluginName) || values.Get("tmp_path") != "/www/server/panel/temp/"+pluginName || (values.Get("install_opt") != "i" && values.Get("install_opt") != "u") { + return errors.New("panel plugin package import is outside the free runtime-component allowlist") + } + case "a": + pluginName, method := values.Get("name"), values.Get("s") + allowed := (pluginName == "nodejs" && slices.Contains([]string{"get_online_version_list", "install_nodejs"}, method)) || + (pluginName == "pythonmamager" && method == "GetPythonV") + if !allowed { + return errors.New("panel plugin method is outside the free runtime-manager allowlist") + } + if method == "install_nodejs" && !runtimeVersionPattern.MatchString(values.Get("version")) { + return errors.New("invalid runtime version") + } + } + } + return nil +} + +func cloneValues(values url.Values) url.Values { + cloned := make(url.Values, len(values)) + for key, entries := range values { + cloned[key] = append([]string(nil), entries...) + } + return cloned +} + +func (c *Client) call(ctx context.Context, method, path string, values url.Values) (apiResponse, error) { + body, err := c.request(ctx, method, path, values) + if err != nil { + return apiResponse{}, err + } + var result apiResponse + if err := json.Unmarshal(body, &result); err != nil { + return apiResponse{}, fmt.Errorf("panel returned non-JSON response: %w", err) + } + if failed(result.Status) { + message := result.Msg + if strings.TrimSpace(message) == "" { + message = result.Message + } + if strings.TrimSpace(message) == "" { + message = result.ErrorMsg + } + return result, errors.New(safeMessage(message)) + } + return result, nil +} + +func failed(status any) bool { + switch value := status.(type) { + case bool: + return !value + case string: + return value == "false" || value == "error" + default: + return false + } +} + +func safeMessage(message string) string { + if strings.TrimSpace(message) == "" { + return "panel operation failed" + } + if len(message) > 240 { + return message[:240] + } + return message +} + +func (c *Client) Ping(ctx context.Context) error { + _, err := c.call(ctx, http.MethodPost, "/system", url.Values{"action": {"GetSystemTotal"}}) + return err +} + +func (c *Client) phpVersions(ctx context.Context) ([]string, error) { + body, err := c.request(ctx, http.MethodPost, "/site", url.Values{"action": {"GetPHPVersion"}}) + if err != nil { + return nil, fmt.Errorf("read PHP versions: %w", err) + } + var phpVersions []struct { + Version string `json:"version"` + Status bool `json:"status"` + } + if err = json.Unmarshal(body, &phpVersions); err != nil { + return nil, fmt.Errorf("decode PHP versions: %w", err) + } + php := make([]string, 0, len(phpVersions)) + for _, item := range phpVersions { + if item.Status && item.Version != "00" { + php = append(php, normalizePHPVersion(item.Version)) + } + } + return sortDottedVersionsDescending(cleanVersions(php)), nil +} + +func (c *Client) nodeVersions(ctx context.Context) ([]string, error) { + body, err := c.request(ctx, http.MethodPost, "/project/nodejs/get_nodejs_version/stype", nil) + if err != nil { + return nil, fmt.Errorf("read Node.js versions: %w", err) + } + var nodeVersions []string + if err = json.Unmarshal(body, &nodeVersions); err != nil { + return nil, fmt.Errorf("decode Node.js versions: %w", err) + } + return sortDottedVersionsDescending(cleanVersions(nodeVersions)), nil +} + +func (c *Client) pythonVersions(ctx context.Context) ([]string, error) { + installations, err := c.pythonInstallations(ctx) + if err != nil { + return nil, err + } + versions := make([]string, 0, len(installations)) + for _, installation := range installations { + versions = append(versions, installation.Version) + } + // Older patch releases may remain on disk for existing projects, but new + // project creation must only offer the newest installed patch per branch. + return latestPythonBranchVersions(versions), nil +} + +func sortDottedVersionsDescending(versions []string) []string { + sort.SliceStable(versions, func(left, right int) bool { + leftParts := strings.Split(strings.TrimLeft(versions[left], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), ".") + rightParts := strings.Split(strings.TrimLeft(versions[right], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), ".") + partCount := max(len(leftParts), len(rightParts)) + for index := 0; index < partCount; index++ { + leftPart, rightPart := 0, 0 + if index < len(leftParts) { + leftPart, _ = strconv.Atoi(leftParts[index]) + } + if index < len(rightParts) { + rightPart, _ = strconv.Atoi(rightParts[index]) + } + if leftPart != rightPart { + return leftPart > rightPart + } + } + return versions[left] > versions[right] + }) + return versions +} + +func (c *Client) pythonInstallations(ctx context.Context) ([]pythonInstallation, error) { + body, err := c.request(ctx, http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"pythonmamager"}, "s": {"GetPythonV"}}) + if err != nil { + return nil, fmt.Errorf("read Python installations: %w", err) + } + var installed []string + if err = json.Unmarshal(body, &installed); err != nil { + return nil, fmt.Errorf("decode Python installations: %w", err) + } + versions := cleanVersions(installed) + result := make([]pythonInstallation, 0, len(versions)) + for _, version := range versions { + result = append(result, pythonInstallation{ + Version: version, PythonPath: "/www/server/python_manager/versions/" + version + "/bin", + }) + } + return result, nil +} + +func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, error) { + // The legacy Python manager list contains the first patch releases of many + // branches (for example 3.12.0) and is not updated consistently. aaPanel's + // project SDK catalog tracks the current stable patch of each branch even + // when its bundled installer cannot fetch that release. + body, err := c.request(ctx, http.MethodPost, "/project/python/list_py_version/stype", nil) + if err != nil { + return nil, fmt.Errorf("read latest Python versions: %w", err) + } + var response struct { + Status any `json:"status"` + Msg string `json:"msg"` + SDK struct { + Streamline []runtimeSDK `json:"streamline"` + All []runtimeSDK `json:"all"` + } `json:"sdk"` + } + if err = json.Unmarshal(body, &response); err != nil { + return nil, fmt.Errorf("decode latest Python versions: %w", err) + } + if failed(response.Status) { + return nil, fmt.Errorf("read latest Python versions: %s", safeMessage(response.Msg)) + } + versions := make([]string, 0, len(response.SDK.Streamline)+len(response.SDK.All)) + for _, item := range append(response.SDK.Streamline, response.SDK.All...) { + versions = append(versions, item.Version) + } + versions = latestPythonBranchVersions(versions) + if len(versions) == 0 { + return nil, errors.New("latest Python branch catalog is empty") + } + return versions, nil +} + +func latestPythonBranchVersions(candidates []string) []string { + latest := make(map[string]string) + for _, candidate := range candidates { + version := strings.TrimSpace(candidate) + parts := strings.Split(version, ".") + if !stablePythonVersionPattern.MatchString(version) { + continue + } + minor, err := strconv.Atoi(parts[1]) + if err != nil || minor < 10 { + continue + } + branch := parts[0] + "." + parts[1] + if current := latest[branch]; current == "" || sortDottedVersionsDescending([]string{current, version})[0] == version { + latest[branch] = version + } + } + versions := make([]string, 0, len(latest)) + for _, version := range latest { + versions = append(versions, version) + } + return sortDottedVersionsDescending(cleanVersions(versions)) +} + +func (c *Client) goVersions(ctx context.Context) ([]string, error) { + body, err := c.goSDKInventory(ctx, false) + if err != nil { + return nil, fmt.Errorf("read Go versions: %w", err) + } + var goResponse struct { + Status any `json:"status"` + Msg string `json:"msg"` + Installed []string `json:"installed"` + } + if err = json.Unmarshal(body, &goResponse); err != nil { + return nil, fmt.Errorf("decode Go versions: %w", err) + } + if failed(goResponse.Status) { + return nil, fmt.Errorf("read Go versions: %s", safeMessage(goResponse.Msg)) + } + return sortDottedVersionsDescending(cleanVersions(goResponse.Installed)), nil +} + +func (c *Client) javaVersions(ctx context.Context) ([]string, error) { + javaInstallations, err := c.javaInstallations(ctx) + if err != nil { + return nil, err + } + javaVersions := make([]string, 0, len(javaInstallations)) + for _, item := range javaInstallations { + if item.Operation == 1 || strings.TrimSpace(item.Path) != "" { + javaVersions = append(javaVersions, item.Name) + } + } + return sortDottedVersionsDescending(cleanVersions(javaVersions)), nil +} + +func (c *Client) RuntimeCapabilities(ctx context.Context) (RuntimeCapabilities, error) { + type runtimeProbe struct { + name, policy string + read func(context.Context) ([]string, error) + } + type runtimeProbeResult struct { + probe runtimeProbe + versions []string + err error + } + probes := []runtimeProbe{ + {name: "PHP", policy: PolicyFreeCore, read: c.phpVersions}, + {name: "Node.js", policy: PolicyFreeProject, read: c.nodeVersions}, + {name: "Python", policy: PolicyFreeProject, read: c.pythonVersions}, + {name: "Go", policy: PolicyFreeProject, read: c.goVersions}, + {name: "Java", policy: PolicyFreeProject, read: c.javaVersions}, + } + results := make(chan runtimeProbeResult, len(probes)) + for _, item := range probes { + item := item + go func() { + versions, err := item.read(ctx) + results <- runtimeProbeResult{probe: item, versions: versions, err: err} + }() + } + capabilities := make(RuntimeCapabilities, len(probes)) + for range probes { + result := <-results + capability := RuntimeCapability{Status: RuntimeAvailable, Versions: result.versions, Policy: result.probe.policy} + if result.err != nil { + capability.Status = RuntimeProbeFailed + capability.Versions = []string{} + capability.Detail = runtimeProbeDetail(result.err) + } else if len(result.versions) == 0 { + capability.Status = RuntimeNotInstalled + capability.Versions = []string{} + } + capabilities[result.probe.name] = capability + } + return capabilities, nil +} + +func runtimeProbeDetail(err error) string { + message := strings.ToLower(err.Error()) + switch { + case strings.Contains(message, "http 404") || strings.Contains(message, "not found"): + return "接口不存在或组件未安装" + case strings.Contains(message, "decode") || strings.Contains(message, "non-json"): + return "接口返回格式与当前适配器不兼容" + case errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled): + return "运行环境探测超时" + default: + return "运行环境接口暂不可用" + } +} + +func (c *Client) RuntimeCatalog(ctx context.Context) (RuntimeCatalog, error) { + capabilities, err := c.RuntimeCapabilities(ctx) + if err != nil { + return nil, err + } + catalog := make(RuntimeCatalog, len(capabilities)) + for name, capability := range capabilities { + catalog[name] = capability.Versions + } + return catalog, nil +} + +func (c *Client) javaInstallations(ctx context.Context) ([]javaInstallation, error) { + body, err := c.request(ctx, http.MethodGet, "/mod/java/project/get_system_info/stype", nil) + if err != nil { + return nil, fmt.Errorf("read Java versions: %w", err) + } + var response struct { + Status any `json:"status"` + Msg string `json:"msg"` + Data struct { + JDKInfo []javaInstallation `json:"jdk_info"` + } `json:"data"` + } + if err = json.Unmarshal(body, &response); err != nil { + return nil, fmt.Errorf("decode Java versions: %w", err) + } + if failed(response.Status) { + return nil, fmt.Errorf("read Java versions: %s", safeMessage(response.Msg)) + } + return response.Data.JDKInfo, nil +} + +func normalizePHPVersion(version string) string { + version = strings.TrimSpace(version) + if strings.Contains(version, ".") { + return version + } + if len(version) >= 2 { + return version[:len(version)-1] + "." + version[len(version)-1:] + } + return version +} + +func cleanVersions(versions []string) []string { + cleaned := make([]string, 0, len(versions)) + seen := make(map[string]bool, len(versions)) + for _, version := range versions { + version = strings.TrimSpace(version) + if !runtimeVersionPattern.MatchString(version) || seen[version] { + continue + } + seen[version] = true + cleaned = append(cleaned, version) + } + return cleaned +} + +func panelNumberEquals(value any, expected string) bool { + switch item := value.(type) { + case float64: + parsed, err := strconv.ParseFloat(expected, 64) + return err == nil && item == parsed + case string: + return strings.TrimSpace(item) == expected + case bool: + return (expected == "1" && item) || (expected == "0" && !item) + default: + return false + } +} + +func (c *Client) runtimePlugin(ctx context.Context, pluginName, componentTitle string) (runtimePluginInfo, error) { + body, err := c.request(ctx, http.MethodPost, "/plugin", url.Values{"action": {"get_soft_find"}, "sName": {pluginName}}) + if err != nil { + return runtimePluginInfo{}, fmt.Errorf("read %s component: %w", componentTitle, err) + } + var result runtimePluginInfo + if err = json.Unmarshal(body, &result); err != nil { + return runtimePluginInfo{}, fmt.Errorf("decode %s component: %w", componentTitle, err) + } + if result.Name != pluginName || !panelNumberEquals(result.Price, "0") || !panelNumberEquals(result.PanelFree, "1") { + return runtimePluginInfo{}, fmt.Errorf("%s is not available as a free official component", componentTitle) + } + return result, nil +} + +func latestRuntimePluginRelease(plugin runtimePluginInfo) (runtimePluginRelease, bool) { + for _, release := range plugin.Versions { + if release.Beta == 0 && runtimeVersionPattern.MatchString(release.MVersion) && runtimeVersionPattern.MatchString(release.Version) { + return release, true + } + } + if runtimeVersionPattern.MatchString(plugin.MVersion) && runtimeVersionPattern.MatchString(plugin.MinVersion) { + return runtimePluginRelease{MVersion: plugin.MVersion, Version: plugin.MinVersion}, true + } + return runtimePluginRelease{}, false +} + +func runtimePluginReleaseLabel(release runtimePluginRelease) string { + return release.MVersion + "." + release.Version +} + +func runtimePluginVersionCurrent(current string, release runtimePluginRelease) bool { + current = strings.TrimSpace(current) + return current == release.Version || current == runtimePluginReleaseLabel(release) +} + +func (c *Client) nodeAvailableVersions(ctx context.Context) ([]string, error) { + body, err := c.request(ctx, http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"nodejs"}, "s": {"get_online_version_list"}}) + if err != nil { + return nil, fmt.Errorf("read available Node.js versions: %w", err) + } + type nodeVersion struct { + Version string `json:"version"` + } + var direct []nodeVersion + if json.Unmarshal(body, &direct) == nil { + versions := make([]string, 0, len(direct)) + for _, item := range direct { + versions = append(versions, item.Version) + } + return cleanVersions(versions), nil + } + var wrapped struct { + Status any `json:"status"` + Msg string `json:"msg"` + Data []nodeVersion `json:"data"` + } + if err = json.Unmarshal(body, &wrapped); err != nil { + return nil, fmt.Errorf("decode available Node.js versions: %w", err) + } + if failed(wrapped.Status) { + return nil, errors.New(safeMessage(wrapped.Msg)) + } + versions := make([]string, 0, len(wrapped.Data)) + for _, item := range wrapped.Data { + versions = append(versions, item.Version) + } + return cleanVersions(versions), nil +} + +func splitSDK(items []runtimeSDK) (available, installed, installing []string) { + for _, item := range items { + version := strings.TrimSpace(item.Version) + if !runtimeVersionPattern.MatchString(version) { + continue + } + available = append(available, version) + if panelTruthy(item.Installed) { + installed = append(installed, version) + } + if panelTruthy(item.Installing) { + installing = append(installing, version) + } + } + return cleanVersions(available), cleanVersions(installed), cleanVersions(installing) +} + +func recommendedVersion(available, installed []string) string { + if len(available) == 0 { + return "" + } + installedSet := make(map[string]bool, len(installed)) + for _, version := range installed { + installedSet[version] = true + } + if !installedSet[available[0]] { + return available[0] + } + return "" +} + +func (c *Client) RuntimeEnvironments(ctx context.Context) ([]RuntimeEnvironment, error) { + php, phpErr := c.phpVersions(ctx) + goBody, goErr := c.goSDKInventory(ctx, true) + javaItems, javaErr := c.javaInstallations(ctx) + nodePlugin, nodeErr := c.runtimePlugin(ctx, "nodejs", "Node.js version manager") + pythonPlugin, pythonPluginErr := c.runtimePlugin(ctx, "pythonmamager", "Python project manager") + + items := []RuntimeEnvironment{ + {Name: "PHP", ComponentTitle: "PHP 运行环境", ComponentStatus: RuntimeComponentReady, Installed: php, Available: []string{}, Installing: []string{}, Detail: "PHP 版本由宝塔软件商店管理,Sea vHost 仅使用已安装版本。"}, + {Name: "Node.js", ComponentTitle: "Node.js 版本管理器", ComponentStatus: RuntimeComponentFailed, Installed: []string{}, Available: []string{}, Installing: []string{}}, + {Name: "Python", ComponentTitle: "Python 项目管理器", ComponentStatus: RuntimeComponentFailed, Installed: []string{}, Available: []string{}, Installing: []string{}}, + {Name: "Go", ComponentTitle: "Go 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{}, Available: []string{}, Installing: []string{}}, + {Name: "Java", ComponentTitle: "Java 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{}, Available: []string{}, Installing: []string{}}, + } + if phpErr != nil { + items[0].ComponentStatus, items[0].Detail = RuntimeComponentFailed, runtimeProbeDetail(phpErr) + } + if nodeErr != nil { + items[1].Detail = runtimeProbeDetail(nodeErr) + } else if !panelTruthy(nodePlugin.Setup) { + items[1].ComponentStatus = RuntimeComponentMissing + items[1].ComponentInstallable = true + if latest, ok := latestRuntimePluginRelease(nodePlugin); ok { + items[1].ComponentLatestVersion = runtimePluginReleaseLabel(latest) + } + items[1].Detail = "可安装宝塔官方免费 Node.js 版本管理器。" + } else { + items[1].ComponentStatus = RuntimeComponentReady + items[1].ComponentVersion = nodePlugin.MinVersion + if latest, ok := latestRuntimePluginRelease(nodePlugin); ok { + items[1].ComponentLatestVersion = runtimePluginReleaseLabel(latest) + items[1].ComponentUpdateAvailable = nodePlugin.MinVersion != "" && !runtimePluginVersionCurrent(nodePlugin.MinVersion, latest) + items[1].ComponentInstallable = items[1].ComponentUpdateAvailable + } + installed, installedErr := c.nodeVersions(ctx) + available, availableErr := c.nodeAvailableVersions(ctx) + if installedErr != nil || availableErr != nil { + items[1].ComponentStatus = RuntimeComponentFailed + items[1].Detail = "Node.js 版本清单暂不可用" + } else { + items[1].Installed, items[1].Available = installed, available + items[1].Recommended = recommendedVersion(available, installed) + } + } + + if pythonPluginErr != nil { + items[2].Detail = runtimeProbeDetail(pythonPluginErr) + } else if !panelTruthy(pythonPlugin.Setup) { + items[2].ComponentStatus = RuntimeComponentMissing + items[2].ComponentInstallable = true + if latest, ok := latestRuntimePluginRelease(pythonPlugin); ok { + items[2].ComponentLatestVersion = runtimePluginReleaseLabel(latest) + } + items[2].Detail = "可安装宝塔官方免费 Python 项目管理器,安装后再选择 Python 版本。" + } else { + items[2].ComponentStatus = RuntimeComponentReady + items[2].ComponentVersion = pythonPlugin.MinVersion + if latest, ok := latestRuntimePluginRelease(pythonPlugin); ok { + items[2].ComponentLatestVersion = runtimePluginReleaseLabel(latest) + items[2].ComponentUpdateAvailable = pythonPlugin.MinVersion != "" && !runtimePluginVersionCurrent(pythonPlugin.MinVersion, latest) + items[2].ComponentInstallable = items[2].ComponentUpdateAvailable + } + installations, installedErr := c.pythonInstallations(ctx) + available, availableErr := c.pythonLatestAvailableVersions(ctx) + if installedErr != nil || availableErr != nil { + items[2].ComponentStatus, items[2].Detail = RuntimeComponentFailed, "Python 版本清单暂不可用" + } else { + installed := make([]string, 0, len(installations)) + for _, item := range installations { + installed = append(installed, item.Version) + } + items[2].Available, items[2].Installed = available, cleanVersions(installed) + items[2].Recommended = recommendedVersion(available, installed) + } + } + + if goErr != nil { + items[3].ComponentStatus, items[3].Detail = RuntimeComponentFailed, runtimeProbeDetail(goErr) + } else { + var response struct { + Status any `json:"status"` + Installed []string `json:"installed"` + SDK struct { + All []runtimeSDK `json:"all"` + Streamline []runtimeSDK `json:"streamline"` + } `json:"sdk"` + } + if err := json.Unmarshal(goBody, &response); err != nil || failed(response.Status) { + items[3].ComponentStatus, items[3].Detail = RuntimeComponentFailed, "Go 版本清单暂不可用" + } else { + available, installed, installing := splitSDK(append(response.SDK.Streamline, response.SDK.All...)) + installed = cleanVersions(append(installed, response.Installed...)) + items[3].Available, items[3].Installed, items[3].Installing = available, installed, installing + items[3].Recommended = recommendedVersion(available, installed) + } + } + + if javaErr != nil { + items[4].ComponentStatus, items[4].Detail = RuntimeComponentFailed, runtimeProbeDetail(javaErr) + } else { + for _, item := range javaItems { + if !runtimeVersionPattern.MatchString(item.Name) { + continue + } + items[4].Available = append(items[4].Available, item.Name) + if item.Operation == 1 || strings.TrimSpace(item.Path) != "" { + items[4].Installed = append(items[4].Installed, item.Name) + } else if item.Operation == 3 { + items[4].Installing = append(items[4].Installing, item.Name) + } + } + items[4].Available = cleanVersions(items[4].Available) + items[4].Installed = cleanVersions(items[4].Installed) + items[4].Installing = cleanVersions(items[4].Installing) + items[4].Recommended = recommendedVersion(items[4].Available, items[4].Installed) + } + items[0].Patches = c.phpRuntimePatches(ctx, php) + return items, nil +} + +func (c *Client) InstallRuntimeComponent(ctx context.Context, runtimeName string) error { + pluginName := "" + componentTitle := "" + switch runtimeName { + case "Node.js": + pluginName, componentTitle = "nodejs", "Node.js version manager" + case "Python": + // aaPanel's official plugin identifier intentionally contains this + // historical spelling; it is verified against the free-plugin metadata. + pluginName, componentTitle = "pythonmamager", "Python project manager" + default: + return errors.New("only official free Node.js and Python managers can be installed") + } + plugin, err := c.runtimePlugin(ctx, pluginName, componentTitle) + if err != nil { + return err + } + release, ok := latestRuntimePluginRelease(plugin) + if !ok { + return fmt.Errorf("%s component metadata is invalid", runtimeName) + } + installed := panelTruthy(plugin.Setup) + if installed && runtimePluginVersionCurrent(plugin.MinVersion, release) { + return nil + } + values := url.Values{"action": {"install_plugin"}, "sName": {pluginName}, "version": {release.MVersion}, "min_version": {release.Version}, "type": {"0"}} + if installed { + values = url.Values{"action": {"upgrade_plugin"}, "plugin_name": {pluginName}, "version": {release.MVersion}, "min_version": {release.Version}} + } + body, err := c.request(ctx, http.MethodPost, "/plugin", values) + if err != nil { + return err + } + var prepared runtimePluginPreparation + if err := json.Unmarshal(body, &prepared); err != nil { + return fmt.Errorf("decode %s component package: %w", runtimeName, err) + } + if failed(prepared.Status) { + message := prepared.Msg + if strings.TrimSpace(message) == "" { + message = prepared.Message + } + if strings.TrimSpace(message) == "" { + message = prepared.ErrorMsg + } + return errors.New(safeMessage(message)) + } + // Older panel builds may complete the installation in one request. + if panelTruthy(prepared.Status) && prepared.TmpPath == "" { + return nil + } + expectedOpt := "i" + if installed { + expectedOpt = "u" + } + if prepared.Name != pluginName || prepared.TmpPath != "/www/server/panel/temp/"+pluginName || prepared.InstallOpt != expectedOpt { + return fmt.Errorf("panel returned invalid %s component package metadata", runtimeName) + } + result, err := c.call(ctx, http.MethodPost, "/plugin", url.Values{ + "action": {"input_package"}, "tmp_path": {prepared.TmpPath}, "plugin_name": {prepared.Name}, "install_opt": {prepared.InstallOpt}, + }) + if err != nil { + return err + } + if !panelTruthy(result.Status) { + return fmt.Errorf("panel did not confirm %s component installation", runtimeName) + } + return nil +} + +func (c *Client) InstallRuntimeEnvironment(ctx context.Context, runtimeName, version string) error { + if !runtimeVersionPattern.MatchString(version) || !slices.Contains([]string{"Node.js", "Python", "Go", "Java"}, runtimeName) { + return errors.New("invalid runtime installation request") + } + inventory, err := c.RuntimeEnvironments(ctx) + if err != nil { + return err + } + allowed := false + for _, item := range inventory { + if item.Name == runtimeName && item.ComponentStatus == RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) && !slices.Contains(item.Installing, version) { + allowed = true + break + } + } + if !allowed { + return errors.New("runtime version is not available for installation") + } + switch runtimeName { + case "Node.js": + _, err = c.call(ctx, http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"nodejs"}, "s": {"install_nodejs"}, "version": {version}}) + case "Python": + return errors.New("Python source installation must use the privileged isolation installer") + case "Go": + _, err = c.call(ctx, http.MethodPost, "/project/go/install_go_sdk/stype", url.Values{"version": {version}}) + case "Java": + _, err = c.call(ctx, http.MethodPost, "/mod/java/project/install_jdk_new/stype", url.Values{"version": {version}}) + } + return err +} + +func (c *Client) CreateSite(ctx context.Context, spec SiteSpec) (int64, error) { + version, siteType := "00", "" + if spec.Runtime == "PHP" { + version, siteType = strings.ReplaceAll(spec.Version, ".", ""), "PHP" + } + webname, _ := json.Marshal(map[string]any{"domain": spec.Domain, "domainlist": []string{}, "count": 0}) + result, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"AddSite"}, "webname": {string(webname)}, "path": {spec.Path}, "type": {siteType}, "version": {version}, "port": {"80"}, "ps": {"Sea vHost: " + spec.Name}, "ftp": {"false"}, "sql": {"false"}}) + if err != nil { + return 0, err + } + ids, _ := json.Marshal([]int64{result.SiteID}) + if _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"multiple_basedir"}, "site_ids": {string(ids)}, "stat": {"open"}}); err != nil { + _ = c.DeleteSite(context.WithoutCancel(ctx), result.SiteID, spec.Domain) + return 0, fmt.Errorf("enable open_basedir: %w", err) + } + if spec.RunPath != "" && spec.RunPath != "/" { + if err = c.SetSiteRunPath(ctx, result.SiteID, spec.RunPath); err != nil { + _ = c.DeleteSite(context.WithoutCancel(ctx), result.SiteID, spec.Domain) + return 0, fmt.Errorf("set site run path: %w", err) + } + } + return result.SiteID, nil +} + +func (c *Client) ListUnmanagedSites(ctx context.Context) ([]ExistingSite, error) { + body, err := c.request(ctx, http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"sites"}, "limit": {"1000"}, "p": {"1"}, "search": {""}}) + if err != nil { + return nil, err + } + var response struct { + Status any `json:"status"` + Msg string `json:"msg"` + Data []json.RawMessage `json:"data"` + } + if err = json.Unmarshal(body, &response); err != nil || failed(response.Status) { + return nil, errors.New("panel returned an invalid site list") + } + items := make([]ExistingSite, 0, len(response.Data)) + for _, raw := range response.Data { + var row struct { + ID json.RawMessage `json:"id"` + Name string `json:"name"` + Path string `json:"path"` + Status string `json:"status"` + PHPVersion string `json:"php_version"` + } + if json.Unmarshal(raw, &row) != nil { + continue + } + id, parseErr := parsePanelID(row.ID) + domain := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(row.Name), ".")) + cleanPath := pathpkg.Clean(strings.TrimSpace(row.Path)) + if parseErr != nil || id <= 0 || !brokerCompatibleDomain(domain) || !pathpkg.IsAbs(cleanPath) || !strings.HasPrefix(cleanPath+"/", "/www/wwwroot/") { + continue + } + items = append(items, ExistingSite{ID: id, Domain: domain, Path: cleanPath, PHPVersion: normalizePHPVersion(row.PHPVersion), Status: row.Status}) + } + return items, nil +} + +func brokerCompatibleDomain(value string) bool { + if len(value) < 4 || len(value) > 253 || strings.ContainsAny(value, " /\\:\t\r\n") { + return false + } + return strings.Contains(value, ".") +} + +func (c *Client) SetSitePath(ctx context.Context, siteID int64, newPath string) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"SetPath"}, "id": {strconv.FormatInt(siteID, 10)}, "path": {newPath}}) + return err +} + +func (c *Client) AdoptSite(ctx context.Context, siteID int64, sourcePath string, spec SiteSpec) error { + items, err := c.ListUnmanagedSites(ctx) + if err != nil { + return err + } + found := false + for _, item := range items { + if item.ID == siteID && item.Domain == strings.ToLower(spec.Domain) && pathpkg.Clean(item.Path) == pathpkg.Clean(sourcePath) { + found = true + break + } + } + if !found { + return errors.New("panel site changed before adoption") + } + if err = c.SetSitePath(ctx, siteID, spec.Path); err != nil { + return err + } + if spec.RunPath != "" && spec.RunPath != "/" { + if err = c.SetSiteRunPath(ctx, siteID, spec.RunPath); err != nil { + _ = c.SetSitePath(context.WithoutCancel(ctx), siteID, sourcePath) + return err + } + } + ids, _ := json.Marshal([]int64{siteID}) + if _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"multiple_basedir"}, "site_ids": {string(ids)}, "stat": {"open"}}); err != nil { + _ = c.SetSitePath(context.WithoutCancel(ctx), siteID, sourcePath) + return err + } + return nil +} + +func (c *Client) RollbackAdoption(ctx context.Context, siteID int64, _ string, sourcePath string) error { + return c.SetSitePath(ctx, siteID, sourcePath) +} + +func (c *Client) SetSiteRunPath(ctx context.Context, siteID int64, runPath string) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"SetSiteRunPath"}, "id": {strconv.FormatInt(siteID, 10)}, "runPath": {runPath}}) + return err +} + +func (c *Client) MigrateRuntimeIdentity(context.Context, int64, string, bool) error { + return errors.New("runtime identity migration is only available through the managed broker") +} + +func (c *Client) DeleteSite(ctx context.Context, id int64, name string) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"DeleteSite"}, "id": {strconv.FormatInt(id, 10)}, "webname": {name}}) + return err +} + +func (c *Client) AddDomain(ctx context.Context, siteID int64, siteName, domain string) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"AddDomain"}, "id": {strconv.FormatInt(siteID, 10)}, "webname": {siteName}, "domain": {domain}}) + return err +} + +func (c *Client) DeleteDomain(ctx context.Context, siteID int64, siteName, domain string) error { + // The panel can have committed a prior attempt before a local registry save + // failed. Read the exact site's bindings to make a retry safe. + body, err := c.request(ctx, http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"domain"}, "search": {strconv.FormatInt(siteID, 10)}, "list": {"true"}}) + if err != nil { + return err + } + var rows []struct { + Name string `json:"name"` + Port int `json:"port"` + PID int64 `json:"pid"` + } + if err = json.Unmarshal(body, &rows); err != nil { + return errors.New("panel returned an invalid domain list") + } + found := false + for _, row := range rows { + if row.PID != siteID { + return errors.New("panel returned bindings from another site") + } + if strings.EqualFold(row.Name, domain) && row.Port == 80 { + found = true + } + } + if !found { + return nil + } + _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"DelDomain"}, "id": {strconv.FormatInt(siteID, 10)}, "webname": {siteName}, "domain": {domain}, "port": {"80"}}) + return err +} + +func (c *Client) CreateFTP(ctx context.Context, username, password, path string, maxBytes int64) (int64, error) { + // Storage enforcement is tenant-wide and implemented by Sea vHost's + // directory scanner. Do not depend on aaPanel's optional FTP quota route: + // it is not consistently available across free panel/Pure-FTPd versions. + _ = maxBytes + result, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"AddUser"}, "ftp_username": {username}, "ftp_password": {password}, "path": {path}, "ps": {"Managed by Sea vHost"}}) + if err != nil { + return 0, err + } + if result.ID <= 0 { + return c.lookupResourceID(ctx, "ftps", username) + } + return result.ID, nil +} + +func (c *Client) DeleteFTP(ctx context.Context, id int64, username string) error { + _, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"DeleteUser"}, "id": {strconv.FormatInt(id, 10)}, "username": {username}}) + return err +} + +func (c *Client) SetFTPState(ctx context.Context, id int64, username string, enabled bool) error { + status := "0" + if enabled { + status = "1" + } + _, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"SetStatus"}, "id": {strconv.FormatInt(id, 10)}, "username": {username}, "status": {status}}) + return err +} + +func (c *Client) CreateDatabase(ctx context.Context, name, username, password string, siteID int64) (int64, error) { + result, err := c.call(ctx, http.MethodPost, "/database", url.Values{"action": {"AddDatabase"}, "sid": {"0"}, "name": {name}, "db_user": {username}, "password": {password}, "address": {"127.0.0.1"}, "codeing": {"utf8mb4"}, "pid": {strconv.FormatInt(siteID, 10)}, "ps": {"Managed by Sea vHost"}}) + if err != nil { + return 0, err + } + if result.ID <= 0 { + return c.lookupResourceID(ctx, "databases", name) + } + return result.ID, nil +} + +func (c *Client) lookupResourceID(ctx context.Context, table, exactName string) (int64, error) { + body, err := c.request(ctx, http.MethodPost, "/data", url.Values{ + "action": {"getData"}, "table": {table}, "search": {exactName}, "limit": {"20"}, "p": {"1"}, + }) + if err != nil { + return 0, fmt.Errorf("resolve created %s resource: %w", table, err) + } + var response struct { + Status any `json:"status"` + Msg string `json:"msg"` + Data []json.RawMessage `json:"data"` + } + if err = json.Unmarshal(body, &response); err != nil { + return 0, fmt.Errorf("resolve created %s resource: invalid response", table) + } + if failed(response.Status) { + return 0, fmt.Errorf("resolve created %s resource: %s", table, safeMessage(response.Msg)) + } + var matchedID int64 + for _, raw := range response.Data { + var row struct { + ID json.RawMessage `json:"id"` + Name string `json:"name"` + Username string `json:"username"` + } + if json.Unmarshal(raw, &row) != nil || (row.Name != exactName && row.Username != exactName) { + continue + } + id, parseErr := parsePanelID(row.ID) + if parseErr != nil || id <= 0 || (matchedID > 0 && matchedID != id) { + return 0, fmt.Errorf("resolve created %s resource: ambiguous or invalid id", table) + } + matchedID = id + } + if matchedID <= 0 { + return 0, fmt.Errorf("resolve created %s resource: exact resource not found", table) + } + return matchedID, nil +} + +func parsePanelID(raw json.RawMessage) (int64, error) { + text := strings.TrimSpace(string(raw)) + if len(text) >= 2 && text[0] == '"' && text[len(text)-1] == '"' { + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return 0, err + } + text = value + } + return strconv.ParseInt(text, 10, 64) +} + +func (c *Client) DeleteDatabase(ctx context.Context, id int64, name string) error { + _, err := c.call(ctx, http.MethodPost, "/database", url.Values{"action": {"DeleteDatabase"}, "id": {strconv.FormatInt(id, 10)}, "sid": {"0"}, "name": {name}, "db_user": {name}}) + return err +} + +// DatabaseSize uses aaPanel's free core GetInfo action. The panel returns a +// human-readable binary size, so normalize it before it crosses the broker. +func (c *Client) DatabaseSize(ctx context.Context, _ int64, name string) (uint64, error) { + body, err := c.request(ctx, http.MethodPost, "/database", url.Values{"action": {"GetInfo"}, "db_name": {name}}) + if err != nil { + return 0, err + } + var response struct { + DataSize string `json:"data_size"` + Database string `json:"database"` + Status any `json:"status"` + Msg string `json:"msg"` + } + if err = json.Unmarshal(body, &response); err != nil { + return 0, errors.New("panel returned an invalid database size") + } + if failed(response.Status) || (response.Database != "" && response.Database != name) { + return 0, fmt.Errorf("database size query failed: %s", safeMessage(response.Msg)) + } + return parsePanelByteSize(response.DataSize) +} + +func parsePanelByteSize(value string) (uint64, error) { + match := regexp.MustCompile(`(?i)^\s*([0-9]+(?:\.[0-9]+)?)\s*(b|kb|mb|gb|tb)?\s*$`).FindStringSubmatch(value) + if match == nil { + return 0, errors.New("panel returned an invalid database size") + } + number, err := strconv.ParseFloat(match[1], 64) + if err != nil || number < 0 { + return 0, errors.New("panel returned an invalid database size") + } + power := map[string]int{"": 0, "b": 0, "kb": 1, "mb": 2, "gb": 3, "tb": 4}[strings.ToLower(match[2])] + bytes := number * math.Pow(1024, float64(power)) + if bytes > math.MaxUint64 { + return 0, errors.New("database size overflow") + } + return uint64(math.Ceil(bytes)), nil +} + +func (c *Client) ConfigureRuntime(ctx context.Context, spec RuntimeSpec) error { + if spec.Runtime == "PHP" { + return nil + } + workingDirectory := pathpkg.Join(spec.Path, strings.TrimPrefix(spec.RunPath, "/")) + entryPath := pathpkg.Join(workingDirectory, spec.EntryFile) + if !pathpkg.IsAbs(workingDirectory) || !strings.HasPrefix(workingDirectory+"/", strings.TrimRight(spec.Path, "/")+"/") { + return errors.New("runtime working directory is outside the managed site") + } + var createPath string + var values url.Values + switch spec.Runtime { + case "Node.js": + versions, err := c.nodeVersions(ctx) + if err != nil { + return err + } + if !slicesContains(versions, spec.Version) { + return errors.New("selected Node.js version is not installed") + } + projectScript := fmt.Sprintf("env PORT=%d npm run start", spec.Port) + if spec.Runner { + projectScript = "/usr/local/libexec/sea-vhost-run " + spec.ProjectName + } + createPath = "/project/nodejs/create_project/stype" + values = url.Values{ + "project_name": {spec.ProjectName}, "project_cwd": {workingDirectory}, "project_script": {projectScript}, + "project_ps": {"Managed by Sea vHost"}, "bind_extranet": {"0"}, "domains": {"[]"}, + "is_power_on": {"1"}, "run_user": {spec.RunUser}, "max_memory_limit": {"0"}, + "nodejs_version": {spec.Version}, "pkg_manager": {"npm"}, "port": {strconv.Itoa(spec.Port)}, + } + case "Python": + installations, err := c.pythonInstallations(ctx) + if err != nil { + return err + } + basePythonPath := "" + for _, installation := range installations { + if installation.Version == spec.Version { + basePythonPath = installation.PythonPath + break + } + } + if basePythonPath == "" { + return errors.New("selected Python interpreter path is unavailable") + } + // Register only the root-managed SDK in the panel's environment inventory. + // Detecting a tenant-writable virtualenv as root could execute tenant code. + // The panel inventory canonicalizes python3 symlinks to python3.. + pythonBin := pathpkg.Join(basePythonPath, "python"+strings.Join(strings.Split(spec.Version, ".")[:2], ".")) + if _, err = c.call(ctx, http.MethodPost, "/mod/python/environment/add_environment/stype", url.Values{"add_type": {"system"}, "path": {pythonBin}}); err != nil { + return fmt.Errorf("register managed Python interpreter: %w", err) + } + pythonPath := pathpkg.Join(workingDirectory, ".sea-runtime/python", spec.ProjectName+"-"+spec.Version) + createPath = "/project/python/CreateProject" + values = url.Values{ + "pjname": {spec.ProjectName}, "port": {strconv.Itoa(spec.Port)}, "stype": {"command"}, + "path": {workingDirectory}, "user": {spec.RunUser}, "venv_path": {pythonPath}, + "python_bin": {pythonBin}, + "project_cmd": {fmt.Sprintf("env PORT=%d %s %s", spec.Port, pathpkg.Join(pythonPath, "bin", "python3"), entryPath)}, "framework": {"python"}, + "auto_run": {"true"}, "env_list": {"[]"}, + } + case "Go": + versions, err := c.goVersions(ctx) + if err != nil { + return err + } + if !slicesContains(versions, spec.Version) { + return errors.New("selected Go version is not installed") + } + createPath = "/project/go/create_project/stype" + values = url.Values{ + "project_name": {spec.ProjectName}, "project_exe": {entryPath}, "project_cmd": {entryPath}, + "project_ps": {"Managed by Sea vHost"}, "bind_extranet": {"0"}, "domains": {"[]"}, + "is_power_on": {"1"}, "run_user": {spec.RunUser}, "port": {strconv.Itoa(spec.Port)}, + "env_list": {fmt.Sprintf(`[{"k":"PORT","v":"%d"}]`, spec.Port)}, "project_log": {"1"}, "web_log": {"0"}, + } + case "Java": + installations, err := c.javaInstallations(ctx) + if err != nil { + return err + } + jdkPath := "" + for _, installation := range installations { + if installation.Name == spec.Version && (installation.Operation == 1 || strings.TrimSpace(installation.Path) != "") { + jdkPath = strings.TrimSpace(installation.Path) + break + } + } + if jdkPath == "" { + return errors.New("selected JDK is not installed") + } + javaCommand := fmt.Sprintf("%s -jar %s --server.port=%d", jdkPath, entryPath, spec.Port) + if spec.Runner { + // The native Java module validates both paths in its command. The + // launcher verifies them against root-owned state before using it. + javaCommand = "/usr/local/libexec/sea-vhost-run " + spec.ProjectName + " --java " + jdkPath + " " + entryPath + } + data, _ := json.Marshal(map[string]any{ + "project_name": spec.ProjectName, "project_jar": entryPath, "project_jdk": jdkPath, + "run_user": spec.RunUser, "project_cmd": javaCommand, + "project_ps": "Managed by Sea vHost", "domains": []string{}, "bind_extranet": 0, + "port": spec.Port, "auth": 1, "is_separation": 0, "api_url": "/", "nohup_log": 1, + }) + createPath = "/mod/java/project/create_spring_boot_project/stype" + values = url.Values{"data": {string(data)}} + default: + return fmt.Errorf("unsupported runtime %q", spec.Runtime) + } + if spec.Runner && (spec.Runtime == "Python" || spec.Runtime == "Go") { + values.Set("project_cmd", "/usr/local/libexec/sea-vhost-run "+spec.ProjectName) + } + if _, err := c.call(ctx, http.MethodPost, createPath, values); err != nil { + // Several aaPanel language modules insert the project and launch its + // process before reporting a later PID/log failure. The broker has not + // registered the runtime at this point, so its normal delete operation is + // deliberately unavailable. Re-query the module and remove only an exact + // name + managed-directory match to prevent an untracked tenant process. + if cleanupErr := c.removePartialRuntime(context.WithoutCancel(ctx), spec); cleanupErr != nil { + return fmt.Errorf("create %s project: %w; partial-project cleanup was not confirmed: %v", spec.Runtime, err, cleanupErr) + } + return fmt.Errorf("create %s project: %w", spec.Runtime, err) + } + waitAttempts := 5 + if spec.Runtime == "Python" { + waitAttempts = 60 + } else if spec.Runtime == "Java" { + waitAttempts = 30 + } + if err := c.waitRuntimeRunning(ctx, spec, waitAttempts); err != nil { + // The create handlers in several aaPanel project modules discard the + // result returned by their internal start call. Invoke start once through + // its public route so a concrete launch error is surfaced to Sea vHost. + if startErr := c.callRuntimeState(ctx, spec, true); startErr != nil { + // Java and some Python builds report "already running" as an error. + // Never trust that text, but allow the normal list/status probe to + // prove the process and listening port are actually healthy. + if validationErr := c.waitRuntimeRunning(ctx, spec, 15); validationErr == nil { + return nil + } + _ = c.RemoveRuntime(context.WithoutCancel(ctx), spec) + return fmt.Errorf("%s 项目启动失败: %w", spec.Runtime, startErr) + } + err = c.waitRuntimeRunning(ctx, spec, 15) + if err == nil { + return nil + } + _ = c.RemoveRuntime(context.WithoutCancel(ctx), spec) + return err + } + return nil +} + +func (c *Client) removePartialRuntime(ctx context.Context, spec RuntimeSpec) error { + route, err := c.runtimeRoute(spec.Runtime, "get_project_list") + if err != nil { + return err + } + body, err := c.request(ctx, http.MethodPost, route, url.Values{"search": {spec.ProjectName}, "p": {"1"}, "limit": {"20"}}) + if err != nil { + return fmt.Errorf("query partial runtime: %w", err) + } + var response struct { + Data []map[string]any `json:"data"` + } + if err = json.Unmarshal(body, &response); err != nil { + return errors.New("query partial runtime: panel returned invalid data") + } + workingDirectory := pathpkg.Clean(pathpkg.Join(spec.Path, strings.TrimPrefix(spec.RunPath, "/"))) + found := false + for _, item := range response.Data { + name, _ := item["name"].(string) + if name == "" { + name, _ = item["project_name"].(string) + } + if name != spec.ProjectName { + continue + } + if found { + return errors.New("query partial runtime: duplicate exact project names") + } + found = true + if !runtimeRecordMatchesManagedDirectory(item, workingDirectory) { + return errors.New("query partial runtime: exact project name has an untrusted path") + } + if value, ok := runtimeRecordPort(item); ok && value != spec.Port { + return errors.New("query partial runtime: exact project name has a different port") + } + } + if !found { + return nil + } + if err = c.RemoveRuntime(ctx, spec); err != nil { + return fmt.Errorf("remove exact partial runtime: %w", err) + } + return nil +} + +func runtimeRecordMatchesManagedDirectory(item map[string]any, workingDirectory string) bool { + values := []string{} + appendPaths := func(source map[string]any) { + for _, key := range []string{"path", "project_cwd", "project_path", "jar_path"} { + if value, ok := source[key].(string); ok && strings.TrimSpace(value) != "" { + values = append(values, pathpkg.Clean(value)) + } + } + } + appendPaths(item) + if raw, ok := item["project_config"].(string); ok { + var config map[string]any + if json.Unmarshal([]byte(raw), &config) == nil { + appendPaths(config) + } + } else if config, ok := item["project_config"].(map[string]any); ok { + appendPaths(config) + } + for _, value := range values { + if value == workingDirectory || strings.HasPrefix(value+"/", strings.TrimRight(workingDirectory, "/")+"/") { + return true + } + } + return false +} + +func runtimeRecordPort(item map[string]any) (int, bool) { + for _, source := range []map[string]any{item, runtimeRecordConfig(item)} { + value, exists := source["port"] + if !exists { + continue + } + switch typed := value.(type) { + case float64: + if typed == float64(int(typed)) { + return int(typed), true + } + case string: + parsed, err := strconv.Atoi(strings.TrimSpace(typed)) + if err == nil { + return parsed, true + } + } + } + return 0, false +} + +func runtimeRecordConfig(item map[string]any) map[string]any { + if config, ok := item["project_config"].(map[string]any); ok { + return config + } + if raw, ok := item["project_config"].(string); ok { + var config map[string]any + if json.Unmarshal([]byte(raw), &config) == nil { + return config + } + } + return map[string]any{} +} + +func slicesContains(values []string, target string) bool { + for _, value := range values { + if value == target { + return true + } + } + return false +} + +func (c *Client) runtimeRoute(runtimeName, operation string) (string, error) { + if runtimeName == "Java" { + if operation == "get_project_list" { + operation = "project_list" + } + return "/mod/java/project/" + operation + "/stype", nil + } + prefix := map[string]string{ + "Node.js": "/project/nodejs/", "Python": "/project/python/", "Go": "/project/go/", + }[runtimeName] + if prefix == "" { + return "", fmt.Errorf("unsupported runtime %q", runtimeName) + } + if runtimeName == "Python" { + operation = map[string]string{ + "get_project_list": "GetProjectList", + "start_project": "StartProject", + "stop_project": "StopProject", + "remove_project": "RemoveProject", + }[operation] + if operation == "" { + return "", errors.New("unsupported Python project operation") + } + } + return prefix + operation + "/stype", nil +} + +func (c *Client) waitRuntimeRunning(ctx context.Context, spec RuntimeSpec, attempts int) error { + route, err := c.runtimeRoute(spec.Runtime, "get_project_list") + if err != nil { + return err + } + var lastState string + for attempt := 0; attempt < attempts; attempt++ { + body, requestErr := c.request(ctx, http.MethodPost, route, url.Values{"search": {spec.ProjectName}, "p": {"1"}, "limit": {"20"}}) + if requestErr == nil { + var response struct { + Data []struct { + Name string `json:"name"` + Run any `json:"run"` + ListenOK any `json:"listen_ok"` + PID any `json:"pid"` + Listen []any `json:"listen"` + } `json:"data"` + } + if json.Unmarshal(body, &response) == nil { + for _, item := range response.Data { + if item.Name != spec.ProjectName { + continue + } + lastState = "项目记录存在但进程未运行" + if spec.Runtime == "Java" { + if panelTruthy(item.PID) && panelListenContains(item.Listen, spec.Port) { + return nil + } + continue + } + if panelTruthy(item.Run) && (item.ListenOK == nil || panelTruthy(item.ListenOK)) { + return nil + } + } + } + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } + if lastState == "" { + lastState = "宝塔未返回新建项目记录" + } + return fmt.Errorf("%s 项目启动验证失败: %s", spec.Runtime, lastState) +} + +func panelTruthy(value any) bool { + switch typed := value.(type) { + case bool: + return typed + case float64: + return typed > 0 + case string: + value := strings.TrimSpace(strings.ToLower(typed)) + return value != "" && value != "0" && value != "false" && value != "none" && value != "null" + default: + return false + } +} + +func panelListenContains(values []any, port int) bool { + wanted := strconv.Itoa(port) + for _, value := range values { + switch typed := value.(type) { + case float64: + if int(typed) == port && typed == float64(int(typed)) { + return true + } + case string: + if strings.TrimSpace(typed) == wanted { + return true + } + } + } + return false +} + +func (c *Client) RemoveRuntime(ctx context.Context, spec RuntimeSpec) error { + if spec.Runtime == "PHP" { + return nil + } + route, err := c.runtimeRoute(spec.Runtime, "remove_project") + if err != nil { + return err + } + // Python's legacy removal handler can erase the project record without + // stopping processes started by the newer service manager. Stop through + // the public runtime API and verify its listener before destroying the + // metadata needed to find and stop the managed process. + if err := c.SetRuntimeState(ctx, spec, false); err != nil { + return fmt.Errorf("stop managed runtime before deletion: %w", err) + } + _, err = c.call(ctx, http.MethodPost, route, url.Values{"project_name": {spec.ProjectName}, "name": {spec.ProjectName}}) + if err == nil { + return waitRuntimePortStopped(ctx, spec, 8) + } + // Retrying a deletion is safe only when both the exact project record and + // its managed listener are absent. Never swallow a generic panel error. + present, verifyErr := c.runtimeRecordPresent(ctx, spec) + if verifyErr == nil && !present && waitRuntimePortStopped(ctx, spec, 4) == nil { + return nil + } + return err +} + +func (c *Client) runtimeRecordPresent(ctx context.Context, spec RuntimeSpec) (bool, error) { + route, err := c.runtimeRoute(spec.Runtime, "get_project_list") + if err != nil { + return false, err + } + body, err := c.request(ctx, http.MethodPost, route, url.Values{"search": {spec.ProjectName}, "p": {"1"}, "limit": {"20"}}) + if err != nil { + return false, err + } + var response struct { + Data []map[string]any `json:"data"` + Status any `json:"status"` + } + if json.Unmarshal(body, &response) != nil || response.Data == nil || failed(response.Status) { + return false, errors.New("cannot verify managed runtime record") + } + for _, item := range response.Data { + name, _ := item["name"].(string) + if name == "" { + name, _ = item["project_name"].(string) + } + if name == spec.ProjectName { + return true, nil + } + } + if len(response.Data) >= 20 { + return false, errors.New("runtime record query was truncated") + } + return false, nil +} + +func (c *Client) SetRuntimeState(ctx context.Context, spec RuntimeSpec, enabled bool) error { + if spec.Runtime == "PHP" { + return nil + } + stateErr := c.callRuntimeState(ctx, spec, enabled) + if enabled { + if stateErr != nil { + return stateErr + } + return c.waitRuntimeRunning(ctx, spec, 30) + } + stopErr := waitRuntimePortStopped(ctx, spec, 20) + if stopErr == nil { + // Treat aaPanel's version-dependent "already stopped" response as + // idempotent only when the managed backend port proves the process is + // no longer serving. + return nil + } + if stateErr != nil { + return stateErr + } + return stopErr +} + +func waitRuntimePortStopped(ctx context.Context, spec RuntimeSpec, attempts int) error { + address := net.JoinHostPort("127.0.0.1", strconv.Itoa(spec.Port)) + const requiredClosedChecks = 4 + closedChecks := 0 + for attempt := 0; attempt < attempts; attempt++ { + connection, err := (&net.Dialer{Timeout: 500 * time.Millisecond}).DialContext(ctx, "tcp", address) + if err != nil { + closedChecks++ + if closedChecks >= requiredClosedChecks { + return nil + } + } else { + _ = connection.Close() + closedChecks = 0 + } + if attempt+1 == attempts { + break + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(500 * time.Millisecond): + } + } + return fmt.Errorf("%s 项目停止验证失败: 后端端口 %d 仍在监听", spec.Runtime, spec.Port) +} + +func (c *Client) callRuntimeState(ctx context.Context, spec RuntimeSpec, enabled bool) error { + operation := "stop_project" + if enabled { + operation = "start_project" + } + route, err := c.runtimeRoute(spec.Runtime, operation) + if err != nil { + return err + } + _, err = c.call(ctx, http.MethodPost, route, url.Values{"project_name": {spec.ProjectName}, "name": {spec.ProjectName}}) + return err +} + +func (c *Client) ConfigureProxy(ctx context.Context, siteID int64, domain string, port int) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"CreateProxy"}, "sitename": {domain}, "proxyname": {"sea-vhost-runtime"}, "proxydir": {"/"}, "proxysite": {fmt.Sprintf("http://127.0.0.1:%d", port)}, "todomain": {domain}, "type": {"1"}, "cache": {"0"}, "cachetime": {"1"}, "subfilter": {"[]"}, "advanced": {"0"}}) + return err +} + +func (c *Client) RequestCertificate(ctx context.Context, id int64, path string, domains []string) error { + _, err := c.IssueManagedCertificate(ctx, id, path, domains) + return err +} +func (c *Client) IssueManagedCertificate(ctx context.Context, siteID int64, path string, domains []string) (string, error) { + if siteID <= 0 || len(domains) == 0 || strings.TrimSpace(domains[0]) == "" { + return "", errors.New("invalid managed site certificate request") + } + encoded, _ := json.Marshal(domains) + raw, err := c.request(ctx, http.MethodPost, "/acme", url.Values{"action": {"apply_cert_api"}, "id": {strconv.FormatInt(siteID, 10)}, "domains": {string(encoded)}, "auth_type": {"http"}, "auth_to": {strconv.FormatInt(siteID, 10)}, "ca": {"letsencrypt"}}) + if err != nil { + return "", fmt.Errorf("create ACME order: %w", err) + } + var order apiResponse + if json.Unmarshal(raw, &order) != nil { + return "", errors.New("panel returned an invalid ACME response") + } + if failed(order.Status) { + return "", errors.New("panel ACME request failed: " + safeMessage(order.Msg)) + } + // Current aaPanel completes issuance synchronously. Keep private material + // inside this privileged adapter and install only a matching, valid leaf. + var issued struct { + Certificate string `json:"cert"` + Root string `json:"root"` + PrivateKey string `json:"private_key"` + Domains []string `json:"domains"` + } + if json.Unmarshal(raw, &issued) == nil && (issued.Certificate != "" || issued.PrivateKey != "") { + chain := strings.TrimSpace(issued.Certificate) + "\n" + strings.TrimSpace(issued.Root) + "\n" + if len(chain) > 96<<10 || len(issued.PrivateKey) > 32<<10 { + return "", errors.New("panel issued an oversized certificate") + } + pair, e := tls.X509KeyPair([]byte(chain), []byte(issued.PrivateKey)) + if e != nil || len(pair.Certificate) == 0 { + return "", errors.New("panel issued an invalid certificate or private key") + } + leaf, e := x509.ParseCertificate(pair.Certificate[0]) + if e != nil || !leaf.NotAfter.After(time.Now()) || leaf.NotBefore.After(time.Now().Add(5*time.Minute)) { + return "", errors.New("panel issued a certificate outside its validity period") + } + for _, domain := range domains { + if leaf.VerifyHostname(domain) != nil { + return "", errors.New("panel certificate does not cover every managed domain") + } + } + if len(issued.Domains) == 0 { + issued.Domains = domains + } + if !sameDomainSet(issued.Domains, domains) { + return "", errors.New("panel certificate order has unexpected domains") + } + if e = c.InstallCertificate(ctx, siteID, strings.ToLower(strings.TrimSpace(domains[0])), issued.PrivateKey, chain); e != nil { + return "", fmt.Errorf("deploy issued certificate: %w", e) + } + return managedACMEIndex(issued.Domains), nil + } + order.Index = strings.TrimSpace(order.Index) + if order.Index == "" { + return "", errors.New("panel ACME response did not include an order index") + } + + status := strings.ToLower(strings.TrimSpace(fmt.Sprint(order.Status))) + for attempt := 0; status != "valid"; attempt++ { + if status == "expired" || status == "invalid" || status == "revoked" || status == "deactivated" { + return "", fmt.Errorf("ACME order ended with status %s", status) + } + if attempt >= 30 { + return "", errors.New("ACME order did not become valid before the timeout") + } + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-time.After(2 * time.Second): + } + detail, detailErr := c.call(ctx, http.MethodPost, "/acme", url.Values{"action": {"get_order_find"}, "index": {order.Index}}) + if detailErr != nil { + return "", fmt.Errorf("read ACME order: %w", detailErr) + } + status = strings.ToLower(strings.TrimSpace(fmt.Sprint(detail.Status))) + } + + if _, err = c.call(ctx, http.MethodPost, "/acme", url.Values{"action": {"SetCertToSite"}, "index": {order.Index}, "siteName": {strings.ToLower(strings.TrimSpace(domains[0]))}}); err != nil { + return "", fmt.Errorf("deploy ACME certificate: %w", err) + } + return order.Index, nil +} + +func (c *Client) InstallCertificate(ctx context.Context, _ int64, siteName, privateKey, certificate string) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{ + "action": {"SetSSL"}, "siteName": {siteName}, "key": {privateKey}, "csr": {certificate}, + }) + return err +} + +func (c *Client) DisableCertificate(ctx context.Context, _ int64, siteName string) error { + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{ + "action": {"CloseSSLConf"}, "siteName": {siteName}, "updateOf": {"1"}, + }) + return err +} + +func (c *Client) SetSiteState(ctx context.Context, siteID int64, name string, enabled bool) error { + action := "SiteStop" + if enabled { + action = "SiteStart" + } + _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {action}, "id": {strconv.FormatInt(siteID, 10)}, "name": {name}}) + return err +} diff --git a/backend/internal/panel/client_test.go b/backend/internal/panel/client_test.go new file mode 100644 index 0000000..19facde --- /dev/null +++ b/backend/internal/panel/client_test.go @@ -0,0 +1,808 @@ +package panel + +import ( + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "testing" + "time" +) + +func TestSignatureMatchesPanelProtocol(t *testing.T) { + got := Signature("example-key", 1700000000) + const want = "22f7cc469919f6fdfe667286a3c7a64a" + if got != want { + t.Fatalf("Signature() = %q, want %q", got, want) + } +} + +func TestDeleteDomainUsesExactSiteAndRetriesAfterRemoval(t *testing.T) { + deleted := 0 + present := true + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/data" { + if r.Form.Get("search") != "17" || r.Form.Get("table") != "domain" || r.Form.Get("list") != "true" { + t.Error("unscoped domain query") + } + if present { + _, _ = w.Write([]byte(`[{"pid":17,"name":"custom.example.com","port":80}]`)) + } else { + _, _ = w.Write([]byte(`[]`)) + } + return + } + if r.URL.Path != "/site" || r.Form.Get("action") != "DelDomain" || r.Form.Get("id") != "17" || r.Form.Get("domain") != "custom.example.com" || r.Form.Get("port") != "80" { + t.Error("incorrect deletion payload") + } + deleted++ + present = false + _, _ = w.Write([]byte(`{"status":true,"msg":"ok"}`)) + })) + defer server.Close() + client := NewClient(server.URL, "key", false, 5*time.Second) + var err error + for range 2 { + if err = client.DeleteDomain(context.Background(), 17, "host.example.com", "custom.example.com"); err != nil { + t.Fatal(err) + } + } + if deleted != 1 { + t.Fatalf("delete calls=%d", deleted) + } +} + +func TestLatestPythonBranchesExcludePrereleasesAndOrderPatchesNumerically(t *testing.T) { + got := latestPythonBranchVersions([]string{ + "3.12.9", "3.12.15", "3.12.15", "3.14.9", "3.14.10rc1", "3.16.0a1", + "3.13.17", "3.13.18.dev1", "3.010.99", "3.12.015", "3.9.25", "2.7.18", "bad", + }) + want := []string{"3.14.9", "3.13.17", "3.12.15"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("latest stable branches = %#v, want %#v", got, want) + } +} + +func TestParsePanelByteSize(t *testing.T) { + tests := map[string]uint64{"0.00b": 0, "1 KB": 1024, "1.5 MB": 1572864, "2GB": 2147483648} + for input, want := range tests { + got, err := parsePanelByteSize(input) + if err != nil || got != want { + t.Fatalf("parsePanelByteSize(%q) = %d, %v; want %d", input, got, err, want) + } + } + if _, err := parsePanelByteSize("unknown"); err == nil { + t.Fatal("invalid panel size was accepted") + } +} + +func TestRuntimeCatalogUsesAaPanelProjectRoutes(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/site": + if r.FormValue("action") != "GetPHPVersion" { + t.Fatalf("unexpected site action %q", r.FormValue("action")) + } + _ = json.NewEncoder(w).Encode([]map[string]any{{"version": "74", "status": true}, {"version": "84", "status": true}, {"version": "00", "status": true}, {"version": "83", "status": false}}) + case "/project/nodejs/get_nodejs_version/stype": + _ = json.NewEncoder(w).Encode([]string{"v24.21.0", "v22.23.3", "v24.22.1"}) + case "/plugin": + if r.FormValue("action") != "a" || r.FormValue("name") != "pythonmamager" || r.FormValue("s") != "GetPythonV" { + t.Fatalf("unexpected Python manager request: %#v", r.Form) + } + _ = json.NewEncoder(w).Encode([]string{"3.12.15", "3.12.0", "3.11.17", "3.9.10"}) + case "/project/go/list_go_sdk/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.25.14", "go1.27.1", "go1.27.3"}}) + case "/mod/java/project/get_system_info/stype": + if r.Method != http.MethodGet { + t.Fatalf("Java inventory method = %s, want GET", r.Method) + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []map[string]any{{"name": "jdk-21.0.2", "path": "/www/server/java/jdk-21.0.2", "operation": 1}, {"name": "jdk-25.0.3", "path": "/www/server/java/jdk-25.0.3", "operation": 1}, {"name": "invalid value", "path": "/tmp", "operation": 1}}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + catalog, err := client.RuntimeCatalog(context.Background()) + if err != nil { + t.Fatal(err) + } + want := RuntimeCatalog{ + "PHP": {"8.4", "7.4"}, "Node.js": {"v24.22.1", "v24.21.0", "v22.23.3"}, "Python": {"3.12.15", "3.11.17"}, + "Go": {"go1.27.3", "go1.27.1", "go1.25.14"}, "Java": {"jdk-25.0.3", "jdk-21.0.2"}, + } + if !reflect.DeepEqual(catalog, want) { + t.Fatalf("RuntimeCatalog() = %#v, want %#v", catalog, want) + } +} + +func TestRuntimeCapabilitiesDoNotFailAsAGroup(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/site": + _ = json.NewEncoder(w).Encode([]map[string]any{{"version": "84", "status": true}}) + case "/project/nodejs/get_nodejs_version/stype": + http.Error(w, "not installed", http.StatusNotFound) + case "/plugin": + _ = json.NewEncoder(w).Encode([]string{}) + case "/project/go/list_go_sdk/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}}) + case "/mod/java/project/get_system_info/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": false, "msg": "module unavailable"}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + capabilities, err := client.RuntimeCapabilities(context.Background()) + if err != nil { + t.Fatal(err) + } + if capabilities["PHP"].Status != RuntimeAvailable || capabilities["Python"].Status != RuntimeNotInstalled { + t.Fatalf("unexpected available/not-installed states: %#v", capabilities) + } + if capabilities["Node.js"].Status != RuntimeProbeFailed || capabilities["Java"].Status != RuntimeProbeFailed { + t.Fatalf("optional project failures were not isolated: %#v", capabilities) + } + if capabilities["Node.js"].Detail != "接口不存在或组件未安装" || strings.Contains(capabilities["Node.js"].Detail, "request_token") { + t.Fatalf("runtime probe detail is unsafe or unclear: %#v", capabilities["Node.js"]) + } + if capabilities["Go"].Policy != PolicyFreeProject || capabilities["PHP"].Policy != PolicyFreeCore { + t.Fatalf("unexpected runtime policies: %#v", capabilities) + } + catalog, err := client.RuntimeCatalog(context.Background()) + if err != nil || len(catalog["PHP"]) != 1 || len(catalog["Node.js"]) != 0 { + t.Fatalf("partial catalog = %#v, err = %v", catalog, err) + } +} + +func TestFreePanelRequestPolicyRejectsPaidAndGenericRoutes(t *testing.T) { + for _, test := range []struct { + method, path, action string + }{ + {http.MethodPost, "/plugin", "btwaf"}, + {http.MethodPost, "/site", "GetWafConfig"}, + {http.MethodPost, "/system", "SetSystemHardening"}, + } { + if err := validateFreePanelRequest(test.method, test.path, url.Values{"action": {test.action}}); err == nil { + t.Fatalf("request unexpectedly allowed: %s %s action=%s", test.method, test.path, test.action) + } + } + if err := validateFreePanelRequest(http.MethodPost, "/site", url.Values{"action": {"AddSite"}}); err != nil { + t.Fatalf("free-core site request was rejected: %v", err) + } + if err := validateFreePanelRequest(http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"users"}}); err == nil { + t.Fatal("generic panel data-table access was accepted") + } + if err := validateFreePanelRequest(http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"ftps"}}); err != nil { + t.Fatalf("managed FTP lookup was rejected: %v", err) + } + if err := validateFreePanelRequest(http.MethodPost, "/plugin", url.Values{"action": {"get_soft_find"}, "sName": {"btwaf"}}); err == nil { + t.Fatal("paid plugin metadata request was accepted") + } + if err := validateFreePanelRequest(http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"nodejs"}, "s": {"uninstall_nodejs"}}); err == nil { + t.Fatal("Node.js plugin uninstall method was accepted") + } +} + +func TestRuntimeEnvironmentInventoryUsesOnlyAdvertisedVersions(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/site": + _ = json.NewEncoder(w).Encode([]map[string]any{{"version": "84", "status": true}}) + case "/plugin": + switch r.FormValue("action") { + case "get_soft_find": + switch r.FormValue("sName") { + case "php-8.4": + _ = json.NewEncoder(w).Encode(map[string]any{"name": "php-8.4", "price": 0, "panel_free": 1, "setup": true, "version": "8.4.25", "versions": []map[string]any{{"m_version": "8.4", "version": "27", "beta": 0}}}) + case "nodejs": + _ = json.NewEncoder(w).Encode(map[string]any{"name": "nodejs", "title": "Node.js版本管理器", "price": 0, "panel_free": 1, "setup": true, "version": "8", "versions": []map[string]any{{"m_version": "2", "version": "8", "beta": 0}}}) + case "pythonmamager": + _ = json.NewEncoder(w).Encode(map[string]any{"name": "pythonmamager", "title": "Python项目管理器", "price": 0, "panel_free": 1, "setup": true, "version": "2.5.1", "versions": []map[string]any{{"m_version": "2", "version": "5.1", "beta": 0}}}) + default: + t.Fatalf("unexpected plugin metadata name %q", r.FormValue("sName")) + } + case "a": + switch r.FormValue("name") + "/" + r.FormValue("s") { + case "nodejs/get_online_version_list": + _ = json.NewEncoder(w).Encode([]map[string]any{{"version": "v24.12.0"}, {"version": "v22.23.3"}}) + case "pythonmamager/GetCloudPython": + _ = json.NewEncoder(w).Encode([][]string{{"3.12.0", "0"}, {"3.11.4", "0"}}) + case "pythonmamager/GetPythonV": + _ = json.NewEncoder(w).Encode([]string{"3.12.0"}) + default: + t.Fatalf("unexpected plugin method %s/%s", r.FormValue("name"), r.FormValue("s")) + } + default: + t.Fatalf("unexpected plugin action %q", r.FormValue("action")) + } + case "/project/nodejs/get_nodejs_version/stype": + _ = json.NewEncoder(w).Encode([]string{"v22.23.3"}) + case "/project/python/list_py_version/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "sdk": map[string]any{"streamline": []map[string]any{{"version": "3.15.1"}, {"version": "3.14.9"}, {"version": "3.13.17"}, {"version": "3.12.15"}, {"version": "3.11.17"}, {"version": "3.10.22"}, {"version": "3.9.25"}}}}) + case "/project/go/list_go_sdk/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.25.4"}, "sdk": map[string]any{"streamline": []map[string]any{{"version": "go1.26.1", "installed": false}, {"version": "go1.25.4", "installed": true}}}}) + case "/mod/java/project/get_system_info/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []map[string]any{{"name": "jdk-25.0.1", "path": "", "operation": 0}, {"name": "jdk-21.0.2", "path": "/www/server/java/jdk-21.0.2", "operation": 1}}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + items, err := client.RuntimeEnvironments(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(items) != 5 || items[1].Recommended != "v24.12.0" || !reflect.DeepEqual(items[2].Installed, []string{"3.12.0"}) || !reflect.DeepEqual(items[2].Available, []string{"3.15.1", "3.14.9", "3.13.17", "3.12.15", "3.11.17", "3.10.22"}) || items[2].Recommended != "3.15.1" || items[3].Recommended != "go1.26.1" || items[4].Recommended != "jdk-25.0.1" { + t.Fatalf("unexpected runtime inventory: %#v", items) + } +} + +func TestInstallPythonComponentUsesOfficialFreePlugin(t *testing.T) { + installed := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/plugin" { + http.NotFound(w, r) + return + } + switch r.FormValue("action") { + case "get_soft_find": + _ = json.NewEncoder(w).Encode(map[string]any{ + "name": "pythonmamager", "price": 0, "panel_free": 1, "setup": false, + "versions": []map[string]any{{"m_version": "2", "version": "5.1", "beta": 0}}, + }) + case "install_plugin": + if r.FormValue("sName") != "pythonmamager" || r.FormValue("version") != "2" || r.FormValue("min_version") != "5.1" || r.FormValue("type") != "0" { + t.Fatalf("unexpected Python component install form: %#v", r.Form) + } + _ = json.NewEncoder(w).Encode(map[string]any{"name": "pythonmamager", "tmp_path": "/www/server/panel/temp/pythonmamager", "install_opt": "i"}) + case "input_package": + if r.FormValue("plugin_name") != "pythonmamager" || r.FormValue("tmp_path") != "/www/server/panel/temp/pythonmamager" || r.FormValue("install_opt") != "i" { + t.Fatalf("unexpected Python component package form: %#v", r.Form) + } + installed = true + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + default: + t.Fatalf("unexpected plugin action %q", r.FormValue("action")) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + if err := client.InstallRuntimeComponent(context.Background(), "Python"); err != nil { + t.Fatal(err) + } + if !installed { + t.Fatal("Python component installation was not completed") + } +} + +func TestDirectPanelClientCannotInstallPythonSource(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/site" { + _ = json.NewEncoder(w).Encode([]map[string]any{}) + return + } + if r.URL.Path == "/plugin" && r.FormValue("action") == "get_soft_find" { + _ = json.NewEncoder(w).Encode(map[string]any{"name": r.FormValue("sName"), "price": 0, "panel_free": 1, "setup": true, "version": "2.5.1", "versions": []map[string]any{{"m_version": "2", "version": "5.1", "beta": 0}}}) + return + } + if r.URL.Path == "/plugin" && r.FormValue("name") == "pythonmamager" { + switch r.FormValue("s") { + case "GetPythonV": + _ = json.NewEncoder(w).Encode([]string{}) + default: + t.Fatalf("unexpected Python manager method %q", r.FormValue("s")) + } + return + } + switch r.URL.Path { + case "/project/nodejs/get_nodejs_version/stype": + _ = json.NewEncoder(w).Encode([]string{}) + case "/project/python/list_py_version/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "sdk": map[string]any{"streamline": []map[string]any{{"version": "3.12.15"}}}}) + case "/project/go/list_go_sdk/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "sdk": map[string]any{}}) + case "/mod/java/project/get_system_info/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []any{}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, 5*time.Second) + err := client.InstallRuntimeEnvironment(context.Background(), "Python", "3.12.15") + if err == nil || !strings.Contains(err.Error(), "isolation installer") { + t.Fatalf("direct Python install error = %v", err) + } +} + +func TestInstallNodeComponentUsesLatestStablePluginRelease(t *testing.T) { + prepared := false + installed := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/plugin" { + http.NotFound(w, r) + return + } + switch r.FormValue("action") { + case "get_soft_find": + _ = json.NewEncoder(w).Encode(map[string]any{ + "name": "nodejs", "price": 0, "panel_free": 1, "setup": false, + "versions": []map[string]any{{"m_version": "2", "version": "8", "beta": 0}, {"m_version": "3", "version": "9", "beta": 1}}, + }) + case "install_plugin": + if r.FormValue("sName") != "nodejs" || r.FormValue("version") != "2" || r.FormValue("min_version") != "8" || r.FormValue("type") != "0" { + t.Fatalf("unexpected Node.js component install form: %#v", r.Form) + } + prepared = true + _ = json.NewEncoder(w).Encode(map[string]any{"name": "nodejs", "tmp_path": "/www/server/panel/temp/nodejs", "install_opt": "i"}) + case "input_package": + if !prepared || r.FormValue("plugin_name") != "nodejs" || r.FormValue("tmp_path") != "/www/server/panel/temp/nodejs" || r.FormValue("install_opt") != "i" { + t.Fatalf("unexpected Node.js component package form: %#v", r.Form) + } + installed = true + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "安装成功"}) + default: + t.Fatalf("unexpected plugin action %q", r.FormValue("action")) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + if err := client.InstallRuntimeComponent(context.Background(), "Node.js"); err != nil { + t.Fatal(err) + } + if !installed { + t.Fatal("Node.js component installation was not submitted") + } +} + +func TestRecommendedRuntimeVersionDoesNotSuggestAnOlderRelease(t *testing.T) { + available := []string{"v26.12.1", "v26.12.0", "v24.22.1"} + if got := recommendedVersion(available, []string{"v26.12.1"}); got != "" { + t.Fatalf("recommendedVersion() = %q; want no downgrade recommendation", got) + } + if got := recommendedVersion(available, []string{"v24.22.1"}); got != "v26.12.1" { + t.Fatalf("recommendedVersion() = %q; want latest release", got) + } +} + +func TestUpdateNodeComponentUsesTwoPhaseUpgrade(t *testing.T) { + upgraded := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/plugin" { + http.NotFound(w, r) + return + } + switch r.FormValue("action") { + case "get_soft_find": + _ = json.NewEncoder(w).Encode(map[string]any{ + "name": "nodejs", "price": 0, "panel_free": 1, "setup": true, "version": "2.7", + "versions": []map[string]any{{"m_version": "2", "version": "8", "beta": 0}}, + }) + case "upgrade_plugin": + if r.FormValue("plugin_name") != "nodejs" || r.FormValue("version") != "2" || r.FormValue("min_version") != "8" { + t.Fatalf("unexpected Node.js component update form: %#v", r.Form) + } + _ = json.NewEncoder(w).Encode(map[string]any{"name": "nodejs", "tmp_path": "/www/server/panel/temp/nodejs", "install_opt": "u"}) + case "input_package": + if r.FormValue("install_opt") != "u" { + t.Fatalf("unexpected Node.js component update package form: %#v", r.Form) + } + upgraded = true + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + default: + t.Fatalf("unexpected plugin action %q", r.FormValue("action")) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + if err := client.InstallRuntimeComponent(context.Background(), "Node.js"); err != nil { + t.Fatal(err) + } + if !upgraded { + t.Fatal("Node.js component update was not completed") + } +} + +func TestCreateResourcesResolveIDsWhenAaPanelOmitsThem(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/ftp", "/database": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + case "/data": + switch r.FormValue("table") { + case "ftps": + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"id": "17", "name": "sv0123456789"}}}) + case "databases": + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"id": 29, "name": "sv0123456789", "username": "sv0123456789"}}}) + default: + http.Error(w, "unexpected table", http.StatusBadRequest) + } + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + ftpID, err := client.CreateFTP(context.Background(), "sv0123456789", "Aa0123456789Bb012345", "/managed", 1<<30) + if err != nil || ftpID != 17 { + t.Fatalf("CreateFTP() = %d, %v; want 17", ftpID, err) + } + databaseID, err := client.CreateDatabase(context.Background(), "sv0123456789", "sv0123456789", "Cc0123456789Dd012345", 3) + if err != nil || databaseID != 29 { + t.Fatalf("CreateDatabase() = %d, %v; want 29", databaseID, err) + } +} + +func TestMutationParametersMatchAaPanelAPI(t *testing.T) { + requests := make(chan *http.Request, 5) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + t.Fatal(err) + } + clone := r.Clone(r.Context()) + clone.Form = cloneValues(r.Form) + requests <- clone + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + if err := client.DeleteDatabase(context.Background(), 42, "sv_acme_blog"); err != nil { + t.Fatal(err) + } + deleted := <-requests + if deleted.Form.Get("sid") != "0" || deleted.Form.Get("db_user") != "sv_acme_blog" { + t.Fatalf("DeleteDatabase form = %#v", deleted.Form) + } + if err := client.ConfigureProxy(context.Background(), 7, "blog.hosts.example.com", 20020); err != nil { + t.Fatal(err) + } + proxy := <-requests + if proxy.Form.Get("cachetime") == "" || proxy.Form.Get("todomain") != "blog.hosts.example.com" { + t.Fatalf("ConfigureProxy form = %#v", proxy.Form) + } + if err := client.SetSiteRunPath(context.Background(), 7, "/apps/web/public"); err != nil { + t.Fatal(err) + } + runPath := <-requests + if runPath.Form.Get("action") != "SetSiteRunPath" || runPath.Form.Get("id") != "7" || runPath.Form.Get("runPath") != "/apps/web/public" { + t.Fatalf("SetSiteRunPath form = %#v", runPath.Form) + } + if err := client.InstallCertificate(context.Background(), 7, "blog.hosts.example.com", "private-key-pem", "certificate-chain-pem"); err != nil { + t.Fatal(err) + } + certificate := <-requests + if certificate.URL.Path != "/site" || certificate.Form.Get("action") != "SetSSL" || certificate.Form.Get("siteName") != "blog.hosts.example.com" || certificate.Form.Get("key") != "private-key-pem" || certificate.Form.Get("csr") != "certificate-chain-pem" { + t.Fatalf("InstallCertificate form = %#v", certificate.Form) + } + if err := client.DisableCertificate(context.Background(), 7, "blog.hosts.example.com"); err != nil { + t.Fatal(err) + } + disabled := <-requests + if disabled.URL.Path != "/site" || disabled.Form.Get("action") != "CloseSSLConf" || disabled.Form.Get("siteName") != "blog.hosts.example.com" || disabled.Form.Get("updateOf") != "1" { + t.Fatalf("DisableCertificate form = %#v", disabled.Form) + } +} + +func TestRequestCertificateDeploysValidACMEOrder(t *testing.T) { + requests := make(chan url.Values, 3) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + t.Fatal(err) + } + requests <- cloneValues(r.Form) + w.Header().Set("Content-Type", "application/json") + switch r.FormValue("action") { + case "apply_cert_api": + _ = json.NewEncoder(w).Encode(map[string]any{"status": "valid", "index": "order-123"}) + case "SetCertToSite": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "SSL enabled"}) + default: + t.Fatalf("unexpected ACME action %q", r.FormValue("action")) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + if err := client.RequestCertificate(context.Background(), 7, "/www/example", []string{"blog.hosts.example.com", "www.example.com"}); err != nil { + t.Fatal(err) + } + created := <-requests + if created.Get("action") != "apply_cert_api" || created.Get("id") != "7" || created.Get("auth_type") != "http" || created.Get("auth_to") != "7" || created.Get("domains") != `["blog.hosts.example.com","www.example.com"]` { + t.Fatalf("ACME create form = %#v", created) + } + deployed := <-requests + if deployed.Get("action") != "SetCertToSite" || deployed.Get("index") != "order-123" || deployed.Get("siteName") != "blog.hosts.example.com" { + t.Fatalf("ACME deployment form = %#v", deployed) + } +} + +func TestRequestCertificateRejectsMissingOrderIndex(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"}) + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, 5*time.Second) + err := client.RequestCertificate(context.Background(), 7, "/www/example", []string{"blog.hosts.example.com"}) + if err == nil || !strings.Contains(err.Error(), "order index") { + t.Fatalf("RequestCertificate() error = %v", err) + } +} + +func TestConfigureJavaResolvesServerOwnedJDKPath(t *testing.T) { + var createData map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/mod/java/project/get_system_info/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "data": map[string]any{"jdk_info": []map[string]any{{"name": "jdk-21.0.2", "path": "/www/server/java/jdk-21/bin/java", "operation": 1}}}}) + case "/mod/java/project/create_spring_boot_project/stype": + if err := json.Unmarshal([]byte(r.FormValue("data")), &createData); err != nil { + t.Fatal(err) + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + case "/mod/java/project/project_list/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"name": "sv0123456789", "pid": "1234", "listen": []int{20020}}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + err := client.ConfigureRuntime(context.Background(), RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Java", Version: "jdk-21.0.2", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public", EntryFile: "app.jar", Domain: "sv0123456789.hosts.example.com", RunUser: "www", Port: 20020}) + if err != nil { + t.Fatal(err) + } + if createData["project_jdk"] != "/www/server/java/jdk-21/bin/java" { + t.Fatalf("project_jdk = %#v", createData["project_jdk"]) + } + if createData["project_jar"] != "/www/wwwroot/seavHost/vHost/sv0123456789/public/app.jar" || createData["bind_extranet"] != float64(0) { + t.Fatalf("Java project data = %#v", createData) + } + if err := client.ConfigureRuntime(context.Background(), RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Java", Version: "jdk-21.0.2", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public", EntryFile: "app.jar", Domain: "sv0123456789.hosts.example.com", RunUser: "www", Port: 20020, Runner: true}); err != nil { + t.Fatal(err) + } + if createData["project_cmd"] != "/usr/local/libexec/sea-vhost-run sv0123456789 --java /www/server/java/jdk-21/bin/java /www/wwwroot/seavHost/vHost/sv0123456789/public/app.jar" { + t.Fatal("Java launcher must carry verified native-module paths") + } + +} + +func TestConfigureLanguageRuntimeContracts(t *testing.T) { + created := make(map[string]url.Values) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + t.Fatal(err) + } + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/project/nodejs/get_nodejs_version/stype": + _ = json.NewEncoder(w).Encode([]string{"v24.21.0"}) + case "/plugin": + if r.FormValue("name") == "pythonmamager" && r.FormValue("s") == "GetPythonV" { + _ = json.NewEncoder(w).Encode([]string{"3.12.0"}) + return + } + http.NotFound(w, r) + case "/project/go/list_go_sdk/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}}) + case "/mod/python/environment/add_environment/stype": + if r.FormValue("add_type") != "system" || r.FormValue("path") != "/www/server/python_manager/versions/3.12.0/bin/python3.12" { + t.Fatalf("only root-managed SDKs may be detected: %#v", r.Form) + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + case "/project/nodejs/create_project/stype", "/project/python/CreateProject", "/project/go/create_project/stype": + created[r.URL.Path] = cloneValues(r.Form) + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + case "/project/nodejs/get_project_list/stype", "/project/python/GetProjectList/stype", "/project/go/get_project_list/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"name": r.FormValue("search"), "run": true, "listen_ok": true}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient(server.URL, "test-key", false, 5*time.Second) + base := RuntimeSpec{ProjectName: "sv0123456789", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/apps/api", Domain: "sv0123456789.hosts.example.com", RunUser: "www", Port: 20020, ProcessLimit: 4} + for _, test := range []struct { + runtime, version, entry string + }{ + {"Node.js", "v24.21.0", "package.json"}, + {"Python", "3.12.0", "app.py"}, + {"Go", "go1.27.1", "app"}, + } { + spec := base + spec.Runtime, spec.Version, spec.EntryFile = test.runtime, test.version, test.entry + if err := client.ConfigureRuntime(context.Background(), spec); err != nil { + t.Fatalf("ConfigureRuntime(%s): %v", test.runtime, err) + } + } + if form := created["/project/nodejs/create_project/stype"]; form.Get("project_cwd") != base.Path+"/apps/api" || form.Get("project_script") != "env PORT=20020 npm run start" || form.Get("bind_extranet") != "0" { + t.Fatalf("Node.js create form = %#v", form) + } + if form := created["/project/python/CreateProject"]; !strings.Contains(form.Get("project_cmd"), "/.sea-runtime/python/sv0123456789-3.12.0/bin/python3 "+base.Path+"/apps/api/app.py") || form.Get("venv_path") != base.Path+"/apps/api/.sea-runtime/python/sv0123456789-3.12.0" || form.Get("python_bin") != "/www/server/python_manager/versions/3.12.0/bin/python3.12" || form.Get("user") != "www" || form.Get("stype") != "command" { + t.Fatalf("Python create form = %#v", form) + } + if form := created["/project/go/create_project/stype"]; form.Get("project_exe") != base.Path+"/apps/api/app" || form.Get("project_cmd") != base.Path+"/apps/api/app" { + t.Fatalf("Go create form = %#v", form) + } +} + +func TestPythonEnvironmentRegistrationRejectsTenantInterpreters(t *testing.T) { + const endpoint = "/mod/python/environment/add_environment/stype" + for _, input := range []url.Values{ + {"add_type": {"venv"}, "path": {"/www/server/python_manager/versions/3.12.15/bin/python3.12"}}, + {"add_type": {"system"}, "path": {"/www/wwwroot/seavHost/vHost/sv0123456789/.sea-runtime/bin/python3.12"}}, + {"add_type": {"system"}, "path": {"/www/server/python_manager/versions/../../../wwwroot/app/bin/python3.12"}}, + } { + if err := validateFreePanelRequest(http.MethodPost, endpoint, input); err == nil { + t.Fatalf("untrusted interpreter registration accepted: %#v", input) + } + } +} + +func TestConfigureRuntimeDoesNotReportStoppedProcessAsSuccess(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/project/go/list_go_sdk/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}}) + case "/project/go/create_project/stype", "/project/go/remove_project/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + case "/project/go/get_project_list/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"name": "sv0123456789", "run": false}}}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + err := client.ConfigureRuntime(ctx, RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Go", Version: "go1.27.1", Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/", EntryFile: "app", RunUser: "www", Port: 20020, ProcessLimit: 2}) + if err == nil { + t.Fatal("stopped Go process was reported as successfully deployed") + } +} + +func TestConfigureRuntimeRemovesExactPartialProjectAfterCreateError(t *testing.T) { + removed := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/project/nodejs/get_nodejs_version/stype": + _ = json.NewEncoder(w).Encode([]string{"v24.21.0"}) + case "/project/nodejs/create_project/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": false, "msg": "PID file was not created"}) + case "/project/nodejs/get_project_list/stype": + _ = r.ParseForm() + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{ + "name": r.FormValue("search"), "path": "/www/wwwroot/seavHost/vHost/sv0123456789/public", "port": 20020, + }}}) + case "/project/nodejs/remove_project/stype": + removed = true + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, time.Second) + err := client.ConfigureRuntime(context.Background(), RuntimeSpec{ + ProjectName: "sv0123456789", Runtime: "Node.js", Version: "v24.21.0", + Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public", + EntryFile: "package.json", RunUser: "sv0123456789", Port: 20020, + }) + if err == nil || !strings.Contains(err.Error(), "PID file") { + t.Fatalf("create error = %v", err) + } + if !removed { + t.Fatal("exact partial Node.js project was not removed") + } +} + +func TestConfigureRuntimeRefusesToRemovePartialProjectAtUnexpectedPath(t *testing.T) { + removed := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/project/nodejs/get_nodejs_version/stype": + _ = json.NewEncoder(w).Encode([]string{"v24.21.0"}) + case "/project/nodejs/create_project/stype": + _ = json.NewEncoder(w).Encode(map[string]any{"status": false, "msg": "create failed"}) + case "/project/nodejs/get_project_list/stype": + _ = r.ParseForm() + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{ + "name": r.FormValue("search"), "path": "/www/wwwroot/unmanaged", "port": 20020, + }}}) + case "/project/nodejs/remove_project/stype": + removed = true + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, time.Second) + err := client.ConfigureRuntime(context.Background(), RuntimeSpec{ + ProjectName: "sv0123456789", Runtime: "Node.js", Version: "v24.21.0", + Path: "/www/wwwroot/seavHost/vHost/sv0123456789", RunPath: "/public", + EntryFile: "package.json", RunUser: "sv0123456789", Port: 20020, + }) + if err == nil || !strings.Contains(err.Error(), "untrusted path") { + t.Fatalf("unsafe cleanup error = %v", err) + } + if removed { + t.Fatal("unexpected-path project was removed") + } +} + +func TestWaitRuntimePortStopped(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := listener.Addr().(*net.TCPAddr).Port + spec := RuntimeSpec{Runtime: "Python", Port: port} + if err = waitRuntimePortStopped(context.Background(), spec, 4); err == nil || !strings.Contains(err.Error(), "仍在监听") { + t.Fatalf("listening port error = %v", err) + } + if err = listener.Close(); err != nil { + t.Fatal(err) + } + if err = waitRuntimePortStopped(context.Background(), spec, 4); err != nil { + t.Fatalf("closed port error = %v", err) + } +} + +func TestWaitRuntimePortStoppedRejectsTransientClosure(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + address := listener.Addr().String() + port := listener.Addr().(*net.TCPAddr).Port + if err = listener.Close(); err != nil { + t.Fatal(err) + } + result := make(chan error, 1) + go func() { + result <- waitRuntimePortStopped(context.Background(), RuntimeSpec{Runtime: "Python", Port: port}, 4) + }() + time.Sleep(100 * time.Millisecond) + active, err := net.Listen("tcp", address) + if err != nil { + t.Fatal("cannot reopen transient listener:", err) + } + defer active.Close() + if err = <-result; err == nil || !strings.Contains(err.Error(), "仍在监听") { + t.Fatalf("transient closure error = %v", err) + } +} diff --git a/backend/internal/panel/credential_passwords.go b/backend/internal/panel/credential_passwords.go new file mode 100644 index 0000000..08c43b3 --- /dev/null +++ b/backend/internal/panel/credential_passwords.go @@ -0,0 +1,37 @@ +package panel + +import ( + "context" + "errors" + "net/http" + "net/url" + "regexp" + "strconv" +) + +var managedPasswordPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{20,128}$`) + +func (c *Client) SetFTPPassword(ctx context.Context, id int64, name, password string) error { + if id <= 0 || !brokerHostPattern.MatchString(name) || !managedPasswordPattern.MatchString(password) { + return errors.New("invalid managed credential reset") + } + _, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"SetUserPassword"}, "id": {strconv.FormatInt(id, 10)}, "ftp_username": {name}, "new_password": {password}}) + return err +} +func (c *Client) SetDatabasePassword(ctx context.Context, id int64, name, password string) error { + if id <= 0 || !brokerHostPattern.MatchString(name) || !managedPasswordPattern.MatchString(password) { + return errors.New("invalid managed credential reset") + } + _, err := c.call(ctx, http.MethodPost, "/database", url.Values{"action": {"ResDatabasePassword"}, "id": {strconv.FormatInt(id, 10)}, "name": {name}, "password": {password}}) + return err +} +func (c *BrokerClient) SetFTPPassword(ctx context.Context, id int64, name, password string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "set_ftp_password", ID: id, Username: name, Password: password}) + return err +} +func (c *BrokerClient) SetDatabasePassword(ctx context.Context, id int64, name, password string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "set_database_password", ID: id, Name: name, Password: password}) + return err +} +func (*Mock) SetFTPPassword(context.Context, int64, string, string) error { return nil } +func (*Mock) SetDatabasePassword(context.Context, int64, string, string) error { return nil } diff --git a/backend/internal/panel/credential_passwords_test.go b/backend/internal/panel/credential_passwords_test.go new file mode 100644 index 0000000..af1cba2 --- /dev/null +++ b/backend/internal/panel/credential_passwords_test.go @@ -0,0 +1,72 @@ +package panel + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCredentialResetUsesInstalledPanelArgumentsAndRejectsShellText(t *testing.T) { + calls := 0 + password := strings.Repeat("aB9_", 6) + name := "sv0123456789" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + r.ParseForm() + if r.Method != "POST" || r.FormValue("id") != "17" { + t.Error("wrong reset target") + } + switch r.URL.Path { + case "/ftp": + if r.FormValue("action") != "SetUserPassword" || r.FormValue("ftp_username") != name || r.FormValue("new_password") != password { + t.Error("incorrect FTP API arguments") + } + case "/database": + if r.FormValue("action") != "ResDatabasePassword" || r.FormValue("name") != name || r.FormValue("password") != password { + t.Error("incorrect database API arguments") + } + default: + t.Error("unexpected panel path") + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":true}`)) + })) + defer server.Close() + c := &Client{baseURL: server.URL, apiKey: "test", http: server.Client()} + ctx := context.Background() + if err := c.SetFTPPassword(ctx, 17, name, password); err != nil { + t.Fatal(err) + } + if err := c.SetDatabasePassword(ctx, 17, name, password); err != nil { + t.Fatal(err) + } + for _, bad := range []string{"short", strings.Repeat("a", 20) + "\nEOF\nid", strings.Repeat("a", 20) + "$(id)"} { + if c.SetFTPPassword(ctx, 17, name, bad) == nil || c.SetDatabasePassword(ctx, 17, name, bad) == nil { + t.Fatal("unsafe password accepted") + } + } + if calls != 2 { + t.Fatal("invalid reset reached native panel") + } +} +func TestBrokerCredentialResetRequiresExactManagedIDAndName(t *testing.T) { + server, err := newBrokerServer(t.TempDir(), t.TempDir(), strings.Repeat("t", 32), func(BrokerCredentials) Interface { return NewMock() }) + if err != nil { + t.Fatal(err) + } + server.direct = NewMock() + server.registry.FTP[17] = "sv0123456789" + server.registry.Databases[18] = "sv0123456789" + for _, request := range []brokerRequest{{Operation: "set_ftp_password", ID: 17, Username: "sv0123456789", Password: strings.Repeat("a", 24)}, {Operation: "set_database_password", ID: 18, Name: "sv0123456789", Password: strings.Repeat("b", 24)}} { + if _, err = server.execute(context.Background(), request); err != nil { + t.Fatal(err) + } + request.ID++ + if _, err = server.execute(context.Background(), request); !errors.Is(err, errOutsideManaged) { + t.Fatal("unmanaged credential reset allowed") + } + } +} diff --git a/backend/internal/panel/go_metadata.go b/backend/internal/panel/go_metadata.go new file mode 100644 index 0000000..0d57d31 --- /dev/null +++ b/backend/internal/panel/go_metadata.go @@ -0,0 +1,53 @@ +package panel + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/url" + "time" +) + +// aaPanel caches Go release lists until force=true is supplied. Refresh that +// metadata at most once a minute; installed SDKs still come from its real ls. +func (c *Client) goSDKInventory(ctx context.Context, refresh bool) ([]byte, error) { + c.goMetadataMu.Lock() + force := refresh && time.Now().After(c.goRefreshAfter) + if force { + c.goRefreshAfter = time.Now().Add(time.Minute) + } + cached, measured := append([]byte(nil), c.goLastGood...), c.goLastGoodAt + c.goMetadataMu.Unlock() + valid := func(body []byte, err error) bool { + var state struct { + Status any `json:"status"` + } + return err == nil && json.Unmarshal(body, &state) == nil && !failed(state.Status) + } + body, err := c.request(ctx, http.MethodPost, "/project/go/list_go_sdk/stype", nil) + good := valid(body, err) + if force && ctx.Err() == nil { + updated, updateErr := c.request(ctx, http.MethodPost, "/project/go/list_go_sdk/stype", url.Values{"force": {"true"}}) + if valid(updated, updateErr) { + body, err, good = updated, nil, true + } + } + if good { + c.goMetadataMu.Lock() + c.goLastGood = append([]byte(nil), body...) + c.goLastGoodAt = time.Now() + c.goMetadataMu.Unlock() + return body, nil + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + if len(cached) > 0 && time.Since(measured) < time.Minute { + return cached, nil + } + if err == nil { + err = errors.New("Go SDK metadata is temporarily unavailable") + } + return nil, err +} diff --git a/backend/internal/panel/go_metadata_test.go b/backend/internal/panel/go_metadata_test.go new file mode 100644 index 0000000..5074715 --- /dev/null +++ b/backend/internal/panel/go_metadata_test.go @@ -0,0 +1,50 @@ +package panel + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestGoReleaseRefreshDoesNotRemainOnPanelCachedPatch(t *testing.T) { + force := 0 + latest := "go1.27.1" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.FormValue("force") == "true" { + force++ + latest = "go1.27.3" + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}, "sdk": map[string]any{"all": []map[string]any{{"version": latest}}}}) + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, time.Second) + for range 2 { + body, err := client.goSDKInventory(context.Background(), true) + if err != nil || !strings.Contains(string(body), "go1.27.3") { + t.Fatalf("stale SDK list: %s %v", body, err) + } + } + if force != 1 { + t.Fatalf("metadata refresh requests: %d", force) + } +} + +func TestGoMetadataRefreshFailurePreservesInstalledInventory(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.FormValue("force") == "true" { + http.Error(w, "cloud unavailable", 502) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true, "installed": []string{"go1.27.1"}}) + })) + defer server.Close() + client := NewClient(server.URL, "test-key", false, time.Second) + body, err := client.goSDKInventory(context.Background(), true) + if err != nil || !strings.Contains(string(body), "go1.27.1") { + t.Fatalf("lost installed SDK inventory: %s %v", body, err) + } +} diff --git a/backend/internal/panel/mock.go b/backend/internal/panel/mock.go new file mode 100644 index 0000000..d24f0cd --- /dev/null +++ b/backend/internal/panel/mock.go @@ -0,0 +1,85 @@ +package panel + +import ( + "context" + "sync" +) + +type Mock struct { + mu sync.Mutex + next int64 +} + +func NewMock() *Mock { return &Mock{next: 1000} } +func (m *Mock) id() int64 { m.mu.Lock(); defer m.mu.Unlock(); m.next++; return m.next } +func (*Mock) Ping(context.Context) error { return nil } +func (*Mock) RuntimeCapabilities(context.Context) (RuntimeCapabilities, error) { + versions := RuntimeCatalog{ + "PHP": {"8.4", "8.2", "8.1"}, + "Node.js": {"v22.23.3", "v20.19.5"}, + "Python": {"3.12.3", "3.11.9"}, + "Go": {"go1.25.4", "go1.24.10"}, + "Java": {"jdk-21.0.2", "jdk-17.0.12"}, + } + capabilities := make(RuntimeCapabilities, len(versions)) + for runtime, items := range versions { + policy := PolicyFreeProject + if runtime == "PHP" { + policy = PolicyFreeCore + } + capabilities[runtime] = RuntimeCapability{Status: RuntimeAvailable, Versions: items, Policy: policy} + } + return capabilities, nil +} +func (m *Mock) RuntimeCatalog(ctx context.Context) (RuntimeCatalog, error) { + capabilities, err := m.RuntimeCapabilities(ctx) + if err != nil { + return nil, err + } + catalog := make(RuntimeCatalog, len(capabilities)) + for runtime, capability := range capabilities { + catalog[runtime] = capability.Versions + } + return catalog, nil +} +func (*Mock) RuntimeEnvironments(context.Context) ([]RuntimeEnvironment, error) { + return []RuntimeEnvironment{ + {Name: "PHP", ComponentTitle: "PHP 运行环境", ComponentStatus: RuntimeComponentReady, Installed: []string{"8.4", "8.2"}, Available: []string{}, Installing: []string{}}, + {Name: "Node.js", ComponentTitle: "Node.js 版本管理器", ComponentStatus: RuntimeComponentReady, Installed: []string{"v22.23.3"}, Available: []string{"v24.12.0", "v22.23.3"}, Installing: []string{}, Recommended: "v24.12.0"}, + {Name: "Python", ComponentTitle: "Python 项目管理器", ComponentStatus: RuntimeComponentReady, Installed: []string{"3.12.3"}, Available: []string{"3.13.1", "3.12.3"}, Installing: []string{}, Recommended: "3.13.1"}, + {Name: "Go", ComponentTitle: "Go 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{"go1.25.4"}, Available: []string{"go1.26.1", "go1.25.4"}, Installing: []string{}, Recommended: "go1.26.1"}, + {Name: "Java", ComponentTitle: "Java 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{"jdk-21.0.2"}, Available: []string{"jdk-25.0.1", "jdk-21.0.2"}, Installing: []string{}, Recommended: "jdk-25.0.1"}, + }, nil +} +func (*Mock) InstallRuntimeComponent(context.Context, string) error { return nil } +func (*Mock) InstallRuntimeEnvironment(context.Context, string, string) error { return nil } +func (m *Mock) CreateSite(context.Context, SiteSpec) (int64, error) { return m.id(), nil } +func (*Mock) ListUnmanagedSites(context.Context) ([]ExistingSite, error) { + return []ExistingSite{}, nil +} +func (*Mock) AdoptSite(context.Context, int64, string, SiteSpec) error { return nil } +func (*Mock) RollbackAdoption(context.Context, int64, string, string) error { return nil } +func (*Mock) SetSitePath(context.Context, int64, string) error { return nil } +func (m *Mock) SetSiteRunPath(context.Context, int64, string) error { return nil } +func (m *Mock) MigrateRuntimeIdentity(context.Context, int64, string, bool) error { return nil } +func (*Mock) DeleteSite(context.Context, int64, string) error { return nil } +func (*Mock) AddDomain(context.Context, int64, string, string) error { return nil } +func (*Mock) DeleteDomain(context.Context, int64, string, string) error { return nil } +func (m *Mock) CreateFTP(context.Context, string, string, string, int64) (int64, error) { + return m.id(), nil +} +func (*Mock) DeleteFTP(context.Context, int64, string) error { return nil } +func (*Mock) SetFTPState(context.Context, int64, string, bool) error { return nil } +func (m *Mock) CreateDatabase(context.Context, string, string, string, int64) (int64, error) { + return m.id(), nil +} +func (*Mock) DeleteDatabase(context.Context, int64, string) error { return nil } +func (*Mock) DatabaseSize(context.Context, int64, string) (uint64, error) { return 0, nil } +func (*Mock) ConfigureRuntime(context.Context, RuntimeSpec) error { return nil } +func (*Mock) RemoveRuntime(context.Context, RuntimeSpec) error { return nil } +func (*Mock) SetRuntimeState(context.Context, RuntimeSpec, bool) error { return nil } +func (*Mock) ConfigureProxy(context.Context, int64, string, int) error { return nil } +func (*Mock) RequestCertificate(context.Context, int64, string, []string) error { return nil } +func (*Mock) InstallCertificate(context.Context, int64, string, string, string) error { return nil } +func (*Mock) DisableCertificate(context.Context, int64, string) error { return nil } +func (*Mock) SetSiteState(context.Context, int64, string, bool) error { return nil } diff --git a/backend/internal/panel/panel.go b/backend/internal/panel/panel.go new file mode 100644 index 0000000..d52834c --- /dev/null +++ b/backend/internal/panel/panel.go @@ -0,0 +1,134 @@ +package panel + +import "context" + +type SiteSpec struct { + Name, Domain, Path, RunPath, Runtime, Version, RunUser string + Port, ProcessLimit int +} + +type ExistingSite struct { + ID int64 `json:"id"` + Domain string `json:"domain"` + Path string `json:"path"` + PHPVersion string `json:"phpVersion,omitempty"` + Status string `json:"status"` +} + +type RuntimeSpec struct { + Runner bool + ProjectName, Runtime, Version, Path, RunPath, EntryFile, Domain string + RunUser string + Port, ProcessLimit int +} + +// RuntimeCatalog uses the public runtime names accepted by project creation as +// keys. Values are the exact version identifiers returned by aaPanel. +type RuntimeCatalog map[string][]string + +const ( + RuntimeAvailable = "available" + RuntimeNotInstalled = "not_installed" + RuntimeProbeFailed = "probe_failed" + PolicyFreeCore = "free_core" + PolicyFreeProject = "free_project" +) + +// RuntimeCapability records each language independently. A missing or broken +// optional project route must not prevent Sea vHost itself from being installed. +type RuntimeCapability struct { + Status string `json:"status"` + Versions []string `json:"versions"` + Policy string `json:"policy"` + Detail string `json:"detail,omitempty"` +} + +type RuntimeCapabilities map[string]RuntimeCapability + +const ( + RuntimeComponentReady = "installed" + RuntimeComponentMissing = "not_installed" + RuntimeComponentFailed = "probe_failed" +) + +// RuntimeEnvironment is the administrator-facing installation inventory. The +// install endpoints only accept versions present in Available; callers cannot +// pass package names, URLs, shell fragments, or arbitrary panel operations. +type RuntimeEnvironment struct { + Name string `json:"name"` + ComponentTitle string `json:"componentTitle"` + ComponentStatus string `json:"componentStatus"` + ComponentVersion string `json:"componentVersion,omitempty"` + ComponentLatestVersion string `json:"componentLatestVersion,omitempty"` + ComponentUpdateAvailable bool `json:"componentUpdateAvailable"` + ComponentInstallable bool `json:"componentInstallable"` + Installed []string `json:"installed"` + Available []string `json:"available"` + Installing []string `json:"installing"` + Recommended string `json:"recommended,omitempty"` + Detail string `json:"detail,omitempty"` + Patches []RuntimePatch `json:"patches,omitempty"` +} + +type RuntimePatch struct { + Branch string `json:"branch"` + Installed string `json:"installed"` + Latest string `json:"latest"` + UpdateAvailable bool `json:"updateAvailable"` +} + +// RuntimeMaintenance exposes only fixed PHP updates and existing managed +// runtime records. It is not a generic panel API proxy. +type ManagedCertificateIssuer interface { + IssueManagedCertificate(context.Context, int64, string, []string) (string, error) + ClearManagedCertificateOrder(context.Context, string) error +} + +type RuntimeResetter interface { + ResetManagedRuntime(context.Context, int64, string) error +} + +type RuntimeMaintenance interface { + UpdatePHPRuntime(context.Context, string, string) error + PHPRuntimeUpdatePending(context.Context, string) (bool, error) + ManagedRuntime(context.Context, int64) (RuntimeSpec, error) + ReplaceManagedRuntime(context.Context, int64, RuntimeSpec) error +} + +type Interface interface { + Ping(context.Context) error + RuntimeCapabilities(context.Context) (RuntimeCapabilities, error) + RuntimeCatalog(context.Context) (RuntimeCatalog, error) + RuntimeEnvironments(context.Context) ([]RuntimeEnvironment, error) + InstallRuntimeComponent(context.Context, string) error + InstallRuntimeEnvironment(context.Context, string, string) error + CreateSite(context.Context, SiteSpec) (int64, error) + ListUnmanagedSites(context.Context) ([]ExistingSite, error) + AdoptSite(context.Context, int64, string, SiteSpec) error + RollbackAdoption(context.Context, int64, string, string) error + SetSitePath(context.Context, int64, string) error + DeleteSite(context.Context, int64, string) error + AddDomain(context.Context, int64, string, string) error + DeleteDomain(context.Context, int64, string, string) error + CreateFTP(context.Context, string, string, string, int64) (int64, error) + DeleteFTP(context.Context, int64, string) error + SetFTPState(context.Context, int64, string, bool) error + CreateDatabase(context.Context, string, string, string, int64) (int64, error) + DeleteDatabase(context.Context, int64, string) error + DatabaseSize(context.Context, int64, string) (uint64, error) + ConfigureRuntime(context.Context, RuntimeSpec) error + RemoveRuntime(context.Context, RuntimeSpec) error + SetRuntimeState(context.Context, RuntimeSpec, bool) error + ConfigureProxy(context.Context, int64, string, int) error + RequestCertificate(context.Context, int64, string, []string) error + InstallCertificate(context.Context, int64, string, string, string) error + DisableCertificate(context.Context, int64, string) error + SetSiteState(context.Context, int64, string, bool) error + SetSiteRunPath(context.Context, int64, string) error + MigrateRuntimeIdentity(context.Context, int64, string, bool) error +} + +type CredentialManager interface { + SetFTPPassword(context.Context, int64, string, string) error + SetDatabasePassword(context.Context, int64, string, string) error +} diff --git a/backend/internal/panel/runtime_updates.go b/backend/internal/panel/runtime_updates.go new file mode 100644 index 0000000..4668595 --- /dev/null +++ b/backend/internal/panel/runtime_updates.go @@ -0,0 +1,171 @@ +package panel + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" + "sync" +) + +var phpSoftwarePattern = regexp.MustCompile(`^php-[5-9]\.[0-9]$`) +var phpPatchNumberPattern = regexp.MustCompile(`^[0-9]{1,4}$`) +var phpPatchVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]\.[0-9]+$`) + +func (c *Client) phpRuntimePatches(ctx context.Context, branches []string) []RuntimePatch { + results := make([]*RuntimePatch, len(branches)) + var wg sync.WaitGroup + for index, branch := range branches { + if !phpSoftwarePattern.MatchString("php-" + branch) { + continue + } + wg.Go(func() { + plugin, err := c.runtimePlugin(ctx, "php-"+branch, "PHP") + if err != nil { + return + } + for _, release := range plugin.Versions { + latest := release.MVersion + "." + release.Version + if release.MVersion != branch || release.Beta != 0 || !phpPatchVersionPattern.MatchString(latest) { + continue + } + results[index] = &RuntimePatch{Branch: branch, Installed: plugin.MinVersion, Latest: latest, UpdateAvailable: plugin.MinVersion != "" && newerRuntimeVersion(latest, plugin.MinVersion)} + break + } + }) + } + wg.Wait() + items := make([]RuntimePatch, 0, len(branches)) + for _, item := range results { + if item != nil { + items = append(items, *item) + } + } + return items +} + +func newerRuntimeVersion(candidate, installed string) bool { + return candidate != installed && sortDottedVersionsDescending([]string{candidate, installed})[0] == candidate +} + +func (c *Client) UpdatePHPRuntime(ctx context.Context, branch, target string) error { + if !phpSoftwarePattern.MatchString("php-" + branch) { + return errors.New("invalid PHP branch") + } + patches := c.phpRuntimePatches(ctx, []string{branch}) + if len(patches) != 1 || !patches[0].UpdateAvailable || patches[0].Latest != target { + return errors.New("PHP target is not the advertised stable patch") + } + _, err := c.call(ctx, http.MethodPost, "/plugin", url.Values{"action": {"install_plugin"}, "sName": {"php-" + branch}, "version": {branch}, "min_version": {strings.TrimPrefix(target, branch+".")}, "type": {"0"}, "upgrade": {"1"}}) + return err +} + +func (c *Client) PHPRuntimeUpdatePending(ctx context.Context, branch string) (bool, error) { + if !phpSoftwarePattern.MatchString("php-" + branch) { + return false, errors.New("invalid PHP branch") + } + name := "upgrade[php-" + branch + "]" + // aaPanel searches tasks by status OR type, not by name. Fetch only + // execution tasks, then match the exact managed PHP branch locally. + body, err := c.request(ctx, http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"tasks"}, "limit": {"1000"}, "p": {"1"}, "search": {"execshell"}}) + if err != nil { + return false, err + } + var response struct { + Data []struct { + Name string `json:"name"` + Status any `json:"status"` + } `json:"data"` + } + if json.Unmarshal(body, &response) != nil || response.Data == nil { + return false, errors.New("cannot verify PHP update queue") + } + if len(response.Data) >= 1000 { + return false, errors.New("PHP update queue exceeded verification limit") + } + for _, task := range response.Data { + status := fmt.Sprint(task.Status) + if task.Name == name && (status == "0" || status == "-1") { + return true, nil + } + } + return false, nil +} + +func (c *Client) ManagedRuntime(context.Context, int64) (RuntimeSpec, error) { + return RuntimeSpec{}, errors.New("managed runtime records require the panel broker") +} +func (c *Client) ReplaceManagedRuntime(context.Context, int64, RuntimeSpec) error { + return errors.New("runtime replacement requires the panel broker") +} + +func (c *BrokerClient) UpdatePHPRuntime(ctx context.Context, branch, target string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "update_php_runtime", Name: branch, Version: target}) + return err +} +func (c *BrokerClient) PHPRuntimeUpdatePending(ctx context.Context, branch string) (bool, error) { + r, err := c.operation(ctx, brokerRequest{Operation: "php_update_pending", Name: branch}) + return r.Pending, err +} +func (c *BrokerClient) ManagedRuntime(ctx context.Context, id int64) (RuntimeSpec, error) { + r, err := c.operation(ctx, brokerRequest{Operation: "managed_runtime", SiteID: id}) + if err != nil { + return RuntimeSpec{}, err + } + if r.Runtime == nil { + return RuntimeSpec{}, errors.New("site has no deployed language project") + } + return *r.Runtime, nil +} +func (c *BrokerClient) ReplaceManagedRuntime(ctx context.Context, id int64, spec RuntimeSpec) error { + _, err := c.operation(ctx, brokerRequest{Operation: "replace_runtime", SiteID: id, Runtime: &spec}) + return err +} + +func (c *BrokerClient) ResetManagedRuntime(ctx context.Context, id int64, name string) error { + _, err := c.operation(ctx, brokerRequest{Operation: "reset_managed_runtime", SiteID: id, Name: name}) + return err +} +func (c *Client) ResetManagedRuntime(context.Context, int64, string) error { + return errors.New("runtime reset requires the panel broker") +} +func (c *Client) RemoveManagedProxy(ctx context.Context, domain string) error { + exists := func() (bool, error) { + raw, err := c.request(ctx, http.MethodPost, "/site", url.Values{"action": {"GetProxyList"}, "sitename": {domain}}) + if err != nil { + return false, err + } + var rows []struct { + Site string `json:"sitename"` + Name string `json:"proxyname"` + } + if json.Unmarshal(raw, &rows) != nil { + return false, errors.New("cannot verify managed proxy records") + } + for _, row := range rows { + if row.Site == domain && row.Name == "sea-vhost-runtime" { + return true, nil + } + } + return false, nil + } + found, err := exists() + if err != nil || !found { + return err + } + if _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"RemoveProxy"}, "sitename": {domain}, "proxyname": {"sea-vhost-runtime"}}); err != nil { + return err + } + found, err = exists() + if err != nil { + return err + } + if found { + return errors.New("panel did not remove the managed proxy") + } + return nil +} diff --git a/backend/internal/panel/runtime_updates_test.go b/backend/internal/panel/runtime_updates_test.go new file mode 100644 index 0000000..4617d1a --- /dev/null +++ b/backend/internal/panel/runtime_updates_test.go @@ -0,0 +1,294 @@ +package panel + +import ( + "context" + "encoding/json" + "errors" + "net" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +func TestPHPPatchUpdateUsesOnlyAdvertisedFreeBranch(t *testing.T) { + submitted := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.FormValue("action") { + case "get_soft_find": + _ = json.NewEncoder(w).Encode(map[string]any{"name": "php-8.4", "price": 0, "panel_free": 1, "setup": true, "version": "8.4.25", "versions": []map[string]any{{"m_version": "8.4", "version": "27", "beta": 0}}}) + case "install_plugin": + submitted++ + if r.FormValue("sName") != "php-8.4" || r.FormValue("version") != "8.4" || r.FormValue("min_version") != "27" || r.FormValue("upgrade") != "1" { + t.Error("PHP update parameters escaped the selected branch") + } + _ = json.NewEncoder(w).Encode(map[string]any{"status": true}) + default: + t.Errorf("unexpected request %s", r.FormValue("action")) + } + })) + defer server.Close() + client := NewClient(server.URL, "test", false, 5*time.Second) + if err := client.UpdatePHPRuntime(context.Background(), "8.4", "8.5.0"); err == nil { + t.Fatal("cross-branch patch target accepted") + } + if submitted != 0 { + t.Fatal("invalid target mutated panel") + } + if err := client.UpdatePHPRuntime(context.Background(), "8.4", "8.4.27"); err != nil { + t.Fatal(err) + } + if submitted != 1 { + t.Fatalf("submitted %d updates", submitted) + } + for _, values := range []url.Values{ + {"action": {"install_plugin"}, "sName": {"php-8.4"}, "version": {"8.5"}, "min_version": {"27"}, "type": {"0"}, "upgrade": {"1"}}, + {"action": {"install_plugin"}, "sName": {"php-8.4"}, "version": {"8.4"}, "min_version": {"27;id"}, "type": {"0"}, "upgrade": {"1"}}, + {"action": {"getData"}, "table": {"tasks"}, "search": {""}}, + } { + route := "/plugin" + if values.Get("table") != "" { + route = "/data" + } + if validateFreePanelRequest("POST", route, values) == nil { + t.Fatal("invalid maintenance operation passed allowlist") + } + } +} + +func TestPHPQueueUsesTaskTypeAndExactBranch(t *testing.T) { + for _, test := range []struct { + tasks string + pending bool + }{ + {`[{"name":"upgrade[php-8.4]","status":"0"}]`, true}, + {`[{"name":"upgrade[php-8.4]","status":-1}]`, true}, + {`[{"name":"upgrade[php-8.5]","status":"0"},{"name":"upgrade[php-8.4]","status":"1"}]`, false}, + {`[]`, false}, + } { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.FormValue("search") != "execshell" || r.FormValue("table") != "tasks" { + t.Error("aaPanel task search must use type rather than name") + } + _, _ = w.Write([]byte(`{"data":` + test.tasks + `}`)) + })) + client := NewClient(server.URL, "test", false, time.Second) + pending, err := client.PHPRuntimeUpdatePending(context.Background(), "8.4") + server.Close() + if err != nil || pending != test.pending { + t.Fatalf("queue result=%v err=%v", pending, err) + } + } +} + +type runtimeReplacementPanel struct { + Interface + calls []RuntimeSpec + failVersion string +} + +func (p *runtimeReplacementPanel) RuntimeEnvironments(context.Context) ([]RuntimeEnvironment, error) { + return []RuntimeEnvironment{{Name: "Python", Installed: []string{"3.12.0", "3.12.15"}}}, nil +} +func (p *runtimeReplacementPanel) ConfigureRuntime(_ context.Context, s RuntimeSpec) error { + p.calls = append(p.calls, s) + if s.Version == p.failVersion { + return errors.New("injected launch failure") + } + return nil +} +func TestBrokerRuntimeReplacementRollsBackAndRejectsPathChanges(t *testing.T) { + direct := &runtimeReplacementPanel{Interface: NewMock(), failVersion: "3.12.15"} + server, err := newBrokerServer(t.TempDir(), t.TempDir(), "01234567890123456789012345678901", func(BrokerCredentials) Interface { return direct }) + if err != nil { + t.Fatal(err) + } + server.direct = direct + old := RuntimeSpec{ProjectName: "sv0123456789", Runtime: "Python", Version: "3.12.0", Path: filepath.Join(server.tenantRoot, "sv0123456789"), RunPath: "/", RunUser: "sv0123456789", Port: 20501, ProcessLimit: 10} + server.registry.Sites[1] = &managedSite{Runtime: &old} + next := old + next.Version = "3.12.15" + next.Path = "/etc" + if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &next}); err == nil { + t.Fatal("unmanaged path accepted") + } + if len(direct.calls) != 0 { + t.Fatal("invalid runtime triggered mutation") + } + next.Path = old.Path + if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &next}); err == nil { + t.Fatal("injected migration failure hidden") + } + if !reflect.DeepEqual(direct.calls, []RuntimeSpec{next, old}) { + t.Fatalf("rollback calls=%#v", direct.calls) + } + if *server.registry.Sites[1].Runtime != old { + t.Fatal("registry lost original runtime") + } + direct.failVersion = "" + if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &next}); err != nil { + t.Fatal(err) + } + if *server.registry.Sites[1].Runtime != next { + t.Fatal("registry did not commit target runtime") + } + // The old patch is still installed and must remain available for rollback. + if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &old}); err != nil { + t.Fatal(err) + } + before := len(direct.calls) + if _, err = server.execute(context.Background(), brokerRequest{Operation: "replace_runtime", SiteID: 1, Runtime: &old}); err != nil || len(direct.calls) != before+1 { + t.Fatal("same registered version must still repair a missing actual project") + } +} + +func TestRuntimeRemovalStopsListenerBeforeDeletingMetadata(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + port := listener.Addr().(*net.TCPAddr).Port + var calls []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/project/python/StopProject/stype": + calls = append(calls, "stop") + _ = listener.Close() + case "/project/python/RemoveProject/stype": + calls = append(calls, "remove") + default: + t.Errorf("unexpected route: %s", r.URL.Path) + } + _, _ = w.Write([]byte(`{"status":true}`)) + })) + defer server.Close() + client := NewClient(server.URL, "test", false, time.Second) + if err = client.RemoveRuntime(context.Background(), RuntimeSpec{Runtime: "Python", ProjectName: "sv0123456789", Port: port}); err != nil { + t.Fatal(err) + } + if strings.Join(calls, ",") != "stop,remove" { + t.Fatalf("runtime deletion order = %v", calls) + } +} + +func TestRuntimeRemovalPreservesMetadataWhenStopDoesNotCloseListener(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + port := listener.Addr().(*net.TCPAddr).Port + removed := false + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/project/python/RemoveProject/stype" { + removed = true + } + _, _ = w.Write([]byte(`{"status":true}`)) + })) + defer server.Close() + client := NewClient(server.URL, "test", false, time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond) + defer cancel() + if err = client.RemoveRuntime(ctx, RuntimeSpec{Runtime: "Python", ProjectName: "sv0123456789", Port: port}); err == nil { + t.Fatal("runtime with a residual listener was removed") + } + if removed { + t.Fatal("project metadata was deleted before its listener stopped") + } +} + +func TestRuntimeRemovalRetryRequiresAbsentRecordAndClosedPort(t *testing.T) { + for _, test := range []struct { + name string + present, listening, invalid bool + wantErr bool + }{ + {"absent", false, false, false, false}, {"residual listener", false, true, false, true}, {"record remains", true, false, false, true}, {"unverifiable", false, false, true, true}, + } { + t.Run(test.name, func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := listener.Addr().(*net.TCPAddr).Port + if !test.listening { + _ = listener.Close() + } else { + defer listener.Close() + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/project/python/RemoveProject/stype" { + _, _ = w.Write([]byte(`{"status":false,"msg":"missing project"}`)) + return + } + if test.invalid { + _, _ = w.Write([]byte(`{"status":false}`)) + return + } + items := []map[string]any{} + if test.present { + items = append(items, map[string]any{"name": "sv0123456789"}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"data": items}) + })) + defer server.Close() + client := NewClient(server.URL, "test", false, time.Second) + err = client.RemoveRuntime(context.Background(), RuntimeSpec{Runtime: "Python", ProjectName: "sv0123456789", Port: port}) + if (err != nil) != test.wantErr { + t.Fatalf("removal error=%v", err) + } + }) + } +} + +type runtimeResetTestPanel struct { + Interface + proxies []string + removed int +} + +func (p *runtimeResetTestPanel) RemoveManagedProxy(_ context.Context, name string) error { + p.proxies = append(p.proxies, name) + return nil +} +func (p *runtimeResetTestPanel) RemoveRuntime(context.Context, RuntimeSpec) error { + p.removed++ + return nil +} +func TestRuntimeResetOnlyTouchesManagedSiteAndFixedProxy(t *testing.T) { + direct := &runtimeResetTestPanel{Interface: NewMock()} + server, e := newBrokerServer(t.TempDir(), t.TempDir(), "01234567890123456789012345678901", func(BrokerCredentials) Interface { return direct }) + if e != nil { + t.Fatal(e) + } + server.direct = direct + old := RuntimeSpec{Runtime: "Node.js", ProjectName: "sv0123456789", Port: 20050} + server.registry.Sites[3] = &managedSite{Domain: "host.example.com", Runtime: &old, Port: 20050, ProxyReady: true} + for _, req := range []brokerRequest{{Operation: "reset_managed_runtime", SiteID: 9, Name: "host.example.com"}, {Operation: "reset_managed_runtime", SiteID: 3, Name: "outside.example.com"}} { + if _, e = server.execute(context.Background(), req); e == nil { + t.Fatal("unmanaged runtime reset accepted") + } + } + if direct.removed != 0 || len(direct.proxies) != 0 { + t.Fatal("unmanaged request mutated panel") + } + if _, e = server.execute(context.Background(), brokerRequest{Operation: "reset_managed_runtime", SiteID: 3, Name: "host.example.com"}); e != nil { + t.Fatal(e) + } + if direct.removed != 1 || !reflect.DeepEqual(direct.proxies, []string{"host.example.com"}) || server.registry.Sites[3].Runtime != nil || server.registry.Sites[3].ProxyReady { + t.Fatal("managed reset incomplete") + } + if _, e = server.execute(context.Background(), brokerRequest{Operation: "reset_managed_runtime", SiteID: 3, Name: "host.example.com"}); e != nil { + t.Fatal("reset not idempotent", e) + } + if direct.removed != 1 { + t.Fatal("repeated reset removed another project") + } +} diff --git a/backend/internal/panel/scheduler.go b/backend/internal/panel/scheduler.go new file mode 100644 index 0000000..078e92a --- /dev/null +++ b/backend/internal/panel/scheduler.go @@ -0,0 +1,67 @@ +package panel + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/url" + "sea-vhost/internal/schedulerbridge" + "strconv" + "strings" +) + +type SystemScheduler interface { + EnsureSystemScheduler(context.Context) (int64, error) +} + +func (c *BrokerClient) EnsureSystemScheduler(ctx context.Context) (int64, error) { + v, e := c.operation(ctx, brokerRequest{Operation: "ensure_scheduler"}) + return v.ID, e +} +func (Mock) EnsureSystemScheduler(context.Context) (int64, error) { return 1, nil } +func (c *Client) EnsureSystemScheduler(ctx context.Context) (int64, error) { + raw, e := c.request(ctx, http.MethodPost, "/crontab", url.Values{"action": {"GetCrontab"}, "search": {schedulerbridge.CronName}}) + if e != nil { + return 0, e + } + type task struct { + ID int64 `json:"id"` + Name string `json:"name"` + Body string `json:"sBody"` + Status int `json:"status"` + Type string `json:"type"` + Where1 json.RawMessage `json:"where1"` + } + var rows []task + if json.Unmarshal(raw, &rows) != nil { + var envelope struct { + Data []task `json:"data"` + } + if json.Unmarshal(raw, &envelope) != nil || envelope.Data == nil { + return 0, errors.New("无法读取宝塔计划任务") + } + rows = envelope.Data + } + for _, v := range rows { + if v.Name == schedulerbridge.CronName { + if v.Body != schedulerbridge.Command || v.Type != "minute-n" || strings.Trim(string(v.Where1), `"`) != "1" { + return 0, errors.New("同名计划任务配置不同,请在宝塔检查") + } + if v.Status != 1 { + if _, e = c.call(ctx, http.MethodPost, "/crontab", url.Values{"action": {"set_cron_status"}, "id": {strconv.FormatInt(v.ID, 10)}}); e != nil { + return 0, e + } + } + return v.ID, nil + } + } + v, e := c.call(ctx, http.MethodPost, "/crontab", url.Values{"action": {"AddCrontab"}, "name": {schedulerbridge.CronName}, "type": {"minute-n"}, "where1": {"1"}, "where_hour": {"0"}, "where_minute": {"0"}, "user": {"root"}, "urladdress": {"http://"}, "save_local": {"0"}, "notice": {"0"}, "notice_channel": {""}, "sType": {"toShell"}, "sBody": {schedulerbridge.Command}, "sName": {schedulerbridge.CronName}, "save": {"0"}, "backupTo": {"localhost"}}) + if e != nil { + return 0, e + } + if v.ID < 1 { + return 0, errors.New("宝塔未返回计划任务编号") + } + return v.ID, nil +} diff --git a/backend/internal/panel/scheduler_test.go b/backend/internal/panel/scheduler_test.go new file mode 100644 index 0000000..aa975f5 --- /dev/null +++ b/backend/internal/panel/scheduler_test.go @@ -0,0 +1,57 @@ +package panel + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "sea-vhost/internal/schedulerbridge" + "testing" + "time" +) + +func TestSystemSchedulerUsesOnlyFixedFreePanelTask(t *testing.T) { + created := false + mutations := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.FormValue("action") { + case "GetCrontab": + if r.FormValue("search") != schedulerbridge.CronName { + t.Error("unbounded cron lookup") + } + if !created { + fmt.Fprint(w, `[]`) + } else { + json.NewEncoder(w).Encode([]map[string]any{{"id": 123, "name": schedulerbridge.CronName, "sBody": schedulerbridge.Command, "type": "minute-n", "where1": 1, "status": 1}}) + } + case "AddCrontab": + if r.FormValue("sBody") != schedulerbridge.Command || r.FormValue("user") != "root" || r.FormValue("where1") != "1" { + t.Error("non-fixed scheduler mutation") + } + mutations++ + created = true + fmt.Fprint(w, `{"status":true,"id":123}`) + default: + t.Error("unexpected native operation") + } + })) + defer srv.Close() + client := NewClient(srv.URL, "test-key", false, time.Second) + for i := 0; i < 2; i++ { + id, e := client.EnsureSystemScheduler(context.Background()) + if e != nil || id != 123 { + t.Fatalf("scheduler id=%d error=%v", id, e) + } + } + if mutations != 1 { + t.Fatal("duplicate native system crons created") + } + if validateFreePanelRequest("POST", "/crontab", url.Values{"action": {"AddCrontab"}, "name": {schedulerbridge.CronName}, "sBody": {"touch /etc/pwned"}, "type": {"minute-n"}, "where1": {"1"}, "sType": {"toShell"}, "user": {"root"}}) == nil { + t.Fatal("arbitrary root cron accepted") + } + if validateFreePanelRequest("POST", "/crontab", url.Values{"action": {"GetCrontab"}}) == nil { + t.Fatal("unbounded native cron read accepted") + } +} diff --git a/backend/internal/panel/scoped_executor.go b/backend/internal/panel/scoped_executor.go new file mode 100644 index 0000000..4f98b66 --- /dev/null +++ b/backend/internal/panel/scoped_executor.go @@ -0,0 +1,142 @@ +package panel + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "path" + "path/filepath" + "strings" +) + +// ScopedExecution carries the controller's resource snapshot. It is never +// persisted by the node. Native panel state remains authoritative for paths. +type ScopedExecution struct { + Request json.RawMessage `json:"request"` + Registry json.RawMessage `json:"registry"` +} +type ScopedResult struct { + Response json.RawMessage `json:"response"` + Registry json.RawMessage `json:"registry"` +} + +func ExecuteScoped(ctx context.Context, direct Interface, tenantRoot string, in ScopedExecution) (ScopedResult, error) { + var request brokerRequest + decoder := json.NewDecoder(bytes.NewReader(in.Request)) + decoder.DisallowUnknownFields() + if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF { + return ScopedResult{}, errors.New("invalid scoped operation") + } + var registry brokerRegistry + decoder = json.NewDecoder(bytes.NewReader(in.Registry)) + decoder.DisallowUnknownFields() + if decoder.Decode(®istry) != nil || decoder.Decode(&struct{}{}) != io.EOF || registry.Version != 1 || registry.Sites == nil || registry.FTP == nil || registry.Databases == nil { + return ScopedResult{}, errors.New("invalid controller resource snapshot") + } + if !filepath.IsAbs(tenantRoot) || path.Clean(tenantRoot) != tenantRoot || tenantRoot == "/" { + return ScopedResult{}, errors.New("invalid node resource root") + } + server := &BrokerServer{stateless: true, tenantRoot: tenantRoot, direct: direct, registry: registry, runtimeJobs: map[string]bool{}} + for _, site := range registry.Sites { + if site == nil || !brokerHostPattern.MatchString(site.ResourceName) || path.Clean(site.Path) != path.Join(tenantRoot, site.ResourceName) || site.RunUser != site.ResourceName || !validRunPath(site.RunPath) { + return ScopedResult{}, errors.New("snapshot resource is outside the node namespace") + } + } + for _, name := range registry.FTP { + if !brokerHostPattern.MatchString(name) { + return ScopedResult{}, errors.New("invalid scoped FTP identity") + } + } + for _, name := range registry.Databases { + if !brokerHostPattern.MatchString(name) { + return ScopedResult{}, errors.New("invalid scoped database identity") + } + } + if native, ok := direct.(interface { + VerifyScopedResources(context.Context, string, json.RawMessage, json.RawMessage) error + }); ok { + if err := native.VerifyScopedResources(ctx, tenantRoot, in.Request, in.Registry); err != nil { + return ScopedResult{}, err + } + } else if _, ok := direct.(*Client); ok { + return ScopedResult{}, errors.New("native resource verification is unavailable") + } + result, err := server.execute(ctx, request) + if err != nil { + return ScopedResult{}, err + } + response, err := json.Marshal(result) + if err != nil { + return ScopedResult{}, err + } + snapshot, err := json.Marshal(server.registry) + if err != nil { + return ScopedResult{}, err + } + return ScopedResult{Response: response, Registry: snapshot}, nil +} + +// Verify only the resource touched by the operation, using real panel data. +// A forged snapshot must not turn an unrelated panel site into a managed site. +func (c *Client) VerifyScopedResources(ctx context.Context, root string, rawRequest, rawRegistry json.RawMessage) error { + var request brokerRequest + var registry brokerRegistry + if json.Unmarshal(rawRequest, &request) != nil || json.Unmarshal(rawRegistry, ®istry) != nil { + return errors.New("invalid resource proof") + } + if request.Operation=="delete_ftp"||request.Operation=="set_ftp_state" { + name,ok:=registry.FTP[request.ID];if !ok||name!=request.Username{return errOutsideManaged} + id,err:=c.lookupResourceID(ctx,"ftps",name);if err!=nil||id!=request.ID{return errors.New("native FTP identity does not match controller scope")};return nil + } + if request.Operation=="delete_database"||request.Operation=="database_size" { + name,ok:=registry.Databases[request.ID];if !ok||name!=request.Name{return errOutsideManaged} + id,err:=c.lookupResourceID(ctx,"databases",name);if err!=nil||id!=request.ID{return errors.New("native database identity does not match controller scope")};return nil + } + var target *managedSite + var id int64 + if request.SiteID != 0 { + id = request.SiteID + } else if registry.Sites[request.ID] != nil { + id = request.ID + } + if id != 0 { + target = registry.Sites[id] + } + if target == nil && request.Runtime != nil { + for key, site := range registry.Sites { + if site.Path == request.Runtime.Path && site.Domain == request.Runtime.Domain { + target = site + id = key + break + } + } + } + if target == nil || strings.HasPrefix(request.Operation, "create_") || request.Operation == "adopt_site" || request.Operation == "rollback_adoption" { + return nil + } + // FTP/database IDs may equal a site ID. They are checked by their own name + // registry inside the broker; do not accidentally compare unrelated tables. + if strings.Contains(request.Operation, "ftp") || strings.Contains(request.Operation, "database") { + return nil + } + actual, err := c.ListUnmanagedSites(ctx) + if err != nil { + return err + } + for _, site := range actual { + if site.ID == id { + if path.Clean(site.Path) != path.Clean(target.Path) || !strings.HasPrefix(path.Clean(site.Path)+"/", root+"/") || !strings.EqualFold(site.Domain, target.Domain) { + return errors.New("native site does not match controller resource scope") + } + return nil + } + } + // A repeated delete may already have removed the native record. The broker + // still validates the exact registered domain and never deletes by path. + if request.Operation == "delete_site" { + return nil + } + return errors.New("managed native site is missing") +} diff --git a/backend/internal/panel/stateless_server.go b/backend/internal/panel/stateless_server.go new file mode 100644 index 0000000..843e0d8 --- /dev/null +++ b/backend/internal/panel/stateless_server.go @@ -0,0 +1,22 @@ +package panel + +import ( + "encoding/json" + "errors" + "net/http" +) + +// Stateless mode retains only local panel credentials, never a platform +// resource registry. The network gateway cannot reconfigure credentials. +func(s *BrokerServer) EnableStateless()error{ + if s.direct==nil{return errors.New("local panel credentials must be configured before enabling the node broker")} + s.stateless=true;s.registry=brokerRegistry{};return nil +} +func(s *BrokerServer) scopedOperations(w http.ResponseWriter,r *http.Request){ + var input ScopedExecution + if !brokerDecode(w,r,&input){return} + s.mu.Lock();defer s.mu.Unlock() + result,err:=ExecuteScoped(r.Context(),s.direct,s.tenantRoot,input) + if err!=nil{brokerWriteError(w,http.StatusUnprocessableEntity,safeBrokerError("节点面板操作失败",err));return} + w.Header().Set("Content-Type","application/json");_ = json.NewEncoder(w).Encode(result) +} diff --git a/backend/internal/schedulerbridge/bridge.go b/backend/internal/schedulerbridge/bridge.go new file mode 100644 index 0000000..2089cce --- /dev/null +++ b/backend/internal/schedulerbridge/bridge.go @@ -0,0 +1,10 @@ +package schedulerbridge + +import("crypto/hmac";"crypto/sha256";"encoding/hex";"fmt";"net/url";"strings") +const ConfigPath="/etc/sea-vhost/scheduler.json" +const TickPath="/api/v1/system/scheduler/tick" +const Command="exec /opt/sea-vhost/bin/sea-vhost-scheduler tick >/dev/null 2>&1" +const CronName="Sea vHost 系统调度器" +type Config struct{Controller string `json:"controller"`;NodeID uint64 `json:"nodeId"`;Key string `json:"key"`} +func(c Config)Validate()error{u,e:=url.Parse(c.Controller);if e!=nil||u.Scheme!="https"||u.Hostname()==""||u.User!=nil||u.RawQuery!=""||u.Fragment!=""||(u.Path!=""&&u.Path!="/")||strings.ContainsAny(c.Controller,"\r\n\x00")||c.NodeID==0{return fmt.Errorf("invalid controller configuration")};key,e:=hex.DecodeString(c.Key);if e!=nil||len(key)!=32{return fmt.Errorf("invalid trigger identity")};return nil} +func Signature(key,node,stamp,nonce string)string{mac:=hmac.New(sha256.New,[]byte(key));fmt.Fprintf(mac,"POST\n%s\n%s\n%s\n%s",TickPath,node,stamp,nonce);return hex.EncodeToString(mac.Sum(nil))} diff --git a/backend/internal/scope/context.go b/backend/internal/scope/context.go new file mode 100644 index 0000000..b78af22 --- /dev/null +++ b/backend/internal/scope/context.go @@ -0,0 +1,60 @@ +// Package scope carries server-authorized placement, never a browser supplied +// filesystem path or panel identifier. HTTP handlers bind it after ownership +// checks; background work binds it from the persisted resource/job. +package scope + +import "context" + +type key uint8 + +const ( + nodeKey key = iota + projectKey + administratorKey + accountKey + batchItemKey + integrationKey +) + +func WithNode(ctx context.Context, id uint64) context.Context { + return context.WithValue(ctx, nodeKey, id) +} +func Node(ctx context.Context) uint64 { + if id, ok := ctx.Value(nodeKey).(uint64); ok && id > 0 { + return id + } + return 1 +} +func ExplicitNode(ctx context.Context) (uint64, bool) { + id, ok := ctx.Value(nodeKey).(uint64) + return id, ok && id > 0 +} +func WithProject(ctx context.Context, projectID, nodeID uint64) context.Context { + return context.WithValue(WithNode(ctx, nodeID), projectKey, projectID) +} +func Project(ctx context.Context) uint64 { id, _ := ctx.Value(projectKey).(uint64); return id } +func WithAdministrator(ctx context.Context, id uint64) context.Context { + return context.WithValue(ctx, administratorKey, id) +} +func Administrator(ctx context.Context) uint64 { + id, _ := ctx.Value(administratorKey).(uint64) + return id +} + +// Account identifies the authenticated customer account independently from a +// host's immutable internal namespace. Only HTTP authorization binds this value. +func WithAccount(ctx context.Context, id uint64) context.Context { + return context.WithValue(ctx, accountKey, id) +} +func Account(ctx context.Context) uint64 { id, _ := ctx.Value(accountKey).(uint64); return id } +func WithBatchItem(ctx context.Context, id uint64) context.Context { + return context.WithValue(ctx, batchItemKey, id) +} +func BatchItem(ctx context.Context) uint64 { id, _ := ctx.Value(batchItemKey).(uint64); return id } +func WithIntegrationKey(ctx context.Context, id uint64) context.Context { + return context.WithValue(ctx, integrationKey, id) +} +func IntegrationKey(ctx context.Context) uint64 { + id, _ := ctx.Value(integrationKey).(uint64) + return id +} diff --git a/backend/internal/secrets/box.go b/backend/internal/secrets/box.go new file mode 100644 index 0000000..f646efb --- /dev/null +++ b/backend/internal/secrets/box.go @@ -0,0 +1,57 @@ +package secrets + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "errors" + "io" +) + +const formatVersion byte = 1 + +type Box struct{ key [32]byte } + +func New(masterSecret string) *Box { + return &Box{key: sha256.Sum256([]byte("sea-vhost/credential-box/v1\x00" + masterSecret))} +} + +func (b *Box) Seal(label, plaintext string) ([]byte, error) { + block, err := aes.NewCipher(b.key[:]) + if err != nil { + return nil, err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } + result := make([]byte, 1+len(nonce)) + result[0] = formatVersion + copy(result[1:], nonce) + return gcm.Seal(result, nonce, []byte(plaintext), []byte(label)), nil +} + +func (b *Box) Open(label string, ciphertext []byte) (string, error) { + block, err := aes.NewCipher(b.key[:]) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + if len(ciphertext) < 1+gcm.NonceSize()+gcm.Overhead() || ciphertext[0] != formatVersion { + return "", errors.New("invalid credential ciphertext") + } + nonce := ciphertext[1 : 1+gcm.NonceSize()] + plaintext, err := gcm.Open(nil, nonce, ciphertext[1+gcm.NonceSize():], []byte(label)) + if err != nil { + return "", errors.New("credential authentication failed") + } + return string(plaintext), nil +} diff --git a/backend/internal/secrets/box_test.go b/backend/internal/secrets/box_test.go new file mode 100644 index 0000000..3c4f2d9 --- /dev/null +++ b/backend/internal/secrets/box_test.go @@ -0,0 +1,28 @@ +package secrets + +import ( + "bytes" + "testing" +) + +func TestBoxRoundTripAndAuthentication(t *testing.T) { + box := New("a sufficiently long installation secret") + sealed, err := box.Seal("ftp:42", "random-password") + if err != nil { + t.Fatal(err) + } + if bytes.Contains(sealed, []byte("random-password")) { + t.Fatal("ciphertext contains plaintext") + } + opened, err := box.Open("ftp:42", sealed) + if err != nil || opened != "random-password" { + t.Fatalf("Open() = %q, %v", opened, err) + } + if _, err = box.Open("database:42", sealed); err == nil { + t.Fatal("ciphertext was accepted for another resource label") + } + sealed[len(sealed)-1] ^= 1 + if _, err = box.Open("ftp:42", sealed); err == nil { + t.Fatal("tampered ciphertext was accepted") + } +} diff --git a/backend/internal/service/certificates.go b/backend/internal/service/certificates.go new file mode 100644 index 0000000..f5f8fb5 --- /dev/null +++ b/backend/internal/service/certificates.go @@ -0,0 +1,270 @@ +package service + +import ( + "bytes" + "context" + "crypto" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "strings" + "time" + + "sea-vhost/internal/isolation" + "sea-vhost/internal/store" +) + +const ( + maxManualCertificateBytes = 96 << 10 + maxManualPrivateKeyBytes = 32 << 10 +) + +// RequestAutoCertificate enables automatic certificate management and runs a +// complete HTTP-01 issuance cycle. aaPanel's ACME order endpoint does not +// deploy the resulting certificate by itself, so the panel adapter also waits +// for a valid order and explicitly installs it on the managed site. +func (s *Projects) RequestAutoCertificate(ctx context.Context, user store.User, projectID, siteID uint64) (store.Site, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, err + } + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.Site{}, err + } + return s.requestAutoCertificate(ctx, project, site) +} + +func (s *Projects) DisableCertificate(ctx context.Context, user store.User, projectID, siteID uint64) (store.Site, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, err + } + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.Site{}, err + } + if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" { + return store.Site{}, errors.New("网站尚未完成创建,不能关闭证书") + } + if err = s.panel.DisableCertificate(ctx, site.PanelSiteID, site.Domain); err != nil { + return store.Site{}, fmt.Errorf("宝塔关闭证书失败: %w", err) + } + if err = s.store.SetCertificateOff(ctx, project.TenantID, project.ID, site.ID); err != nil { + return store.Site{}, fmt.Errorf("证书已关闭,但保存状态失败: %w", err) + } + return s.store.Site(ctx, project.TenantID, project.ID, site.ID) +} + +func (s *Projects) requestAutoCertificate(ctx context.Context, project store.Project, site store.Site) (store.Site, error) { + if site.Status != "running" { + return store.Site{}, errors.New("请先部署并启动网站,再使用 HTTP-01 申请证书;未运行的网站可使用 DNS-01 或上传证书") + } + if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" { + return store.Site{}, errors.New("网站尚未完成创建,不能申请证书") + } + identity, err := s.phpIdentitySpec(ctx, project, site) + protection := isolation.WebProtectionSpec{Project: identity.Project, Domain: site.Domain} + if err != nil { + return store.Site{}, err + } + if err = s.isolation.ApplyWebProtection(ctx, protection); err != nil { + return store.Site{}, fmt.Errorf("准备 HTTP-01 验证目录失败: %w", err) + } + domains, err := s.siteCertificateDomains(ctx, project, site) + if err != nil { + return store.Site{}, err + } + if err = s.store.SetAutoCertificateStatus(ctx, project.TenantID, project.ID, site.ID, "pending", ""); err != nil { + return store.Site{}, err + } + + // aaPanel keeps ACME orders in a shared panel-level store. Serializing the + // short order/deploy transaction prevents one tenant's operation from being + // interleaved with another tenant's retry. + s.certificateMu.Lock() + err = s.panel.RequestCertificate(ctx, site.PanelSiteID, project.Path, domains) + s.certificateMu.Unlock() + if err != nil { + _ = s.store.SetAutoCertificateStatus(context.WithoutCancel(ctx), project.TenantID, project.ID, site.ID, "failed", err.Error()) + return store.Site{}, fmt.Errorf("宝塔自动证书申请失败: %w", err) + } + if err = s.store.SetAutoCertificateStatus(ctx, project.TenantID, project.ID, site.ID, "active", ""); err != nil { + return store.Site{}, fmt.Errorf("证书已部署,但保存状态失败: %w", err) + } + return s.store.Site(ctx, project.TenantID, project.ID, site.ID) +} + +func (s *Projects) siteCertificateDomains(ctx context.Context, project store.Project, site store.Site) ([]string, error) { + domains := []string{strings.ToLower(strings.TrimSpace(site.Domain))} + resources, err := s.store.ListDomains(ctx, project.TenantID, &project.ID) + if err != nil { + return nil, err + } + seen := map[string]struct{}{domains[0]: {}} + for _, item := range resources { + name := strings.ToLower(strings.TrimSpace(item.Domain)) + if item.SiteID != site.ID || item.Status != "approved" || name == "" { + continue + } + if _, exists := seen[name]; exists { + continue + } + seen[name] = struct{}{} + domains = append(domains, name) + if len(domains) > maxDomainsPerSite { + return nil, fmt.Errorf("网站证书域名数量超过上限(%d)", maxDomainsPerSite) + } + } + return domains, nil +} + +// InstallManualCertificate validates the complete certificate/key pair before +// passing it to the privileged broker. The private key is never persisted by +// Sea vHost or included in an audit message. +func (s *Projects) InstallManualCertificate(ctx context.Context, user store.User, projectID, siteID uint64, certificatePEM, privateKeyPEM string) (store.Site, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, err + } + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.Site{}, err + } + if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" { + return store.Site{}, errors.New("网站尚未完成创建,不能安装证书") + } + + domains, err := s.siteCertificateDomains(ctx, project, site) + if err != nil { + return store.Site{}, err + } + if err = validateManualCertificate(certificatePEM, privateKeyPEM, domains, time.Now()); err != nil { + return store.Site{}, err + } + if err = s.panel.InstallCertificate(ctx, site.PanelSiteID, site.Domain, privateKeyPEM, certificatePEM); err != nil { + return store.Site{}, fmt.Errorf("宝塔安装证书失败: %w", err) + } + leaf, err := manualCertificateLeaf(certificatePEM) + if err != nil { + return store.Site{}, err + } + if err = s.store.SetManualCertificateActive(ctx, project.TenantID, project.ID, site.ID, leaf.NotAfter); err != nil { + return store.Site{}, fmt.Errorf("证书已安装,但保存状态失败: %w", err) + } + return s.store.Site(ctx, project.TenantID, project.ID, site.ID) +} + +func manualCertificateLeaf(certificatePEM string) (*x509.Certificate, error) { + block, _ := pem.Decode([]byte(certificatePEM)) + if block == nil || block.Type != "CERTIFICATE" { + return nil, errors.New("未找到有效的 PEM 证书") + } + certificate, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, errors.New("证书链包含无法解析的证书") + } + return certificate, nil +} + +func validateManualCertificate(certificatePEM, privateKeyPEM string, domains []string, now time.Time) error { + if len(certificatePEM) == 0 || len(certificatePEM) > maxManualCertificateBytes { + return errors.New("证书链不能为空且不得超过 96 KiB") + } + if len(privateKeyPEM) == 0 || len(privateKeyPEM) > maxManualPrivateKeyBytes { + return errors.New("私钥不能为空且不得超过 32 KiB") + } + + certificateData := []byte(certificatePEM) + var leaf *x509.Certificate + certificateCount := 0 + for len(bytes.TrimSpace(certificateData)) > 0 { + block, rest := pem.Decode(certificateData) + if block == nil || block.Type != "CERTIFICATE" { + return errors.New("证书链必须仅包含 PEM CERTIFICATE 块") + } + certificate, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return errors.New("证书链包含无法解析的证书") + } + if leaf == nil { + leaf = certificate + } + certificateCount++ + certificateData = rest + } + if leaf == nil || certificateCount == 0 { + return errors.New("未找到有效的 PEM 证书") + } + if leaf.IsCA { + return errors.New("证书链首张证书不能是 CA 证书") + } + if now.Before(leaf.NotBefore) || !now.Before(leaf.NotAfter) { + return errors.New("网站证书尚未生效或已过期") + } + if len(leaf.ExtKeyUsage) > 0 { + validUsage := false + for _, usage := range leaf.ExtKeyUsage { + if usage == x509.ExtKeyUsageServerAuth || usage == x509.ExtKeyUsageAny { + validUsage = true + break + } + } + if !validUsage { + return errors.New("证书不允许用于 TLS Web 服务器") + } + } + for _, domain := range domains { + if err := leaf.VerifyHostname(domain); err != nil { + return fmt.Errorf("证书不包含已启用域名 %s", domain) + } + } + + keyBlock, keyRest := pem.Decode([]byte(privateKeyPEM)) + if keyBlock == nil || len(bytes.TrimSpace(keyRest)) != 0 { + return errors.New("私钥必须是且只能是一个 PEM 私钥块") + } + if x509.IsEncryptedPEMBlock(keyBlock) || strings.Contains(strings.ToUpper(keyBlock.Type), "ENCRYPTED") { + return errors.New("不支持加密私钥,请上传无口令 PEM 私钥") + } + privateKey, err := parsePrivateKey(keyBlock.Bytes) + if err != nil { + return errors.New("私钥格式无效,仅支持 PKCS#8、PKCS#1 或 EC 私钥") + } + signer, ok := privateKey.(crypto.Signer) + if !ok { + return errors.New("私钥类型不能用于 TLS 签名") + } + certificatePublic, err := x509.MarshalPKIXPublicKey(leaf.PublicKey) + if err != nil { + return errors.New("证书公钥格式无效") + } + privatePublic, err := x509.MarshalPKIXPublicKey(signer.Public()) + if err != nil || !bytes.Equal(certificatePublic, privatePublic) { + return errors.New("证书与私钥不匹配") + } + return nil +} + +func parsePrivateKey(der []byte) (any, error) { + if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { + return key, nil + } + if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { + return key, nil + } + if key, err := x509.ParseECPrivateKey(der); err == nil { + return key, nil + } + return nil, errors.New("unsupported private key") +} diff --git a/backend/internal/service/certificates_test.go b/backend/internal/service/certificates_test.go new file mode 100644 index 0000000..1e243fc --- /dev/null +++ b/backend/internal/service/certificates_test.go @@ -0,0 +1,77 @@ +package service + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "strings" + "testing" + "time" +) + +func TestValidateManualCertificate(t *testing.T) { + now := time.Now().UTC() + certificate, privateKey := testCertificatePair(t, []string{"site.hosts.example.com", "www.example.com"}, now) + if err := validateManualCertificate(certificate, privateKey, []string{"site.hosts.example.com", "www.example.com"}, now); err != nil { + t.Fatalf("valid certificate rejected: %v", err) + } +} + +func TestValidateManualCertificateRejectsMissingDomain(t *testing.T) { + now := time.Now().UTC() + certificate, privateKey := testCertificatePair(t, []string{"site.hosts.example.com"}, now) + err := validateManualCertificate(certificate, privateKey, []string{"site.hosts.example.com", "www.example.com"}, now) + if err == nil || !strings.Contains(err.Error(), "www.example.com") { + t.Fatalf("missing domain error = %v", err) + } +} + +func TestValidateManualCertificateRejectsMismatchedKey(t *testing.T) { + now := time.Now().UTC() + certificate, _ := testCertificatePair(t, []string{"site.hosts.example.com"}, now) + _, privateKey := testCertificatePair(t, []string{"site.hosts.example.com"}, now) + err := validateManualCertificate(certificate, privateKey, []string{"site.hosts.example.com"}, now) + if err == nil || !strings.Contains(err.Error(), "不匹配") { + t.Fatalf("mismatched key error = %v", err) + } +} + +func TestValidateManualCertificateRejectsTrailingPEMData(t *testing.T) { + now := time.Now().UTC() + certificate, privateKey := testCertificatePair(t, []string{"site.hosts.example.com"}, now) + err := validateManualCertificate(certificate+"not-pem", privateKey, []string{"site.hosts.example.com"}, now) + if err == nil || !strings.Contains(err.Error(), "PEM CERTIFICATE") { + t.Fatalf("trailing data error = %v", err) + } +} + +func testCertificatePair(t *testing.T, domains []string, now time.Time) (string, string) { + t.Helper() + publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: domains[0]}, + DNSNames: domains, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey) + if err != nil { + t.Fatal(err) + } + certificatePEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) + return string(certificatePEM), string(privateKeyPEM) +} diff --git a/backend/internal/service/dns_certificates.go b/backend/internal/service/dns_certificates.go new file mode 100644 index 0000000..95d06ad --- /dev/null +++ b/backend/internal/service/dns_certificates.go @@ -0,0 +1,570 @@ +package service + +import ( + "context" + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "log/slog" + "net" + "strings" + "time" + + "golang.org/x/crypto/acme" + + "sea-vhost/internal/dnsprovider" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +const ( + acmeAccountSecretKey = "acme-account-key-v1" + certificateCooldown = 5 * time.Minute + dnsCredentialCooldown = time.Minute + dnsPropagationLimit = 3 * time.Minute + dnsCleanupAttempts = 3 + dnsCleanupAttemptLimit = 10 * time.Second + dnsCleanupRetryDelay = 250 * time.Millisecond +) + +type DNSCredentialInput struct { + VerificationToken string `json:"verificationToken"` + Label string `json:"label"` + Provider string `json:"provider"` + ZoneName string `json:"zoneName"` + Credential dnsprovider.Credential `json:"credential"` +} + +func (s *Projects) ListDNSCredentials(ctx context.Context, user store.User, platform bool) ([]store.DNSCredential, error) { + owner, err := dnsCredentialOwner(user, platform) + if err != nil { + return nil, err + } + return s.store.ListDNSCredentials(ctx, owner) +} + +func (s *Projects) SaveDNSCredential(ctx context.Context, user store.User, platform bool, id uint64, input DNSCredentialInput) (store.DNSCredential, error) { + owner, err := dnsCredentialOwner(user, platform) + if err != nil { + return store.DNSCredential{}, err + } + label := strings.TrimSpace(input.Label) + provider := strings.ToLower(strings.TrimSpace(input.Provider)) + zone := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.ZoneName), ".")) + if len(label) < 2 || len(label) > 80 { + return store.DNSCredential{}, errors.New("凭据名称应为 2 至 80 个字符") + } + if !domainPattern.MatchString(zone) { + return store.DNSCredential{}, errors.New("DNS 区域域名格式不正确") + } + if err = dnsprovider.Validate(provider, input.Credential); err != nil { + return store.DNSCredential{}, err + } + if err=s.verifyDNSZoneChoice(user,platform,input);err!=nil{return store.DNSCredential{},err} + plain, err := json.Marshal(input.Credential) + if err != nil { + return store.DNSCredential{}, err + } + if len(plain) > 3072 { + return store.DNSCredential{}, errors.New("DNS 凭据内容过大") + } + secretRef, err := randomSecretRef() + if err != nil { + return store.DNSCredential{}, err + } + ciphertext, err := s.credentials.Seal("dns-credential:"+secretRef, string(plain)) + if err != nil { + return store.DNSCredential{}, err + } + scopeKey := "platform" + if owner != nil { + scopeKey = fmt.Sprintf("tenant:%d", *owner) + } + if id == 0 { + count, countErr := s.store.CountDNSCredentials(ctx, owner) + if countErr != nil { + return store.DNSCredential{}, errors.New("无法核对 DNS 凭据数量") + } + limit := 200 + if owner != nil { + limit = 50 + } + if count >= limit { + return store.DNSCredential{}, fmt.Errorf("DNS 凭据数量已达到上限(%d)", limit) + } + id, err = s.store.InsertDNSCredential(ctx, store.NewDNSCredential{TenantID: owner, ScopeKey: scopeKey, SecretRef: secretRef, Label: label, Provider: provider, ZoneName: zone, CredentialCiphertext: ciphertext}) + } else { + err = s.store.UpdateDNSCredential(ctx, id, owner, label, provider, zone, secretRef, ciphertext) + } + if err != nil { + return store.DNSCredential{}, fmt.Errorf("保存 DNS 凭据失败: %w", err) + } + return s.store.DNSCredential(ctx, id, owner) +} + +func (s *Projects) DeleteDNSCredential(ctx context.Context, user store.User, platform bool, id uint64) error { + owner, err := dnsCredentialOwner(user, platform) + if err != nil { + return err + } + return s.store.DeleteDNSCredential(ctx, id, owner) +} + +// TestDNSCredential verifies only the minimum permission needed by DNS-01: +// create one unpredictable TXT record inside the configured zone and delete +// that exact provider record ID. It deliberately does not contact an ACME CA. +func (s *Projects) TestDNSCredential(ctx context.Context, user store.User, platform bool, id uint64) (store.DNSCredential, error) { + owner, err := dnsCredentialOwner(user, platform) + if err != nil { + return store.DNSCredential{}, err + } + credential, err := s.store.DNSCredential(ctx, id, owner) + if err != nil { + return store.DNSCredential{}, err + } + now := time.Now().UTC() + if err = s.store.BeginDNSCredentialTest(ctx, id, owner, credential.SecretRef, now, dnsCredentialCooldown); err != nil { + return store.DNSCredential{}, err + } + + testErr := func() error { + provider, providerErr := s.dnsProvider(credential) + if providerErr != nil { + return providerErr + } + nonce, nonceErr := randomSecretRef() + if nonceErr != nil { + return errors.New("无法生成 DNS 测试记录") + } + fqdn := "_svh-check-" + nonce[:12] + "." + credential.ZoneName + if len(fqdn) > 253 { + return errors.New("DNS 区域域名过长,无法创建测试记录") + } + value, valueErr := randomSecretRef() + if valueErr != nil { + return errors.New("无法生成 DNS 测试值") + } + return verifyDNSCredential(ctx, provider, fqdn, "sea-vhost-verification="+value) + }() + + failure := "" + if testErr != nil { + failure = testErr.Error() + } + completeCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if completeErr := s.store.CompleteDNSCredentialTest(completeCtx, id, owner, credential.SecretRef, testErr == nil, failure); completeErr != nil { + if testErr == nil { + return store.DNSCredential{}, errors.New("DNS 测试已完成,但无法保存测试状态") + } + slog.Warn("cannot persist DNS credential test result", "credential_id", id, "error", completeErr) + } + if testErr != nil { + return store.DNSCredential{}, fmt.Errorf("DNS 凭据测试失败: %w", testErr) + } + return s.store.DNSCredential(ctx, id, owner) +} + +func verifyDNSCredential(ctx context.Context, provider dnsprovider.Provider, fqdn, value string) error { + recordID, err := provider.Present(ctx, fqdn, value) + if err != nil { + return fmt.Errorf("创建 TXT 记录失败: %w", err) + } + cleanupCtx, cancel := context.WithTimeout(context.Background(), 35*time.Second) + defer cancel() + if err = cleanupDNSRecord(cleanupCtx, provider, recordID); err != nil { + return fmt.Errorf("TXT 记录已创建但精确删除失败: %w", err) + } + return nil +} + +func cleanupDNSRecord(ctx context.Context, provider dnsprovider.Provider, recordID string) error { + var lastErr error + for attempt := 0; attempt < dnsCleanupAttempts; attempt++ { + attemptCtx, cancel := context.WithTimeout(ctx, dnsCleanupAttemptLimit) + lastErr = provider.Cleanup(attemptCtx, recordID) + cancel() + if lastErr == nil { + return nil + } + if attempt == dnsCleanupAttempts-1 { + break + } + timer := time.NewTimer(time.Duration(attempt+1) * dnsCleanupRetryDelay) + select { + case <-ctx.Done(): + timer.Stop() + return errors.Join(lastErr, ctx.Err()) + case <-timer.C: + } + } + return lastErr +} + +func dnsCredentialOwner(user store.User, platform bool) (*uint64, error) { + if platform { + if user.Role != "admin" { + return nil, errors.New("需要管理员权限") + } + return nil, nil + } + if user.Role != "tenant" || user.TenantID == nil { + return nil, errors.New("只有用户账号可以管理 DNS 凭据") + } + value := *user.TenantID + return &value, nil +} + +func randomSecretRef() (string, error) { + data := make([]byte, 16) + if _, err := rand.Read(data); err != nil { + return "", err + } + return hex.EncodeToString(data), nil +} + +func (s *Projects) RequestDNSCertificate(ctx context.Context, user store.User, projectID, siteID uint64) (store.Site, store.CertificateAutomation, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, store.CertificateAutomation{}, err + } + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, store.CertificateAutomation{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.Site{}, store.CertificateAutomation{}, err + } + if err = s.issueDNSCertificate(ctx, project, site); err != nil { + return store.Site{}, store.CertificateAutomation{}, err + } + updated, err := s.store.Site(ctx, project.TenantID, project.ID, site.ID) + if err != nil { + return store.Site{}, store.CertificateAutomation{}, err + } + automation, err := s.store.CertificateAutomation(ctx, project.TenantID, project.ID, site.ID) + return updated, automation, err +} + +func (s *Projects) CertificateAutomation(ctx context.Context, user store.User, projectID, siteID uint64) (store.CertificateAutomation, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.CertificateAutomation{}, err + } + return s.store.CertificateAutomation(ctx, project.TenantID, project.ID, siteID) +} + +func (s *Projects) issueDNSCertificate(ctx context.Context, project store.Project, site store.Site) (resultErr error) { + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if site.PanelSiteID <= 0 || site.Status == "provisioning" || site.Status == "failed" { + return errors.New("网站尚未完成创建,不能申请证书") + } + now := time.Now().UTC() + if err := s.store.BeginDNSCertificateAttempt(ctx, project.TenantID, project.ID, site.ID, now, certificateCooldown); err != nil { + if errors.Is(err, store.ErrCertificateCooldown) { + return errors.New("证书签发请求过于频繁,请五分钟后重试") + } + return err + } + completed := false + defer func() { + if !completed { + message := "DNS-01 证书签发失败" + if resultErr != nil { + message = resultErr.Error() + } + _ = s.store.CompleteDNSCertificateAttempt(context.WithoutCancel(ctx), project.TenantID, project.ID, site.ID, nil, message, time.Now().UTC()) + } + }() + + domains, err := s.siteCertificateDomains(ctx, project, site) + if err != nil { + return err + } + credentials, err := s.store.CertificateDNSCredentials(ctx, project.TenantID) + if err != nil { + return err + } + routes, err := routeDNSCredentials(domains, s.nodeRootDomain(ctx), credentials) + if err != nil { + return err + } + accountKey, err := s.acmeAccountKey(ctx) + if err != nil { + return fmt.Errorf("读取 ACME 账户失败: %w", err) + } + client := &acme.Client{Key: accountKey, DirectoryURL: acme.LetsEncryptURL} + if _, err = client.Register(ctx, &acme.Account{}, acme.AcceptTOS); err != nil && !errors.Is(err, acme.ErrAccountAlreadyExists) { + return fmt.Errorf("注册 ACME 账户失败: %w", err) + } + order, err := client.AuthorizeOrder(ctx, acme.DomainIDs(domains...)) + if err != nil { + return fmt.Errorf("创建 ACME 订单失败: %w", err) + } + + type challengeRecord struct { + provider dnsprovider.Provider + recordID string + fqdn, value, authzURL string + challenge *acme.Challenge + } + records := make([]challengeRecord, 0, len(order.AuthzURLs)) + defer func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + for index := len(records) - 1; index >= 0; index-- { + if err := cleanupDNSRecord(cleanupCtx, records[index].provider, records[index].recordID); err != nil { + slog.Warn("ACME TXT cleanup failed", "site_id", site.ID, "record", records[index].fqdn, "error", err) + } + } + }() + + for _, authzURL := range order.AuthzURLs { + authorization, authErr := client.GetAuthorization(ctx, authzURL) + if authErr != nil { + return fmt.Errorf("读取 ACME 验证失败: %w", authErr) + } + if authorization.Status == acme.StatusValid { + continue + } + var challenge *acme.Challenge + for _, candidate := range authorization.Challenges { + if candidate.Type == "dns-01" { + challenge = candidate + break + } + } + if challenge == nil { + return fmt.Errorf("域名 %s 不支持 DNS-01 验证", authorization.Identifier.Value) + } + value, challengeErr := client.DNS01ChallengeRecord(challenge.Token) + if challengeErr != nil { + return challengeErr + } + identifier := strings.ToLower(strings.TrimPrefix(authorization.Identifier.Value, "*.")) + credential, found := routes[identifier] + if !found { + return fmt.Errorf("域名 %s 没有可用的 DNS 凭据", identifier) + } + provider, providerErr := s.dnsProvider(credential) + if providerErr != nil { + return providerErr + } + fqdn := "_acme-challenge." + identifier + recordID, presentErr := provider.Present(ctx, fqdn, value) + if presentErr != nil { + return fmt.Errorf("写入 %s 的 TXT 记录失败: %w", identifier, presentErr) + } + records = append(records, challengeRecord{provider: provider, recordID: recordID, fqdn: fqdn, value: value, authzURL: authzURL, challenge: challenge}) + } + for _, record := range records { + if err = waitForTXT(ctx, record.fqdn, record.value, dnsPropagationLimit); err != nil { + return err + } + } + for _, record := range records { + if _, err = client.Accept(ctx, record.challenge); err != nil { + return fmt.Errorf("提交 DNS 验证失败: %w", err) + } + if _, err = client.WaitAuthorization(ctx, record.authzURL); err != nil { + return fmt.Errorf("DNS 验证未通过: %w", err) + } + } + order, err = client.WaitOrder(ctx, order.URI) + if err != nil { + return fmt.Errorf("等待 ACME 订单失败: %w", err) + } + certificateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return err + } + csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{DNSNames: domains}, certificateKey) + if err != nil { + return err + } + derChain, _, err := client.CreateOrderCert(ctx, order.FinalizeURL, csr, true) + if err != nil { + return fmt.Errorf("签发证书失败: %w", err) + } + if len(derChain) == 0 { + return errors.New("ACME 未返回证书") + } + leaf, err := x509.ParseCertificate(derChain[0]) + if err != nil { + return errors.New("ACME 返回的证书格式无效") + } + keyDER, err := x509.MarshalPKCS8PrivateKey(certificateKey) + if err != nil { + return err + } + privateKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) + var certificatePEM strings.Builder + for _, der := range derChain { + _ = pem.Encode(&certificatePEM, &pem.Block{Type: "CERTIFICATE", Bytes: der}) + } + + s.certificateMu.Lock() + err = s.panel.InstallCertificate(ctx, site.PanelSiteID, site.Domain, string(privateKeyPEM), certificatePEM.String()) + s.certificateMu.Unlock() + if err != nil { + return fmt.Errorf("宝塔安装 DNS 证书失败: %w", err) + } + if err = s.store.CompleteDNSCertificateAttempt(ctx, project.TenantID, project.ID, site.ID, &leaf.NotAfter, "", time.Now().UTC()); err != nil { + return fmt.Errorf("证书已安装,但保存续期状态失败: %w", err) + } + completed = true + return nil +} + +func routeDNSCredentials(domains []string, rootDomain string, credentials []store.DNSCredential) (map[string]store.DNSCredential, error) { + rootDomain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(rootDomain), ".")) + routes := make(map[string]store.DNSCredential, len(domains)) + for _, rawDomain := range domains { + domain := strings.ToLower(strings.TrimPrefix(strings.TrimSuffix(strings.TrimSpace(rawDomain), "."), "*.")) + platformDomain := domain == rootDomain || strings.HasSuffix(domain, "."+rootDomain) + bestLength := -1 + var best store.DNSCredential + for _, credential := range credentials { + isPlatform := credential.TenantID == nil + if isPlatform != platformDomain { + continue + } + zone := strings.ToLower(strings.TrimSuffix(credential.ZoneName, ".")) + if domain != zone && !strings.HasSuffix(domain, "."+zone) { + continue + } + if len(zone) > bestLength { + best, bestLength = credential, len(zone) + } + } + if bestLength < 0 { + if platformDomain { + return nil, fmt.Errorf("管理员尚未配置平台根域 %s 的 DNS 凭据", rootDomain) + } + return nil, fmt.Errorf("用户尚未配置可管理域名 %s 的 DNS 凭据", domain) + } + routes[domain] = best + } + return routes, nil +} + +func (s *Projects) dnsProvider(credential store.DNSCredential) (dnsprovider.Provider, error) { + plain, err := s.credentials.Open("dns-credential:"+credential.SecretRef, credential.CredentialCiphertext) + if err != nil { + return nil, errors.New("DNS 凭据无法解密,请重新保存") + } + var secret dnsprovider.Credential + if err = json.Unmarshal([]byte(plain), &secret); err != nil { + return nil, errors.New("DNS 凭据格式无效,请重新保存") + } + return dnsprovider.New(credential.Provider, credential.ZoneName, secret) +} + +func (s *Projects) acmeAccountKey(ctx context.Context) (crypto.Signer, error) { + ciphertext, err := s.store.SystemSecret(ctx, acmeAccountSecretKey) + if errors.Is(err, store.ErrNotFound) { + key, keyErr := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if keyErr != nil { + return nil, keyErr + } + der, keyErr := x509.MarshalPKCS8PrivateKey(key) + if keyErr != nil { + return nil, keyErr + } + sealed, keyErr := s.credentials.Seal("system:"+acmeAccountSecretKey, string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}))) + if keyErr != nil { + return nil, keyErr + } + if keyErr = s.store.InsertSystemSecretIfAbsent(ctx, acmeAccountSecretKey, sealed); keyErr != nil { + return nil, keyErr + } + ciphertext, err = s.store.SystemSecret(ctx, acmeAccountSecretKey) + } + if err != nil { + return nil, err + } + plain, err := s.credentials.Open("system:"+acmeAccountSecretKey, ciphertext) + if err != nil { + return nil, err + } + block, rest := pem.Decode([]byte(plain)) + if block == nil || len(strings.TrimSpace(string(rest))) != 0 { + return nil, errors.New("ACME 账户密钥格式无效") + } + key, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, err + } + signer, ok := key.(crypto.Signer) + if !ok { + return nil, errors.New("ACME 账户密钥类型无效") + } + return signer, nil +} + +func waitForTXT(ctx context.Context, fqdn, wanted string, limit time.Duration) error { + deadline := time.Now().Add(limit) + for { + values, err := net.DefaultResolver.LookupTXT(ctx, fqdn) + if err == nil { + for _, value := range values { + if value == wanted { + return nil + } + } + } + if time.Now().After(deadline) { + return fmt.Errorf("等待 %s 的 TXT 记录生效超时", fqdn) + } + timer := time.NewTimer(5 * time.Second) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } +} + +func (s *Projects) RunCertificateRenewalMonitor(ctx context.Context, interval time.Duration) { + if interval < time.Hour { + interval = 12 * time.Hour + } + run := func() { + renewalCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) + defer cancel() + items, err := s.store.DueDNSCertificateRenewals(renewalCtx, time.Now().UTC(), 25) + if err != nil { + if !errors.Is(err, context.Canceled) { + slog.Error("read DNS certificate renewals", "error", err) + } + return + } + for _, item := range items { + if err = s.issueDNSCertificate(renewalCtx, item.Project, item.Site); err != nil { + slog.Warn("DNS certificate renewal failed", "site_id", item.Site.ID, "error", err) + s.store.LogEvent(context.WithoutCancel(renewalCtx), &item.Project.TenantID, nil, "renew", "dns_certificate", fmt.Sprintf("%d", item.Site.ID), "system", false, "DNS-01 自动续期失败") + } else { + s.store.LogEvent(context.WithoutCancel(renewalCtx), &item.Project.TenantID, nil, "renew", "dns_certificate", fmt.Sprintf("%d", item.Site.ID), "system", true, "DNS-01 自动续期并部署成功") + } + } + } + run() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + run() + } + } +} diff --git a/backend/internal/service/dns_certificates_test.go b/backend/internal/service/dns_certificates_test.go new file mode 100644 index 0000000..04a4fa3 --- /dev/null +++ b/backend/internal/service/dns_certificates_test.go @@ -0,0 +1,105 @@ +package service + +import ( + "context" + "errors" + "testing" + + "sea-vhost/internal/store" +) + +type dnsCredentialTestProvider struct { + presentName, presentValue string + cleanedID string + cleanupCalls int + cleanupFailures int + cleanupErr error +} + +func (p *dnsCredentialTestProvider) Present(_ context.Context, name, value string) (string, error) { + p.presentName, p.presentValue = name, value + return "provider-record-42", nil +} +func (p *dnsCredentialTestProvider) CreateRecord(ctx context.Context, name, _ string, value string) (string, error) { + return p.Present(ctx, name, value) +} + +func (p *dnsCredentialTestProvider) Cleanup(_ context.Context, id string) error { + p.cleanedID = id + p.cleanupCalls++ + if p.cleanupFailures > 0 { + p.cleanupFailures-- + return errors.New("temporary provider failure") + } + return p.cleanupErr +} + +func TestRouteDNSCredentialsSeparatesPlatformAndTenantZones(t *testing.T) { + tenantID := uint64(8) + platform := store.DNSCredential{ID: 1, ZoneName: "example.net"} + tenant := store.DNSCredential{ID: 2, TenantID: &tenantID, ZoneName: "customer.example"} + routes, err := routeDNSCredentials([]string{"sv1.hosts.example.net", "www.customer.example"}, "hosts.example.net", []store.DNSCredential{tenant, platform}) + if err != nil { + t.Fatal(err) + } + if routes["sv1.hosts.example.net"].ID != platform.ID { + t.Fatal("assigned domain did not select platform credential") + } + if routes["www.customer.example"].ID != tenant.ID { + t.Fatal("custom domain did not select tenant credential") + } +} + +func TestRouteDNSCredentialsUsesLongestZoneSuffix(t *testing.T) { + tenantID := uint64(8) + credentials := []store.DNSCredential{ + {ID: 1, TenantID: &tenantID, ZoneName: "example.com"}, + {ID: 2, TenantID: &tenantID, ZoneName: "app.example.com"}, + } + routes, err := routeDNSCredentials([]string{"www.app.example.com"}, "hosts.platform.test", credentials) + if err != nil { + t.Fatal(err) + } + if routes["www.app.example.com"].ID != 2 { + t.Fatal("did not select longest matching DNS zone") + } +} + +func TestRouteDNSCredentialsWillNotUseTenantKeyForPlatformDomain(t *testing.T) { + tenantID := uint64(8) + _, err := routeDNSCredentials([]string{"sv1.hosts.example.net"}, "hosts.example.net", []store.DNSCredential{{ID: 2, TenantID: &tenantID, ZoneName: "example.net"}}) + if err == nil { + t.Fatal("tenant credential must not manage the platform root domain") + } +} + +func TestVerifyDNSCredentialCreatesAndDeletesExactRecord(t *testing.T) { + provider := &dnsCredentialTestProvider{} + if err := verifyDNSCredential(context.Background(), provider, "_svh-check-a.example.com", "verification-value"); err != nil { + t.Fatal(err) + } + if provider.presentName != "_svh-check-a.example.com" || provider.presentValue != "verification-value" { + t.Fatalf("unexpected TXT record: %q %q", provider.presentName, provider.presentValue) + } + if provider.cleanedID != "provider-record-42" { + t.Fatalf("cleanup used %q instead of exact provider record id", provider.cleanedID) + } +} + +func TestVerifyDNSCredentialReportsCleanupFailure(t *testing.T) { + provider := &dnsCredentialTestProvider{cleanupErr: errors.New("delete denied")} + err := verifyDNSCredential(context.Background(), provider, "_svh-check-a.example.com", "verification-value") + if err == nil || provider.cleanedID != "provider-record-42" || provider.cleanupCalls != dnsCleanupAttempts { + t.Fatal("cleanup permission failure was not reported") + } +} + +func TestVerifyDNSCredentialRetriesTransientCleanupFailure(t *testing.T) { + provider := &dnsCredentialTestProvider{cleanupFailures: 1} + if err := verifyDNSCredential(context.Background(), provider, "_svh-check-a.example.com", "verification-value"); err != nil { + t.Fatal(err) + } + if provider.cleanupCalls != 2 { + t.Fatalf("cleanup calls = %d, want 2", provider.cleanupCalls) + } +} diff --git a/backend/internal/service/dns_discovery.go b/backend/internal/service/dns_discovery.go new file mode 100644 index 0000000..7a4e047 --- /dev/null +++ b/backend/internal/service/dns_discovery.go @@ -0,0 +1,88 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "sea-vhost/internal/dnsprovider" + "sea-vhost/internal/store" + "strings" + "time" +) + +type DNSZoneChoice struct { + dnsprovider.Zone + VerificationToken string `json:"verificationToken"` +} +type dnsZoneProof struct { + Owner, Provider, Hash, ID, Zone string + Expires int64 +} + +func credentialHash(c dnsprovider.Credential) string { + c.ZoneID = "" + raw, _ := json.Marshal(c) + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} +func (s *Projects) DiscoverDNSZones(ctx context.Context, u store.User, platform bool, input DNSCredentialInput) ([]DNSZoneChoice, error) { + owner, err := dnsCredentialOwner(u, platform) + if err != nil { + return nil, err + } + ownerKey := "platform" + if owner != nil { + ownerKey = fmt.Sprintf("tenant:%d", *owner) + } + hint := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.ZoneName), ".")) + if hint != "" && !domainPattern.MatchString(hint) { + return nil, errors.New("指定域名格式无效") + } + zones, err := dnsprovider.DiscoverZones(ctx, input.Provider, input.Credential, hint) + if err != nil { + return nil, err + } + out := []DNSZoneChoice{} + for _, z := range zones { + if !domainPattern.MatchString(z.Name) { + continue + } + proof := dnsZoneProof{Owner: ownerKey, Provider: input.Provider, Hash: credentialHash(input.Credential), ID: z.ID, Zone: z.Name, Expires: time.Now().Add(15 * time.Minute).Unix()} + raw, _ := json.Marshal(proof) + token, e := s.credentials.Seal("dns-zone-choice", string(raw)) + if e != nil { + return nil, e + } + out = append(out, DNSZoneChoice{Zone: z, VerificationToken: hex.EncodeToString(token)}) + } + return out, nil +} +func (s *Projects) verifyDNSZoneChoice(u store.User, platform bool, input DNSCredentialInput) error { + owner, e := dnsCredentialOwner(u, platform) + if e != nil { + return e + } + ownerKey := "platform" + if owner != nil { + ownerKey = fmt.Sprintf("tenant:%d", *owner) + } + raw, e := hex.DecodeString(input.VerificationToken) + if e != nil || len(raw) > 4096 { + return errors.New("请先读取并选择 DNS 域名") + } + plain, e := s.credentials.Open("dns-zone-choice", raw) + if e != nil { + return errors.New("DNS 域名选择已失效,请重新读取") + } + var p dnsZoneProof + if json.Unmarshal([]byte(plain), &p) != nil || p.Owner != ownerKey || p.Provider != input.Provider || p.Hash != credentialHash(input.Credential) || p.Zone != input.ZoneName || p.Expires < time.Now().Unix() { + return errors.New("DNS 域名选择已失效或票据已变更,请重新读取") + } + if (input.Provider == "cloudflare" || input.Provider == "dnsmgr") && input.Credential.ZoneID != p.ID { + return errors.New("DNS 区域编号与已验证域名不一致") + } + return nil +} diff --git a/backend/internal/service/dns_discovery_test.go b/backend/internal/service/dns_discovery_test.go new file mode 100644 index 0000000..74fd6a2 --- /dev/null +++ b/backend/internal/service/dns_discovery_test.go @@ -0,0 +1,50 @@ +package service + +import ( + "encoding/hex" + "encoding/json" + "sea-vhost/internal/dnsprovider" + "sea-vhost/internal/secrets" + "sea-vhost/internal/store" + "testing" + "time" +) + +func TestDNSZoneChoiceBindsOwnerCredentialAndZone(t *testing.T) { + s := &Projects{credentials: secrets.New("dns-proof-test-secret-at-least-thirty-two-bytes")} + owner := uint64(12) + u := store.User{Role: "tenant", TenantID: &owner} + c := dnsprovider.Credential{APIToken: "fixture-api-token-with-sufficient-length", ZoneID: "zone12345678"} + proof := dnsZoneProof{Owner: "tenant:12", Provider: "cloudflare", Hash: credentialHash(c), ID: c.ZoneID, Zone: "example.com", Expires: time.Now().Add(time.Minute).Unix()} + raw, _ := json.Marshal(proof) + sealed, e := s.credentials.Seal("dns-zone-choice", string(raw)) + if e != nil { + t.Fatal(e) + } + input := DNSCredentialInput{Provider: "cloudflare", ZoneName: "example.com", Credential: c, VerificationToken: hex.EncodeToString(sealed)} + if e = s.verifyDNSZoneChoice(u, false, input); e != nil { + t.Fatal(e) + } + other := input + other.ZoneName = "victim.example" + if s.verifyDNSZoneChoice(u, false, other) == nil { + t.Fatal("zone substitution accepted") + } + other = input + other.Credential.ZoneID = "another-zone" + if s.verifyDNSZoneChoice(u, false, other) == nil { + t.Fatal("zone ID substitution accepted") + } + other = input + other.Credential.APIToken = "different-api-token" + if s.verifyDNSZoneChoice(u, false, other) == nil { + t.Fatal("credential substitution accepted") + } + second := uint64(13) + if s.verifyDNSZoneChoice(store.User{Role: "tenant", TenantID: &second}, false, input) == nil { + t.Fatal("cross-account proof accepted") + } + if s.verifyDNSZoneChoice(store.User{Role: "admin"}, true, input) == nil { + t.Fatal("tenant proof accepted as platform credentials") + } +} diff --git a/backend/internal/service/dns_records.go b/backend/internal/service/dns_records.go new file mode 100644 index 0000000..9a80c95 --- /dev/null +++ b/backend/internal/service/dns_records.go @@ -0,0 +1,149 @@ +package service + +import ( + "context" + "errors" + "fmt" + "strings" + + "sea-vhost/internal/store" +) + +// ProvisionDomainDNS creates an exact, provider-tracked CNAME for an approved +// customer domain. Platform credentials are never used for a customer's zone; +// routeDNSCredentials enforces that ownership boundary. +func (s *Projects) ProvisionDomainDNS(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) { + s.domainMu.Lock() + defer s.domainMu.Unlock() + item, err := s.authorizedDomain(ctx, user, domainID) + if err != nil { + return store.DomainResource{}, err + } + if item.Kind != "custom" || item.Status != "approved" { + return store.DomainResource{}, errors.New("仅已批准的自绑定域名可以创建托管解析") + } + if item.DNSRecordID != "" { + return store.DomainResource{}, errors.New("该域名已有托管 DNS 记录,请先删除原记录") + } + target := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(item.SiteAssignedDomain), ".")) + if !domainPattern.MatchString(target) || s.isReservedDomain(item.Domain) { + return store.DomainResource{}, errors.New("域名解析目标或域名范围无效") + } + credentials, err := s.store.CertificateDNSCredentials(ctx, item.TenantID) + if err != nil { + return store.DomainResource{}, err + } + routes, err := routeDNSCredentials([]string{item.Domain}, s.nodeRootDomain(ctx), credentials) + if err != nil { + return store.DomainResource{}, err + } + credential := routes[strings.ToLower(strings.TrimSuffix(item.Domain, "."))] + provider, err := s.dnsProvider(credential) + if err != nil { + return store.DomainResource{}, err + } + recordID, err := provider.CreateRecord(ctx, item.Domain, "CNAME", target) + if err != nil { + _ = s.store.SetDomainDNSError(context.WithoutCancel(ctx), item.ID, err.Error()) + return store.DomainResource{}, fmt.Errorf("创建 CNAME 记录失败: %w", err) + } + if err = s.store.SetDomainDNSRecord(ctx, item.ID, credential.ID, recordID, "CNAME"); err != nil { + cleanupErr := cleanupDNSRecord(context.WithoutCancel(ctx), provider, recordID) + if cleanupErr != nil { + return store.DomainResource{}, fmt.Errorf("DNS 记录已创建但状态保存和回滚均失败: %w", errors.Join(err, cleanupErr)) + } + return store.DomainResource{}, err + } + return s.store.DomainByID(ctx, item.ID) +} + +func (s *Projects) RemoveDomainDNS(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) { + s.domainMu.Lock() + defer s.domainMu.Unlock() + return s.removeDomainDNS(ctx, user, domainID) +} + +func (s *Projects) removeDomainDNS(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) { + item, err := s.authorizedDomain(ctx, user, domainID) + if err != nil { + return store.DomainResource{}, err + } + if item.DNSCredentialID == nil || item.DNSRecordID == "" { + return store.DomainResource{}, errors.New("该域名没有托管 DNS 记录") + } + owner, err := s.store.ProjectOwner(ctx, item.ProjectID) + if err != nil || owner == nil { + return store.DomainResource{}, errors.New("当前主机未绑定可管理此 DNS 凭据的用户") + } + credential, err := s.store.DNSCredential(ctx, *item.DNSCredentialID, owner) + if err != nil { + return store.DomainResource{}, errors.New("创建该记录的 DNS 凭据已不可用,无法安全删除远端记录") + } + provider, err := s.dnsProvider(credential) + if err != nil { + return store.DomainResource{}, err + } + if err = cleanupDNSRecord(ctx, provider, item.DNSRecordID); err != nil { + _ = s.store.SetDomainDNSError(context.WithoutCancel(ctx), item.ID, err.Error()) + return store.DomainResource{}, fmt.Errorf("删除 DNS 记录失败: %w", err) + } + if err = s.store.ClearDomainDNSRecord(ctx, item.ID, credential.ID, item.DNSRecordID); err != nil { + return store.DomainResource{}, errors.New("远端记录已删除,但本地状态清理失败,请刷新后核对") + } + return s.store.DomainByID(ctx, item.ID) +} + +// UnbindDomain keeps the row until both tracked external resources are gone, +// so a failed operation remains visible and can be retried safely. +func (s *Projects) UnbindDomain(ctx context.Context, user store.User, domainID uint64) error { + if user.Role == "admin" { + item, err := s.store.DomainByID(ctx, domainID) + if err != nil { + return err + } + release, err := s.BeginHostAccess(item.ProjectID) + if err != nil { + return err + } + defer release() + } + s.domainMu.Lock() + defer s.domainMu.Unlock() + item, err := s.authorizedDomain(ctx, user, domainID) + if err != nil { + return err + } + if item.Kind != "custom" { + return errors.New("默认主机域名随主机管理,不能单独解绑") + } + if item.DNSRecordID != "" { + if _, err = s.removeDomainDNS(ctx, user, domainID); err != nil { + return err + } + } + if item.PanelSiteID > 0 { + if err = s.panel.DeleteDomain(ctx, item.PanelSiteID, item.SiteAssignedDomain, item.Domain); err != nil { + return fmt.Errorf("移除宝塔域名绑定失败,可重试: %w", err) + } + } + return s.store.DeleteCustomDomain(ctx, item.ID, item.ProjectID) +} + +func (s *Projects) authorizedDomain(ctx context.Context, user store.User, domainID uint64) (store.DomainResource, error) { + item, err := s.store.DomainByID(ctx, domainID) + if err != nil { + return store.DomainResource{}, err + } + if user.Role != "admin" { + if (user.Role != "tenant" && user.Role != "host") || user.TenantID == nil { + return store.DomainResource{}, store.ErrNotFound + } + if _, err = s.store.ProjectForUser(ctx, user, item.ProjectID); err != nil { + return store.DomainResource{}, err + } + if err = s.ensureTenantWritable(ctx, item.TenantID); err != nil { + return store.DomainResource{}, err + } + } + return item, nil +} diff --git a/backend/internal/service/domains_test.go b/backend/internal/service/domains_test.go new file mode 100644 index 0000000..654a337 --- /dev/null +++ b/backend/internal/service/domains_test.go @@ -0,0 +1,25 @@ +package service + +import ( + "context" + "strings" + "testing" +) + +func TestCustomDomainRejectsEveryPlatformReservedZone(t *testing.T) { + projects := &Projects{reservedDomains: []string{"hosts.example.com", "console.example.com", "ftp.example.com"}} + tests := []string{ + "hosts.example.com", + "tenant.hosts.example.com", + "console.example.com", + "login.console.example.com", + "ftp.example.com", + "files.ftp.example.com", + } + for _, domain := range tests { + _, _, err := projects.customDomain(context.Background(), domain) + if err == nil || !strings.Contains(err.Error(), "平台保留域名") { + t.Errorf("reserved domain %q was accepted: %v", domain, err) + } + } +} diff --git a/backend/internal/service/files.go b/backend/internal/service/files.go new file mode 100644 index 0000000..4da957b --- /dev/null +++ b/backend/internal/service/files.go @@ -0,0 +1,20 @@ +package service + +import ( + "context" + "path/filepath" + "sea-vhost/internal/nodefiles" +) + +func (s *Projects) WithFileOpener(open func(context.Context, string) (*nodefiles.Root, error)) *Projects { + s.fileOpener = open + return s +} +func (s *Projects) OpenFiles(ctx context.Context, root string) (*nodefiles.Root, error) { + if s.fileOpener != nil { + return s.fileOpener(ctx, root) + } + return nodefiles.New(ctx, filepath.Base(root), func(_ context.Context, q nodefiles.Request) (nodefiles.Response, error) { + return nodefiles.Execute(root, q), nil + }), nil +} diff --git a/backend/internal/service/ftp_management.go b/backend/internal/service/ftp_management.go new file mode 100644 index 0000000..102614c --- /dev/null +++ b/backend/internal/service/ftp_management.go @@ -0,0 +1,88 @@ +package service + +import ( + "context" + "errors" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +func (s *Projects) ManageFTP(ctx context.Context, u store.User, id uint64, action string) (string, error) { + p, e := s.authorizedProject(ctx, u, id) + if e != nil { + return "", e + } + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + if action != "disable" { + if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil { + return "", e + } + } + rows, e := s.store.ListFTPResources(ctx, p.TenantID, &id) + if e != nil || len(rows) != 1 { + return "", errors.New("FTP 账号不存在") + } + ftp := rows[0] + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return "", e + } + agent, ok := s.isolation.(isolation.FTPManager) + if !ok { + return "", errors.New("节点未支持 FTP 管理") + } + spec := isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: p.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(p.ProcessLimit)} + switch action { + case "enable", "disable": + enabled := action == "enable" + if e = s.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, enabled); e != nil { + return "", e + } + if e = s.store.SetFTPEnabled(ctx, p.ID, enabled); e != nil { + _ = s.panel.SetFTPState(context.WithoutCancel(ctx), ftp.PanelID, ftp.Username, ftp.Enabled) + return "", e + } + if !enabled { + if e = agent.DisconnectFTP(ctx, spec); e != nil { + return "", errors.New("FTP 已停用,旧连接断开失败,请稍后重试") + } + } + return "", nil + case "reset": + adapter, ok := s.panel.(panel.CredentialManager) + if !ok { + return "", errors.New("面板未支持改密") + } + stored, e := s.store.Credentials(ctx, p.TenantID, p.ID) + if e != nil { + return "", e + } + old, e := s.credentials.Open(credentialLabel("ftp", p.ID), stored.FTPPasswordCipher) + if e != nil { + return "", e + } + password, e := randomPanelPassword() + if e != nil { + return "", e + } + cipher, e := s.credentials.Seal(credentialLabel("ftp", p.ID), password) + if e != nil { + return "", e + } + if e = adapter.SetFTPPassword(ctx, ftp.PanelID, ftp.Username, password); e != nil { + return "", e + } + if e = s.store.SetFTPPasswordCipher(ctx, p.ID, cipher); e != nil { + _ = adapter.SetFTPPassword(context.WithoutCancel(ctx), ftp.PanelID, ftp.Username, old) + return "", e + } + if e = agent.DisconnectFTP(ctx, spec); e != nil { + return password, errors.New("密码已更新,旧连接断开失败,请停用后重新启用 FTP") + } + return password, nil + default: + return "", errors.New("不支持的 FTP 操作") + } +} diff --git a/backend/internal/service/host_lifecycle.go b/backend/internal/service/host_lifecycle.go new file mode 100644 index 0000000..8e5c2a9 --- /dev/null +++ b/backend/internal/service/host_lifecycle.go @@ -0,0 +1,171 @@ +package service + +import ( + "context" + "errors" + "fmt" + "sea-vhost/internal/isolation" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "time" +) + +func (s *Projects) processHostLifecycle(ctx context.Context) { + now := time.Now().UTC() + if err := s.store.AdvanceHostLifecycle(ctx, now); err != nil { + return + } + hosts, err := s.store.HostLifecycles(ctx) + if err != nil { + return + } + for _, h := range hosts { + operation, cancel := context.WithTimeout(scope.WithProject(ctx, h.ProjectID, h.NodeID), 15*time.Minute) + err = s.withHostOwnershipChange(operation, h.ProjectID, func() error { + // Reload after acquiring the host lock: a restore may have won the race. + current, e := s.store.HostLifecycle(operation, h.ProjectID) + if e != nil { + return e + } + if current.State != "grace" && current.State != "recycle" { + return nil + } + if e = s.suspendLifecycleHost(operation, current); e != nil { + return e + } + if current.State == "recycle" && current.PurgeAfter != nil && !current.PurgeAfter.After(time.Now().UTC()) { + p, e := s.store.Project(operation, current.TenantID, current.ProjectID) + if e != nil { + return e + } + plan, _, e := s.store.PlanAndUsage(operation, current.TenantID) + if e != nil { + return e + } + return s.purgeExpiredTenant(operation, store.TenantSummary{ID: current.TenantID, Name: p.HostName, BackupPurgeAfter: current.BackupPurgeAfter}, []store.Project{p}, plan) + } + return nil + }) + if err != nil { + _ = s.store.RecordRecycleError(context.WithoutCancel(operation), h.ProjectID, err.Error()) + _ = s.store.EnqueueAdminNotification(context.WithoutCancel(operation), "critical", "lifecycle", "主机停用或回收清理未完成", fmt.Sprintf("主机 #%d,节点 %d:%v", h.ProjectID, h.NodeID, err)) + } + cancel() + } + backups, err := s.store.ExpiredTenantBackups(ctx, now, 100) + if err != nil { + return + } + for _, backup := range backups { + op := scope.WithNode(ctx, backup.NodeID) + if err = s.isolation.DeleteProjectBackup(op, isolation.ProjectBackup{TenantID: backup.TenantID, HostName: backup.HostName, ArchivePath: backup.ArchivePath, SizeBytes: backup.SizeBytes}); err == nil { + _ = s.store.MarkTenantBackupDeleted(op, backup.ID) + } + } +} + +// suspension is repeatable and attempts every service even if one fails. +func (s *Projects) suspendLifecycleHost(ctx context.Context, h store.HostLifecycle) error { + p, err := s.store.Project(ctx, h.TenantID, h.ProjectID) + if err != nil { + return err + } + plan, _, err := s.store.PlanAndUsage(ctx, h.TenantID) + if err != nil { + return err + } + sites, err := s.store.ListSites(ctx, h.TenantID, h.ProjectID) + if err != nil { + return err + } + var failures []error + for _, site := range sites { + if site.Runtime == "PHP" { + phpSpec, e := s.phpIdentitySpec(ctx, p, site) + if e != nil { + failures = append(failures, e) + } else if e = s.isolation.SetPHPIdentityState(ctx, phpSpec, false); e != nil { + failures = append(failures, e) + } + } + if site.PanelSiteID > 0 { + if e := s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false); e != nil { + failures = append(failures, e) + } + } + } + spec := isolation.ProjectSpec{TenantID: h.TenantID, HostName: p.HostName, RunPath: p.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(p.ProcessLimit)} + if e := s.isolation.TerminateProcesses(ctx, spec); e != nil { + failures = append(failures, e) + } + ftps, e := s.store.ListFTPResources(ctx, h.TenantID, &h.ProjectID) + if e != nil { + failures = append(failures, e) + } + for _, ftp := range ftps { + if e = s.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, false); e != nil { + failures = append(failures, e) + } + } + databases, e := s.store.ListDatabaseResources(ctx, h.TenantID, &h.ProjectID) + if e != nil { + failures = append(failures, e) + } + for _, db := range databases { + if e = s.isolation.ConfigureDatabaseAccess(ctx, isolation.DatabaseAccessSpec{Project: spec, Database: db.Name, ReadOnly: true, BlockCleanup: true}); e != nil { + failures = append(failures, e) + } + } + if manager, ok := s.isolation.(isolation.CredentialSessions); ok { + if e = manager.DisconnectCredentialSessions(ctx, spec); e != nil { + failures = append(failures, e) + } + } else { + failures = append(failures, errors.New("节点不支持撤销 FTP 与数据库现有连接")) + } + if len(failures) > 0 { + return errors.Join(failures...) + } + if e = s.store.ForceTenantStopped(ctx, h.TenantID); e != nil { + return e + } + return s.store.RecordRecycleError(ctx, h.ProjectID, "") +} +func (s *Projects) RecycleManagedHost(ctx context.Context, id uint64) error { + return s.withHostOwnershipChange(ctx, id, func() error { + if err := s.store.RecycleHost(ctx, id, time.Now().UTC()); err != nil { + return err + } + h, err := s.store.HostLifecycle(ctx, id) + if err == nil { + err = s.suspendLifecycleHost(ctx, h) + } + if err != nil { + _ = s.store.RecordRecycleError(context.WithoutCancel(ctx), id, err.Error()) + return fmt.Errorf("主机已进入回收期,部分服务停用失败,调度器将重试:%w", err) + } + return nil + }) +} +func (s *Projects) RestoreManagedHost(ctx context.Context, id uint64) error { + return s.withHostOwnershipChange(ctx, id, func() error { + // Complete suspension before lifting the access barrier; websites stay stopped. + h, err := s.store.HostLifecycle(ctx, id) + if err != nil { + return err + } + if h.State != "recycle" { + return errors.New("主机不在回收期") + } + if err = s.suspendLifecycleHost(ctx, h); err != nil { + return err + } + return s.store.RestoreHost(ctx, id, time.Now().UTC()) + }) +} +func (s *Projects) UpdateManagedNode(ctx context.Context, id uint64, input store.Node) error { + return s.withNodeMaintenanceWait(scope.WithNode(ctx, id), 10*time.Second, func() error { return s.store.UpdateNodeMetadata(ctx, id, input) }) +} +func (s *Projects) DeleteManagedNode(ctx context.Context, id uint64) error { + return s.withNodeMaintenanceWait(scope.WithNode(ctx, id), 10*time.Second, func() error { return s.store.DeleteNode(ctx, id) }) +} diff --git a/backend/internal/service/managed_hosts.go b/backend/internal/service/managed_hosts.go new file mode 100644 index 0000000..402e644 --- /dev/null +++ b/backend/internal/service/managed_hosts.go @@ -0,0 +1,116 @@ +package service + +import ( + "context" + "errors" + "sea-vhost/internal/auth" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "sync" + "time" +) + +func (s *Projects) hostAccessGate(id uint64) *sync.RWMutex { + gate, _ := s.hostAccessGates.LoadOrStore(id, &sync.RWMutex{}) + return gate.(*sync.RWMutex) +} +func (s *Projects) BeginHostAccess(id uint64) (func(), error) { + gate := s.hostAccessGate(id) + if !gate.TryRLock() { + return nil, store.ErrManagementLocked + } + return gate.RUnlock, nil +} +func (s *Projects) withHostOwnershipChange(ctx context.Context, id uint64, operation func() error) error { + gate := s.hostAccessGate(id) + deadline := time.NewTimer(10 * time.Second) + defer deadline.Stop() + for !gate.TryLock() { + select { + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + return errors.New("主机正在处理访问请求,请稍后重试") + case <-time.After(20 * time.Millisecond): + } + } + defer gate.Unlock() + return s.withNodeMaintenanceWait(ctx, 10*time.Second, operation) +} + +func (s *Projects) AssignUnassignedHost(ctx context.Context, id, version, target uint64) error { + return s.withHostOwnershipChange(ctx, id, func() error { return s.store.BindUnassignedHost(ctx, id, version, target) }) +} +func (s *Projects) ResetManagedHostLogin(ctx context.Context, id, version uint64) (string, error) { + var password string + err := s.withHostOwnershipChange(ctx, id, func() error { + hosts, e := s.store.ListAdminProjects(ctx) + if e != nil { + return e + } + var host *store.AdminProject + for i := range hosts { + if hosts[i].ID == id { + host = &hosts[i] + break + } + } + if host == nil { + return store.ErrNotFound + } + if host.ManagementLocked { + return store.ErrManagementLocked + } + if host.OwnershipVersion != version { + return errors.New("主机归属已变化,请重新预览") + } + password, e = randomPassword() + if e != nil { + return e + } + hash, e := auth.HashPassword(password) + if e != nil { + return e + } + return s.store.ResetHostPassword(ctx, host.TenantID, id, hash) + }) + return password, err +} + +// A resource namespace is permanent. Customer ownership may be absent or +// change later without renaming the UID, directory, database or FTP identity. +func (s *Projects) CreateManagedHost(ctx context.Context, ownerTenantID uint64, input CreateProjectInput) (CreatedProject, error) { + if ownerTenantID > 0 { + if _, err := s.store.TenantOwner(ctx, ownerTenantID); err != nil { + return CreatedProject{}, errors.New("用户不存在或已停用") + } + } + if input.NodeID == 0 || input.PlanID == 0 { + return CreatedProject{}, errors.New("请选择节点和套餐") + } + if _, err := s.store.Plan(ctx, input.PlanID); err != nil { + return CreatedProject{}, errors.New("套餐不存在") + } + node, err := s.store.Node(ctx, input.NodeID) + if err != nil || !node.Enabled { + return CreatedProject{}, errors.New("节点不可用") + } + ctx = scope.WithNode(ctx, node.ID) + if err = s.validateRuntime(ctx, input.Runtime, input.Version); err != nil { + return CreatedProject{}, err + } + namespace, err := s.store.NewResourceNamespace(ctx, input.PlanID) + if err != nil { + return CreatedProject{}, err + } + input.OwnershipSpecified = true + input.OwnerTenantID = nil + if ownerTenantID > 0 { + input.OwnerTenantID = &ownerTenantID + } + result, err := s.Create(ctx, store.User{Role: "tenant", TenantID: &namespace}, input) + if err != nil { + _ = s.store.DeleteUnusedResourceNamespace(context.WithoutCancel(ctx), namespace) + } + return result, err +} diff --git a/backend/internal/service/node_context.go b/backend/internal/service/node_context.go new file mode 100644 index 0000000..5bdc3e8 --- /dev/null +++ b/backend/internal/service/node_context.go @@ -0,0 +1,16 @@ +package service + +import ( + "context" + "sea-vhost/internal/scope" +) + +func (s *Projects) nodeRootDomain(ctx context.Context) string { + if s.store != nil { + n, err := s.store.Node(ctx, scope.Node(ctx)) + if err == nil { + return n.RootDomain + } + } + return s.rootDomain +} diff --git a/backend/internal/service/node_operations.go b/backend/internal/service/node_operations.go new file mode 100644 index 0000000..5160d52 --- /dev/null +++ b/backend/internal/service/node_operations.go @@ -0,0 +1,48 @@ +package service + +import ( + "context" + "errors" + "time" +) + +func (s *Projects) withNodeMaintenance(ctx context.Context, operation func() error) error { + return s.withNodeMaintenanceWait(ctx, 0, operation) +} + +func (s *Projects) withNodeMaintenanceWait(ctx context.Context, wait time.Duration, operation func() error) error { + gate := s.nodeGate(ctx) + deadline := time.Now().Add(wait) + for !gate.TryLock() { + if wait == 0 || !time.Now().Before(deadline) { + return errors.New("节点正在执行主机操作或环境维护,请稍后重试") + } + timer := time.NewTimer(50 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + defer gate.Unlock() + blocked, err := s.store.RuntimeMutationBlocked(ctx) + if err != nil { + return err + } + if blocked { + return errors.New("请先完成当前节点的运行环境维护任务") + } + return operation() +} +func (s *Projects) ReconcileNodeIdentities(ctx context.Context) error { + return s.withNodeMaintenanceWait(ctx, 10*time.Second, func() error { return s.ReconcileIdentities(ctx) }) +} +func (s *Projects) ApplyHostSubscription(ctx context.Context, id, plan uint64, expiry *time.Time) error { + return s.withNodeMaintenance(ctx, func() error { + if err := s.store.SetHostSubscription(ctx, id, plan, expiry); err != nil { + return err + } + return s.ReconcileIdentities(ctx) + }) +} diff --git a/backend/internal/service/ownership_changes.go b/backend/internal/service/ownership_changes.go new file mode 100644 index 0000000..ea0d2c9 --- /dev/null +++ b/backend/internal/service/ownership_changes.go @@ -0,0 +1,213 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "sea-vhost/internal/auth" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +var ErrOwnershipIncomplete = errors.New("归属变更未完成,主机管理已锁定,请按原目标和策略恢复") + +type OwnershipCredentials struct { + HostPassword string `json:"hostPassword,omitempty"` + FTPPassword string `json:"ftpPassword,omitempty"` + DatabasePassword string `json:"databasePassword,omitempty"` +} + +// Ownership changes never rename a resource namespace, Unix identity or directory. +// Persist staged credentials before native mutations so an explicit recovery can +// repeat those mutations with the same passwords after a timeout or restart. +func (s *Projects) ChangeHostOwner(ctx context.Context, id, version, target uint64, mode string, stop, resume bool) (OwnershipCredentials, error) { + var result OwnershipCredentials + if mode != "preserve" && mode != "reset" { + return result, errors.New("请选择保留或重置凭据") + } + err := s.withHostOwnershipChange(ctx, id, func() error { + hosts, e := s.store.ListAdminProjects(ctx) + if e != nil { + return e + } + var host *store.AdminProject + for i := range hosts { + if hosts[i].ID == id { + host = &hosts[i] + break + } + } + if host == nil { + return store.ErrNotFound + } + if host.OwnershipVersion != version { + return errors.New("主机归属已变化,请重新预览") + } + if !host.ManagementLocked && ((host.OwnerTenantID == nil && target == 0) || (host.OwnerTenantID != nil && *host.OwnerTenantID == target)) { + return nil + } + ctx = scope.WithProject(ctx, id, host.NodeID) + var manager panel.CredentialManager + var sessions isolation.CredentialSessions + if mode == "reset" { + var ok bool + manager, ok = s.panel.(panel.CredentialManager) + if !ok { + return errors.New("面板尚未支持凭据重置") + } + sessions, ok = s.isolation.(isolation.CredentialSessions) + if !ok { + return errors.New("节点尚未支持旧连接注销") + } + } + label := fmt.Sprintf("ownership-change:%d:%d", id, version) + var cipher []byte + if !host.ManagementLocked && mode == "reset" { + result.HostPassword, e = randomPassword() + if e != nil { + return e + } + result.FTPPassword, e = randomPanelPassword() + if e != nil { + return e + } + result.DatabasePassword, e = randomPanelPassword() + if e != nil { + return e + } + raw, _ := json.Marshal(result) + cipher, e = s.credentials.Seal(label, string(raw)) + if e != nil { + return e + } + } + pending, e := s.store.BeginOwnershipChange(ctx, id, version, target, mode, stop, resume, cipher) + if e != nil { + return e + } + // From this point any failure is deliberately fail-closed and recoverable. + finish := func() error { + if mode == "reset" { + raw, e := s.credentials.Open(label, pending.CredentialsCipher) + if e != nil { + return e + } + if e = json.Unmarshal([]byte(raw), &result); e != nil { + return e + } + if result.HostPassword == "" || result.FTPPassword == "" || result.DatabasePassword == "" { + return errors.New("staged credentials missing") + } + } + if stop { + sites, e := s.store.ListSites(ctx, host.TenantID, id) + if e != nil { + return e + } + for _, site := range sites { + if site.PanelSiteID == 0 { + continue + } + e = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false) + if e != nil && site.Runtime != "PHP" { + plan, _, planErr := s.store.PlanAndUsage(ctx, host.TenantID) + if planErr != nil { + return planErr + } + if terminateErr := s.isolation.TerminateRuntime(ctx, isolation.RuntimeProcessSpec{Project: isolation.ProjectSpec{TenantID: host.TenantID, HostName: host.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}}); terminateErr != nil { + return terminateErr + } + e = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false) + } + if e != nil { + return e + } + if site.Runtime == "PHP" { + spec, e := s.phpIdentitySpec(ctx, host.Project, site) + if e != nil { + return e + } + if e = s.isolation.SetPHPIdentityState(ctx, spec, false); e != nil { + return e + } + } + if site.Primary { + e = s.store.SetProjectState(ctx, host.TenantID, id, "stopped") + } else { + e = s.store.SetSiteState(ctx, host.TenantID, id, site.ID, "stopped") + } + if e != nil { + return e + } + } + } + var hash string + var ftpCipher, dbCipher []byte + if mode == "reset" { + ftps, e := s.store.ListFTPResources(ctx, host.TenantID, &id) + if e != nil { + return e + } + var ftp *store.FTPResource + for i := range ftps { + if ftps[i].ProjectID == id { + ftp = &ftps[i] + break + } + } + dbs, e := s.store.ListDatabaseResources(ctx, host.TenantID, &id) + if e != nil { + return e + } + var database *store.DatabaseResource + for i := range dbs { + if dbs[i].ProjectID == id { + database = &dbs[i] + break + } + } + if ftp == nil || database == nil { + return errors.New("native resources missing") + } + if e = manager.SetFTPPassword(ctx, ftp.PanelID, ftp.Username, result.FTPPassword); e != nil { + return e + } + if e = manager.SetDatabasePassword(ctx, database.PanelID, database.Username, result.DatabasePassword); e != nil { + return e + } + plan, _, e := s.store.PlanAndUsage(ctx, host.TenantID) + if e != nil { + return e + } + if e = sessions.DisconnectCredentialSessions(ctx, isolation.ProjectSpec{TenantID: host.TenantID, HostName: host.HostName, RunPath: host.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(host.ProcessLimit)}); e != nil { + return e + } + hash, e = auth.HashPassword(result.HostPassword) + if e != nil { + return e + } + ftpCipher, e = s.credentials.Seal(credentialLabel("ftp", id), result.FTPPassword) + if e != nil { + return e + } + dbCipher, e = s.credentials.Seal(credentialLabel("database", id), result.DatabasePassword) + if e != nil { + return e + } + } + return s.store.CompleteOwnershipChange(ctx, id, version, target, mode, hash, ftpCipher, dbCipher) + } + if e = finish(); e != nil { + return ErrOwnershipIncomplete + } + return nil + }) + if err != nil { + return OwnershipCredentials{}, err + } + return result, nil +} diff --git a/backend/internal/service/phpmyadmin.go b/backend/internal/service/phpmyadmin.go new file mode 100644 index 0000000..bc779fe --- /dev/null +++ b/backend/internal/service/phpmyadmin.go @@ -0,0 +1,43 @@ +package service + +import ( + "context" + "errors" + "fmt" + "sea-vhost/internal/isolation" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +func (s *Projects) PHPMyAdmin(ctx context.Context, u store.User, id uint64, q isolation.PHPMyAdminRequest) (isolation.PHPMyAdminResponse, error) { + p, e := s.authorizedProject(ctx, u, id) + if e != nil { + return isolation.PHPMyAdminResponse{}, e + } + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + if q.Method == "POST" { + if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil { + return isolation.PHPMyAdminResponse{}, e + } + } + stored, e := s.store.Credentials(ctx, p.TenantID, p.ID) + if e != nil { + return isolation.PHPMyAdminResponse{}, e + } + password, e := s.credentials.Open(credentialLabel("database", p.ID), stored.DatabasePasswordCipher) + if e != nil { + return isolation.PHPMyAdminResponse{}, errors.New("无法解密数据库凭据") + } + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return isolation.PHPMyAdminResponse{}, e + } + q.Project = isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: p.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(p.ProcessLimit)} + q.Username = stored.DatabaseUsername + q.Password = password + proxy, ok := s.isolation.(isolation.PHPMyAdminProxy) + if !ok { + return isolation.PHPMyAdminResponse{}, fmt.Errorf("节点未支持 phpMyAdmin") + } + return proxy.PHPMyAdmin(ctx, q) +} diff --git a/backend/internal/service/projects.go b/backend/internal/service/projects.go new file mode 100644 index 0000000..4f4e481 --- /dev/null +++ b/backend/internal/service/projects.go @@ -0,0 +1,2000 @@ +package service + +import ( + "context" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "log/slog" + "os" + "path" + "regexp" + "slices" + "strings" + "sync" + "time" + + "sea-vhost/internal/auth" + fileguard "sea-vhost/internal/files" + "sea-vhost/internal/isolation" + "sea-vhost/internal/nodefiles" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/secrets" + "sea-vhost/internal/store" +) + +var ErrQuotaSuspended = errors.New("tenant quota suspended") + +const maxDomainsPerSite = 100 + +var slugPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`) +var domainPattern = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)$`) + +type Projects struct { + scheduleInit sync.Once + scheduleSlots chan struct{} + hostAccessGates sync.Map + fileOpener func(context.Context, string) (*nodefiles.Root, error) + store *store.Store + panel panel.Interface + isolation isolation.Interface + credentials *secrets.Box + rootDomain, tenantRoot string + ftpCertificateDomain string + domainApproval bool + storageQuota *StorageQuota + certificateMu sync.Mutex + domainMu sync.Mutex + runtimeMu sync.Mutex + maintenanceGate sync.RWMutex + nodeGates sync.Map + runtimeCatalog panel.RuntimeCatalog + runtimeCatalogExpires time.Time + runtimeCatalogLoading chan struct{} + runtimeInstallJobs map[string]bool + reservedDomains []string +} + +type CreateProjectInput struct { + OwnerTenantID *uint64 `json:"-"` + OwnershipSpecified bool `json:"-"` + NodeID uint64 `json:"nodeId"` + PlanID uint64 `json:"planId"` + Name, Runtime, Version, RunPath, CustomDomain string + AutoSSL bool + existingSiteID int64 + existingSourcePath, existingDomain string +} + +type AdoptProjectInput struct { + NodeID uint64 + PlanID uint64 + TenantID uint64 + PanelSiteID int64 + Name string + Runtime string + Version string + RunPath string + AutoSSL bool +} + +type CreatedProject struct { + Project store.Project `json:"project"` + Credentials struct { + FTPUsername string `json:"ftpUsername"` + FTPPassword string `json:"ftpPassword"` + FTPHost string `json:"ftpHost"` + FTPTLSPolicy string `json:"ftpTLSPolicy"` + DatabaseName string `json:"databaseName"` + DatabaseUsername string `json:"databaseUsername"` + DatabasePassword string `json:"databasePassword"` + HostLogin string `json:"hostLogin"` + HostPassword string `json:"hostPassword"` + } `json:"credentials"` +} + +type CreateSiteInput struct { + Name, Runtime, Version, RunPath, CustomDomain string + AutoSSL bool +} + +type DeploymentCheck struct { + Runtime string `json:"runtime"` + EntryFile string `json:"entryFile"` + Ready bool `json:"ready"` + AdapterReady bool `json:"adapterReady"` + Size int64 `json:"size,omitempty"` + Message string `json:"message"` +} + +func NewProjects(database *store.Store, panelClient panel.Interface, isolator isolation.Interface, rootDomain, tenantRoot string, domainApproval bool, credentialSecret, ftpCertificateDomain string, reservedDomains ...string) *Projects { + reserved := []string{strings.ToLower(strings.TrimSuffix(rootDomain, "."))} + for _, domain := range reservedDomains { + domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), ".")) + if domain != "" { + reserved = append(reserved, domain) + } + } + return &Projects{store: database, panel: panelClient, isolation: isolator, credentials: secrets.New(credentialSecret), rootDomain: rootDomain, tenantRoot: tenantRoot, ftpCertificateDomain: ftpCertificateDomain, domainApproval: domainApproval, storageQuota: NewStorageQuota(database, panelClient, isolator, tenantRoot), runtimeInstallJobs: map[string]bool{}, reservedDomains: reserved} +} + +func (s *Projects) RunStorageQuotaMonitor(ctx context.Context, interval time.Duration) { + s.storageQuota.Run(ctx, interval) +} + +func (s *Projects) RunLifecycleMonitor(ctx context.Context, interval time.Duration) { + process := func() { s.processHostLifecycle(ctx) } + process() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + process() + } + } +} + +func (s *Projects) purgeExpiredTenant(ctx context.Context, tenant store.TenantSummary, projects []store.Project, plan store.Plan) error { + if tenant.BackupPurgeAfter == nil { + return errors.New("backup expiry is missing") + } + for _, project := range projects { + databases, err := s.store.ListDatabaseResources(ctx, tenant.ID, &project.ID) + if err != nil { + return err + } + oldArchive, databaseCount, err := s.store.TenantBackupDetails(ctx, tenant.ID, project.ID) + if err != nil { + return err + } + spec := isolation.ProjectSpec{TenantID: tenant.ID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)} + for _, database := range databases { + if database.Name != project.HostName || database.Username != project.HostName { + return errors.New("inconsistent managed database identity") + } + spec.Databases = append(spec.Databases, database.Name) + } + if oldArchive != "" && databaseCount >= len(databases) { + if verifyErr := s.isolation.VerifyProjectBackup(ctx, isolation.ProjectBackup{TenantID: tenant.ID, HostName: project.HostName, ArchivePath: oldArchive, DatabaseCount: databaseCount}); verifyErr != nil { + databaseCount = -1 + } + } + if oldArchive == "" || databaseCount < len(databases) { + for _, database := range databases { + if accessErr := s.isolation.ConfigureDatabaseAccess(ctx, isolation.DatabaseAccessSpec{Project: spec, Database: database.Name, ReadOnly: true, BlockCleanup: true}); accessErr != nil { + return fmt.Errorf("freeze database for recovery backup: %w", accessErr) + } + } + backup, backupErr := s.isolation.CreateProjectBackup(ctx, spec) + if backupErr != nil { + return fmt.Errorf("backup %s: %w", project.HostName, backupErr) + } + if backup.ArchivePath == "" || backup.HostName != project.HostName || backup.TenantID != tenant.ID || backup.DatabaseCount != len(databases) { + return fmt.Errorf("backup %s returned inconsistent identity", project.HostName) + } + if verifyErr := s.isolation.VerifyProjectBackup(ctx, backup); verifyErr != nil { + _ = s.isolation.DeleteProjectBackup(context.WithoutCancel(ctx), backup) + return fmt.Errorf("verify recovery backup %s: %w", project.HostName, verifyErr) + } + // A delayed cleanup must still retain a newly created backup for 14 days. + backupExpiresAt := time.Now().UTC().Add(14 * 24 * time.Hour) + if backupErr = s.store.CreateTenantBackup(ctx, tenant.ID, project.ID, project.HostName, backup.ArchivePath, backup.SizeBytes, backupExpiresAt, backup.DatabaseCount); backupErr != nil { + _ = s.isolation.DeleteProjectBackup(context.WithoutCancel(ctx), backup) + return fmt.Errorf("record backup %s: %w", project.HostName, backupErr) + } + if oldArchive != "" && oldArchive != backup.ArchivePath { + _ = s.isolation.DeleteProjectBackup(ctx, isolation.ProjectBackup{TenantID: tenant.ID, HostName: project.HostName, ArchivePath: oldArchive}) + } + } + sites, err := s.store.ListSites(ctx, tenant.ID, project.ID) + if err != nil { + return err + } + for _, site := range sites { + siteSpec := isolation.ProjectSpec{TenantID: tenant.ID, HostName: project.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)} + _ = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false) + if site.Runtime == "PHP" { + _ = s.isolation.RemovePHPIdentity(ctx, isolation.PHPIdentitySpec{Project: siteSpec, SiteName: lifecycleSiteName(project, site), Domain: site.Domain, Version: site.Version, ProcessLimit: uint32(site.ProcessLimit)}) + } else { + _ = s.panel.RemoveRuntime(ctx, panel.RuntimeSpec{ProjectName: lifecycleSiteName(project, site), Runtime: site.Runtime, Version: site.Version, Path: project.Path, RunPath: site.RunPath, Domain: site.Domain, RunUser: project.HostName, Port: site.BackendPort, ProcessLimit: site.ProcessLimit}) + } + _ = s.isolation.RemoveWebProtection(ctx, isolation.WebProtectionSpec{Project: siteSpec, Domain: site.Domain}) + if err = s.panel.DeleteSite(ctx, site.PanelSiteID, site.Domain); err != nil { + return fmt.Errorf("delete panel site %s: %w", site.Domain, err) + } + } + ftps, err := s.store.ListFTPResources(ctx, tenant.ID, &project.ID) + if err != nil { + return err + } + for _, ftp := range ftps { + if err = s.panel.DeleteFTP(ctx, ftp.PanelID, ftp.Username); err != nil { + return fmt.Errorf("delete FTP %s: %w", ftp.Username, err) + } + } + for _, database := range databases { + if err = s.panel.DeleteDatabase(ctx, database.PanelID, database.Name); err != nil { + return fmt.Errorf("delete database %s: %w", database.Name, err) + } + } + if err = s.isolation.PurgeProject(ctx, spec); err != nil { + return fmt.Errorf("purge directory %s: %w", project.HostName, err) + } + } + return s.store.MarkTenantPurged(ctx, tenant.ID) +} + +func lifecycleSiteName(project store.Project, site store.Site) string { + if site.Primary { + return project.HostName + } + return fmt.Sprintf("%s_%d", project.HostName, site.ID) +} + +func (s *Projects) ConfigureProjectNetwork(ctx context.Context, projectID uint64, ipID *uint64, dedicated bool, httpPort, httpsPort int) error { + return s.withNodeMaintenance(ctx, func() error { return s.configureProjectNetwork(ctx, projectID, ipID, dedicated, httpPort, httpsPort) }) +} + +func (s *Projects) configureProjectNetwork(ctx context.Context, projectID uint64, ipID *uint64, dedicated bool, httpPort, httpsPort int) error { + projects, err := s.store.ListAdminProjects(ctx) + if err != nil { + return err + } + var project *store.AdminProject + for index := range projects { + if projects[index].ID == projectID { + project = &projects[index] + break + } + } + if project == nil { + return store.ErrNotFound + } + address := "" + if dedicated { + if ipID == nil { + return errors.New("dedicated ip is required") + } + ip, lookupErr := s.store.IPAddress(ctx, *ipID) + if lookupErr != nil { + return lookupErr + } + if !ip.Enabled || ip.AllocationMode != "dedicated" || ip.NodeID != project.NodeID { + return errors.New("ip is not available for dedicated allocation") + } + if ip.AssignedSites > 0 && !(project.DedicatedIP && project.IPAddress == ip.Address) { + return errors.New("dedicated ip is already assigned") + } + address = ip.Address + } else { + ipID = nil + } + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return err + } + spec := isolation.NginxNetworkSpec{Project: isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}, Domain: project.Domain, IPAddress: address, Dedicated: dedicated, HTTPPort: httpPort, HTTPSPort: httpsPort} + if err = s.isolation.ConfigureNginxNetwork(ctx, spec); err != nil { + return err + } + return s.store.SetProjectNetwork(ctx, projectID, ipID, dedicated, httpPort, httpsPort) +} + +// ReconcileIdentities upgrades existing managed hosts from the legacy shared +// www runtime to locked per-host Linux identities before the API accepts +// tenant traffic. A partial migration is treated as a startup failure. +func (s *Projects) ReconcileIdentities(ctx context.Context) error { + projects, err := s.store.AllProjects(ctx) + if err != nil { + return err + } + var failures []error + for _, project := range projects { + err := func() error { + ctx := scope.WithProject(ctx, project.ID, project.NodeID) + _ = s.store.SetHostIdentityVerified(ctx, project.ID, false) + plan, _, planErr := s.store.PlanAndUsage(ctx, project.TenantID) + if planErr != nil { + return fmt.Errorf("read plan for %s: %w", project.HostName, planErr) + } + baseSpec := isolation.ProjectSpec{ + TenantID: project.TenantID, HostName: project.HostName, RunPath: project.RunPath, + StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit), + } + prepared, prepareErr := s.isolation.Prepare(ctx, baseSpec) + if prepareErr != nil || path.Clean(prepared.RootPath) != path.Clean(project.Path) || prepared.RunUser != project.HostName { + if prepareErr == nil { + prepareErr = errors.New("隔离代理返回了不一致的主机身份") + } + return fmt.Errorf("reconcile host %s: %w", project.HostName, prepareErr) + } + ftpUsername, ftpErr := s.store.FTPUsername(ctx, project.TenantID, project.ID) + if ftpErr == nil { + if ftpErr = s.isolation.ConfigureFTPIdentity(ctx, isolation.FTPIdentitySpec{Project: baseSpec, Username: ftpUsername}); ftpErr != nil { + return fmt.Errorf("reconcile FTP identity for %s: %w", project.HostName, ftpErr) + } + } else if !errors.Is(ftpErr, store.ErrNotFound) { + return ftpErr + } + sites, listErr := s.store.ListSites(ctx, project.TenantID, project.ID) + if listErr != nil { + return listErr + } + for _, site := range sites { + if site.PanelSiteID <= 0 { + continue + } + siteSpec := baseSpec + siteSpec.RunPath = site.RunPath + siteSpec.ProcessLimit = uint32(site.ProcessLimit) + if _, prepareErr = s.isolation.Prepare(ctx, siteSpec); prepareErr != nil { + return fmt.Errorf("reconcile site directory %s: %w", site.Domain, prepareErr) + } + if site.Runtime == "Node.js" || site.Runtime == "Python" { + if err = s.isolation.PreparePanelRuntime(ctx, isolation.PanelRuntimeSpec{Project: siteSpec, Runtime: site.Runtime, Version: site.Version, ProjectName: lifecycleSiteName(project, site)}); err != nil { + return fmt.Errorf("reconcile %s panel compatibility for %s: %w", site.Runtime, site.Domain, err) + } + } + if err = s.panel.MigrateRuntimeIdentity(ctx, site.PanelSiteID, project.HostName, site.Status == "running"); err != nil { + return fmt.Errorf("reconcile runtime identity for %s: %w", site.Domain, err) + } + if site.Runtime == "PHP" { + phpSpec, phpErr := s.phpIdentitySpec(ctx, project, site) + if phpErr != nil { + return phpErr + } + if phpErr = s.isolation.ConfigurePHPIdentity(ctx, phpSpec); phpErr != nil { + return fmt.Errorf("reconcile PHP identity for %s: %w", site.Domain, phpErr) + } + if site.Status != "running" { + if phpErr = s.isolation.SetPHPIdentityState(ctx, phpSpec, false); phpErr != nil { + return fmt.Errorf("restore stopped PHP state for %s: %w", site.Domain, phpErr) + } + } + } + } + suspended, _, err := s.store.TenantQuotaSuspension(ctx, project.TenantID) + if err != nil { + return err + } + if suspended { + if err = s.isolation.FreezeWrites(ctx, baseSpec); err != nil { + return err + } + } + if err = s.store.SetHostIdentityVerified(ctx, project.ID, true); err != nil { + return err + } + if !suspended && s.store.HostWritable(ctx, project.TenantID) == nil { + resources, err := s.store.ListFTPResources(ctx, project.TenantID, &project.ID) + if err != nil { + return err + } + for _, ftp := range resources { + if !ftp.Enabled { + continue + } + if err = s.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, true); err != nil { + _ = s.store.SetHostIdentityVerified(context.WithoutCancel(ctx), project.ID, false) + return err + } + } + } + return nil + }() + if err != nil { + failures = append(failures, err) + } + } + return errors.Join(failures...) +} + +func (s *Projects) CheckStorageWrite(ctx context.Context, tenantID, additionalBytes uint64) error { + return s.storageQuota.CheckWrite(ctx, tenantID, additionalBytes) +} + +func (s *Projects) ensureTenantWritable(ctx context.Context, tenantID uint64) error { + if err := s.store.HostWritable(ctx, tenantID); err != nil { + return err + } + suspended, reason, err := s.store.TenantQuotaSuspension(ctx, tenantID) + if err != nil { + return err + } + if suspended { + return fmt.Errorf("%w: %s", ErrQuotaSuspended, reason) + } + return nil +} + +func (s *Projects) RuntimeCatalog(ctx context.Context) (panel.RuntimeCatalog, error) { + if s.store != nil { + return s.panel.RuntimeCatalog(ctx) + } + for { + now := time.Now() + s.runtimeMu.Lock() + if now.Before(s.runtimeCatalogExpires) && s.runtimeCatalog != nil { + catalog := cloneRuntimeCatalog(s.runtimeCatalog) + s.runtimeMu.Unlock() + return catalog, nil + } + if s.runtimeCatalogLoading != nil { + loading := s.runtimeCatalogLoading + s.runtimeMu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-loading: + continue + } + } + loading := make(chan struct{}) + s.runtimeCatalogLoading = loading + s.runtimeMu.Unlock() + catalog, err := s.panel.RuntimeCatalog(ctx) + s.runtimeMu.Lock() + if err == nil { + s.runtimeCatalog = cloneRuntimeCatalog(catalog) + s.runtimeCatalogExpires = time.Now().Add(time.Minute) + } + close(loading) + s.runtimeCatalogLoading = nil + s.runtimeMu.Unlock() + return cloneRuntimeCatalog(catalog), err + } +} + +func cloneRuntimeCatalog(source panel.RuntimeCatalog) panel.RuntimeCatalog { + if source == nil { + return panel.RuntimeCatalog{} + } + result := make(panel.RuntimeCatalog, len(source)) + for runtimeName, versions := range source { + result[runtimeName] = append([]string(nil), versions...) + } + return result +} + +func (s *Projects) RuntimeEnvironments(ctx context.Context) ([]panel.RuntimeEnvironment, error) { + items, err := s.panel.RuntimeEnvironments(ctx) + if err != nil { + return nil, err + } + if s.store != nil { + jobs, jobErr := s.store.RuntimeJobs(ctx) + if jobErr != nil { + return nil, jobErr + } + for _, job := range jobs { + if job.Action != "install" || (job.Status != "queued" && job.Status != "running" && job.Status != "interrupted") { + continue + } + for index := range items { + if items[index].Name == job.Runtime && !slices.Contains(items[index].Installing, job.TargetVersion) { + items[index].Installing = append(items[index].Installing, job.TargetVersion) + } + } + } + } + s.runtimeMu.Lock() + defer s.runtimeMu.Unlock() + for index := range items { + prefix := items[index].Name + "/" + for key := range s.runtimeInstallJobs { + if strings.HasPrefix(key, prefix) { + version := strings.TrimPrefix(key, prefix) + if !slices.Contains(items[index].Installing, version) { + items[index].Installing = append(items[index].Installing, version) + } + } + } + } + return items, nil +} + +func (s *Projects) InstallRuntimeComponent(ctx context.Context, runtimeName string) error { + if err := s.panel.InstallRuntimeComponent(ctx, runtimeName); err != nil { + return err + } + s.invalidateRuntimeCatalog() + return nil +} + +func (s *Projects) installRuntimeEnvironmentLegacy(ctx context.Context, runtimeName, version string) error { + if runtimeName == "Python" { + items, err := s.panel.RuntimeEnvironments(ctx) + if err != nil { + return err + } + allowed := false + for _, item := range items { + if item.Name == runtimeName && item.ComponentStatus == panel.RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) { + allowed = true + break + } + } + if !allowed { + return errors.New("Python version is not the latest installable patch of a supported branch") + } + key := runtimeName + "/" + version + s.runtimeMu.Lock() + if s.runtimeInstallJobs[key] { + s.runtimeMu.Unlock() + return errors.New("runtime version installation is already running") + } + s.runtimeInstallJobs[key] = true + s.runtimeMu.Unlock() + go func() { + installCtx, cancel := context.WithTimeout(context.Background(), 2*time.Hour) + defer cancel() + installErr := s.isolation.InstallPythonRuntime(installCtx, version) + s.runtimeMu.Lock() + delete(s.runtimeInstallJobs, key) + s.runtimeCatalog = nil + s.runtimeCatalogExpires = time.Time{} + s.runtimeMu.Unlock() + if installErr != nil { + slog.Error("Python runtime installation failed", "version", version, "error", installErr) + if s.store != nil { + _ = s.store.EnqueueAdminNotification(context.Background(), "critical", "runtime", "Python 运行环境安装失败", fmt.Sprintf("Python %s:%v", version, installErr)) + } + } + }() + return nil + } + if err := s.panel.InstallRuntimeEnvironment(ctx, runtimeName, version); err != nil { + return err + } + s.invalidateRuntimeCatalog() + return nil +} + +func (s *Projects) invalidateRuntimeCatalog() { + s.runtimeMu.Lock() + s.runtimeCatalog = nil + s.runtimeCatalogExpires = time.Time{} + s.runtimeMu.Unlock() +} + +func (s *Projects) Create(ctx context.Context, user store.User, input CreateProjectInput) (CreatedProject, error) { + if input.NodeID == 0 || input.PlanID == 0 { + return CreatedProject{}, errors.New("请选择节点和主机套餐") + } + node, err := s.store.Node(ctx, input.NodeID) + if err != nil || !node.Enabled { + return CreatedProject{}, errors.New("节点不存在或已停用") + } + ctx = scope.WithNode(ctx, node.ID) + + if user.TenantID == nil || user.Role == "host" { + return CreatedProject{}, errors.New("tenant account required") + } + if err := s.ensureTenantWritable(ctx, *user.TenantID); err != nil { + return CreatedProject{}, err + } + slug := strings.ToLower(strings.TrimSpace(input.Name)) + if !slugPattern.MatchString(slug) { + return CreatedProject{}, errors.New("项目名称仅允许 3-50 位小写字母、数字和连字符") + } + allowedRuntime := map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true} + if !allowedRuntime[input.Runtime] { + return CreatedProject{}, errors.New("不支持的运行环境") + } + runPath, err := normalizeRunPath(input.RunPath) + if err != nil { + return CreatedProject{}, err + } + customDomain, customDomainStatus := "", "" + if input.existingSiteID == 0 { + customDomain, customDomainStatus, err = s.customDomain(ctx, input.CustomDomain) + if err != nil { + return CreatedProject{}, err + } + } + input.Version = strings.TrimSpace(input.Version) + catalog, err := s.panel.RuntimeCatalog(ctx) + if err != nil { + return CreatedProject{}, fmt.Errorf("无法读取宝塔运行环境: %w", err) + } + versionAvailable := false + for _, version := range catalog[input.Runtime] { + if version == input.Version { + versionAvailable = true + break + } + } + if !versionAvailable { + return CreatedProject{}, errors.New("所选运行版本未安装或已不可用") + } + plan, err := s.store.Plan(ctx, input.PlanID) + if err != nil { + return CreatedProject{}, err + } + processLimit := int(plan.ProcessLimit) + ftpTLSPolicy, err := s.ftpTLSPolicy(ctx) + if err != nil { + return CreatedProject{}, err + } + hostName, err := randomHostName() + if err != nil { + return CreatedProject{}, errors.New("无法生成安全主机名") + } + defaultDomain := hostName + "." + node.RootDomain + domain := defaultDomain + if input.existingSiteID > 0 { + domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.existingDomain), ".")) + if !domainPattern.MatchString(domain) || strings.TrimSpace(input.existingSourcePath) == "" { + return CreatedProject{}, errors.New("待接管宝塔站点信息无效") + } + customDomain, customDomainStatus = defaultDomain, "approved" + } + root := path.Join(node.TenantRoot, hostName) + port := 0 + hostPassword, err := randomPassword() + if err != nil { + return CreatedProject{}, errors.New("无法生成主机登录密码") + } + hostPasswordHash, err := auth.HashPassword(hostPassword) + if err != nil { + return CreatedProject{}, errors.New("无法保护主机登录密码") + } + projectID, err := s.store.InsertProject(ctx, store.NewProject{TenantID: *user.TenantID, OwnerTenantID: input.OwnerTenantID, OwnershipSpecified: input.OwnershipSpecified, NodeID: node.ID, PlanID: plan.ID, HostName: hostName, Slug: slug, Runtime: input.Runtime, Version: input.Version, Path: root, RunPath: runPath, Domain: domain, BackendPort: port, ProcessLimit: processLimit, AutoSSL: input.AutoSSL, HostPasswordHash: hostPasswordHash}) + if err != nil { + return CreatedProject{}, err + } + createdRecord, err := s.store.Project(ctx, *user.TenantID, projectID) + if err != nil { + return CreatedProject{}, err + } + port = createdRecord.BackendPort + ctx = scope.WithProject(ctx, projectID, node.ID) + isolationSpec := isolation.ProjectSpec{TenantID: *user.TenantID, HostName: hostName, RunPath: runPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(processLimit)} + prepared, err := s.isolation.Prepare(ctx, isolationSpec) + if err != nil { + _ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec) + _ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, err.Error()) + return CreatedProject{}, fmt.Errorf("创建主机隔离环境失败: %w", err) + } + if path.Clean(prepared.RootPath) != path.Clean(root) { + _ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec) + err = errors.New("隔离代理返回了不一致的主机目录") + _ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, err.Error()) + return CreatedProject{}, err + } + if input.existingSiteID > 0 { + if err = s.isolation.ImportLegacyProject(ctx, isolation.LegacyImportSpec{Project: isolationSpec, SourcePath: input.existingSourcePath}); err != nil { + _ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec) + _ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, err.Error()) + return CreatedProject{}, fmt.Errorf("复制原宝塔站点数据失败: %w", err) + } + } + + var siteID, ftpID, databaseID int64 + ftpUser := hostName + dbName := hostName + dbUser := dbName + ftpPassword, err := randomPanelPassword() + if err != nil { + return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法生成 FTP 密码")) + } + dbPassword, err := randomPanelPassword() + if err != nil { + return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法生成数据库密码")) + } + ftpPasswordCipher, err := s.credentials.Seal(credentialLabel("ftp", projectID), ftpPassword) + if err != nil { + return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法加密 FTP 密码")) + } + dbPasswordCipher, err := s.credentials.Seal(credentialLabel("database", projectID), dbPassword) + if err != nil { + return failBeforeResources(s, ctx, isolationSpec, projectID, errors.New("无法加密数据库密码")) + } + protectionSpec := isolation.WebProtectionSpec{Project: isolationSpec, Domain: domain} + protectionApplied := false + phpIdentitySpec := isolation.PHPIdentitySpec{Project: isolationSpec, SiteName: hostName, Domain: domain, Version: input.Version, ProcessLimit: uint32(processLimit)} + phpIdentityConfigured := false + adopted := false + fail := func(cause error) (CreatedProject, error) { + if databaseID > 0 { + _ = s.panel.DeleteDatabase(context.WithoutCancel(ctx), databaseID, dbName) + } + if ftpID > 0 { + _ = s.panel.DeleteFTP(context.WithoutCancel(ctx), ftpID, ftpUser) + } + if protectionApplied { + _ = s.isolation.RemoveWebProtection(context.WithoutCancel(ctx), protectionSpec) + } + if phpIdentityConfigured { + _ = s.isolation.RemovePHPIdentity(context.WithoutCancel(ctx), phpIdentitySpec) + } + if adopted { + _ = s.panel.RollbackAdoption(context.WithoutCancel(ctx), siteID, domain, input.existingSourcePath) + } else if siteID > 0 { + _ = s.panel.DeleteSite(context.WithoutCancel(ctx), siteID, domain) + } + _ = s.isolation.Quarantine(context.WithoutCancel(ctx), isolationSpec) + _ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, cause.Error()) + return CreatedProject{}, cause + } + siteSpec := panel.SiteSpec{Name: hostName, Domain: domain, Path: root, RunPath: runPath, Runtime: input.Runtime, Version: input.Version, RunUser: prepared.RunUser, Port: port, ProcessLimit: processLimit} + if input.existingSiteID > 0 { + siteID = input.existingSiteID + err = s.panel.AdoptSite(ctx, siteID, input.existingSourcePath, siteSpec) + adopted = err == nil + } else { + siteID, err = s.panel.CreateSite(ctx, siteSpec) + } + if err != nil { + return fail(fmt.Errorf("创建或接管宝塔站点失败: %w", err)) + } + if adopted { + if err = s.panel.AddDomain(ctx, siteID, domain, defaultDomain); err != nil { + return fail(fmt.Errorf("添加平台默认域名失败: %w", err)) + } + } + // aaPanel's site creation may recursively reset the document root to www:www. + // Reassert the managed owner and group after that privileged mutation; do + // not expose a project whose filesystem boundary could not be restored. + repaired, repairErr := s.isolation.Prepare(ctx, isolationSpec) + if repairErr != nil || repaired.RootPath != prepared.RootPath || repaired.RunUser != prepared.RunUser { + if repairErr == nil { + repairErr = errors.New("隔离代理返回了不一致的主机身份") + } + return fail(fmt.Errorf("宝塔建站后恢复主机目录隔离失败: %w", repairErr)) + } + if err = s.isolation.ApplyWebProtection(ctx, protectionSpec); err != nil { + return fail(fmt.Errorf("启用站点基础防护失败: %w", err)) + } + protectionApplied = true + if input.Runtime == "PHP" { + if err = s.isolation.ConfigurePHPIdentity(ctx, phpIdentitySpec); err != nil { + return fail(fmt.Errorf("创建独立 PHP 运行身份失败: %w", err)) + } + phpIdentityConfigured = true + } + ftpID, err = s.panel.CreateFTP(ctx, ftpUser, ftpPassword, root, int64(plan.StorageBytes)) + if err != nil { + return fail(fmt.Errorf("创建 FTP 失败: %w", err)) + } + if err = s.isolation.ConfigureFTPIdentity(ctx, isolation.FTPIdentitySpec{Project: isolationSpec, Username: ftpUser}); err != nil { + return fail(fmt.Errorf("绑定 FTP 独立身份失败: %w", err)) + } + // aaPanel's FTP account creation also resets the FTP root itself to www:www + // on some Pure-FTPd builds. Reassert the application-owned root after the + // account exists so Web file operations work without granting the API user + // membership in the shared www group. + repaired, repairErr = s.isolation.Prepare(ctx, isolationSpec) + if repairErr != nil || repaired.RootPath != prepared.RootPath || repaired.RunUser != prepared.RunUser { + if repairErr == nil { + repairErr = errors.New("隔离代理返回了不一致的主机身份") + } + return fail(fmt.Errorf("宝塔创建 FTP 后恢复主机目录隔离失败: %w", repairErr)) + } + databaseID, err = s.panel.CreateDatabase(ctx, dbName, dbUser, dbPassword, siteID) + if err != nil { + return fail(fmt.Errorf("创建数据库失败: %w", err)) + } + initialStatus := "awaiting_upload" + if input.Runtime == "PHP" { + initialStatus = "running" + } else if err = s.panel.SetSiteState(ctx, siteID, domain, false); err != nil { + return fail(fmt.Errorf("关闭未部署站点的公开访问失败: %w", err)) + } + if customDomain != "" && customDomainStatus == "approved" { + if err = s.panel.AddDomain(ctx, siteID, domain, customDomain); err != nil { + return fail(fmt.Errorf("绑定自定义域名失败: %w", err)) + } + } + if err = s.store.CompleteProject(ctx, projectID, siteID, ftpID, databaseID, ftpUser, dbName, dbUser, ftpPasswordCipher, dbPasswordCipher, initialStatus, customDomain, customDomainStatus, adopted); err != nil { + return fail(err) + } + project, err := s.store.Project(ctx, *user.TenantID, projectID) + if err != nil { + return CreatedProject{}, err + } + if input.AutoSSL { + sites, listErr := s.store.ListSites(ctx, project.TenantID, project.ID) + if listErr == nil { + for _, site := range sites { + if site.Primary { + _, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, site) + break + } + } + if refreshed, refreshErr := s.store.Project(ctx, project.TenantID, project.ID); refreshErr == nil { + project = refreshed + } + } + } + result := CreatedProject{Project: project} + result.Credentials.FTPUsername = ftpUser + result.Credentials.FTPPassword = ftpPassword + result.Credentials.FTPHost = defaultDomain + result.Credentials.FTPTLSPolicy = ftpTLSPolicy + result.Credentials.DatabaseName = dbName + result.Credentials.DatabaseUsername = dbUser + result.Credentials.DatabasePassword = dbPassword + result.Credentials.HostLogin = hostName + result.Credentials.HostPassword = hostPassword + return result, nil +} + +func (s *Projects) Adopt(ctx context.Context, input AdoptProjectInput) (CreatedProject, error) { + if input.TenantID == 0 || input.PanelSiteID <= 0 { + return CreatedProject{}, errors.New("用户或宝塔站点编号无效") + } + items, err := s.panel.ListUnmanagedSites(ctx) + if err != nil { + return CreatedProject{}, fmt.Errorf("读取可接管宝塔站点失败: %w", err) + } + var selected *panel.ExistingSite + for index := range items { + if items[index].ID == input.PanelSiteID { + selected = &items[index] + break + } + } + if selected == nil { + return CreatedProject{}, errors.New("宝塔站点不存在、已被接管或不在允许目录") + } + if s.isReservedDomain(selected.Domain) { + return CreatedProject{}, errors.New("平台管理域名或保留域名不能迁移给用户") + } + tenantID := input.TenantID + return s.Create(ctx, store.User{TenantID: &tenantID, Role: "tenant"}, CreateProjectInput{NodeID: input.NodeID, PlanID: input.PlanID, Name: input.Name, Runtime: input.Runtime, Version: input.Version, RunPath: input.RunPath, AutoSSL: input.AutoSSL, existingSiteID: selected.ID, existingSourcePath: selected.Path, existingDomain: selected.Domain}) +} + +func (s *Projects) UnmanagedPanelSites(ctx context.Context) ([]panel.ExistingSite, error) { + items, err := s.panel.ListUnmanagedSites(ctx) + if err != nil { + return nil, err + } + filtered := make([]panel.ExistingSite, 0, len(items)) + for _, item := range items { + if !s.isReservedDomain(item.Domain) { + filtered = append(filtered, item) + } + } + return filtered, nil +} + +func failBeforeResources(s *Projects, ctx context.Context, spec isolation.ProjectSpec, projectID uint64, cause error) (CreatedProject, error) { + _ = s.isolation.Quarantine(context.WithoutCancel(ctx), spec) + _ = s.store.MarkProjectFailed(context.WithoutCancel(ctx), projectID, cause.Error()) + return CreatedProject{}, cause +} + +func (s *Projects) Credentials(ctx context.Context, user store.User, projectID uint64) (CreatedProject, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return CreatedProject{}, err + } + stored, err := s.store.Credentials(ctx, project.TenantID, project.ID) + if err != nil { + return CreatedProject{}, err + } + ftpPassword, err := s.credentials.Open(credentialLabel("ftp", project.ID), stored.FTPPasswordCipher) + if err != nil { + return CreatedProject{}, errors.New("FTP 凭据无法解密,请重置密码") + } + databasePassword, err := s.credentials.Open(credentialLabel("database", project.ID), stored.DatabasePasswordCipher) + if err != nil { + return CreatedProject{}, errors.New("数据库凭据无法解密,请重置密码") + } + result := CreatedProject{Project: project} + result.Credentials.FTPUsername = stored.FTPUsername + result.Credentials.FTPPassword = ftpPassword + result.Credentials.FTPHost, err = s.store.ProjectAssignedDomain(ctx, project.TenantID, project.ID) + if err != nil { + return CreatedProject{}, err + } + result.Credentials.FTPTLSPolicy = s.store.Setting(ctx, fmt.Sprintf("node/%d/ftp_tls_policy", project.NodeID), "unknown") + result.Credentials.DatabaseName = stored.DatabaseName + result.Credentials.DatabaseUsername = stored.DatabaseUsername + result.Credentials.DatabasePassword = databasePassword + result.Credentials.HostLogin = project.HostName + return result, nil +} + +func (s *Projects) ftpTLSPolicy(ctx context.Context) (string, error) { + certificateDomain := s.ftpCertificateDomain + if s.store != nil { + node, err := s.store.Node(ctx, scope.Node(ctx)) + if err != nil { + return "", err + } + certificateDomain = node.FTPCertificateDomain + } + policy := "plain_allowed_no_certificate" + if strings.TrimSpace(certificateDomain) != "" { + var err error + policy, err = s.isolation.ConfigureFTPTLS(ctx, certificateDomain) + if err != nil { + return "", errors.New("FTP TLS 配置失败,请检查 FTP 证书来源域名") + } + } + if s.store != nil { + if err := s.store.SetSetting(ctx, fmt.Sprintf("node/%d/ftp_tls_policy", scope.Node(ctx)), policy); err != nil { + return "", err + } + } + return policy, nil +} + +func (s *Projects) ResetHostPassword(ctx context.Context, user store.User, projectID uint64) (string, error) { + if user.Role == "host" { + return "", errors.New("请使用用户账号重置主机登录密码") + } + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return "", err + } + password, err := randomPassword() + if err != nil { + return "", errors.New("无法生成主机登录密码") + } + hash, err := auth.HashPassword(password) + if err != nil { + return "", errors.New("无法保护主机登录密码") + } + if err = s.store.ResetHostPassword(ctx, project.TenantID, project.ID, hash); err != nil { + return "", err + } + return password, nil +} + +func credentialLabel(kind string, projectID uint64) string { + return fmt.Sprintf("%s:%d", kind, projectID) +} + +func (s *Projects) Sites(ctx context.Context, user store.User, projectID uint64) ([]store.Site, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return nil, err + } + return s.store.ListSites(ctx, project.TenantID, project.ID) +} + +// CheckDeployment performs a read-only preflight. It deliberately does not +// call aaPanel: the root-capable broker must only receive a runtime mutation +// after the uploaded entry file and the version-specific adapter are known. +func (s *Projects) CheckDeployment(ctx context.Context, user store.User, projectID, siteID uint64, requestedEntry string) (DeploymentCheck, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return DeploymentCheck{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return DeploymentCheck{}, err + } + if site.Runtime == "PHP" { + return DeploymentCheck{Runtime: site.Runtime, Ready: true, AdapterReady: true, Message: "PHP 网站由 Nginx/PHP-FPM 直接运行,无需单独创建语言进程"}, nil + } + if site.Status != "awaiting_upload" { + return DeploymentCheck{}, errors.New("仅待上传的网站可以执行部署检查") + } + entry, err := normalizeDeploymentEntry(site.Runtime, requestedEntry) + if err != nil { + return DeploymentCheck{}, err + } + relative := path.Join(strings.TrimPrefix(site.RunPath, "/"), entry) + result := DeploymentCheck{Runtime: site.Runtime, EntryFile: entry, AdapterReady: true} + projectFiles, err := s.OpenFiles(scope.WithProject(ctx, project.ID, project.NodeID), project.Path) + if err != nil { + return DeploymentCheck{}, err + } + defer projectFiles.Close() + info, err := projectFiles.Lstat(relative) + if err == nil && !info.Mode().IsRegular() { + err = fileguard.ErrNotRegular + } + if err != nil { + if errors.Is(err, os.ErrNotExist) { + result.Message = "入口文件不存在,请先通过 FTP 或文件管理上传" + return result, nil + } + if errors.Is(err, fileguard.ErrNotRegular) { + result.Message = "入口路径必须指向普通文件" + return result, nil + } + return DeploymentCheck{}, errors.New("入口文件路径无效或不可访问") + } + if info.Size() <= 0 { + result.Message = "入口文件为空,不能用于部署" + return result, nil + } + result.Ready = true + result.Size = info.Size() + result.Message = "入口文件检查通过,可以创建宝塔语言项目并验证运行状态" + return result, nil +} + +func (s *Projects) DeploySite(ctx context.Context, user store.User, projectID, siteID uint64, requestedEntry string) (store.Site, error) { + check, err := s.CheckDeployment(ctx, user, projectID, siteID, requestedEntry) + if err != nil { + return store.Site{}, err + } + if !check.Ready || !check.AdapterReady { + return store.Site{}, errors.New(check.Message) + } + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, err + } + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.Site{}, err + } + if site.Runtime == "PHP" { + return site, nil + } + if site.PanelSiteID <= 0 { + return store.Site{}, errors.New("宝塔网站尚未创建完成") + } + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return store.Site{}, err + } + isolationSpec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)} + prepared, err := s.isolation.Prepare(ctx, isolationSpec) + if err != nil || path.Clean(prepared.RootPath) != path.Clean(project.Path) { + if err == nil { + err = errors.New("隔离代理返回了不一致的主机目录") + } + return store.Site{}, fmt.Errorf("部署前恢复主机目录隔离失败: %w", err) + } + if site.Runtime == "Go" { + relativeEntry := path.Join(strings.TrimPrefix(site.RunPath, "/"), check.EntryFile) + if err = s.isolation.PrepareExecutable(ctx, isolation.ExecutableSpec{Project: isolationSpec, RelativePath: relativeEntry}); err != nil { + return store.Site{}, fmt.Errorf("无法将 Go 入口设置为可执行文件: %w", err) + } + } + if site.Runtime == "Node.js" { + // aaPanel's free Node project module refuses to start any package.json + // project when npm leaves no node_modules directory (valid for a + // dependency-free application). Create only that exact directory through + // an os.Root-confined helper; dependency installation remains aaPanel's job. + relativeModules := path.Join(strings.TrimPrefix(site.RunPath, "/"), "node_modules") + projectFiles, openErr := s.OpenFiles(ctx, project.Path) + if openErr != nil { + return store.Site{}, openErr + } + defer projectFiles.Close() + if err = projectFiles.MkdirAll(relativeModules, 0770); err != nil { + return store.Site{}, fmt.Errorf("准备 Node.js 依赖目录失败: %w", err) + } + } + runtimeProjectName := project.HostName + if !site.Primary { + runtimeProjectName = fmt.Sprintf("%s_%d", project.HostName, site.ID) + } + if site.Runtime == "Node.js" || site.Runtime == "Python" { + if err = s.isolation.PreparePanelRuntime(ctx, isolation.PanelRuntimeSpec{Project: isolationSpec, Runtime: site.Runtime, Version: site.Version, ProjectName: runtimeProjectName}); err != nil { + return store.Site{}, fmt.Errorf("准备宝塔 %s 隔离身份失败: %w", site.Runtime, err) + } + } + runtimeSpec := panel.RuntimeSpec{ + ProjectName: runtimeProjectName, Runtime: site.Runtime, Version: site.Version, + Path: project.Path, RunPath: site.RunPath, EntryFile: check.EntryFile, + Domain: site.Domain, RunUser: prepared.RunUser, Port: site.BackendPort, ProcessLimit: site.ProcessLimit, + } + runtimeSpec.Runner, err = s.prepareSavedRunner(ctx, project, site, check.EntryFile, site.Version) + if err != nil { + return store.Site{}, err + } + + if err = s.panel.ConfigureRuntime(ctx, runtimeSpec); err != nil { + return store.Site{}, fmt.Errorf("创建宝塔 %s 项目失败: %w", site.Runtime, err) + } + rollbackRuntime := func() { + rollback := context.WithoutCancel(ctx) + _ = s.panel.SetSiteState(rollback, site.PanelSiteID, site.Domain, false) + if reset, ok := s.panel.(panel.RuntimeResetter); ok { + _ = reset.ResetManagedRuntime(rollback, site.PanelSiteID, site.Domain) + } else { + _ = s.panel.RemoveRuntime(rollback, runtimeSpec) + } + } + repaired, repairErr := s.isolation.Prepare(ctx, isolationSpec) + if repairErr != nil || path.Clean(repaired.RootPath) != path.Clean(project.Path) || repaired.RunUser != prepared.RunUser { + rollbackRuntime() + if repairErr == nil { + repairErr = errors.New("隔离代理返回了不一致的主机身份") + } + return store.Site{}, fmt.Errorf("宝塔创建语言项目后恢复目录隔离失败: %w", repairErr) + } + if err = s.panel.ConfigureProxy(ctx, site.PanelSiteID, site.Domain, site.BackendPort); err != nil { + rollbackRuntime() + return store.Site{}, fmt.Errorf("创建语言项目反向代理失败: %w", err) + } + if err = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, true); err != nil { + rollbackRuntime() + return store.Site{}, fmt.Errorf("开放已部署网站失败: %w", err) + } + if err = s.restoreSiteIsolation(ctx, project, site.RunPath, site.ProcessLimit); err != nil { + rollbackRuntime() + return store.Site{}, fmt.Errorf("开放网站后恢复目录隔离失败: %w", err) + } + // Broker operations are idempotent. If this database commit fails, a retry + // observes the already-managed runtime/proxy and safely completes the state + // transition without creating a duplicate root-owned process. + if err = s.store.CompleteSiteDeployment(ctx, project.TenantID, project.ID, site.ID); err != nil { + return store.Site{}, fmt.Errorf("保存部署状态失败,可安全重试: %w", err) + } + if site.AutoSSL { + if deployed, e := s.store.Site(ctx, project.TenantID, project.ID, site.ID); e == nil { + _, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, deployed) + } + } + return s.store.Site(ctx, project.TenantID, project.ID, site.ID) +} + +func (s *Projects) CreateSite(ctx context.Context, user store.User, projectID uint64, input CreateSiteInput) (store.Site, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, err + } + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, err + } + if !project.AllowRuntimeChange && input.Runtime != project.Runtime { + return store.Site{}, errors.New("此主机仅允许使用已分配的语言;请联系管理员开启切换运行环境权限") + } + name := strings.ToLower(strings.TrimSpace(input.Name)) + if !slugPattern.MatchString(name) { + return store.Site{}, errors.New("网站名称仅允许 3-50 位小写字母、数字和连字符") + } + runPath, err := normalizeRunPath(input.RunPath) + if err != nil { + return store.Site{}, err + } + customDomain, customDomainStatus, err := s.customDomain(ctx, input.CustomDomain) + if err != nil { + return store.Site{}, err + } + if err = s.validateRuntime(ctx, input.Runtime, strings.TrimSpace(input.Version)); err != nil { + return store.Site{}, err + } + sites, err := s.store.ListSites(ctx, project.TenantID, project.ID) + if err != nil { + return store.Site{}, err + } + planLimit, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return store.Site{}, err + } + if len(sites) >= min(20, int(planLimit.ProjectLimit)) { + return store.Site{}, errors.New("单台虚拟主机最多创建 20 个网站") + } + for _, existing := range sites { + if runPathsOverlap(existing.RunPath, runPath) { + return store.Site{}, errors.New("运行目录不能与另一个网站相同、包含或被其包含") + } + } + domainSuffix, err := randomHex(4) + if err != nil { + return store.Site{}, errors.New("无法生成网站域名") + } + node, err := s.store.Node(ctx, project.NodeID) + if err != nil { + return store.Site{}, err + } + domain := project.HostName + "-" + domainSuffix + "." + node.RootDomain + port := 0 + for candidate := project.BackendPort + 1; candidate < project.BackendPort+20; candidate++ { + used := false + for _, site := range sites { + used = used || site.BackendPort == candidate + } + if !used { + port = candidate + break + } + } + if port == 0 { + return store.Site{}, errors.New("主机运行端口已用尽") + } + + siteID, err := s.store.InsertSite(ctx, store.NewSite{TenantID: project.TenantID, ProjectID: project.ID, Name: name, Domain: domain, RunPath: runPath, Runtime: input.Runtime, Version: strings.TrimSpace(input.Version), BackendPort: port, ProcessLimit: project.ProcessLimit, AutoSSL: input.AutoSSL}) + if err != nil { + return store.Site{}, err + } + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + _ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, err.Error()) + return store.Site{}, err + } + isolationSpec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: runPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)} + prepared, err := s.isolation.Prepare(ctx, isolationSpec) + if err != nil || path.Clean(prepared.RootPath) != path.Clean(project.Path) { + if err == nil { + err = errors.New("隔离代理返回了不一致的主机目录") + } + _ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, err.Error()) + return store.Site{}, err + } + panelSiteID, err := s.panel.CreateSite(ctx, panel.SiteSpec{Name: project.HostName, Domain: domain, Path: project.Path, RunPath: runPath, Runtime: input.Runtime, Version: strings.TrimSpace(input.Version), RunUser: prepared.RunUser, Port: port, ProcessLimit: project.ProcessLimit}) + if err != nil { + _ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, err.Error()) + return store.Site{}, fmt.Errorf("创建宝塔网站失败: %w", err) + } + // aaPanel may recursively reset ownership while creating a site. Reassert + // the host boundary before publishing the new website, as is done for the + // primary site during virtual-host creation. + repaired, repairErr := s.isolation.Prepare(ctx, isolationSpec) + if repairErr != nil || path.Clean(repaired.RootPath) != path.Clean(project.Path) || repaired.RunUser != prepared.RunUser { + if repairErr == nil { + repairErr = errors.New("隔离代理返回了不一致的主机身份") + } + _ = s.panel.DeleteSite(context.WithoutCancel(ctx), panelSiteID, domain) + _ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, repairErr.Error()) + return store.Site{}, fmt.Errorf("宝塔建站后恢复主机目录隔离失败: %w", repairErr) + } + protection := isolation.WebProtectionSpec{Project: isolationSpec, Domain: domain} + phpIdentity := isolation.PHPIdentitySpec{Project: isolationSpec, SiteName: fmt.Sprintf("%s_%d", project.HostName, siteID), Domain: domain, Version: strings.TrimSpace(input.Version), ProcessLimit: uint32(project.ProcessLimit)} + phpIdentityConfigured := false + fail := func(cause error) (store.Site, error) { + if phpIdentityConfigured { + _ = s.isolation.RemovePHPIdentity(context.WithoutCancel(ctx), phpIdentity) + } + _ = s.isolation.RemoveWebProtection(context.WithoutCancel(ctx), protection) + _ = s.panel.DeleteSite(context.WithoutCancel(ctx), panelSiteID, domain) + _ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), siteID, cause.Error()) + return store.Site{}, cause + } + if err = s.isolation.ApplyWebProtection(ctx, protection); err != nil { + return fail(fmt.Errorf("启用网站基础防护失败: %w", err)) + } + if input.Runtime == "PHP" { + if err = s.isolation.ConfigurePHPIdentity(ctx, phpIdentity); err != nil { + return fail(fmt.Errorf("创建独立 PHP 运行身份失败: %w", err)) + } + phpIdentityConfigured = true + } + status := "awaiting_upload" + if input.Runtime == "PHP" { + status = "running" + } else if err = s.panel.SetSiteState(ctx, panelSiteID, domain, false); err != nil { + return fail(fmt.Errorf("关闭未部署站点的公开访问失败: %w", err)) + } + if customDomain != "" && customDomainStatus == "approved" { + if err = s.panel.AddDomain(ctx, panelSiteID, domain, customDomain); err != nil { + return fail(fmt.Errorf("绑定自定义域名失败: %w", err)) + } + } + if err = s.store.CompleteSite(ctx, siteID, panelSiteID, status, customDomain, customDomainStatus); err != nil { + return fail(err) + } + items, err := s.store.ListSites(ctx, project.TenantID, project.ID) + if err != nil { + return store.Site{}, err + } + for _, item := range items { + if item.ID == siteID { + if input.AutoSSL { + _, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, item) + return s.store.Site(ctx, project.TenantID, project.ID, siteID) + } + return item, nil + } + } + return store.Site{}, store.ErrNotFound +} + +func (s *Projects) SetSiteState(ctx context.Context, user store.User, projectID, siteID uint64, enabled bool) (store.Site, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Site{}, err + } + if enabled { + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Site{}, err + } + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.Site{}, err + } + if site.Primary { + if err = s.SetState(ctx, user, projectID, enabled); err != nil { + return store.Site{}, err + } + } else { + if site.Status != "running" && site.Status != "stopped" { + return store.Site{}, errors.New("网站尚未完成部署,不能执行启停操作") + } + var phpIdentity isolation.PHPIdentitySpec + if site.Runtime == "PHP" { + phpIdentity, err = s.phpIdentitySpec(ctx, project, site) + if err != nil { + return store.Site{}, err + } + if enabled { + if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, true); err != nil { + return store.Site{}, fmt.Errorf("启动独立 PHP 运行身份失败: %w", err) + } + } + } + if err = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, enabled); err != nil { + if !enabled && site.Runtime != "PHP" { + // Some aaPanel language modules acknowledge stop before their + // launcher has actually removed the listener. The broker verifies + // the port and reports that mismatch. Recover only processes owned + // by this host identity whose cwd is inside this site's exact run + // directory, then retry the idempotent panel/Nginx transition. + plan, _, planErr := s.store.PlanAndUsage(ctx, project.TenantID) + if planErr == nil { + runtimeSpec := isolation.RuntimeProcessSpec{Project: isolation.ProjectSpec{ + TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath, + StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit), + }} + if terminateErr := s.isolation.TerminateRuntime(ctx, runtimeSpec); terminateErr == nil { + err = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false) + } else { + err = fmt.Errorf("%w; 精确终止残留运行进程失败: %v", err, terminateErr) + } + } else { + err = fmt.Errorf("%w; 读取资源套餐失败: %v", err, planErr) + } + } + } + if err != nil { + if enabled && site.Runtime == "PHP" { + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, false) + } + return store.Site{}, err + } + if !enabled && site.Runtime == "PHP" { + if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, false); err != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, true) + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true) + return store.Site{}, fmt.Errorf("停止独立 PHP 运行身份失败: %w", err) + } + } + // aaPanel's language-project start handlers recursively chown the project + // directory to www:www. Restore Sea vHost's application-owned boundary + // after every successful start so Web file operations remain available + // without adding the API process to the shared www group. + if enabled && site.Runtime != "PHP" { + if err = s.restoreSiteIsolation(ctx, project, site.RunPath, site.ProcessLimit); err != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, false) + return store.Site{}, fmt.Errorf("启动后恢复主机目录隔离失败: %w", err) + } + } + state := "stopped" + if enabled { + state = "running" + } + if err = s.store.SetSiteState(ctx, project.TenantID, project.ID, site.ID, state); err != nil { + // Restore the panel state when the local state transition cannot be + // committed, so the control plane never knowingly reports the inverse. + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, !enabled) + if site.Runtime == "PHP" { + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, !enabled) + } + if !enabled && site.Runtime != "PHP" { + // A rollback from stopped to running invokes the same aaPanel chown. + // If ownership cannot be restored, leave the runtime stopped. + if repairErr := s.restoreSiteIsolation(context.WithoutCancel(ctx), project, site.RunPath, site.ProcessLimit); repairErr != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), site.PanelSiteID, site.Domain, false) + } + } + return store.Site{}, err + } + } + updated, readErr := s.store.Site(ctx, project.TenantID, project.ID, site.ID) + if readErr == nil { + if _, supported := s.isolation.(isolation.RuntimeMaintenance); supported { + _ = s.verifyRuntimeTarget(ctx, store.RuntimeTarget{Site: updated, Project: project, HostName: project.HostName}) + } + } + return updated, readErr +} + +func (s *Projects) DeleteSite(ctx context.Context, user store.User, projectID, siteID uint64) error { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return err + } + if site.Primary { + return errors.New("主站不能在网站列表中删除") + } + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return err + } + isolationSpec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)} + protection := isolation.WebProtectionSpec{Project: isolationSpec, Domain: site.Domain} + var phpIdentity isolation.PHPIdentitySpec + if site.Runtime == "PHP" { + phpIdentity = isolation.PHPIdentitySpec{Project: isolationSpec, SiteName: fmt.Sprintf("%s_%d", project.HostName, site.ID), Domain: site.Domain, Version: site.Version, ProcessLimit: uint32(site.ProcessLimit)} + if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, false); err != nil { + return fmt.Errorf("停止独立 PHP 运行身份失败: %w", err) + } + } + // Runtime start handlers may have left the retained source owned by + // www:www. Repair it before deleting the privileged panel resources; site + // deletion intentionally retains source for the tenant to download or trash. + if err = s.restoreSiteIsolation(ctx, project, site.RunPath, site.ProcessLimit); err != nil { + return fmt.Errorf("删除网站前恢复主机目录隔离失败: %w", err) + } + if err = s.isolation.RemoveWebProtection(ctx, protection); err != nil { + if site.Runtime == "PHP" { + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true) + } + return fmt.Errorf("移除网站防护配置失败: %w", err) + } + if err = s.panel.DeleteSite(ctx, site.PanelSiteID, site.Domain); err != nil { + _ = s.isolation.ApplyWebProtection(context.WithoutCancel(ctx), protection) + if site.Runtime == "PHP" { + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true) + } + return fmt.Errorf("删除宝塔网站失败: %w", err) + } + if site.Runtime == "PHP" { + _ = s.isolation.RemovePHPIdentity(context.WithoutCancel(ctx), phpIdentity) + } + // The site no longer serves this directory, so aaPanel's immutable + // open_basedir file is no longer needed. Cleanup is best effort here; + // PrepareTrash can safely recover the same exact file after an interruption. + _ = s.isolation.ReleaseRunPath(context.WithoutCancel(ctx), isolationSpec) + if err = s.store.DeleteSite(ctx, project.TenantID, project.ID, site.ID); err != nil { + _ = s.store.MarkSiteFailed(context.WithoutCancel(ctx), site.ID, "panel site deleted but local record cleanup failed: "+err.Error()) + return err + } + // The run directory and uploaded source are deliberately retained inside + // the host root. Deleting a website only removes its serving configuration. + return nil +} + +func (s *Projects) BindDomain(ctx context.Context, user store.User, projectID uint64, domain string) (store.DomainResource, error) { + s.domainMu.Lock() + defer s.domainMu.Unlock() + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.DomainResource{}, err + } + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.DomainResource{}, err + } + sites, err := s.store.ListSites(ctx, project.TenantID, project.ID) + if err != nil { + return store.DomainResource{}, err + } + for _, site := range sites { + if site.Primary { + return s.bindSiteDomain(ctx, project, site, domain) + } + } + return store.DomainResource{}, store.ErrNotFound +} + +func (s *Projects) BindSiteDomain(ctx context.Context, user store.User, projectID, siteID uint64, domain string) (store.DomainResource, error) { + s.domainMu.Lock() + defer s.domainMu.Unlock() + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.DomainResource{}, err + } + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.DomainResource{}, err + } + site, err := s.store.Site(ctx, project.TenantID, project.ID, siteID) + if err != nil { + return store.DomainResource{}, err + } + return s.bindSiteDomain(ctx, project, site, domain) +} + +func (s *Projects) bindSiteDomain(ctx context.Context, project store.Project, site store.Site, domain string) (store.DomainResource, error) { + domain, desiredStatus, err := s.customDomain(ctx, domain) + if err != nil { + return store.DomainResource{}, err + } + if domain == "" { + return store.DomainResource{}, errors.New("域名不能为空") + } + if site.Status == "provisioning" || site.Status == "failed" || site.PanelSiteID <= 0 { + return store.DomainResource{}, errors.New("网站尚未完成部署,不能绑定域名") + } + // Reserve the globally unique domain before mutating aaPanel. This keeps a + // concurrent request from binding the same name to a second managed site. + if err = s.store.AddCustomDomainForSite(ctx, project.TenantID, project.ID, site.ID, domain, "pending", maxDomainsPerSite); err != nil { + if errors.Is(err, store.ErrDomainLimit) { + return store.DomainResource{}, fmt.Errorf("网站域名总数已达到上限(%d,含默认域名)", maxDomainsPerSite) + } + return store.DomainResource{}, errors.New("域名已被使用或无法保存") + } + item, err := s.store.DomainByName(ctx, project.TenantID, project.ID, site.ID, domain) + if err != nil { + return store.DomainResource{}, err + } + filingRequired := s.store.Setting(ctx, "filing_required", "false") == "true" + if err = s.store.InitializeCustomDomainPolicy(ctx, item.ID, site.Domain, filingRequired); err != nil { + return store.DomainResource{}, err + } + item.ResolutionMode = "cname" + item.CNAME = site.Domain + if filingRequired { + item.FilingStatus = "pending" + desiredStatus = "pending" + } else { + item.FilingStatus = "exempt" + } + if desiredStatus == "pending" { + return item, nil + } + if err = s.panel.AddDomain(ctx, site.PanelSiteID, site.Domain, domain); err != nil { + _ = s.store.DeletePendingDomain(context.WithoutCancel(ctx), item.ID) + return store.DomainResource{}, err + } + if err = s.store.SetDomainStatus(ctx, item.ID, "pending", "approved"); err != nil { + // The panel binding remains registered and the pending row remains visible + // to an administrator, which is safer than losing track of the domain. + return store.DomainResource{}, err + } + if site.AutoSSL { + _, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, site) + } + item.Status = "approved" + return item, nil +} + +func (s *Projects) ReviewDomain(ctx context.Context, domainID uint64, approved bool) (store.DomainResource, error) { + s.domainMu.Lock() + defer s.domainMu.Unlock() + item, err := s.store.DomainByID(ctx, domainID) + if err != nil { + return store.DomainResource{}, err + } + if item.Kind != "custom" || item.Status != "pending" { + return store.DomainResource{}, errors.New("域名不在待审核状态") + } + if approved && s.store.Setting(ctx, "filing_required", "false") == "true" && item.FilingStatus != "approved" { + return store.DomainResource{}, errors.New("该域名尚未通过备案审核") + } + if !approved { + if err = s.store.SetDomainStatus(ctx, item.ID, "pending", "rejected"); err != nil { + return store.DomainResource{}, err + } + item.Status = "rejected" + return item, nil + } + if err = s.ensureTenantWritable(ctx, item.TenantID); err != nil { + return store.DomainResource{}, err + } + if item.PanelSiteID <= 0 { + return store.DomainResource{}, errors.New("目标网站尚未完成部署") + } + if err = s.panel.AddDomain(ctx, item.PanelSiteID, item.SiteAssignedDomain, item.Domain); err != nil { + return store.DomainResource{}, fmt.Errorf("宝塔绑定域名失败: %w", err) + } + if err = s.store.SetDomainStatus(ctx, item.ID, "pending", "approved"); err != nil { + return store.DomainResource{}, err + } + if item.AutoSSL { + project, projectErr := s.store.Project(ctx, item.TenantID, item.ProjectID) + site, siteErr := s.store.Site(ctx, item.TenantID, item.ProjectID, item.SiteID) + if projectErr == nil && siteErr == nil { + _, _ = s.requestAutoCertificate(context.WithoutCancel(ctx), project, site) + } + } + item.Status = "approved" + return item, nil +} + +func (s *Projects) SetState(ctx context.Context, user store.User, projectID uint64, enabled bool) error { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return err + } + if enabled { + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return err + } + } + if project.Status != "running" && project.Status != "stopped" { + return errors.New("项目尚未完成部署,不能执行启停操作") + } + var phpIdentity isolation.PHPIdentitySpec + if project.Runtime == "PHP" { + sites, listErr := s.store.ListSites(ctx, project.TenantID, project.ID) + if listErr != nil { + return listErr + } + var primary *store.Site + for index := range sites { + if sites[index].Primary { + primary = &sites[index] + break + } + } + if primary == nil { + return errors.New("主站记录不存在") + } + phpIdentity, err = s.phpIdentitySpec(ctx, project, *primary) + if err != nil { + return err + } + if enabled { + if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, true); err != nil { + return fmt.Errorf("启动独立 PHP 运行身份失败: %w", err) + } + } + } + if err = s.panel.SetSiteState(ctx, project.PanelSiteID, project.Domain, enabled); err != nil { + if enabled && project.Runtime == "PHP" { + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, false) + } + return err + } + if !enabled && project.Runtime == "PHP" { + if err = s.isolation.SetPHPIdentityState(ctx, phpIdentity, false); err != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, true) + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, true) + return fmt.Errorf("停止独立 PHP 运行身份失败: %w", err) + } + } + if enabled && project.Runtime != "PHP" { + if err = s.restoreSiteIsolation(ctx, project, project.RunPath, project.ProcessLimit); err != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, false) + return fmt.Errorf("启动后恢复主机目录隔离失败: %w", err) + } + } + state := "stopped" + if enabled { + state = "running" + } + if err = s.store.SetProjectState(ctx, project.TenantID, projectID, state); err != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, !enabled) + if project.Runtime == "PHP" { + _ = s.isolation.SetPHPIdentityState(context.WithoutCancel(ctx), phpIdentity, !enabled) + } + if !enabled && project.Runtime != "PHP" { + if repairErr := s.restoreSiteIsolation(context.WithoutCancel(ctx), project, project.RunPath, project.ProcessLimit); repairErr != nil { + _ = s.panel.SetSiteState(context.WithoutCancel(ctx), project.PanelSiteID, project.Domain, false) + } + } + return err + } + if _, supported := s.isolation.(isolation.RuntimeMaintenance); supported { + if sites, e := s.store.ListSites(ctx, project.TenantID, project.ID); e == nil { + for _, site := range sites { + if site.Primary { + _ = s.verifyRuntimeTarget(ctx, store.RuntimeTarget{Site: site, Project: project, HostName: project.HostName}) + } + } + } + } + return nil +} + +func (s *Projects) restoreSiteIsolation(ctx context.Context, project store.Project, runPath string, processLimit int) error { + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return err + } + spec := isolation.ProjectSpec{ + TenantID: project.TenantID, HostName: project.HostName, RunPath: runPath, + StorageBytes: plan.StorageBytes, ProcessLimit: uint32(processLimit), + } + prepared, err := s.isolation.Prepare(ctx, spec) + if err != nil { + return err + } + if path.Clean(prepared.RootPath) != path.Clean(project.Path) || prepared.RunUser == "" { + return errors.New("隔离代理返回了不一致的主机目录或运行身份") + } + return nil +} + +func (s *Projects) phpIdentitySpec(ctx context.Context, project store.Project, site store.Site) (isolation.PHPIdentitySpec, error) { + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return isolation.PHPIdentitySpec{}, err + } + siteName := fmt.Sprintf("%s_%d", project.HostName, site.ID) + if site.Primary { + siteName = project.HostName + } + return isolation.PHPIdentitySpec{ + Project: isolation.ProjectSpec{ + TenantID: project.TenantID, HostName: project.HostName, RunPath: site.RunPath, + StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit), + }, + SiteName: siteName, Domain: site.Domain, Version: site.Version, ProcessLimit: uint32(site.ProcessLimit), + }, nil +} + +func (s *Projects) SetRunPath(ctx context.Context, user store.User, projectID uint64, requested string) (store.Project, error) { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return store.Project{}, err + } + ctx = scope.WithProject(ctx, project.ID, project.NodeID) + if err = s.ensureTenantWritable(ctx, project.TenantID); err != nil { + return store.Project{}, err + } + runPath, err := normalizeRunPath(requested) + if err != nil { + return store.Project{}, err + } + if project.Status == "failed" || project.Status == "provisioning" { + return store.Project{}, errors.New("项目尚未完成部署,不能修改运行目录") + } + if project.Runtime != "PHP" && project.Status != "awaiting_upload" { + return store.Project{}, errors.New("语言项目部署后不能直接修改运行目录,请新建网站后重新部署") + } + if project.RunPath == runPath { + return project, nil + } + sites, err := s.store.ListSites(ctx, project.TenantID, project.ID) + if err != nil { + return store.Project{}, err + } + for _, site := range sites { + if !site.Primary && runPathsOverlap(site.RunPath, runPath) { + return store.Project{}, errors.New("运行目录不能与另一个网站相同、包含或被其包含") + } + } + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return store.Project{}, err + } + spec := isolation.ProjectSpec{TenantID: project.TenantID, HostName: project.HostName, RunPath: runPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)} + prepared, err := s.isolation.Prepare(ctx, spec) + if err != nil { + return store.Project{}, fmt.Errorf("准备运行目录失败: %w", err) + } + if path.Clean(prepared.RootPath) != path.Clean(project.Path) { + return store.Project{}, errors.New("隔离代理返回了不一致的主机目录") + } + if err = s.panel.SetSiteRunPath(ctx, project.PanelSiteID, runPath); err != nil { + return store.Project{}, fmt.Errorf("宝塔设置运行目录失败: %w", err) + } + if err = s.isolation.ApplyWebProtection(ctx, isolation.WebProtectionSpec{Project: spec, Domain: project.Domain}); err != nil { + _ = s.panel.SetSiteRunPath(context.WithoutCancel(ctx), project.PanelSiteID, project.RunPath) + return store.Project{}, fmt.Errorf("更新运行目录后恢复站点防护失败: %w", err) + } + if err = s.store.SetProjectRunPath(ctx, project.TenantID, projectID, runPath); err != nil { + _ = s.panel.SetSiteRunPath(context.WithoutCancel(ctx), project.PanelSiteID, project.RunPath) + return store.Project{}, err + } + project.RunPath = runPath + return project, nil +} + +func (s *Projects) PrepareTrash(ctx context.Context, user store.User, projectID uint64) error { + project, err := s.authorizedProject(ctx, user, projectID) + if err != nil { + return err + } + plan, _, err := s.store.PlanAndUsage(ctx, project.TenantID) + if err != nil { + return err + } + return s.isolation.PrepareTrash(ctx, isolation.ProjectSpec{ + TenantID: project.TenantID, HostName: project.HostName, RunPath: "/", + StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit), + }) +} + +func runPathsOverlap(left, right string) bool { + left = path.Clean(left) + right = path.Clean(right) + if left == "/" || right == "/" { + return true + } + return left == right || strings.HasPrefix(left, right+"/") || strings.HasPrefix(right, left+"/") +} + +func (s *Projects) authorizedProject(ctx context.Context, user store.User, projectID uint64) (store.Project, error) { + if user.TenantID == nil { + return store.Project{}, errors.New("tenant account required") + } + if user.ProjectID != nil && *user.ProjectID != projectID { + return store.Project{}, store.ErrNotFound + } + return s.store.ProjectForUser(ctx, user, projectID) +} + +func (s *Projects) validateRuntime(ctx context.Context, runtimeName, versionName string) error { + allowedRuntime := map[string]bool{"PHP": true, "Node.js": true, "Python": true, "Go": true, "Java": true} + if !allowedRuntime[runtimeName] { + return errors.New("不支持的运行环境") + } + catalog, err := s.panel.RuntimeCatalog(ctx) + if err != nil { + return fmt.Errorf("无法读取宝塔运行环境: %w", err) + } + for _, version := range catalog[runtimeName] { + if version == versionName { + return nil + } + } + return errors.New("所选运行版本未安装或已不可用") +} + +func normalizeDeploymentEntry(runtimeName, requested string) (string, error) { + entry := strings.TrimSpace(requested) + if entry == "" { + entry = map[string]string{"Node.js": "package.json", "Python": "app.py", "Go": "app", "Java": "app.jar"}[runtimeName] + } + if len(entry) > 255 || strings.HasPrefix(entry, "/") || strings.Contains(entry, "\\") || path.Clean(entry) != entry || entry == "." || entry == ".." || strings.HasPrefix(entry, "../") { + return "", errors.New("入口文件必须是运行目录内的安全相对路径") + } + for _, segment := range strings.Split(entry, "/") { + if segment == "" || segment == "." || segment == ".." || len(segment) > 100 { + return "", errors.New("入口文件路径无效") + } + for _, character := range segment { + if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) { + return "", errors.New("入口文件仅允许字母、数字、点、下划线、连字符与目录分隔符") + } + } + } + switch runtimeName { + case "Node.js": + if path.Base(entry) != "package.json" { + return "", errors.New("Node.js 项目必须以 package.json 部署,并提供 scripts.start") + } + case "Python": + if path.Ext(entry) != ".py" { + return "", errors.New("Python 入口必须是 .py 文件") + } + case "Java": + if path.Ext(entry) != ".jar" { + return "", errors.New("Java 入口必须是 .jar 文件") + } + case "Go": + if path.Ext(entry) != "" { + return "", errors.New("Go 入口应为不带扩展名的已编译 Linux 可执行文件") + } + default: + return "", errors.New("该运行环境不需要语言项目部署检查") + } + return entry, nil +} + +func (s *Projects) customDomain(ctx context.Context, requested string) (string, string, error) { + if s.store != nil && strings.TrimSpace(requested) != "" { + nodes, err := s.store.Nodes(ctx) + if err != nil { + return "", "", err + } + candidate := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(requested), ".")) + for _, n := range nodes { + if candidate == n.RootDomain || strings.HasSuffix(candidate, "."+n.RootDomain) || candidate == n.FTPCertificateDomain { + return "", "", errors.New("平台节点默认域名与证书域名不能自绑定") + } + } + } + + domain := strings.ToLower(strings.TrimSpace(requested)) + if domain == "" { + return "", "", nil + } + if !domainPattern.MatchString(domain) { + return "", "", errors.New("域名格式不正确") + } + if s.isReservedDomain(domain) { + return "", "", errors.New("该域名属于平台保留域名,不能由用户绑定") + } + status := "approved" + if s.store.DomainApproval(ctx, s.domainApproval) { + status = "pending" + } + return domain, status, nil +} + +func (s *Projects) isReservedDomain(domain string) bool { + domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), ".")) + for _, reserved := range s.reservedDomains { + if domain == reserved || strings.HasSuffix(domain, "."+reserved) { + return true + } + } + return false +} + +func normalizeRunPath(value string) (string, error) { + value = strings.TrimSpace(value) + if value == "" || value == "/" { + return "/", nil + } + if strings.Contains(value, "\\") { + return "", errors.New("运行目录必须使用 / 分隔") + } + if !strings.HasPrefix(value, "/") { + value = "/" + value + } + if len(value) > 255 || path.Clean(value) != value { + return "", errors.New("运行目录必须是规范的站点内相对目录") + } + for _, segment := range strings.Split(strings.TrimPrefix(value, "/"), "/") { + if segment == "" || segment == "." || segment == ".." || len(segment) > 80 { + return "", errors.New("运行目录包含无效路径段") + } + for _, character := range segment { + if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) { + return "", errors.New("运行目录仅允许字母、数字、点、下划线和连字符") + } + } + } + return value, nil +} + +func randomHostName() (string, error) { + data := make([]byte, 5) + if _, err := rand.Read(data); err != nil { + return "", err + } + return "sv" + hex.EncodeToString(data), nil +} +func randomHex(size int) (string, error) { + data := make([]byte, size) + if _, err := rand.Read(data); err != nil { + return "", err + } + return hex.EncodeToString(data), nil +} +func randomPassword() (string, error) { + data := make([]byte, 21) + if _, err := rand.Read(data); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +// aaPanel's FTP and database forms accept at most 20 ASCII letters and digits. +// Twenty independently selected base-62 characters still provide about 119 bits +// of entropy, while avoiding silently rejected punctuation and overlong values. +func randomPanelPassword() (string, error) { + const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + const length = 20 + result := make([]byte, length) + // Rejection sampling avoids modulo bias because 248 is the largest multiple + // of 62 that fits in a byte range. + for index := range result { + for { + var sample [1]byte + if _, err := rand.Read(sample[:]); err != nil { + return "", err + } + if sample[0] < 248 { + result[index] = alphabet[int(sample[0])%len(alphabet)] + break + } + } + } + return string(result), nil +} + +func (s *Projects) nodeGate(ctx context.Context) *sync.RWMutex { + if scope.Node(ctx) == 1 { + return &s.maintenanceGate + } + gate, _ := s.nodeGates.LoadOrStore(scope.Node(ctx), &sync.RWMutex{}) + return gate.(*sync.RWMutex) +} diff --git a/backend/internal/service/projects_test.go b/backend/internal/service/projects_test.go new file mode 100644 index 0000000..f22b391 --- /dev/null +++ b/backend/internal/service/projects_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "regexp" + "testing" +) + +func TestRandomHostNameIsOpaqueAndDNSCompatible(t *testing.T) { + pattern := regexp.MustCompile(`^sv[0-9a-f]{10}$`) + seen := make(map[string]bool, 128) + for range 128 { + name, err := randomHostName() + if err != nil { + t.Fatal(err) + } + if !pattern.MatchString(name) { + t.Fatalf("unexpected host name %q", name) + } + if seen[name] { + t.Fatalf("duplicate host name %q", name) + } + seen[name] = true + } +} + +func TestRandomPanelPasswordMeetsAaPanelContract(t *testing.T) { + pattern := regexp.MustCompile(`^[A-Za-z0-9]{20}$`) + seen := make(map[string]bool, 128) + for range 128 { + password, err := randomPanelPassword() + if err != nil { + t.Fatal(err) + } + if !pattern.MatchString(password) { + t.Fatalf("unexpected panel password %q", password) + } + if seen[password] { + t.Fatalf("duplicate panel password %q", password) + } + seen[password] = true + } +} + +func TestNormalizeRunPathKeepsProjectInsideHostRoot(t *testing.T) { + for input, want := range map[string]string{"": "/", "/": "/", "public": "/public", "/apps/web/dist": "/apps/web/dist", "/.output/public": "/.output/public"} { + got, err := normalizeRunPath(input) + if err != nil || got != want { + t.Fatalf("normalizeRunPath(%q) = %q, %v; want %q", input, got, err, want) + } + } + for _, input := range []string{"/../etc", "/public/../etc", "/public//assets", `C:\\Windows`, "/has space", "/public/"} { + if _, err := normalizeRunPath(input); err == nil { + t.Fatalf("normalizeRunPath(%q) accepted an unsafe path", input) + } + } +} + +func TestNormalizeDeploymentEntry(t *testing.T) { + for runtime, expected := range map[string]string{"Node.js": "package.json", "Python": "app.py", "Go": "app", "Java": "app.jar"} { + got, err := normalizeDeploymentEntry(runtime, "") + if err != nil || got != expected { + t.Fatalf("normalizeDeploymentEntry(%q) = %q, %v", runtime, got, err) + } + } + for _, test := range []struct{ runtime, entry string }{ + {"Java", "../../etc/passwd"}, {"Java", "/app.jar"}, {"Java", "app.sh"}, + {"Node.js", `..\\server.js`}, {"Python", "app.txt"}, {"Go", "app.exe"}, + } { + if _, err := normalizeDeploymentEntry(test.runtime, test.entry); err == nil { + t.Fatalf("normalizeDeploymentEntry(%q, %q) accepted unsafe input", test.runtime, test.entry) + } + } +} + +func TestRunPathsOverlap(t *testing.T) { + for _, pair := range [][2]string{{"/", "/public"}, {"/app", "/app"}, {"/app", "/app/public"}, {"/app/public", "/app"}} { + if !runPathsOverlap(pair[0], pair[1]) { + t.Fatalf("expected %q and %q to overlap", pair[0], pair[1]) + } + } + for _, pair := range [][2]string{{"/app", "/application"}, {"/site-a", "/site-b"}, {"/apps/a", "/apps/b"}} { + if runPathsOverlap(pair[0], pair[1]) { + t.Fatalf("did not expect %q and %q to overlap", pair[0], pair[1]) + } + } +} diff --git a/backend/internal/service/runtime_maintenance.go b/backend/internal/service/runtime_maintenance.go new file mode 100644 index 0000000..dc31095 --- /dev/null +++ b/backend/internal/service/runtime_maintenance.go @@ -0,0 +1,737 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "path" + "slices" + "strconv" + "strings" + "sync" + "time" + + "sea-vhost/internal/cluster" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +var ErrRuntimeSwitchPending = errors.New("该主机的网站正在切换运行环境,请等待切换完成或核验结果") +var ErrNodeConfigurationBusy = errors.New("节点正在调整主机配置,请稍后重试") + +func runtimeBranch(name, version string) string { + value := strings.TrimPrefix(strings.TrimPrefix(strings.TrimPrefix(version, "jdk-"), "go"), "v") + parts := strings.Split(value, ".") + if name == "Node.js" || name == "Java" { + return parts[0] + } + if len(parts) < 2 { + return "" + } + return strings.Join(parts[:2], ".") +} +func runtimeVersionNewer(a, b string) bool { + normalize := func(v string) []string { + return strings.FieldsFunc(strings.TrimLeft(v, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), func(r rune) bool { return r == '.' || r == '_' }) + } + x, y := normalize(a), normalize(b) + for i := 0; i < max(len(x), len(y)); i++ { + var left, right int + if i < len(x) { + left, _ = strconv.Atoi(x[i]) + } + if i < len(y) { + right, _ = strconv.Atoi(y[i]) + } + if left != right { + return left > right + } + } + return false +} +func (s *Projects) InstallRuntimeEnvironment(ctx context.Context, name, version string) error { + if s.store == nil { + return s.installRuntimeEnvironmentLegacy(ctx, name, version) + } + items, err := s.panel.RuntimeEnvironments(ctx) + if err != nil { + return err + } + allowed := false + for _, item := range items { + if item.Name == name && item.ComponentStatus == panel.RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) && !slices.Contains(item.Installing, version) { + allowed = true + } + } + if !allowed { + return errors.New("请选择清单中尚未安装的运行环境版本") + } + _, err = s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "install", Runtime: name, TargetVersion: version}) + return err +} +func (s *Projects) SubmitPHPPatch(ctx context.Context, branch, target string) (uint64, error) { + items, err := s.panel.RuntimeEnvironments(ctx) + if err != nil { + return 0, err + } + for _, item := range items { + if item.Name != "PHP" { + continue + } + for _, patch := range item.Patches { + if patch.Branch == branch && patch.Latest == target && patch.UpdateAvailable { + return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "php_patch", Runtime: "PHP", FromVersion: patch.Installed, TargetVersion: target}) + } + } + } + return 0, errors.New("该 PHP 分支没有匹配的稳定补丁更新") +} +func (s *Projects) SubmitRuntimeMigration(ctx context.Context, siteID uint64, target string, allowBranchChange bool, entryFile string) (uint64, error) { + t, err := s.runtimeTarget(ctx, siteID) + if err != nil { + return 0, err + } + if t.Site.Status != "running" && t.Site.Status != "stopped" { + return 0, errors.New("仅已部署且正常运行或已停止的站点可以迁移运行环境") + } + if t.Site.Version == target && t.Site.Runtime != "Go" { + return 0, errors.New("站点已经使用该版本") + } + if runtimeBranch(t.Site.Runtime, t.Site.Version) != runtimeBranch(t.Site.Runtime, target) && !allowBranchChange { + return 0, errors.New("跨分支升级必须单独确认") + } + items, err := s.panel.RuntimeEnvironments(ctx) + if err != nil { + return 0, err + } + installed := false + for _, item := range items { + if item.Name == t.Site.Runtime && slices.Contains(item.Installed, target) { + installed = true + } + } + if !installed { + return 0, errors.New("请先安装目标运行环境") + } + id := siteID + if t.Site.Runtime == "Go" { + if entryFile == "" { + return 0, errors.New("请上传独立的新程序文件,并填写 Go 目标程序文件名;旧程序需要保留用于回退") + } + entryFile, err = normalizeDeploymentEntry("Go", entryFile) + if err != nil { + return 0, err + } + } + return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "migrate", Runtime: t.Site.Runtime, FromVersion: t.Site.Version, TargetVersion: target, EntryFile: entryFile, SiteID: &id}) +} +func (s *Projects) runtimeTarget(ctx context.Context, id uint64) (store.RuntimeTarget, error) { + items, err := s.store.RuntimeTargets(ctx) + if err != nil { + return store.RuntimeTarget{}, err + } + for _, item := range items { + if item.Site.ID == id { + return item, nil + } + } + return store.RuntimeTarget{}, store.ErrNotFound +} +func (s *Projects) RuntimeMaintenanceState(ctx context.Context) ([]store.RuntimeTarget, []store.RuntimeJob, error) { + t, err := s.store.RuntimeTargets(ctx) + if err != nil { + return nil, nil, err + } + j, err := s.store.RuntimeJobs(ctx) + return t, j, err +} +func (s *Projects) ResumeRuntimeMaintenance(ctx context.Context, id uint64) error { + return s.store.RetryRuntimeJob(ctx, id) +} +func (s *Projects) SubmitRuntimeCheck(ctx context.Context) (uint64, error) { + return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}) +} + +func (s *Projects) RunRuntimeMaintenance(ctx context.Context) { + if err := s.store.InterruptRuntimeJobs(ctx); err != nil { + slog.Error("cannot recover runtime maintenance jobs", "error", err) + return + } + workers := make(chan struct{}, 4) + var running sync.WaitGroup + defer running.Wait() + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + select { + case workers <- struct{}{}: + default: + continue + } + job, err := s.store.ClaimRuntimeJob(ctx) + if errors.Is(err, store.ErrNotFound) { + <-workers + continue + } + if err != nil { + slog.Error("cannot claim runtime maintenance", "error", err) + <-workers + continue + } + running.Add(1) + go func() { defer running.Done(); defer func() { <-workers }(); s.executeRuntimeJob(ctx, job) }() + } + } +} +func (s *Projects) executeRuntimeJob(parent context.Context, job store.RuntimeJob) { + parent = scope.WithNode(parent, job.NodeID) + // Component installation belongs to the panel and must not freeze unrelated + // host operations. Site configuration switches own only their target host. + if (job.Action == "runtime_change" || job.Action == "migrate") && job.SiteID != nil { + target, e := s.runtimeTarget(parent, *job.SiteID) + if e != nil { + _ = s.store.UpdateRuntimeJob(parent, job.ID, "failed", "failed", "网站已不存在") + return + } + // Use the same lock order as tenant requests: host first, then the node. + // A tenant's failed runtime change must never freeze unrelated hosts. + hostGate := s.hostAccessGate(target.Project.ID) + hostGate.Lock() + defer hostGate.Unlock() + s.nodeGate(parent).RLock() + defer s.nodeGate(parent).RUnlock() + } + ctx, cancel := context.WithTimeout(parent, 2*time.Hour) + defer cancel() + phase := func(value string) error { return s.store.UpdateRuntimeJob(ctx, job.ID, "running", value, "") } + var err error + switch job.Action { + case "check": + err = phase("checking") + if err == nil { + err = s.CheckRuntimeUpdates(ctx) + } + case "install": + err = phase("installing") + installed, installing := false, false + if items, inventoryErr := s.panel.RuntimeEnvironments(ctx); inventoryErr == nil { + for _, item := range items { + if item.Name == job.Runtime { + installed = slices.Contains(item.Installed, job.TargetVersion) + installing = slices.Contains(item.Installing, job.TargetVersion) + } + } + } + if err == nil && !installed && !installing { + if job.Runtime == "Python" { + err = s.isolation.InstallPythonRuntime(ctx, job.TargetVersion) + } else { + err = s.panel.InstallRuntimeEnvironment(ctx, job.Runtime, job.TargetVersion) + } + } + if err == nil { + err = s.waitRuntimeInstalled(ctx, job.Runtime, job.TargetVersion) + } + case "php_patch": + err = s.applyPHPPatch(ctx, job, phase) + case "runtime_change": + err = s.changeRuntimeSite(ctx, job, phase) + case "migrate": + err = s.migrateRuntimeSite(ctx, job, phase) + default: + err = errors.New("unknown runtime maintenance action") + } + s.invalidateRuntimeCatalog() + finishCtx, finishCancel := context.WithTimeout(context.WithoutCancel(parent), 30*time.Second) + defer finishCancel() + current, readErr := s.store.RuntimeJob(finishCtx, job.ID) + if readErr == nil && (current.Status == "rolled_back" || current.Status == "interrupted") { + if err != nil { + _ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护需要关注", fmt.Sprintf("任务 #%d %s %s(%s):%s", job.ID, job.Runtime, job.TargetVersion, current.Status, current.Message)) + } + return + } + if err != nil { + status := "failed" + if parent.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, cluster.ErrUncertain) { + status = "interrupted" + } + _ = s.store.UpdateRuntimeJob(finishCtx, job.ID, status, "failed", err.Error()) + _ = s.store.EnqueueAdminNotification(finishCtx, "critical", "runtime", "运行环境维护失败", fmt.Sprintf("任务 #%d %s %s:%v", job.ID, job.Runtime, job.TargetVersion, err)) + return + } + _ = s.store.UpdateRuntimeJob(finishCtx, job.ID, "completed", "verified", "目标版本已核验;原本停止的站点保持停止,待启动后核验进程") +} + +// Coordinate with host identity changes and unfinished site switches, not +// long-running panel component installations or patch updates. +func (s *Projects) BeginRuntimeMutation(ctx context.Context) (func(), error) { + if !s.nodeGate(ctx).TryRLock() { + return nil, ErrNodeConfigurationBusy + } + blocked, err := s.store.RuntimeMutationBlocked(ctx) + if err != nil || blocked { + s.nodeGate(ctx).RUnlock() + if err != nil { + return nil, err + } + return nil, ErrRuntimeSwitchPending + } + return s.nodeGate(ctx).RUnlock, nil +} +func (s *Projects) waitRuntimeInstalled(ctx context.Context, name, version string) error { + for { + items, err := s.panel.RuntimeEnvironments(ctx) + if err == nil { + for _, item := range items { + if item.Name == name && slices.Contains(item.Installed, version) { + return nil + } + } + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(10 * time.Second): + } + } +} +func (s *Projects) applyPHPPatch(ctx context.Context, job store.RuntimeJob, phase func(string) error) error { + agent, ok := s.isolation.(isolation.RuntimeMaintenance) + if !ok { + return errors.New("PHP maintenance agent unavailable") + } + adapter, ok := s.panel.(panel.RuntimeMaintenance) + if !ok { + return errors.New("PHP maintenance adapter unavailable") + } + branch := runtimeBranch("PHP", job.TargetVersion) + if err := phase("backing_up"); err != nil { + return err + } + snapshot, err := agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "backup"}) + if err != nil { + return err + } + data, _ := json.Marshal(snapshot) + if err = s.store.SaveRuntimeRollback(ctx, job.ID, string(data), true); err != nil { + return err + } + if err = phase("installing"); err != nil { + return err + } + pending, err := adapter.PHPRuntimeUpdatePending(ctx, branch) + if err != nil { + return err + } + current, err := agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, Action: "inspect"}) + if err != nil { + return err + } + if current.Version != job.TargetVersion && !pending { + if err = adapter.UpdatePHPRuntime(ctx, branch, job.TargetVersion); err != nil { + return s.interruptRuntimeJob(job, "补丁更新提交状态待确认:"+err.Error()) + } + } + // Allow the panel worker to pick up an acknowledged task before judging it + // complete. A brief empty response must never trigger a concurrent rollback. + idleSamples := 0 + for { + pending, err = adapter.PHPRuntimeUpdatePending(ctx, branch) + if err != nil { + return s.interruptRuntimeJob(job, "无法确认宝塔更新队列是否结束:"+err.Error()) + } + current, err = agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, Action: "inspect"}) + if !pending { + idleSamples++ + } else { + idleSamples = 0 + } + if idleSamples >= 3 { + break + } + select { + case <-ctx.Done(): + return s.interruptRuntimeJob(job, "更新任务仍在面板队列中,请恢复核验,避免与更新任务并发回滚") + case <-time.After(5 * time.Second): + } + } + if err == nil && current.Version != job.TargetVersion { + err = fmt.Errorf("更新后实际 PHP 版本为 %s,期望 %s", current.Version, job.TargetVersion) + } + if err == nil { + for _, extension := range snapshot.Extensions { + if !slices.Contains(current.Extensions, extension) { + err = fmt.Errorf("更新后缺少 PHP 扩展 %s", extension) + break + } + } + } + if err == nil { + if err = phase("restarting"); err == nil { + err = s.refreshPHPBranch(ctx, branch) + } + } + if err == nil { + _, _ = agent.MaintainPHP(ctx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "complete"}) + return nil + } + restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Minute) + defer cancel() + _ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "running", "rolling_back", err.Error()) + if _, restoreErr := agent.MaintainPHP(restoreCtx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "restore"}); restoreErr != nil { + return s.interruptRuntimeJob(job, fmt.Sprintf("更新失败:%v;恢复失败:%v", err, restoreErr)) + } + if restoreErr := s.refreshPHPBranch(restoreCtx, branch); restoreErr != nil { + return s.interruptRuntimeJob(job, "恢复后站点核验失败:"+restoreErr.Error()) + } + _ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "rolled_back", "rolled_back", "更新未通过验证,已恢复更新前环境:"+err.Error()) + _, _ = agent.MaintainPHP(restoreCtx, isolation.PHPMaintenanceSpec{Branch: branch, JobID: job.ID, Action: "complete"}) + return err +} +func (s *Projects) interruptRuntimeJob(job store.RuntimeJob, message string) error { + ctx, cancel := context.WithTimeout(scope.WithNode(context.Background(), job.NodeID), 10*time.Second) + defer cancel() + _ = s.store.UpdateRuntimeJob(ctx, job.ID, "interrupted", job.Phase, message) + return errors.New(message) +} +func (s *Projects) refreshPHPBranch(ctx context.Context, branch string) error { + targets, err := s.store.RuntimeTargets(ctx) + if err != nil { + return err + } + for _, target := range targets { + site := target.Site + if site.Runtime != "PHP" || site.Version != branch { + continue + } + if site.Status != "running" { + continue + } + if err = s.refreshPHPBranchSite(ctx, site.ID, target.Project.ID, branch); err != nil { + return err + } + } + return nil +} +func (s *Projects) refreshPHPBranchSite(ctx context.Context, siteID, projectID uint64, branch string) error { + // Only the short refresh of our private FPM pool needs a host lock. The + // panel's compilation/installation phase holds no tenant access locks. + hostGate := s.hostAccessGate(projectID) + hostGate.Lock() + defer hostGate.Unlock() + s.nodeGate(ctx).RLock() + defer s.nodeGate(ctx).RUnlock() + target, err := s.runtimeTarget(ctx, siteID) + if errors.Is(err, store.ErrNotFound) { + return nil + } + if err != nil { + return err + } + if target.Site.Runtime != "PHP" || target.Site.Version != branch || target.Site.Status != "running" { + return nil + } + spec, err := s.phpIdentitySpec(ctx, target.Project, target.Site) + if err != nil { + return err + } + if err = s.isolation.SetPHPIdentityState(ctx, spec, false); err != nil { + return err + } + if err = s.isolation.SetPHPIdentityState(ctx, spec, true); err != nil { + return err + } + return s.verifyRuntimeTarget(ctx, target) +} +func (s *Projects) runtimeProbeSpec(target store.RuntimeTarget) isolation.RuntimeProbeSpec { + return isolation.RuntimeProbeSpec{Project: isolation.ProjectSpec{TenantID: target.Site.TenantID, HostName: target.HostName, RunPath: target.Site.RunPath, StorageBytes: 1, ProcessLimit: uint32(target.Site.ProcessLimit)}, Runtime: target.Site.Runtime, Version: target.Site.Version, ProjectName: lifecycleSiteName(target.Project, target.Site), Running: target.Site.Status == "running"} +} +func (s *Projects) verifyRuntimeTarget(ctx context.Context, target store.RuntimeTarget) error { + ctx = scope.WithProject(ctx, target.Project.ID, target.Project.NodeID) + agent, ok := s.isolation.(isolation.RuntimeMaintenance) + if !ok { + return errors.New("runtime probe agent unavailable") + } + spec := s.runtimeProbeSpec(target) + if target.Site.Runtime != "PHP" { + adapter, ok := s.panel.(panel.RuntimeMaintenance) + if !ok { + return errors.New("runtime adapter unavailable") + } + runtime, err := adapter.ManagedRuntime(ctx, target.Site.PanelSiteID) + if err != nil { + return err + } + spec.EntryFile = runtime.EntryFile + } + observation, err := agent.ProbeRuntime(ctx, spec) + if err != nil { + _ = s.store.SaveRuntimeObservation(ctx, target.Site.ID, "", "", false, err.Error()) + return err + } + _ = s.store.SaveRuntimeObservation(ctx, target.Site.ID, observation.InstalledVersion, observation.RunningVersion, observation.Healthy, observation.Detail) + if spec.Running && !observation.Healthy { + return errors.New(observation.Detail) + } + return nil +} +func (s *Projects) migrateRuntimeSite(ctx context.Context, job store.RuntimeJob, phase func(string) error) error { + if job.SiteID == nil { + return errors.New("missing site") + } + target, err := s.runtimeTarget(ctx, *job.SiteID) + if err != nil { + return err + } + ctx = scope.WithProject(ctx, target.Project.ID, target.Project.NodeID) + if target.Site.Version != job.FromVersion && target.Site.Version != job.TargetVersion { + return errors.New("站点当前版本与迁移任务不一致") + } + agent, ok := s.isolation.(isolation.RuntimeMaintenance) + if !ok { + return errors.New("runtime migration agent unavailable") + } + adapter, ok := s.panel.(panel.RuntimeMaintenance) + if !ok { + return errors.New("runtime migration adapter unavailable") + } + if err = s.ensureTenantWritable(ctx, target.Site.TenantID); err != nil { + return err + } + oldSite := target.Site + probe := s.runtimeProbeSpec(target) + probe.Version = job.TargetVersion + probe.Running = false + var oldRuntime panel.RuntimeSpec + if target.Site.Runtime != "PHP" { + oldRuntime, err = adapter.ManagedRuntime(ctx, target.Site.PanelSiteID) + if err != nil { + return err + } + probe.EntryFile = oldRuntime.EntryFile + if target.Site.Runtime == "Go" { + probe.EntryFile = job.EntryFile + if probe.EntryFile == oldRuntime.EntryFile { + return errors.New("Go 更新必须使用独立的新程序文件,保留旧文件用于回退") + } + } + // Persist the original record before modifying the broker. + if job.RollbackData != "" { + if json.Unmarshal([]byte(job.RollbackData), &oldRuntime) != nil { + return errors.New("invalid persisted rollback record") + } + } + data, _ := json.Marshal(oldRuntime) + if err = s.store.SaveRuntimeRollback(ctx, job.ID, string(data), true); err != nil { + return err + } + } + if err = phase("preparing"); err != nil { + return err + } + if target.Site.Runtime == "Python" { + spec := isolation.PanelRuntimeSpec{Project: probe.Project, Runtime: "Python", Version: job.TargetVersion, ProjectName: probe.ProjectName} + if err = s.isolation.PreparePanelRuntime(ctx, spec); err != nil { + return err + } + if err = agent.CopyPythonDependencies(ctx, spec, job.FromVersion); err != nil { + return err + } + } + preflight, err := agent.ProbeRuntime(ctx, probe) + if err != nil { + return err + } + if target.Site.Runtime == "Go" && preflight.InstalledVersion != job.TargetVersion { + return errors.New("请先使用目标 Go SDK 重新编译并上传程序,再执行版本切换") + } + if target.Site.Runtime == "Go" { + if err = s.isolation.PrepareExecutable(ctx, isolation.ExecutableSpec{Project: probe.Project, RelativePath: path.Join(strings.TrimPrefix(target.Site.RunPath, "/"), job.EntryFile)}); err != nil { + return err + } + } + if err = phase("switching"); err != nil { + return err + } + apply := func(version string, rollback bool) error { + if target.Site.Runtime == "PHP" { + newSite := oldSite + newSite.Version = version + spec, e := s.phpIdentitySpec(ctx, target.Project, newSite) + if e != nil { + return e + } + if e = s.isolation.ConfigurePHPIdentity(ctx, spec); e != nil { + return e + } + if oldSite.Status == "stopped" { + return s.isolation.SetPHPIdentityState(ctx, spec, false) + } + return nil + } + next := oldRuntime + next.Version = version + if target.Site.Runtime == "Go" && !rollback { + next.EntryFile = job.EntryFile + } + current, lookupErr := adapter.ManagedRuntime(ctx, target.Site.PanelSiteID) + if lookupErr != nil { + return lookupErr + } + if stopErr := s.panel.SetRuntimeState(ctx, current, false); stopErr != nil { + // Some Python modules remove/stop only their launcher. Terminate + // residual processes only under this host UID and exact run tree. + if terminateErr := s.isolation.TerminateRuntime(ctx, isolation.RuntimeProcessSpec{Project: probe.Project}); terminateErr != nil { + return fmt.Errorf("停止迁移前进程失败: %v; %w", stopErr, terminateErr) + } + if stopErr = s.panel.SetRuntimeState(ctx, current, false); stopErr != nil { + return stopErr + } + } + if next.Runner { + if _, e := s.prepareSavedRunner(ctx, target.Project, target.Site, next.EntryFile, next.Version); e != nil { + return e + } + } + replaceErr := adapter.ReplaceManagedRuntime(ctx, target.Site.PanelSiteID, next) + // aaPanel project creation may recursively chown the directory to www, + // including when creation fails and the broker restores the old record. + if repairErr := s.restoreSiteIsolation(ctx, target.Project, target.Site.RunPath, target.Site.ProcessLimit); repairErr != nil { + return fmt.Errorf("恢复站点目录隔离失败: %w", repairErr) + } + if replaceErr != nil { + return replaceErr + } + if oldSite.Status == "stopped" { + return s.panel.SetRuntimeState(ctx, next, false) + } + return nil + } + err = apply(job.TargetVersion, false) + if err == nil { + err = phase("verifying") + } + if err == nil { + target.Site.Version = job.TargetVersion + err = s.verifyRuntimeTarget(ctx, target) + } + if err == nil && oldSite.Version != job.TargetVersion { + err = s.store.ChangeSiteRuntimeVersion(ctx, oldSite, job.TargetVersion) + } + if err == nil { + return nil + } + restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Minute) + defer cancel() + ctx = restoreCtx + if restoreErr := apply(job.FromVersion, true); restoreErr != nil { + return s.interruptRuntimeJob(job, fmt.Sprintf("切换失败:%v;旧版本恢复失败:%v", err, restoreErr)) + } + if oldSite.Version == job.TargetVersion && job.FromVersion != job.TargetVersion { + if restoreErr := s.store.ChangeSiteRuntimeVersion(restoreCtx, oldSite, job.FromVersion); restoreErr != nil { + return s.interruptRuntimeJob(job, "恢复旧版后保存版本记录失败:"+restoreErr.Error()) + } + } + target.Site = oldSite + target.Site.Version = job.FromVersion + if verifyErr := s.verifyRuntimeTarget(restoreCtx, target); verifyErr != nil { + return s.interruptRuntimeJob(job, "旧版本配置已恢复,但运行核验失败:"+verifyErr.Error()) + } + _ = s.store.UpdateRuntimeJob(restoreCtx, job.ID, "rolled_back", "rolled_back", "切换失败,已恢复旧版本:"+err.Error()) + return err +} +func (s *Projects) RunRuntimeUpdateChecks(ctx context.Context) { + runNode := func(ctx context.Context) { + if !s.nodeGate(ctx).TryRLock() { + return + } + defer s.nodeGate(ctx).RUnlock() + checkCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + if blocked, err := s.store.RuntimeMutationBlocked(checkCtx); err != nil || blocked { + return + } + if err := s.CheckRuntimeUpdates(checkCtx); err != nil { + slog.Warn("runtime update check failed", "error", err) + } + } + run := func() { + nodes, err := s.store.Nodes(ctx) + if err != nil { + return + } + for _, n := range nodes { + if n.Enabled { + runNode(scope.WithNode(ctx, n.ID)) + } + } + } + run() + ticker := time.NewTicker(6 * time.Hour) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + run() + } + } +} +func (s *Projects) CheckRuntimeUpdates(ctx context.Context) error { + if s.store != nil { + if _, err := s.ftpTLSPolicy(ctx); err != nil { + _ = s.store.EnqueueAdminNotification(context.WithoutCancel(ctx), "critical", "ftp", "节点 FTP 证书同步失败", fmt.Sprintf("节点 %d:%v", scope.Node(ctx), err)) + return err + } + } + if pruner, ok := s.isolation.(interface{ PruneRuntimeBackups(context.Context) error }); ok { + if err := pruner.PruneRuntimeBackups(ctx); err != nil { + return err + } + } + items, err := s.panel.RuntimeEnvironments(ctx) + if err != nil { + return err + } + for _, item := range items { + if item.Name == "PHP" { + for _, patch := range item.Patches { + if patch.UpdateAvailable { + _ = s.store.NotifyRuntimeRelease(ctx, "PHP/"+patch.Latest, "PHP 补丁更新可用", patch.Installed+" → "+patch.Latest+",请在环境配置中执行更新") + } + } + continue + } + for _, installed := range item.Installed { + latest := installed + for _, version := range item.Available { + if runtimeBranch(item.Name, installed) == runtimeBranch(item.Name, version) && runtimeVersionNewer(version, latest) { + latest = version + } + } + if latest != installed { + _ = s.store.NotifyRuntimeRelease(ctx, item.Name+"/"+latest, item.Name+" 更新可用", installed+" → "+latest+",安装后需要切换项目并验证生效") + } + } + } + targets, err := s.store.RuntimeTargets(ctx) + if err != nil { + return err + } + for _, target := range targets { + if target.Site.Status == "running" || target.Site.Status == "stopped" { + _ = s.verifyRuntimeTarget(ctx, target) + } + } + return nil +} diff --git a/backend/internal/service/runtime_maintenance_test.go b/backend/internal/service/runtime_maintenance_test.go new file mode 100644 index 0000000..0b56af7 --- /dev/null +++ b/backend/internal/service/runtime_maintenance_test.go @@ -0,0 +1,17 @@ +package service + +import "testing" + +func TestPatchBranchesNeverImplicitlyCrossLanguageBranches(t *testing.T) { + for _, test := range []struct{ name, version, branch string }{ + {"PHP", "8.4.27", "8.4"}, {"Python", "3.12.15", "3.12"}, {"Python", "3.13.17", "3.13"}, + {"Node.js", "v24.22.1", "24"}, {"Java", "jdk-21.0.9", "21"}, {"Go", "go1.27.3", "1.27"}, + } { + if got := runtimeBranch(test.name, test.version); got != test.branch { + t.Fatalf("%s %s branch=%s", test.name, test.version, got) + } + } + if !runtimeVersionNewer("3.12.15", "3.12.9") || runtimeVersionNewer("go1.27.1", "go1.27.3") { + t.Fatal("patch versions were compared lexically") + } +} diff --git a/backend/internal/service/scheduler_bridge.go b/backend/internal/service/scheduler_bridge.go new file mode 100644 index 0000000..a2392e2 --- /dev/null +++ b/backend/internal/service/scheduler_bridge.go @@ -0,0 +1,34 @@ +package service + +import ( + "context" + "errors" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/schedulerbridge" + "sea-vhost/internal/scope" +) + +func (s *Projects) ConfigureSystemScheduler(ctx context.Context, v schedulerbridge.Config) error { + if e := v.Validate(); e != nil { + return e + } + node, e := s.store.Node(ctx, v.NodeID) + if e != nil || !node.Enabled { + return errors.New("节点不可用") + } + ctx = scope.WithNode(ctx, v.NodeID) + agent, ok := s.isolation.(isolation.SchedulerBridge) + if !ok { + return errors.New("节点未支持调度触发器") + } + native, ok := s.panel.(panel.SystemScheduler) + if !ok { + return errors.New("宝塔代理未支持系统计划任务") + } + if e = agent.ConfigureSchedulerBridge(ctx, v); e != nil { + return e + } + _, e = native.EnsureSystemScheduler(ctx) + return e +} diff --git a/backend/internal/service/site_runtime.go b/backend/internal/service/site_runtime.go new file mode 100644 index 0000000..ba15e41 --- /dev/null +++ b/backend/internal/service/site_runtime.go @@ -0,0 +1,138 @@ +package service + +import ( + "context" + "errors" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +func (s *Projects) SubmitSiteRuntime(ctx context.Context, u store.User, projectID, siteID uint64, runtime, version, entry string) (uint64, error) { + p, err := s.authorizedProject(ctx, u, projectID) + if err != nil { + return 0, err + } + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + site, err := s.store.Site(ctx, p.TenantID, p.ID, siteID) + if err != nil { + return 0, err + } + if runtime != site.Runtime && !p.AllowRuntimeChange { + return 0, errors.New("管理员未允许此主机切换运行环境") + } + if err = s.ensureTenantWritable(ctx, p.TenantID); err != nil { + return 0, err + } + if err = s.validateRuntime(ctx, runtime, version); err != nil { + return 0, err + } + if site.Status != "running" && site.Status != "stopped" && site.Status != "awaiting_upload" { + return 0, errors.New("当前状态不能切换运行环境") + } + if site.Runtime == runtime && site.Version == version && (runtime != "Go" || site.Status == "awaiting_upload") { + return 0, errors.New("网站已使用此版本") + } + if runtime == "Go" && site.Runtime == "Go" && site.Status != "awaiting_upload" { + if entry == "" { + return 0, errors.New("请上传目标 Go SDK 编译的新程序,并填写独立程序文件名") + } + entry, err = normalizeDeploymentEntry("Go", entry) + if err != nil { + return 0, err + } + } + ownershipVersion, err := s.store.HostOwnershipVersion(ctx, p.ID) + if err != nil { + return 0, err + } + return s.store.CreateRuntimeJob(ctx, store.RuntimeJob{OwnershipVersion: &ownershipVersion, Action: "runtime_change", Runtime: runtime, FromVersion: site.Version, TargetVersion: version, EntryFile: entry, SiteID: &siteID}) +} +func (s *Projects) changeRuntimeSite(ctx context.Context, job store.RuntimeJob, phase func(string) error) error { + if job.SiteID == nil { + return errors.New("missing site") + } + t, err := s.runtimeTarget(ctx, *job.SiteID) + if err != nil { + return err + } + ctx = scope.WithProject(ctx, t.Project.ID, t.Project.NodeID) + ownershipVersion, err := s.store.HostOwnershipVersion(ctx, t.Project.ID) + if err != nil { + return err + } + if job.OwnershipVersion != nil && ownershipVersion != *job.OwnershipVersion { + return errors.New("主机归属已变更,原运行环境任务已取消,请由当前管理者重新提交") + } + p, err := s.store.Project(ctx, t.Site.TenantID, t.Project.ID) + if err != nil { + return err + } + u := store.User{Role: "host", TenantID: &p.TenantID, ProjectID: &p.ID} + if _, err = s.authorizedProject(ctx, u, p.ID); err != nil { + return err + } + if err = s.ensureTenantWritable(ctx, p.TenantID); err != nil { + return err + } + if t.Site.Runtime == job.Runtime && t.Site.Version == job.TargetVersion && job.Runtime != "Go" { + return nil + } + if t.Site.Runtime != job.Runtime && !p.AllowRuntimeChange { + return errors.New("此主机的跨语言切换权限已撤销") + } + if err = s.validateRuntime(ctx, job.Runtime, job.TargetVersion); err != nil { + return err + } + if err = phase("switching"); err != nil { + return err + } + if t.Site.Status == "running" { + t.Site, err = s.SetSiteState(ctx, u, p.ID, t.Site.ID, false) + if err != nil { + return err + } + } + if t.Site.Runtime == job.Runtime && t.Site.Status != "awaiting_upload" { + // The existing migration path verifies the new runtime and retains rollback data. + return s.migrateRuntimeSite(ctx, job, phase) + } + if t.Site.Runtime == "PHP" { + spec, e := s.phpIdentitySpec(ctx, p, t.Site) + if e != nil { + return e + } + if e = s.isolation.RemovePHPIdentity(ctx, spec); e != nil { + return s.interruptRuntimeJob(job, e.Error()) + } + } else if t.Site.Status != "awaiting_upload" { + adapter, ok := s.panel.(panel.RuntimeResetter) + if !ok { + return errors.New("运行环境适配器不支持安全重置") + } + if err = adapter.ResetManagedRuntime(ctx, t.Site.PanelSiteID, t.Site.Domain); err != nil { + return s.interruptRuntimeJob(job, err.Error()) + } + } + next := t.Site + next.Runtime = job.Runtime + next.Version = job.TargetVersion + status := "awaiting_upload" + if next.Runtime == "PHP" { + spec, e := s.phpIdentitySpec(ctx, p, next) + if e != nil { + return s.interruptRuntimeJob(job, e.Error()) + } + if e = s.isolation.ConfigurePHPIdentity(ctx, spec); e != nil { + return s.interruptRuntimeJob(job, e.Error()) + } + if e = s.isolation.SetPHPIdentityState(ctx, spec, false); e != nil { + return s.interruptRuntimeJob(job, e.Error()) + } + status = "stopped" + } + if err = s.store.ChangeSiteLanguage(ctx, t.Site, next.Runtime, next.Version, status); err != nil { + return s.interruptRuntimeJob(job, err.Error()) + } + return nil +} diff --git a/backend/internal/service/site_settings.go b/backend/internal/service/site_settings.go new file mode 100644 index 0000000..f4f6e73 --- /dev/null +++ b/backend/internal/service/site_settings.go @@ -0,0 +1,81 @@ +package service + +import ( + "context" + "errors" + "sea-vhost/internal/hosting" + "sea-vhost/internal/isolation" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +func (s *Projects) WebsiteSettings(ctx context.Context, user store.User, projectID, siteID uint64) (hosting.WebsiteSettings, error) { + p, e := s.authorizedProject(ctx, user, projectID) + if e != nil { + return hosting.WebsiteSettings{}, e + } + if _, e = s.store.Site(ctx, p.TenantID, p.ID, siteID); e != nil { + return hosting.WebsiteSettings{}, e + } + return s.store.WebsiteSettings(ctx, siteID) +} +func (s *Projects) SetWebsiteSettings(ctx context.Context, user store.User, projectID, siteID uint64, v hosting.WebsiteSettings) error { + if e := v.Validate(); e != nil { + return e + } + p, e := s.authorizedProject(ctx, user, projectID) + if e != nil { + return e + } + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil { + return e + } + site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID) + if e != nil { + return e + } + if v.ForceHTTPS && site.SSLStatus != "active" { + return errors.New("请先安装有效 SSL 证书") + } + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return e + } + manager, ok := s.isolation.(isolation.SiteOperations) + if !ok { + return errors.New("节点暂不支持网站设置") + } + old, e := s.store.WebsiteSettings(ctx, siteID) + if e != nil { + return e + } + spec := isolation.WebsiteSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Domain: site.Domain, Runtime: site.Runtime, Settings: v} + if e = manager.ConfigureWebsite(ctx, spec); e != nil { + return e + } + if e = s.store.SaveWebsiteSettings(ctx, siteID, v); e != nil { + spec.Settings = old + _ = manager.ConfigureWebsite(context.WithoutCancel(ctx), spec) + } + return e +} +func (s *Projects) SiteLog(ctx context.Context, user store.User, projectID, siteID uint64, kind, search string, lines int) (isolation.SiteLog, error) { + p, e := s.authorizedProject(ctx, user, projectID) + if e != nil { + return isolation.SiteLog{}, e + } + site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID) + if e != nil { + return isolation.SiteLog{}, e + } + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return isolation.SiteLog{}, e + } + manager, ok := s.isolation.(isolation.SiteOperations) + if !ok { + return isolation.SiteLog{}, errors.New("节点暂不支持日志查看") + } + return manager.ReadSiteLog(ctx, isolation.SiteLogSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Domain: site.Domain, Kind: kind, Search: search, Lines: lines}) +} diff --git a/backend/internal/service/startup.go b/backend/internal/service/startup.go new file mode 100644 index 0000000..bb07c3e --- /dev/null +++ b/backend/internal/service/startup.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "sea-vhost/internal/hosting" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "time" +) + +func (s *Projects) loadStartup(ctx context.Context, site store.Site) (hosting.Startup, error) { + v := hosting.Startup{WorkDir: ".", Arguments: []string{}, Environment: map[string]string{}} + raw, e := s.store.StartupCipher(ctx, site.ID) + if e != nil { + return v, e + } + if len(raw) > 0 { + plain, e := s.credentials.Open(fmt.Sprintf("site-startup:%d", site.ID), raw) + if e != nil { + return v, e + } + e = json.Unmarshal([]byte(plain), &v) + if e != nil { + return v, e + } + if site.Runtime != "PHP" { + if manager, ok := s.panel.(panel.RuntimeMaintenance); ok { + if runtime, e := manager.ManagedRuntime(ctx, site.PanelSiteID); e == nil { + v.EntryFile = runtime.EntryFile + } + } + } + return v, nil + } + if site.Runtime != "PHP" { + if manager, ok := s.panel.(panel.RuntimeMaintenance); ok { + if runtime, e := manager.ManagedRuntime(ctx, site.PanelSiteID); e == nil { + v.EntryFile = runtime.EntryFile + } + } + } + return v, nil +} +func (s *Projects) prepareSavedRunner(ctx context.Context, p store.Project, site store.Site, entry, version string) (bool, error) { + cipher, e := s.store.StartupCipher(ctx, site.ID) + if e != nil || len(cipher) == 0 { + return false, e + } + v, e := s.loadStartup(ctx, site) + if e != nil { + return false, e + } + v.EntryFile = entry + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return false, e + } + manager, ok := s.isolation.(isolation.StartupManager) + if !ok { + return false, errors.New("节点不支持应用启动器") + } + e = manager.ConfigureStartup(ctx, isolation.StartupSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Runtime: site.Runtime, Version: version, Port: site.BackendPort, Config: v}) + return e == nil, e +} +func (s *Projects) Startup(ctx context.Context, user store.User, projectID, siteID uint64) (hosting.Startup, error) { + p, e := s.authorizedProject(ctx, user, projectID) + if e != nil { + return hosting.Startup{}, e + } + site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID) + if e != nil { + return hosting.Startup{}, e + } + return s.loadStartup(ctx, site) +} +func (s *Projects) SetStartup(ctx context.Context, user store.User, projectID, siteID uint64, v hosting.Startup) error { + if e := v.Validate(); e != nil { + return e + } + p, e := s.authorizedProject(ctx, user, projectID) + if e != nil { + return e + } + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil { + return e + } + site, e := s.store.Site(ctx, p.TenantID, p.ID, siteID) + if e != nil { + return e + } + if site.Runtime == "PHP" && (v.EntryFile != "" || len(v.Arguments) > 0 || v.WorkDir != ".") { + return errors.New("PHP 使用网站运行目录,仅需配置环境变量") + } + if site.Runtime != "PHP" { + entry, e := normalizeDeploymentEntry(site.Runtime, v.EntryFile) + if e != nil { + return e + } + v.EntryFile = entry + } + old, e := s.loadStartup(ctx, site) + if e != nil { + return e + } + manager, ok := s.isolation.(isolation.StartupManager) + if !ok { + return errors.New("节点暂不支持启动配置") + } + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return e + } + spec := isolation.StartupSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Runtime: site.Runtime, Version: site.Version, Port: site.BackendPort, Config: v} + if site.Runtime != "PHP" && site.Status == "awaiting_upload" { + raw, _ := json.Marshal(v) + cipher, e := s.credentials.Seal(fmt.Sprintf("site-startup:%d", site.ID), string(raw)) + if e != nil { + return e + } + return s.store.SaveStartupCipher(ctx, site.ID, cipher) + } + if e = manager.ConfigureStartup(ctx, spec); e != nil { + return e + } + var restoreRuntime func(context.Context) error + restore := func() error { + rollback, cancel := context.WithTimeout(context.WithoutCancel(ctx), 60*time.Second) + defer cancel() + spec.Config = old + err := manager.ConfigureStartup(rollback, spec) + if restoreRuntime != nil { + err = errors.Join(err, restoreRuntime(rollback)) + } + return err + } + if site.Runtime == "PHP" { + identity, e := s.phpIdentitySpec(ctx, p, site) + if e != nil { + restore() + return e + } + restoreRuntime = func(rollback context.Context) error { + err := s.isolation.ConfigurePHPIdentity(rollback, identity) + if site.Status != "running" { + err = errors.Join(err, s.isolation.SetPHPIdentityState(rollback, identity, false)) + } + return err + } + if e = s.isolation.ConfigurePHPIdentity(ctx, identity); e != nil { + restore() + return e + } + if site.Status != "running" { + if e = s.isolation.SetPHPIdentityState(ctx, identity, false); e != nil { + return errors.Join(e, restore()) + } + } + } else { + adapter, ok := s.panel.(panel.RuntimeMaintenance) + if !ok { + restore() + return errors.New("面板暂不支持启动配置替换") + } + runtime, e := adapter.ManagedRuntime(ctx, site.PanelSiteID) + if e != nil { + restore() + return e + } + next := runtime + restoreRuntime = func(rollback context.Context) error { + err := adapter.ReplaceManagedRuntime(rollback, site.PanelSiteID, runtime) + if site.Status != "running" { + err = errors.Join(err, s.panel.SetSiteState(rollback, site.PanelSiteID, site.Domain, false)) + } + return err + } + next.Runner = true + next.EntryFile = v.EntryFile + if e = adapter.ReplaceManagedRuntime(ctx, site.PanelSiteID, next); e != nil { + restore() + return e + } + if site.Status != "running" { + if e = s.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false); e != nil { + return errors.Join(e, restore()) + } + } + } + raw, _ := json.Marshal(v) + cipher, e := s.credentials.Seal(fmt.Sprintf("site-startup:%d", site.ID), string(raw)) + if e != nil { + return errors.Join(e, restore()) + } + if e = s.store.SaveStartupCipher(ctx, site.ID, cipher); e != nil { + return errors.Join(e, restore()) + } + return nil +} diff --git a/backend/internal/service/storage_quota.go b/backend/internal/service/storage_quota.go new file mode 100644 index 0000000..013e14d --- /dev/null +++ b/backend/internal/service/storage_quota.go @@ -0,0 +1,270 @@ +package service + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math" + "path/filepath" + "strings" + "sync" + "time" + + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" +) + +var ErrStorageQuotaExceeded = errors.New("storage quota exceeded") + +type StorageQuota struct { + store *store.Store + panel panel.Interface + isolation isolation.Interface + mu sync.Mutex +} + +func NewStorageQuota(database *store.Store, panelClient panel.Interface, isolator isolation.Interface, _ string) *StorageQuota { + return &StorageQuota{store: database, panel: panelClient, isolation: isolator} +} + +// CheckWrite performs a fresh tenant-wide scan before a Web file write. This +// is deliberately conservative: concurrent runtime writes can still create a +// temporary overage, which the background monitor suspends on its next run. +func (q *StorageQuota) CheckWrite(ctx context.Context, tenantID, additionalBytes uint64) error { + used, limit, refreshErr := q.refreshTenant(ctx, tenantID) + suspended, reason, stateErr := q.store.TenantQuotaSuspension(ctx, tenantID) + if stateErr != nil { + return stateErr + } + if suspended { + return fmt.Errorf("%w: %s", ErrQuotaSuspended, reason) + } + if refreshErr != nil { + return refreshErr + } + if used > limit || additionalBytes > limit-used { + return ErrStorageQuotaExceeded + } + return nil +} + +func (q *StorageQuota) Run(ctx context.Context, interval time.Duration) { + if interval <= 0 { + interval = time.Minute + } + q.refreshAll(ctx) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + q.refreshAll(ctx) + } + } +} + +func (q *StorageQuota) refreshAll(ctx context.Context) { + _ = q.store.PruneHostMetrics(ctx) + hosts, err := q.store.AllProjects(ctx) + if err != nil { + slog.Error("storage quota tenant listing failed", "error", err) + return + } + for _, host := range hosts { + if host.Status == "failed" || host.Status == "provisioning" { + continue + } + if _, _, err = q.refreshTenant(scope.WithProject(ctx, host.ID, host.NodeID), host.TenantID); err != nil && !errors.Is(err, store.ErrNotFound) { + slog.Error("storage quota refresh failed", "project_id", host.ID, "error", err) + } + } +} + +func (q *StorageQuota) refreshTenant(ctx context.Context, tenantID uint64) (uint64, uint64, error) { + if err := q.store.HostWritable(ctx, tenantID); err != nil { + return 0, 0, err + } + if scope.Project(ctx) == 0 { + return 0, 0, errors.New("host scope required for quota enforcement") + } + q.mu.Lock() + defer q.mu.Unlock() + projects, err := q.store.ListProjects(ctx, tenantID) + if err != nil { + return 0, 0, err + } + var used uint64 + plan, _, err := q.store.PlanAndUsage(ctx, tenantID) + if err != nil { + return 0, 0, err + } + sites, err := q.store.ListTenantSites(ctx, tenantID, nil) + if err != nil { + return used, plan.StorageBytes, err + } + databaseResources, err := q.store.ListDatabaseResources(ctx, tenantID, nil) + if err != nil { + return used, plan.StorageBytes, err + } + ftpResources, err := q.store.ListFTPResources(ctx, tenantID, nil) + if err != nil { + return used, plan.StorageBytes, err + } + databaseSizes := make(map[uint64]uint64, len(databaseResources)) + var databaseBytes uint64 + for _, database := range databaseResources { + if database.PanelID <= 0 { + return used, plan.StorageBytes, errors.New("managed database is missing its panel id") + } + size, sizeErr := q.panel.DatabaseSize(ctx, database.PanelID, database.Name) + if sizeErr != nil { + return used, plan.StorageBytes, fmt.Errorf("measure database %s: %w", database.Name, sizeErr) + } + if size > math.MaxUint64-databaseBytes { + return used, plan.StorageBytes, errors.New("database usage overflow") + } + databaseBytes += size + databaseSizes[database.ID] = size + } + domainsByProject := make(map[uint64][]string, len(projects)) + for _, site := range sites { + domainsByProject[site.ProjectID] = append(domainsByProject[site.ProjectID], site.Domain) + } + for _, project := range projects { + if err = q.isolation.ConfigureTrafficLimits(ctx, isolation.TrafficLimitSpec{Project: isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}, Domains: domainsByProject[project.ID], Mbps: plan.BandwidthMbps}); err != nil { + return used, plan.StorageBytes, fmt.Errorf("enforce traffic policy: %w", err) + } + } + var bandwidthBytes uint64 + var processCount uint32 + for _, project := range projects { + resourceUsage, usageErr := q.isolation.ResourceUsage(ctx, isolation.ResourceUsageSpec{ + Project: isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)}, + Domains: domainsByProject[project.ID], + }) + if usageErr != nil { + return used, plan.StorageBytes, fmt.Errorf("measure host %s resources: %w", project.HostName, usageErr) + } + if resourceUsage.StorageBytes > math.MaxUint64-used || resourceUsage.BandwidthBytes > math.MaxUint64-bandwidthBytes || resourceUsage.ProcessCount > math.MaxUint32-processCount { + return used, plan.StorageBytes, errors.New("resource usage overflow") + } + var projectDatabase uint64 + for _, database := range databaseResources { + if database.ProjectID == project.ID { + projectDatabase += databaseSizes[database.ID] + } + } + _ = q.store.RecordHostMetric(ctx, project.ID, store.HostMetric{CPUTicks: resourceUsage.CPUTicks, MemoryBytes: resourceUsage.MemoryBytes, ProcessCount: resourceUsage.ProcessCount, StorageBytes: resourceUsage.StorageBytes, DatabaseBytes: projectDatabase, BandwidthBytes: resourceUsage.BandwidthBytes}) + used += resourceUsage.StorageBytes + bandwidthBytes += resourceUsage.BandwidthBytes + processCount += resourceUsage.ProcessCount + } + databaseOver := databaseBytes >= plan.DatabaseBytes + for _, database := range databaseResources { + var owner *store.Project + for i := range projects { + if projects[i].ID == database.ProjectID { + owner = &projects[i] + break + } + } + if owner == nil || database.Name != owner.HostName || database.Username != owner.HostName { + return used, plan.StorageBytes, errors.New("inconsistent database owner") + } + if err = q.isolation.ConfigureDatabaseAccess(ctx, isolation.DatabaseAccessSpec{Project: isolation.ProjectSpec{TenantID: tenantID, HostName: owner.HostName, RunPath: owner.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(owner.ProcessLimit)}, Database: database.Name, ReadOnly: databaseOver}); err != nil { + return used, plan.StorageBytes, fmt.Errorf("enforce database quota: %w", err) + } + } + usage := store.Usage{StorageBytes: used, DatabaseBytes: databaseBytes, BandwidthBytes: bandwidthBytes, ProcessCount: processCount} + now := time.Now() + periodStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()) + if err = q.store.UpdateQuotaMeasurement(ctx, tenantID, usage, periodStart, databaseSizes, databaseOver); err != nil { + return used, plan.StorageBytes, err + } + reasons := make([]string, 0, 4) + if used > plan.StorageBytes { + reasons = append(reasons, "storage quota exceeded") + } + if databaseOver { + reasons = append(reasons, "database quota exceeded") + } + if bandwidthBytes >= plan.BandwidthBytes { + reasons = append(reasons, "bandwidth quota exceeded") + } + if processCount > plan.ProcessLimit { + reasons = append(reasons, "process quota exceeded") + } + wasSuspended := false + for _, project := range projects { + wasSuspended = wasSuspended || project.Status == "quota_suspended" + } + if len(reasons) > 0 { + if err = q.store.SetTenantQuotaSuspended(ctx, tenantID, strings.Join(reasons, ", ")); err != nil { + return used, plan.StorageBytes, err + } + if !wasSuspended { + _ = q.store.EnqueueAdminNotification(context.WithoutCancel(ctx), "critical", "quota", "虚拟主机资源超限", fmt.Sprintf("用户 %d 已暂停:%s", tenantID, strings.Join(reasons, ", "))) + } + var stopErrors []error + for _, site := range sites { + if site.PanelSiteID <= 0 || (site.Status != "running" && site.Status != "quota_suspended") { + continue + } + if stopErr := q.panel.SetSiteState(ctx, site.PanelSiteID, site.Domain, false); stopErr != nil { + stopErrors = append(stopErrors, fmt.Errorf("stop site %d: %w", site.ID, stopErr)) + } + } + for _, ftp := range ftpResources { + if ftp.PanelID > 0 { + if stopErr := q.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, false); stopErr != nil { + stopErrors = append(stopErrors, fmt.Errorf("disable FTP %s: %w", ftp.Username, stopErr)) + } + } + } + for _, project := range projects { + spec := isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)} + if stopErr := q.isolation.TerminateProcesses(ctx, spec); stopErr != nil { + stopErrors = append(stopErrors, fmt.Errorf("terminate host %s processes: %w", project.HostName, stopErr)) + } + if freezeErr := q.isolation.FreezeWrites(ctx, spec); freezeErr != nil { + stopErrors = append(stopErrors, fmt.Errorf("freeze host %s writes: %w", project.HostName, freezeErr)) + } + } + return used, plan.StorageBytes, errors.Join(stopErrors...) + } + if wasSuspended { + var enableErrors []error + for _, project := range projects { + spec := isolation.ProjectSpec{TenantID: tenantID, HostName: project.HostName, RunPath: project.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(project.ProcessLimit)} + prepared, prepareErr := q.isolation.Prepare(ctx, spec) + if prepareErr != nil || filepath.Clean(prepared.RootPath) != filepath.Clean(project.Path) || prepared.RunUser != project.HostName { + if prepareErr == nil { + prepareErr = errors.New("isolation agent returned an inconsistent host identity") + } + enableErrors = append(enableErrors, fmt.Errorf("restore host %s writes: %w", project.HostName, prepareErr)) + } + } + if err = errors.Join(enableErrors...); err != nil { + return used, plan.StorageBytes, err + } + for _, ftp := range ftpResources { + if ftp.PanelID > 0 && ftp.Enabled { + if enableErr := q.panel.SetFTPState(ctx, ftp.PanelID, ftp.Username, true); enableErr != nil { + enableErrors = append(enableErrors, fmt.Errorf("enable FTP %s: %w", ftp.Username, enableErr)) + } + } + } + if err = errors.Join(enableErrors...); err != nil { + return used, plan.StorageBytes, err + } + if err = q.store.ClearTenantStorageSuspension(ctx, tenantID); err != nil { + return used, plan.StorageBytes, err + } + } + return used, plan.StorageBytes, nil +} diff --git a/backend/internal/service/user_schedules.go b/backend/internal/service/user_schedules.go new file mode 100644 index 0000000..5f74a0b --- /dev/null +++ b/backend/internal/service/user_schedules.go @@ -0,0 +1,284 @@ +package service + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/url" + "sea-vhost/internal/hosting" + "sea-vhost/internal/isolation" + "sea-vhost/internal/scope" + "sea-vhost/internal/store" + "strings" + "sync" + "time" +) + +type scheduleConfig struct { + Target string `json:"target"` + Arguments []string `json:"arguments"` +} + +func (s *Projects) openSchedule(v *store.UserSchedule) error { + plain, e := s.credentials.Open("user-schedule:"+v.SecretRef, v.ConfigCipher) + if e != nil { + return e + } + var cfg scheduleConfig + if e = json.Unmarshal([]byte(plain), &cfg); e != nil { + return e + } + v.Target = cfg.Target + v.Arguments = cfg.Arguments + return nil +} +func (s *Projects) UserSchedules(ctx context.Context, u store.User) ([]store.UserSchedule, error) { + if u.Role != "tenant" || u.TenantID == nil { + return nil, store.ErrNotFound + } + rows, e := s.store.UserSchedules(ctx, u.ID) + if e != nil { + return nil, e + } + for i := range rows { + if e = s.openSchedule(&rows[i]); e != nil { + return nil, e + } + } + return rows, nil +} +func (s *Projects) SaveUserSchedule(ctx context.Context, u store.User, v store.UserSchedule) (uint64, error) { + if u.Role != "tenant" || u.TenantID == nil { + return 0, store.ErrNotFound + } + if len(strings.TrimSpace(v.Name)) < 1 || len(v.Name) > 120 { + return 0, errors.New("请输入不超过 120 字节的任务名称") + } + if len(v.Cron) > 120 || len(v.Timezone) > 80 { + return 0, errors.New("计划表达式或时区过长") + } + if v.Timezone == "" { + v.Timezone = "Asia/Shanghai" + } + cron, e := hosting.ParseCron(v.Cron, v.Timezone) + if e != nil { + return 0, e + } + next, e := cron.Next(time.Now()) + if e != nil { + return 0, e + } + ctx = scope.WithAccount(ctx, *u.TenantID) + p, e := s.store.ProjectForUser(ctx, u, v.ProjectID) + if e != nil { + return 0, e + } + release, e := s.BeginHostAccess(p.ID) + if e != nil { + return 0, e + } + defer release() + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil { + return 0, e + } + site, e := s.store.Site(ctx, p.TenantID, p.ID, v.SiteID) + if e != nil { + return 0, store.ErrNotFound + } + params := hosting.Startup{Arguments: v.Arguments} + if e = params.Validate(); e != nil { + return 0, e + } + if len(v.Target) > 512 { + return 0, errors.New("任务路径过长") + } + if v.Kind == "url" { + uri, err := url.ParseRequestURI(v.Target) + if err != nil || uri.IsAbs() || uri.Host != "" || !strings.HasPrefix(v.Target, "/") || strings.HasPrefix(v.Target, "//") || len(v.Arguments) > 0 { + return 0, errors.New("URL 仅支持本站以 / 开头的路径,不能附带启动参数") + } + v.Version = "" + if v.UseHTTPS && site.SSLStatus != "active" { + return 0, errors.New("网站尚未启用 HTTPS") + } + } else { + runtime := map[string]string{"php": "PHP", "python": "Python", "node": "Node.js"}[v.Kind] + if runtime == "" || !hosting.ValidRelative(v.Target) { + return 0, errors.New("请选择 PHP、Python、Node 脚本或本站 URL") + } + if e = s.validateRuntime(ctx, runtime, v.Version); e != nil { + return 0, e + } + v.UseHTTPS = false + } + v.OwnershipVersion, e = s.store.ProjectOwnershipVersion(ctx, p.ID) + if e != nil { + return 0, e + } + v.UserID = u.ID + v.AccountID = *u.TenantID + v.NextRunAt = next + token := make([]byte, 16) + if _, e = rand.Read(token); e != nil { + return 0, e + } + v.SecretRef = hex.EncodeToString(token) + plain, _ := json.Marshal(scheduleConfig{v.Target, v.Arguments}) + v.ConfigCipher, e = s.credentials.Seal("user-schedule:"+v.SecretRef, string(plain)) + if e != nil { + return 0, e + } + v.Target = "" + v.Arguments = []string{} + return s.store.SaveUserSchedule(ctx, v) +} +func (s *Projects) ScheduleRuns(ctx context.Context, u store.User, id uint64) ([]store.ScheduleRun, error) { + if u.Role != "tenant" || u.TenantID == nil { + return nil, store.ErrNotFound + } + if _, e := s.store.UserSchedule(ctx, u.ID, id); e != nil { + return nil, e + } + rows, e := s.store.ScheduleRuns(ctx, u.ID, id) + if e != nil { + return nil, e + } + for i := range rows { + if len(rows[i].OutputCipher) > 0 { + rows[i].Output, e = s.credentials.Open(fmt.Sprintf("schedule-run:%d", rows[i].ID), rows[i].OutputCipher) + if e != nil { + return nil, e + } + } + } + return rows, nil +} + +// Called only by the authenticated controller tick sent by the panel's cron. +func (s *Projects) DispatchUserSchedules(ctx context.Context) error { + return s.dispatchUserSchedules(ctx, true) +} +func (s *Projects) QueueUserSchedules(ctx context.Context) error { + return s.dispatchUserSchedules(ctx, false) +} +func (s *Projects) dispatchUserSchedules(ctx context.Context, wait bool) error { + rows, e := s.store.DueSchedules(ctx) + if e != nil { + return e + } + s.scheduleInit.Do(func() { s.scheduleSlots = make(chan struct{}, 4) }) + var wg sync.WaitGroup + for _, v := range rows { + select { + case s.scheduleSlots <- struct{}{}: + default: + continue + } + wg.Add(1) + go func(v store.UserSchedule) { + defer wg.Done() + defer func() { <-s.scheduleSlots }() + task, cancel := context.WithTimeout(context.WithoutCancel(ctx), 310*time.Second) + defer cancel() + s.executeUserSchedule(task, v) + }(v) + } + if wait { + wg.Wait() + } + return s.store.PruneSchedules(ctx) +} +func (s *Projects) executeUserSchedule(ctx context.Context, v store.UserSchedule) { + cron, e := hosting.ParseCron(v.Cron, v.Timezone) + if e != nil { + return + } + next, e := cron.Next(time.Now()) + if e != nil { + return + } + u, e := s.store.UserByID(ctx, v.UserID) + if e != nil || u.Role != "tenant" || u.TenantID == nil || *u.TenantID != v.AccountID { + return + } + ctx = scope.WithAccount(ctx, v.AccountID) + p, e := s.store.ProjectForUser(ctx, u, v.ProjectID) + if e != nil { + return + } + ctx = scope.WithProject(ctx, p.ID, p.NodeID) + release, e := s.BeginHostAccess(p.ID) + if e != nil { + return + } + defer release() + nodeRelease, e := s.BeginRuntimeMutation(ctx) + if e != nil { + return + } + defer nodeRelease() + run, e := s.store.ClaimSchedule(ctx, v.ID, next, v.SecretRef) + if e != nil || run == 0 { + return + } + code := 1 + output := "计划任务未执行" + state := "failed" + defer func() { + cipher, sealErr := s.credentials.Seal(fmt.Sprintf("schedule-run:%d", run), output) + if sealErr != nil { + cipher = nil + } + done, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + _ = s.store.FinishSchedule(done, v.ID, run, state, code, cipher) + s.store.Log(done, &p.TenantID, u.ID, "execute", "schedule", fmt.Sprint(v.ID), "", state == "succeeded", "执行用户计划任务:"+v.Name) + }() + if e = s.openSchedule(&v); e != nil { + return + } + if e = s.ensureTenantWritable(ctx, p.TenantID); e != nil { + output = e.Error() + return + } + site, e := s.store.Site(ctx, p.TenantID, p.ID, v.SiteID) + if e != nil { + return + } + plan, _, e := s.store.PlanAndUsage(ctx, p.TenantID) + if e != nil { + return + } + env, e := s.loadStartup(ctx, site) + if e != nil { + return + } + port, e := s.store.ScheduleSitePort(ctx, site.ID, v.UseHTTPS) + if e != nil { + return + } + executor, ok := s.isolation.(isolation.ScheduleExecutor) + if !ok { + output = "节点不支持计划任务" + return + } + task, cancel := context.WithTimeout(ctx, 300*time.Second) + defer cancel() + result, e := executor.ExecuteSchedule(task, isolation.ScheduleExecutionSpec{Project: isolation.ProjectSpec{TenantID: p.TenantID, HostName: p.HostName, RunPath: site.RunPath, StorageBytes: plan.StorageBytes, ProcessLimit: uint32(site.ProcessLimit)}, SiteName: lifecycleSiteName(p, site), Kind: v.Kind, Version: v.Version, Target: v.Target, Arguments: v.Arguments, Environment: env.Environment, Domain: site.Domain, Port: port, UseHTTPS: v.UseHTTPS}) + if e != nil { + output = "节点任务执行失败或超时" + return + } + code = result.ExitCode + output = result.Output + if result.Truncated { + output += "\n[输出已截断至 64 KiB]" + } + if code == 0 { + state = "succeeded" + } +} diff --git a/backend/internal/setup/server.go b/backend/internal/setup/server.go new file mode 100644 index 0000000..5ff422a --- /dev/null +++ b/backend/internal/setup/server.go @@ -0,0 +1,424 @@ +package setup + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/mail" + "net/url" + "os" + "regexp" + "strings" + "sync" + "time" + + "github.com/go-sql-driver/mysql" + + "sea-vhost/internal/config" + "sea-vhost/internal/isolation" + "sea-vhost/internal/panel" + "sea-vhost/internal/store" +) + +type DatabaseInput struct { + Host string `json:"host"` + Port int `json:"port"` + Name string `json:"name"` + User string `json:"user"` + Password string `json:"password"` +} + +type PanelInput struct { + URL string `json:"url"` + APIKey string `json:"apiKey"` + TLSInsecure bool `json:"tlsInsecure"` +} + +type InstallRequest struct { + ControllerOnly bool `json:"controllerOnly"` + Database DatabaseInput `json:"database"` + Panel PanelInput `json:"panel"` + RootDomain string `json:"rootDomain"` + ManagementDomain string `json:"managementDomain"` + FTPDomain string `json:"ftpDomain"` + DomainApproval bool `json:"domainApproval"` + AdminEmail string `json:"adminEmail"` + AdminName string `json:"adminName"` + AdminPassword string `json:"adminPassword"` +} + +type Server struct { + token string + done chan struct{} + doneOnce sync.Once + installMu sync.Mutex +} + +func New(token string) (*Server, error) { + if len(strings.TrimSpace(token)) < 24 { + return nil, errors.New("SEA_SETUP_TOKEN must contain at least 24 characters") + } + return &Server{token: token, done: make(chan struct{})}, nil +} + +func (s *Server) Done() <-chan struct{} { return s.done } + +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]string{"status": "setup_required"}) + }) + mux.HandleFunc("GET /api/v1/setup/status", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"required": true, "controllerOnly": os.Getenv("SEA_CONTROLLER_ONLY") == "true"}) + }) + mux.HandleFunc("POST /api/v1/setup/test-database", s.authorize(s.testDatabase)) + mux.HandleFunc("POST /api/v1/setup/test-panel", s.authorize(s.testPanel)) + mux.HandleFunc("POST /api/v1/setup/install", s.authorize(s.install)) + return security(mux) +} + +func (s *Server) authorize(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + supplied := r.Header.Get("X-Setup-Token") + if len(supplied) != len(s.token) || subtle.ConstantTimeCompare([]byte(supplied), []byte(s.token)) != 1 { + writeError(w, http.StatusUnauthorized, "安装令牌无效") + return + } + next(w, r) + } +} + +func (s *Server) testDatabase(w http.ResponseWriter, r *http.Request) { + var input DatabaseInput + if !decode(w, r, &input) { + return + } + dsn, err := databaseDSN(input) + if err == nil { + var database *store.Store + database, err = store.Open(dsn) + if database != nil { + _ = database.Close() + } + } + if err != nil { + slog.Warn("setup database preflight failed", "host", input.Host, "database", input.Name, "user", input.User, "error", err) + writeError(w, http.StatusUnprocessableEntity, safeConnectionError("数据库连接失败", err, input.Password)) + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "数据库连接成功"}) +} + +func (s *Server) testPanel(w http.ResponseWriter, r *http.Request) { + var input PanelInput + if !decode(w, r, &input) { + return + } + if err := validatePanel(input); err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 18*time.Second) + defer cancel() + broker := panel.NewBrokerClient(config.PanelBrokerSocketPath(), 20*time.Second, config.InternalAuthToken()) + credentials := panel.BrokerCredentials{URL: input.URL, APIKey: input.APIKey, TLSInsecure: input.TLSInsecure} + inspection, err := broker.InspectCredentials(ctx, credentials, s.token) + if err != nil { + slog.Warn("setup panel preflight failed", "url", input.URL, "error", err) + writeError(w, http.StatusUnprocessableEntity, safeConnectionError("宝塔连接失败", err, input.APIKey)) + return + } + if err := isolation.NewClient(config.AgentSocketPath(), config.InternalAuthToken()).Ping(ctx); err != nil { + slog.Warn("setup isolation agent preflight failed", "socket", config.AgentSocketPath(), "error", err) + writeError(w, http.StatusUnprocessableEntity, "隔离代理未就绪,请检查 sea-vhost-agent 服务") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "宝塔基础 API 与隔离代理检查成功", "versions": inspection.Versions, "runtimes": inspection.Runtimes}) +} + +func (s *Server) install(w http.ResponseWriter, r *http.Request) { + s.installMu.Lock() + defer s.installMu.Unlock() + if _, err := os.Stat(config.Path()); err == nil { + writeError(w, http.StatusConflict, "系统已经完成安装") + return + } else if !errors.Is(err, os.ErrNotExist) { + writeError(w, http.StatusInternalServerError, "无法检查安装状态") + return + } + var input InstallRequest + if !decode(w, r, &input) { + return + } + if os.Getenv("SEA_CONTROLLER_ONLY") == "true" { + input.ControllerOnly = true + } + if input.ControllerOnly { + input.RootDomain = "node-default.invalid" + input.FTPDomain = input.ManagementDomain + } + dsn, err := databaseDSN(input.Database) + if err == nil && !input.ControllerOnly { + err = validatePanel(input.Panel) + } + if err == nil { + err = validateInstall(input) + } + if err != nil { + writeError(w, http.StatusUnprocessableEntity, err.Error()) + return + } + database, err := store.Open(dsn) + if err != nil { + slog.Warn("setup install database connection failed", "host", input.Database.Host, "database", input.Database.Name, "user", input.Database.User, "error", err) + writeError(w, http.StatusUnprocessableEntity, safeConnectionError("数据库连接失败", err, input.Database.Password)) + return + } + defer database.Close() + ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute) + defer cancel() + broker := panel.NewBrokerClient(config.PanelBrokerSocketPath(), 20*time.Second, config.InternalAuthToken()) + credentials := panel.BrokerCredentials{URL: input.Panel.URL, APIKey: input.Panel.APIKey, TLSInsecure: input.Panel.TLSInsecure} + if !input.ControllerOnly { + if _, err = broker.InspectCredentials(ctx, credentials, s.token); err != nil { + slog.Warn("setup install panel connection failed", "url", input.Panel.URL, "error", err) + writeError(w, http.StatusUnprocessableEntity, safeConnectionError("宝塔连接失败", err, input.Panel.APIKey)) + return + } + if err = isolation.NewClient(config.AgentSocketPath(), config.InternalAuthToken()).Ping(ctx); err != nil { + slog.Warn("setup install isolation agent unavailable", "socket", config.AgentSocketPath(), "error", err) + writeError(w, http.StatusUnprocessableEntity, "隔离代理未就绪,请检查 sea-vhost-agent 服务") + return + } + } + if err = database.Migrate(ctx); err == nil { + err = database.InstallAdmin(ctx, strings.TrimSpace(input.AdminEmail), strings.TrimSpace(input.AdminName), input.AdminPassword) + } + if err == nil { + err = database.SetDomainApproval(ctx, input.DomainApproval) + } + if err != nil { + if errors.Is(err, store.ErrDifferentAdminExists) { + writeError(w, http.StatusConflict, "数据库中已存在其他管理员,请使用空数据库") + return + } + slog.Error("setup database initialization failed", "error", err) + writeError(w, http.StatusInternalServerError, "初始化数据库失败,请检查账号权限") + return + } + if !input.ControllerOnly { + if err = broker.Configure(ctx, credentials, s.token); err != nil { + slog.Error("setup panel broker configuration failed", "error", err) + writeError(w, http.StatusInternalServerError, "无法安全保存宝塔代理配置;如需更换密钥,请由 root 重置 panel broker") + return + } + } + secret, err := randomSecret(48) + if err != nil { + writeError(w, http.StatusInternalServerError, "无法生成安全密钥") + return + } + cfg := config.NewInstalled(dsn, secret, input.RootDomain, input.ManagementDomain, input.FTPDomain, nil, input.DomainApproval) + cfg.ControllerOnly = input.ControllerOnly + if err = config.Save(cfg); err != nil { + if strings.Contains(err.Error(), "already exists") { + writeError(w, http.StatusConflict, "系统已经完成安装") + return + } + slog.Error("setup configuration save failed", "path", config.Path(), "error", err) + writeError(w, http.StatusInternalServerError, "无法安全保存系统配置") + return + } + writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "message": "安装完成,服务正在切换到运行模式"}) + s.doneOnce.Do(func() { close(s.done) }) +} + +func databaseDSN(input DatabaseInput) (string, error) { + input.Host = strings.TrimSpace(input.Host) + input.Name = strings.TrimSpace(input.Name) + input.User = strings.TrimSpace(input.User) + if !isLoopback(input.Host) { + return "", errors.New("数据库必须位于本机,请填写 127.0.0.1 或 localhost") + } + if input.Port < 1 || input.Port > 65535 { + return "", errors.New("数据库端口无效") + } + identifier := regexp.MustCompile(`^[A-Za-z0-9_]{1,64}$`) + if !identifier.MatchString(input.Name) || !identifier.MatchString(input.User) || input.Password == "" { + return "", errors.New("数据库名、用户名或密码无效") + } + mysqlConfig := mysql.NewConfig() + mysqlConfig.User = input.User + mysqlConfig.Passwd = input.Password + mysqlConfig.Net = "tcp" + mysqlConfig.Addr = net.JoinHostPort(input.Host, fmt.Sprintf("%d", input.Port)) + mysqlConfig.DBName = input.Name + mysqlConfig.ParseTime = true + mysqlConfig.Collation = "utf8mb4_unicode_ci" + mysqlConfig.Params = map[string]string{"charset": "utf8mb4"} + return mysqlConfig.FormatDSN(), nil +} + +func validatePanel(input PanelInput) error { + parsed, err := url.Parse(strings.TrimSpace(input.URL)) + if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") { + return errors.New("宝塔面板地址无效") + } + if parsed.User != nil || !isLoopback(parsed.Hostname()) { + return errors.New("宝塔面板必须使用本机回环地址") + } + if len(strings.TrimSpace(input.APIKey)) < 16 { + return errors.New("宝塔 API 密钥无效") + } + return nil +} + +func validateInstall(input InstallRequest) error { + domain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(input.RootDomain)), ".") + validDomain := regexp.MustCompile(`^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`) + if len(domain) > 253 || !validDomain.MatchString(domain) { + return errors.New("三级域名根域无效") + } + managementDomain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(input.ManagementDomain)), ".") + ftpDomain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(input.FTPDomain)), ".") + if !validDomain.MatchString(managementDomain) || !validDomain.MatchString(ftpDomain) { + return errors.New("控制台域名和 FTP 证书来源域名必须填写有效域名") + } + if domainsOverlap(managementDomain, domain) || ftpDomain == domain || strings.HasSuffix(domain, "."+ftpDomain) { + return errors.New("控制台域名必须独立,FTP 证书来源域名不能覆盖租户三级域名") + } + if strings.HasSuffix(ftpDomain, "."+domain) { + prefix := strings.TrimSuffix(ftpDomain, "."+domain) + if regexp.MustCompile(`^sv[0-9a-f]{10}$`).MatchString(prefix) { + return errors.New("FTP 证书来源域名不能占用系统分配的随机主机名") + } + } + address, err := mail.ParseAddress(strings.TrimSpace(input.AdminEmail)) + if err != nil || !strings.EqualFold(address.Address, strings.TrimSpace(input.AdminEmail)) { + return errors.New("管理员邮箱无效") + } + if len([]rune(strings.TrimSpace(input.AdminName))) < 2 || len([]rune(input.AdminName)) > 50 { + return errors.New("管理员名称应为 2–50 个字符") + } + if len(input.AdminPassword) < 12 || len(input.AdminPassword) > 128 { + return errors.New("管理员密码应为 12–128 个字符") + } + return nil +} + +func domainsOverlap(first, second string) bool { + return first == second || strings.HasSuffix(first, "."+second) || strings.HasSuffix(second, "."+first) +} + +func isLoopback(host string) bool { + host = strings.Trim(strings.ToLower(strings.TrimSpace(host)), "[]") + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func randomSecret(size int) (string, error) { + data := make([]byte, size) + if _, err := rand.Read(data); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func decode(w http.ResponseWriter, r *http.Request, target any) bool { + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + writeError(w, http.StatusBadRequest, "请求内容无效") + return false + } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + writeError(w, http.StatusBadRequest, "请求内容必须只包含一个 JSON 对象") + return false + } + return true +} + +func safeConnectionError(prefix string, err error, secrets ...string) string { + message := strings.ReplaceAll(err.Error(), "\n", " ") + for _, secret := range secrets { + if secret != "" { + message = strings.ReplaceAll(message, secret, "[已隐藏]") + } + } + if len(message) > 180 { + message = message[:180] + } + return prefix + ":" + message +} + +func security(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Referrer-Policy", "same-origin") + w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + if r.Method != http.MethodGet { + origin := r.Header.Get("Origin") + if strings.EqualFold(r.Header.Get("Sec-Fetch-Site"), "cross-site") || (origin != "" && !sameOrigin(r)) { + writeError(w, http.StatusForbidden, "不允许跨站请求") + return + } + } + next.ServeHTTP(w, r) + }) +} + +func sameOrigin(r *http.Request) bool { + parsed, err := url.Parse(r.Header.Get("Origin")) + if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { + return false + } + if parsed.Scheme != "http" && parsed.Scheme != "https" { + return false + } + return strings.EqualFold(parsed.Scheme, setupRequestScheme(r)) && strings.EqualFold(parsed.Host, r.Host) +} + +func setupRequestScheme(r *http.Request) string { + if r.TLS != nil { + return "https" + } + if isLoopbackRemote(r.RemoteAddr) { + forwarded := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0])) + if forwarded == "http" || forwarded == "https" { + return forwarded + } + } + return "http" +} + +func isLoopbackRemote(remote string) bool { + host, _, err := net.SplitHostPort(remote) + if err != nil { + host = strings.Trim(remote, "[]") + } + ip := net.ParseIP(strings.Trim(host, "[]")) + return ip != nil && ip.IsLoopback() +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]any{"error": map[string]string{"message": message}}) +} diff --git a/backend/internal/setup/server_test.go b/backend/internal/setup/server_test.go new file mode 100644 index 0000000..202ecf6 --- /dev/null +++ b/backend/internal/setup/server_test.go @@ -0,0 +1,125 @@ +package setup + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestSetupStatusDoesNotExposeToken(t *testing.T) { + server, err := New(strings.Repeat("a", 32)) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodGet, "/api/v1/setup/status", nil) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"required":true`) { + t.Fatalf("unexpected status response: %d %s", response.Code, response.Body.String()) + } + if strings.Contains(response.Body.String(), strings.Repeat("a", 32)) { + t.Fatal("setup token was disclosed") + } + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatal("setup status may be cached") + } +} + +func TestConnectionErrorRedactsSecrets(t *testing.T) { + message := safeConnectionError("连接失败", errors.New("dial failed password=secret"), "secret") + if strings.Contains(message, "secret") || !strings.Contains(message, "[已隐藏]") { + t.Fatalf("secret was not redacted: %s", message) + } +} + +func TestSetupWriteRequiresTokenAndSameOrigin(t *testing.T) { + server, err := New(strings.Repeat("b", 32)) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "/api/v1/setup/test-database", strings.NewReader(`{}`)) + request.Header.Set("Origin", "https://attacker.example") + request.Header.Set("X-Setup-Token", strings.Repeat("b", 32)) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("cross-origin write status = %d, want 403", response.Code) + } + + request = httptest.NewRequest(http.MethodPost, "/api/v1/setup/test-database", strings.NewReader(`{}`)) + response = httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusUnauthorized { + t.Fatalf("unauthorized write status = %d, want 401", response.Code) + } +} + +func TestSetupOriginRequiresMatchingScheme(t *testing.T) { + server, err := New(strings.Repeat("c", 32)) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/setup/test-database", strings.NewReader(`{}`)) + request.Header.Set("Origin", "https://console.example") + request.Header.Set("X-Setup-Token", strings.Repeat("c", 32)) + request.RemoteAddr = "198.51.100.8:40000" + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("scheme-mismatched origin status = %d, want 403", response.Code) + } +} + +func TestSetupRejectsTrailingJSON(t *testing.T) { + server, err := New(strings.Repeat("d", 32)) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/setup/test-database", strings.NewReader(`{} {}`)) + request.Header.Set("Origin", "http://console.example") + request.Header.Set("X-Setup-Token", strings.Repeat("d", 32)) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + if response.Code != http.StatusBadRequest { + t.Fatalf("trailing JSON status = %d, want 400", response.Code) + } +} + +func TestDatabaseDSNRejectsRemoteHost(t *testing.T) { + _, err := databaseDSN(DatabaseInput{Host: "10.0.0.2", Port: 3306, Name: "sea_vhost", User: "sea_vhost", Password: "secret"}) + if err == nil { + t.Fatal("remote database host was accepted") + } +} + +func TestValidateInstallAllowsDedicatedFTPNameUnderTenantRoot(t *testing.T) { + input := InstallRequest{ + RootDomain: "vhost.ser888.cn", ManagementDomain: "host.ser888.cn", FTPDomain: "ftp.vhost.ser888.cn", + AdminEmail: "admin@ser888.cn", AdminName: "管理员", AdminPassword: "correct-horse-battery", + } + if err := validateInstall(input); err != nil { + t.Fatalf("dedicated FTP subdomain was rejected: %v", err) + } +} + +func TestValidateInstallAllowsManagementDomainAsFTPCertificateSource(t *testing.T) { + input := InstallRequest{ + RootDomain: "vhost.ser888.cn", ManagementDomain: "host.ser888.cn", FTPDomain: "host.ser888.cn", + AdminEmail: "admin@ser888.cn", AdminName: "管理员", AdminPassword: "correct-horse-battery", + } + if err := validateInstall(input); err != nil { + t.Fatalf("management-domain FTP certificate source was rejected: %v", err) + } +} + +func TestValidateInstallRejectsManagedHostNameAsFTPDomain(t *testing.T) { + input := InstallRequest{ + RootDomain: "vhost.ser888.cn", ManagementDomain: "host.ser888.cn", FTPDomain: "sv0123456789.vhost.ser888.cn", + AdminEmail: "admin@ser888.cn", AdminName: "管理员", AdminPassword: "correct-horse-battery", + } + if err := validateInstall(input); err == nil || !strings.Contains(err.Error(), "随机主机名") { + t.Fatalf("managed-host FTP domain error = %v", err) + } +} diff --git a/backend/internal/store/admin_batches.go b/backend/internal/store/admin_batches.go new file mode 100644 index 0000000..481d997 --- /dev/null +++ b/backend/internal/store/admin_batches.go @@ -0,0 +1,232 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "sea-vhost/internal/scope" + "time" +) + +type AdminBatch struct { + ID uint64 `json:"id"` + AdministratorID uint64 `json:"administratorId"` + Operation string `json:"operation"` + State string `json:"state"` + Total int `json:"total"` + Succeeded int `json:"succeeded"` + Failed int `json:"failed"` + Uncertain int `json:"uncertain"` + Pending int `json:"pending"` + CreatedAt time.Time `json:"createdAt"` + FinishedAt *time.Time `json:"finishedAt,omitempty"` + SecretsExpireAt *time.Time `json:"secretsExpireAt,omitempty"` + SecretRef string `json:"-"` + Items []AdminBatchItem `json:"items,omitempty"` +} +type AdminBatchItem struct { + ID uint64 `json:"id"` + BatchID uint64 `json:"batchId"` + Row int `json:"row"` + Label string `json:"label"` + State string `json:"state"` + ResourceID *uint64 `json:"resourceId,omitempty"` + Detail string `json:"detail"` + InputCipher []byte `json:"-"` + ResultCipher []byte `json:"-"` +} + +var ErrBatchKeyConflict = errors.New("请求标识已用于其他批次,请刷新后重新预览") +var ErrBatchQueueFull = errors.New("待处理批次过多,请等待现有任务完成") + +func (s *Store) ExistingAdminBatch(ctx context.Context, key, digest string) (uint64, error) { + var id uint64 + var expected string + err := s.db.QueryRowContext(ctx, "SELECT id,input_digest FROM admin_batches WHERE request_key=?", key).Scan(&id, &expected) + if errors.Is(err, sql.ErrNoRows) { + return 0, nil + } + if err != nil { + return 0, err + } + if expected != digest { + return 0, ErrBatchKeyConflict + } + return id, nil +} + +func (s *Store) CreateAdminBatch(ctx context.Context, administrator uint64, key, digest, operation, ref string, items []AdminBatchItem) (uint64, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + var adminID uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE id=? AND role='admin' AND status='active' FOR UPDATE", administrator).Scan(&adminID); err != nil { + return 0, ErrNotFound + } + var id uint64 + var existing string + err = tx.QueryRowContext(ctx, "SELECT id,input_digest FROM admin_batches WHERE request_key=?", key).Scan(&id, &existing) + if err == nil { + if digest != existing { + return 0, ErrBatchKeyConflict + } + return id, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return 0, err + } + var queued int + if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running')").Scan(&queued); err != nil { + return 0, err + } + if queued >= 20 { + return 0, ErrBatchQueueFull + } + var apiKey any + if id := scope.IntegrationKey(ctx); id > 0 { + var activeID uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM integration_keys WHERE id=? AND administrator_id=? AND revoked_at IS NULL AND expires_at>UTC_TIMESTAMP() FOR UPDATE", id, administrator).Scan(&activeID); err != nil { + return 0, ErrNotFound + } + apiKey = id + } + result, err := tx.ExecContext(ctx, "INSERT INTO admin_batches(request_key,input_digest,administrator_id,operation,total_count,secret_ref,integration_key_id) VALUES(?,?,?,?,?,?,?)", key, digest, administrator, operation, len(items), ref, apiKey) + if err != nil { + return 0, err + } + inserted, err := result.LastInsertId() + if err != nil { + return 0, err + } + id = uint64(inserted) + for _, item := range items { + if _, err = tx.ExecContext(ctx, "INSERT INTO admin_batch_items(batch_id,item_number,label,state,input_cipher,detail,resource_id) VALUES(?,?,?,?,?,?,?)", id, item.Row, item.Label, item.State, item.InputCipher, item.Detail, item.ResourceID); err != nil { + return 0, err + } + } + if err = tx.Commit(); err != nil { + return 0, err + } + return id, nil +} + +const batchSummarySQL = `SELECT b.id,b.administrator_id,b.operation,b.state,b.total_count,b.created_at,b.finished_at,b.secrets_expire_at,b.secret_ref,COALESCE(SUM(i.state='succeeded'),0),COALESCE(SUM(i.state IN ('failed','cancelled')),0),COALESCE(SUM(i.state='uncertain'),0),COALESCE(SUM(i.state IN ('pending','running')),0) FROM admin_batches b LEFT JOIN admin_batch_items i ON i.batch_id=b.id` + +func scanAdminBatch(row rowScanner) (AdminBatch, error) { + var b AdminBatch + err := row.Scan(&b.ID, &b.AdministratorID, &b.Operation, &b.State, &b.Total, &b.CreatedAt, &b.FinishedAt, &b.SecretsExpireAt, &b.SecretRef, &b.Succeeded, &b.Failed, &b.Uncertain, &b.Pending) + return b, err +} +func (s *Store) AdminBatches(ctx context.Context) ([]AdminBatch, error) { + rows, err := s.db.QueryContext(ctx, batchSummarySQL+" GROUP BY b.id ORDER BY b.id DESC LIMIT 100") + if err != nil { + return nil, err + } + defer rows.Close() + out := []AdminBatch{} + for rows.Next() { + b, e := scanAdminBatch(rows) + if e != nil { + return nil, e + } + out = append(out, b) + } + return out, rows.Err() +} +func (s *Store) AdminBatch(ctx context.Context, id uint64, includeSecrets bool) (AdminBatch, error) { + b, err := scanAdminBatch(s.db.QueryRowContext(ctx, batchSummarySQL+" WHERE b.id=? GROUP BY b.id", id)) + if err != nil { + return b, err + } + columns := "id,batch_id,item_number,label,state,resource_id,detail" + if includeSecrets { + columns += ",input_cipher,result_cipher" + } + rows, err := s.db.QueryContext(ctx, "SELECT "+columns+" FROM admin_batch_items WHERE batch_id=? ORDER BY item_number", id) + if err != nil { + return b, err + } + defer rows.Close() + b.Items = []AdminBatchItem{} + for rows.Next() { + var item AdminBatchItem + args := []any{&item.ID, &item.BatchID, &item.Row, &item.Label, &item.State, &item.ResourceID, &item.Detail} + if includeSecrets { + args = append(args, &item.InputCipher, &item.ResultCipher) + } + if err = rows.Scan(args...); err != nil { + return b, err + } + b.Items = append(b.Items, item) + } + return b, rows.Err() +} + +// One advisory lock owns the queue across API processes. Restarted work is +// marked uncertain rather than issuing a second potentially destructive call. +func (s *Store) LockBatchWorker(ctx context.Context) (func(), error) { + conn, err := s.db.Conn(ctx) + if err != nil { + return nil, err + } + var locked int + if err = conn.QueryRowContext(ctx, "SELECT GET_LOCK(CONCAT('svh:batch:',LEFT(SHA2(DATABASE(),256),40)),0)").Scan(&locked); err != nil || locked != 1 { + conn.Close() + if err == nil { + err = errors.New("batch worker already active") + } + return nil, err + } + return func() { + release, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, _ = conn.ExecContext(release, "DO RELEASE_LOCK(CONCAT('svh:batch:',LEFT(SHA2(DATABASE(),256),40)))") + conn.Close() + }, nil +} +func (s *Store) RecoverAdminBatches(ctx context.Context) error { + if _, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state='uncertain',detail='服务重启前该项正在执行,请按资源 ID 核验,禁止自动重复执行',finished_at=UTC_TIMESTAMP() WHERE state='running'"); err != nil { + return err + } + _, err := s.db.ExecContext(ctx, "UPDATE admin_batches SET state='queued' WHERE state='running'") + return err +} +func (s *Store) NextAdminBatchItem(ctx context.Context) (AdminBatch, AdminBatchItem, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return AdminBatch{}, AdminBatchItem{}, err + } + defer tx.Rollback() + var b AdminBatch + var item AdminBatchItem + err = tx.QueryRowContext(ctx, `SELECT b.id,b.administrator_id,b.operation,b.secret_ref,i.id,i.item_number,i.label,i.input_cipher FROM admin_batches b JOIN admin_batch_items i ON i.batch_id=b.id WHERE b.state IN ('queued','running') AND i.state='pending' ORDER BY b.id,i.item_number LIMIT 1 FOR UPDATE`).Scan(&b.ID, &b.AdministratorID, &b.Operation, &b.SecretRef, &item.ID, &item.Row, &item.Label, &item.InputCipher) + if err != nil { + return b, item, err + } + item.BatchID = b.ID + if _, err = tx.ExecContext(ctx, "UPDATE admin_batch_items SET state='running',started_at=UTC_TIMESTAMP() WHERE id=? AND state='pending'", item.ID); err != nil { + return b, item, err + } + if _, err = tx.ExecContext(ctx, "UPDATE admin_batches SET state='running' WHERE id=?", b.ID); err != nil { + return b, item, err + } + return b, item, tx.Commit() +} +func (s *Store) FinishAdminBatchItem(ctx context.Context, id uint64, state, detail string, result []byte, resourceID uint64) error { + _, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state=?,detail=?,result_cipher=?,resource_id=COALESCE(NULLIF(?,0),resource_id),finished_at=UTC_TIMESTAMP() WHERE id=? AND state='running'", state, detail, result, resourceID, id) + return err +} +func (s *Store) RefreshAdminBatches(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, `UPDATE admin_batches b SET b.state=CASE WHEN EXISTS(SELECT 1 FROM admin_batch_items i WHERE i.batch_id=b.id AND i.state IN ('failed','uncertain','cancelled')) THEN 'partial' ELSE 'completed' END,b.finished_at=COALESCE(b.finished_at,UTC_TIMESTAMP()),b.secrets_expire_at=COALESCE(b.secrets_expire_at,DATE_ADD(UTC_TIMESTAMP(),INTERVAL 24 HOUR)) WHERE b.state IN ('queued','running') AND NOT EXISTS(SELECT 1 FROM admin_batch_items i WHERE i.batch_id=b.id AND i.state IN ('pending','running'))`) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `UPDATE admin_batch_items i JOIN admin_batches b ON b.id=i.batch_id SET i.input_cipher=NULL,i.result_cipher=NULL WHERE b.secrets_expire_at<=UTC_TIMESTAMP() AND (i.input_cipher IS NOT NULL OR i.result_cipher IS NOT NULL)`) + return err +} +func (s *Store) CancelAdminBatch(ctx context.Context, id uint64) error { + _, err := s.db.ExecContext(ctx, "UPDATE admin_batch_items SET state='cancelled',detail='管理员取消未执行项',finished_at=UTC_TIMESTAMP() WHERE batch_id=? AND state='pending'", id) + return err +} diff --git a/backend/internal/store/audit_filter.go b/backend/internal/store/audit_filter.go new file mode 100644 index 0000000..7bf3dac --- /dev/null +++ b/backend/internal/store/audit_filter.go @@ -0,0 +1,69 @@ +package store + +import ( + "context" + "strings" + "time" +) + +type AuditFilter struct { + MaxID uint64 + Query, Action, Result string + From, To *time.Time + Limit, Page int +} + +func (s *Store) FilterAdminActivities(ctx context.Context, f AuditFilter) ([]AdminActivity, int, error) { + if f.Limit < 1 || f.Limit > 500 { + f.Limit = 100 + } + if f.Page < 1 { + f.Page = 1 + } + where := " WHERE TRUE" + args := []any{} + if f.MaxID > 0 { + where += " AND l.id<=?" + args = append(args, f.MaxID) + } + if f.Query != "" { + where += " AND INSTR(LOWER(CONCAT_WS(' ',a.display_name,t.name,l.action,l.resource_type,l.resource_id,l.ip_address,l.detail)),?)>0" + args = append(args, strings.ToLower(f.Query)) + } + if f.Action != "" { + where += " AND l.action=?" + args = append(args, f.Action) + } + if f.Result != "" { + where += " AND l.success=?" + args = append(args, f.Result == "success") + } + if f.From != nil { + where += " AND l.created_at>=?" + args = append(args, f.From.UTC()) + } + if f.To != nil { + where += " AND l.created_at 0, err +} +func (s *Store) ControlTasks(ctx context.Context, nodeID uint64) ([]ControlTask, error) { + rows, err := s.db.QueryContext(ctx, `SELECT id,node_id,project_id,operation,state,detail,started_at,finished_at FROM control_tasks WHERE node_id=? ORDER BY id DESC LIMIT 100`, nodeID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []ControlTask{} + for rows.Next() { + var t ControlTask + if err = rows.Scan(&t.ID, &t.NodeID, &t.ProjectID, &t.Operation, &t.State, &t.Detail, &t.StartedAt, &t.FinishedAt); err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} +func (s *Store) ResolveControlTask(ctx context.Context, nodeID, id uint64, note string) error { + if len([]rune(note)) < 6 || len(note) > 400 { + return errors.New("请记录实际核验结果(至少六个字)") + } + r, err := s.db.ExecContext(ctx, "UPDATE control_tasks SET state='failed',detail=?,finished_at=UTC_TIMESTAMP() WHERE id=? AND node_id=? AND state='uncertain'", "管理员已核验:"+note, id, nodeID) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n != 1 { + return ErrNotFound + } + return nil +} diff --git a/backend/internal/store/domain_policy.go b/backend/internal/store/domain_policy.go new file mode 100644 index 0000000..455a212 --- /dev/null +++ b/backend/internal/store/domain_policy.go @@ -0,0 +1,21 @@ +package store + +import "context" + +// A single transaction prevents filing and routing changes from partially +// succeeding, and treats saving an unchanged policy as a successful operation. +func (s *Store) UpdateDomainPolicy(ctx context.Context, id uint64, mode, target, status, number, note string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var found uint64 + if err = tx.QueryRowContext(ctx, `SELECT id FROM domains WHERE id=? AND kind='custom' FOR UPDATE`, id).Scan(&found); err != nil { + return ErrNotFound + } + if _, err = tx.ExecContext(ctx, `UPDATE domains SET resolution_mode=?,cname_target=NULLIF(?,''),filing_status=?,filing_number=NULLIF(?,''),filing_note=NULLIF(?,'') WHERE id=?`, mode, target, status, number, note, id); err != nil { + return err + } + return tx.Commit() +} diff --git a/backend/internal/store/ftp_management.go b/backend/internal/store/ftp_management.go new file mode 100644 index 0000000..3af6f36 --- /dev/null +++ b/backend/internal/store/ftp_management.go @@ -0,0 +1,4 @@ +package store +import "context" +func(s *Store)SetFTPEnabled(ctx context.Context,project uint64,enabled bool)error{_,e:=s.db.ExecContext(ctx,"UPDATE ftp_accounts SET enabled=? WHERE project_id=?",enabled,project);return e} +func(s *Store)SetFTPPasswordCipher(ctx context.Context,project uint64,cipher []byte)error{_,e:=s.db.ExecContext(ctx,"UPDATE ftp_accounts SET password_ciphertext=? WHERE project_id=?",cipher,project);return e} diff --git a/backend/internal/store/host_activity_integration_test.go b/backend/internal/store/host_activity_integration_test.go new file mode 100644 index 0000000..a2c6596 --- /dev/null +++ b/backend/internal/store/host_activity_integration_test.go @@ -0,0 +1,115 @@ +package store + +import ( + "context" + "github.com/go-sql-driver/mysql" + "os" + "sea-vhost/internal/scope" + "strconv" + "strings" + "testing" + "time" +) + +func TestHostOperationLogsMySQL(t *testing.T) { + dsn := os.Getenv("SEA_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("dedicated MySQL schema not supplied") + } + config, err := mysql.ParseDSN(dsn) + if err != nil || !strings.HasPrefix(config.DBName, "svh_cluster_test_") { + t.Fatal("refusing a non-test schema") + } + db, err := Open(dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + if err = db.Migrate(ctx); err != nil { + t.Fatal(err) + } + plans, err := db.ListPlans(ctx) + if err != nil || len(plans) == 0 { + t.Fatal("missing plan", err) + } + tenants := []uint64{} + for _, name := range []string{"audit-a", "audit-b"} { + id, e := db.CreateTenant(ctx, NewTenant{Slug: name, Name: name, Email: name + "@example.invalid", DisplayName: "审计测试用户", Password: "integration-only-password-123", PlanID: plans[0].ID}) + if e != nil { + t.Fatal(e) + } + tenants = append(tenants, id) + } + ownerA, err := db.UserByLogin(ctx, "audit-a@example.invalid") + if err != nil { + t.Fatal(err) + } + ownerB, err := db.UserByLogin(ctx, "audit-b@example.invalid") + if err != nil { + t.Fatal(err) + } + hosts := []uint64{} + for i, name := range []string{"sv1111111111", "sv2222222222", "sv3333333333"} { + tenant := tenants[0] + if i == 2 { + tenant = tenants[1] + } + id, e := db.InsertProject(ctx, NewProject{NodeID: 1, PlanID: plans[0].ID, TenantID: tenant, HostName: name, Slug: name, Runtime: "PHP", Version: "8.4", Path: "/www/wwwroot/seavHost/vHost/" + name, RunPath: "/public", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-hash"}) + if e != nil { + t.Fatal(e) + } + hosts = append(hosts, id) + } + result, err := db.db.ExecContext(ctx, `INSERT INTO users(tenant_id,project_id,login_name,email,display_name,password_hash,role) VALUES (?,?,?,?,?,?,'host')`, tenants[0], hosts[0], "audit-host", "audit-host@example.invalid", "主机测试账号", "test-hash") + if err != nil { + t.Fatal(err) + } + actor, _ := result.LastInsertId() + userID := uint64(actor) + a := scope.WithProject(ctx, hosts[0], 1) + b := scope.WithProject(ctx, hosts[1], 1) + db.LogEvent(a, &tenants[0], &ownerA.ID, "update", "site", "1", "127.0.0.1", true, "HOST_A_USER_ACTION") + db.LogEvent(b, &tenants[0], &ownerA.ID, "update", "site", "2", "127.0.0.1", true, "HOST_B_MUST_NOT_LEAK") + db.LogEvent(ctx, &tenants[0], &ownerA.ID, "update", "account", "", "127.0.0.1", true, "ACCOUNT_MUST_NOT_LEAK") + db.LogEvent(ctx, &tenants[0], &userID, "login", "session", "", "127.0.0.1", true, "HOST_A_LOGIN") + db.LogEvent(scope.WithProject(ctx, hosts[2], 1), &tenants[1], &ownerB.ID, "update", "site", "3", "127.0.0.1", true, "OTHER_TENANT_MUST_NOT_LEAK") + db.LogEvent(a, &tenants[0], nil, "update", "site", "1", "127.0.0.1", true, "UNKNOWN_ACTOR_MUST_NOT_LEAK") + items, err := db.Activities(a, tenants[0], 100) + if err != nil || len(items) != 2 { + t.Fatalf("host logs: %+v %v", items, err) + } + for _, item := range items { + if item.ProjectID == nil || *item.ProjectID != hosts[0] || strings.Contains(item.Detail, "MUST_NOT_LEAK") { + t.Fatalf("cross-host log: %+v", item) + } + } + if items, err = db.Activities(ctx, tenants[0], 100); err != nil || len(items) != 4 { + t.Fatalf("tenant logs: %d %v", len(items), err) + } + if items, err = db.Activities(a, tenants[1], 100); err != nil || len(items) != 0 { + t.Fatalf("cross-tenant scope: %+v %v", items, err) + } + if _, err = db.db.ExecContext(ctx, `INSERT INTO operation_logs(tenant_id,user_id,action,resource_type,resource_id,success,detail) VALUES (?,?,'state','project',?,TRUE,'LEGACY_EXACT_HOST'),(?,?,'create','project',?,FALSE,'LEGACY_AMBIGUOUS_FAILED_CREATE')`, tenants[0], ownerA.ID, strconv.FormatUint(hosts[0], 10), tenants[0], ownerA.ID, strconv.FormatUint(hosts[0], 10)); err != nil { + t.Fatal(err) + } + if _, err = db.db.ExecContext(ctx, "DELETE FROM schema_migrations WHERE version='015_host_operation_logs.sql'"); err != nil { + t.Fatal(err) + } + if err = db.Migrate(ctx); err != nil { + t.Fatalf("resume migration 015: %v", err) + } + if err = db.Migrate(ctx); err != nil { + t.Fatalf("repeat migration: %v", err) + } + items, err = db.Activities(a, tenants[0], 100) + if err != nil || len(items) != 3 { + t.Fatalf("legacy host attribution: %+v %v", items, err) + } + for _, item := range items { + if item.Detail == "LEGACY_AMBIGUOUS_FAILED_CREATE" { + t.Fatal("ambiguous historical log was attributed to a host") + } + } +} diff --git a/backend/internal/store/host_lifecycle.go b/backend/internal/store/host_lifecycle.go new file mode 100644 index 0000000..729745b --- /dev/null +++ b/backend/internal/store/host_lifecycle.go @@ -0,0 +1,124 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "sea-vhost/internal/scope" + "time" +) + +type HostLifecycle struct { + ProjectID, TenantID, NodeID uint64 + State string + ExpiresAt, GraceUntil, PurgeAfter, BackupPurgeAfter *time.Time +} + +var ErrHostNotWritable = errors.New("主机已到期或身份核验未通过,请联系管理员") + +func (s *Store) HostLifecycles(ctx context.Context) ([]HostLifecycle, error) { + rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,node_id,lifecycle_state,expires_at,grace_until,purge_after,backup_purge_after FROM projects WHERE management_locked=FALSE AND lifecycle_state IN ('grace','recycle') ORDER BY id`) + if err != nil { + return nil, err + } + defer rows.Close() + out := []HostLifecycle{} + for rows.Next() { + var h HostLifecycle + if err = rows.Scan(&h.ProjectID, &h.TenantID, &h.NodeID, &h.State, &h.ExpiresAt, &h.GraceUntil, &h.PurgeAfter, &h.BackupPurgeAfter); err != nil { + return nil, err + } + out = append(out, h) + } + return out, rows.Err() +} +func (s *Store) AdvanceHostLifecycle(ctx context.Context, now time.Time) error { + _, err := s.db.ExecContext(ctx, `UPDATE projects SET lifecycle_state='grace',grace_until=DATE_ADD(expires_at,INTERVAL 3 DAY),purge_after=DATE_ADD(expires_at,INTERVAL 10 DAY),backup_purge_after=DATE_ADD(expires_at,INTERVAL 24 DAY) WHERE management_locked=FALSE AND lifecycle_state='active' AND expires_at IS NOT NULL AND expires_at<=?`, now) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `UPDATE projects SET lifecycle_state='recycle' WHERE management_locked=FALSE AND lifecycle_state='grace' AND grace_until<=?`, now) + return err +} +func (s *Store) HostWritable(ctx context.Context, tenantID uint64) error { + if scope.Project(ctx) == 0 { + return nil + } + var expired, locked bool + err := s.db.QueryRowContext(ctx, `SELECT management_locked,NOT identity_verified OR lifecycle_state<>'active' OR (expires_at IS NOT NULL AND expires_at<=UTC_TIMESTAMP()) FROM projects WHERE id=? AND tenant_id=?`, scope.Project(ctx), tenantID).Scan(&locked, &expired) + if err != nil { + return err + } + if locked { + return ErrManagementLocked + } + if expired { + return ErrHostNotWritable + } + return nil +} +func (s *Store) SetHostSubscription(ctx context.Context, id, planID uint64, expires *time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var state string + var process uint32 + var locked bool + var manual *time.Time + if err = tx.QueryRowContext(ctx, "SELECT lifecycle_state,management_locked,manual_recycled_at FROM projects WHERE id=? FOR UPDATE", id).Scan(&state, &locked, &manual); err != nil { + return err + } + if locked { + return ErrManagementLocked + } + if manual != nil { + return errors.New("主机已手动回收,请先使用恢复入口") + } + if state == "purged" { + return errors.New("主机已删除") + } + if err = tx.QueryRowContext(ctx, "SELECT process_limit FROM plans WHERE id=?", planID).Scan(&process); err != nil { + return err + } + _, err = tx.ExecContext(ctx, `UPDATE projects SET plan_id=?,process_limit=?,expires_at=?,lifecycle_state='active',grace_until=NULL,purge_after=NULL,backup_purge_after=NULL WHERE id=?`, planID, process, expires, id) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, "UPDATE sites SET process_limit=? WHERE project_id=?", process, id) + if err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetHostIdentityVerified(ctx context.Context, id uint64, verified bool) error { + _, err := s.db.ExecContext(ctx, "UPDATE projects SET identity_verified=? WHERE id=?", verified, id) + return err +} +func (s *Store) PurgeHostRecord(ctx context.Context, id, tenantID uint64) error { + if id == 0 { + return errors.New("host scope required") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.project_id=? AND u.tenant_id=?", id, tenantID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM users WHERE project_id=? AND tenant_id=? AND role='host'", id, tenantID); err != nil { + return err + } + result, err := tx.ExecContext(ctx, "DELETE FROM projects WHERE id=? AND tenant_id=? AND lifecycle_state='recycle'", id, tenantID) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n != 1 { + return sql.ErrNoRows + } + return tx.Commit() +} diff --git a/backend/internal/store/impersonation.go b/backend/internal/store/impersonation.go new file mode 100644 index 0000000..b206d90 --- /dev/null +++ b/backend/internal/store/impersonation.go @@ -0,0 +1,83 @@ +package store + +import ( + "context" + "crypto/sha256" + "database/sql" + "errors" + "time" +) + +func (s *Store) ImpersonationTarget(ctx context.Context, tenantID, projectID uint64) (User, error) { + var id uint64 + query := `SELECT u.id FROM users u JOIN tenants t ON t.id=u.tenant_id WHERE u.status='active' AND t.status='active' AND u.role='tenant' AND u.project_id IS NULL AND u.tenant_id=? ORDER BY u.id LIMIT 1` + value := tenantID + if projectID > 0 { + query = `SELECT u.id FROM users u JOIN projects p ON p.id=u.project_id AND p.tenant_id=u.tenant_id JOIN tenants t ON t.id=u.tenant_id WHERE u.status='active' AND t.status='active' AND u.role='host' AND p.id=? AND p.status NOT IN ('failed','provisioning') ORDER BY u.id LIMIT 1` + value = projectID + } + if err := s.db.QueryRowContext(ctx, query, value).Scan(&id); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return User{}, ErrNotFound + } + return User{}, err + } + return s.UserByID(ctx, id) +} + +func (s *Store) CreateImpersonation(ctx context.Context, parent, token string, administratorID, targetID uint64, expires time.Time) error { + target, err := s.UserByID(ctx, targetID) + if err != nil || target.Role == "admin" || target.TenantID == nil { + return ErrNotFound + } + parentHash, hash := sha256.Sum256([]byte(parent)), sha256.Sum256([]byte(token)) + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE parent_session_hash=? OR expires_at<=UTC_TIMESTAMP()", parentHash[:]); err != nil { + return err + } + result, err := tx.ExecContext(ctx, `INSERT INTO impersonation_sessions(token_hash,parent_session_hash,administrator_id,target_user_id,expires_at) + SELECT ?,s.token_hash,a.id,?,LEAST(s.expires_at,?) FROM sessions s JOIN users a ON a.id=s.user_id + WHERE s.token_hash=? AND a.id=? AND a.role='admin' AND a.status='active' AND s.expires_at>UTC_TIMESTAMP()`, hash[:], targetID, expires.UTC(), parentHash[:], administratorID) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n != 1 { + return ErrNotFound + } + return tx.Commit() +} + +func (s *Store) ImpersonationUser(ctx context.Context, parent, token string, administratorID uint64) (User, error) { + parentHash, hash := sha256.Sum256([]byte(parent)), sha256.Sum256([]byte(token)) + var target uint64 + var expires time.Time + err := s.db.QueryRowContext(ctx, `SELECT i.target_user_id,i.expires_at FROM impersonation_sessions i JOIN sessions s ON s.token_hash=i.parent_session_hash + JOIN users a ON a.id=i.administrator_id WHERE i.token_hash=? AND i.parent_session_hash=? AND i.administrator_id=? + AND s.user_id=a.id AND a.role='admin' AND a.status='active' AND s.expires_at>UTC_TIMESTAMP() AND i.expires_at>UTC_TIMESTAMP()`, hash[:], parentHash[:], administratorID).Scan(&target, &expires) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return User{}, ErrNotFound + } + return User{}, err + } + user, err := s.UserByID(ctx, target) + if err != nil { + return User{}, err + } + if user.Role != "host" && user.Role != "tenant" { + return User{}, ErrNotFound + } + user.Impersonating = true + user.ImpersonationExpiresAt = &expires + return user, nil +} + +func (s *Store) StopImpersonation(ctx context.Context, parent, token string) error { + p, h := sha256.Sum256([]byte(parent)), sha256.Sum256([]byte(token)) + _, err := s.db.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE parent_session_hash=? AND token_hash=?", p[:], h[:]) + return err +} diff --git a/backend/internal/store/integration_api.go b/backend/internal/store/integration_api.go new file mode 100644 index 0000000..d23c55a --- /dev/null +++ b/backend/internal/store/integration_api.go @@ -0,0 +1,135 @@ +package store + +import ( + "context" + "encoding/json" + "time" +) + +type IntegrationKey struct { + ID uint64 `json:"id"` + AdministratorID uint64 `json:"administratorId"` + Name string `json:"name"` + Prefix string `json:"prefix"` + Scopes []string `json:"scopes"` + ExpiresAt time.Time `json:"expiresAt"` + RevokedAt *time.Time `json:"revokedAt"` + LastUsedAt *time.Time `json:"lastUsedAt"` + WebhookURL string `json:"webhookURL"` + WebhookSecret []byte `json:"-"` + CreatedAt time.Time `json:"createdAt"` +} + +const integrationFields = "k.id,k.administrator_id,k.name,k.token_prefix,k.scopes_json,k.expires_at,k.revoked_at,k.last_used_at,k.webhook_url,k.webhook_secret_cipher,k.created_at" + +func scanIntegrationKey(row rowScanner) (IntegrationKey, error) { + var v IntegrationKey + var raw []byte + e := row.Scan(&v.ID, &v.AdministratorID, &v.Name, &v.Prefix, &raw, &v.ExpiresAt, &v.RevokedAt, &v.LastUsedAt, &v.WebhookURL, &v.WebhookSecret, &v.CreatedAt) + if e == nil { + e = json.Unmarshal(raw, &v.Scopes) + } + return v, e +} +func (s *Store) IntegrationKeys(ctx context.Context) ([]IntegrationKey, error) { + rows, e := s.db.QueryContext(ctx, "SELECT "+integrationFields+" FROM integration_keys k ORDER BY k.id DESC LIMIT 100") + if e != nil { + return nil, e + } + defer rows.Close() + out := []IntegrationKey{} + for rows.Next() { + v, e := scanIntegrationKey(rows) + if e != nil { + return nil, e + } + out = append(out, v) + } + return out, rows.Err() +} +func (s *Store) IntegrationKeyByToken(ctx context.Context, hash string) (IntegrationKey, error) { + return scanIntegrationKey(s.db.QueryRowContext(ctx, "SELECT "+integrationFields+" FROM integration_keys k JOIN users u ON u.id=k.administrator_id WHERE k.token_hash=? AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.role='admin' AND u.status='active'", hash)) +} +func (s *Store) IntegrationKeyActive(ctx context.Context, id uint64) bool { + var v bool + e := s.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM integration_keys k JOIN users u ON u.id=k.administrator_id WHERE k.id=? AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.status='active' AND u.role='admin')", id).Scan(&v) + return e == nil && v +} +func (s *Store) CreateIntegrationKey(ctx context.Context, v IntegrationKey, hash string) (uint64, error) { + raw, _ := json.Marshal(v.Scopes) + r, e := s.db.ExecContext(ctx, "INSERT INTO integration_keys(administrator_id,name,token_hash,token_prefix,scopes_json,expires_at,webhook_url,webhook_secret_cipher) VALUES(?,?,?,?,?,?,?,?)", v.AdministratorID, v.Name, hash, v.Prefix, raw, v.ExpiresAt, v.WebhookURL, v.WebhookSecret) + if e != nil { + return 0, e + } + id, _ := r.LastInsertId() + return uint64(id), nil +} +func (s *Store) RevokeIntegrationKey(ctx context.Context, id uint64) error { + _, e := s.db.ExecContext(ctx, "UPDATE integration_keys SET revoked_at=COALESCE(revoked_at,UTC_TIMESTAMP()) WHERE id=?", id) + return e +} +func (s *Store) TouchIntegrationKey(ctx context.Context, id uint64) { + _, _ = s.db.ExecContext(ctx, "UPDATE integration_keys SET last_used_at=UTC_TIMESTAMP() WHERE id=?", id) +} +func (s *Store) BatchIntegrationKey(ctx context.Context, batch uint64) (uint64, error) { + var id uint64 + e := s.db.QueryRowContext(ctx, "SELECT COALESCE(integration_key_id,0) FROM admin_batches WHERE id=?", batch).Scan(&id) + return id, e +} + +type IntegrationWebhook struct { + ID uint64 `json:"id"` + EventID string `json:"eventId"` + KeyID uint64 `json:"keyId"` + BatchID uint64 `json:"batchId"` + State string `json:"state"` + Attempts int `json:"attempts"` + NextAttempt time.Time `json:"nextAttempt"` + Status int `json:"status"` + LastError string `json:"lastError"` + URL string `json:"-"` + Secret []byte `json:"-"` + Prefix string `json:"-"` +} + +func (s *Store) QueueIntegrationWebhooks(ctx context.Context) error { + _, e := s.db.ExecContext(ctx, `INSERT IGNORE INTO integration_webhooks(event_id,key_id,batch_id,next_attempt_at) SELECT LOWER(REPLACE(UUID(),'-','')),k.id,b.id,UTC_TIMESTAMP() FROM admin_batches b JOIN integration_keys k ON k.id=b.integration_key_id WHERE b.state IN ('completed','partial') AND k.webhook_url<>'' AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP()`) + return e +} +func (s *Store) IntegrationWebhooks(ctx context.Context, due bool) ([]IntegrationWebhook, error) { + query := `SELECT w.id,w.event_id,w.key_id,w.batch_id,w.state,w.attempts,w.next_attempt_at,w.last_status,w.last_error,k.webhook_url,k.webhook_secret_cipher,k.token_prefix FROM integration_webhooks w JOIN integration_keys k ON k.id=w.key_id` + if due { + query += ` JOIN users u ON u.id=k.administrator_id WHERE w.state='pending' AND w.attempts<8 AND w.next_attempt_at<=UTC_TIMESTAMP() AND k.revoked_at IS NULL AND k.expires_at>UTC_TIMESTAMP() AND u.status='active' AND u.role='admin' ORDER BY w.id LIMIT 10` + } else { + query += " ORDER BY w.id DESC LIMIT 100" + } + rows, e := s.db.QueryContext(ctx, query) + if e != nil { + return nil, e + } + defer rows.Close() + out := []IntegrationWebhook{} + for rows.Next() { + var v IntegrationWebhook + if e = rows.Scan(&v.ID, &v.EventID, &v.KeyID, &v.BatchID, &v.State, &v.Attempts, &v.NextAttempt, &v.Status, &v.LastError, &v.URL, &v.Secret, &v.Prefix); e != nil { + return nil, e + } + out = append(out, v) + } + return out, rows.Err() +} +func (s *Store) FinishIntegrationWebhook(ctx context.Context, v IntegrationWebhook, delivered bool, status int) error { + state := "pending" + if delivered { + state = "delivered" + } else if v.Attempts+1 >= 8 { + state = "failed" + } + delay := time.Duration(1<= "012_" { + continue + } + raw, err := migrations.Files.ReadFile(entry.Name()) + if err != nil { + t.Fatal(err) + } + for _, statement := range strings.Split(string(raw), ";") { + if strings.TrimSpace(statement) == "" { + continue + } + if _, err = database.db.ExecContext(ctx, statement); err != nil { + t.Fatal(err) + } + } + if _, err = database.db.ExecContext(ctx, "INSERT INTO schema_migrations(version) VALUES(?)", entry.Name()); err != nil { + t.Fatal(err) + } + } + // This fixture intentionally predates migration 014's bandwidth_mbps. + // Read only historical columns until the current migrations have run. + var plan Plan + if err = database.db.QueryRowContext(ctx, "SELECT id,process_limit FROM plans ORDER BY id LIMIT 1").Scan(&plan.ID, &plan.ProcessLimit); err != nil { + t.Fatalf("legacy plan fixture: %v", err) + } + tenant, err := database.CreateTenant(ctx, NewTenant{Slug: "legacy-test", Name: "旧版迁移测试", Email: "legacy@example.invalid", DisplayName: "迁移测试", Password: "legacy-test-only-12345", PlanID: plan.ID}) + if err != nil { + t.Fatal(err) + } + expiry := time.Now().UTC().Add(-5 * 24 * time.Hour).Truncate(time.Second) + if _, err = database.db.ExecContext(ctx, `UPDATE tenants SET status='suspended',lifecycle_state='recycle',expires_at=?,grace_until=DATE_ADD(?,INTERVAL 3 DAY),purge_after=DATE_ADD(?,INTERVAL 10 DAY),backup_purge_after=DATE_ADD(?,INTERVAL 24 DAY) WHERE id=?`, expiry, expiry, expiry, expiry, tenant); err != nil { + t.Fatal(err) + } + result, err := database.db.ExecContext(ctx, `INSERT INTO projects(tenant_id,host_name,slug,runtime,runtime_version,root_path,run_path,assigned_domain,panel_site_id,backend_port,process_limit,status) VALUES(?,'sv3333333333','legacy-host','PHP','8.4','/www/wwwroot/seavHost/vHost/sv3333333333','/custom','sv3333333333.legacy.example.invalid',1001,20000,7,'stopped')`, tenant) + if err != nil { + t.Fatal(err) + } + id, _ := result.LastInsertId() + _, err = database.db.ExecContext(ctx, `INSERT INTO sites(tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,panel_site_id,backend_port,process_limit,status,is_primary) VALUES(?,?,'legacy-site','sv3333333333.legacy.example.invalid','/custom','PHP','8.4',1001,20000,7,'stopped',TRUE)`, tenant, id) + if err != nil { + t.Fatal(err) + } + if interrupted { + raw, err := migrations.Files.ReadFile("012_control_nodes.sql") + if err != nil { + t.Fatal(err) + } + for _, statement := range strings.Split(string(raw), ";") { + statement = strings.TrimSpace(statement) + if statement == "" { + continue + } + if _, err = database.db.ExecContext(ctx, statement); err != nil { + t.Fatal(err) + } + // Simulate a process dying after the old account lifecycle was reset, + // without recording the migration version. Expiry must not be lost. + if strings.HasPrefix(statement, "UPDATE tenants SET status='active'") { + break + } + } + } + if err = database.Migrate(ctx); err != nil { + t.Fatal(err) + } + if err = database.Migrate(ctx); err != nil { + t.Fatal(err) + } + project, err := database.Project(ctx, tenant, uint64(id)) + if err != nil { + t.Fatal(err) + } + owner, err := database.ProjectOwner(ctx, project.ID) + if err != nil || owner == nil || *owner != tenant { + t.Fatalf("legacy customer ownership was not backfilled: %v", err) + } + if project.NodeID != 1 || project.PlanID != plan.ID || project.ProcessLimit != int(plan.ProcessLimit) || project.Status != "stopped" || project.RunPath != "/custom" || project.Domain != "sv3333333333.legacy.example.invalid" { + t.Fatalf("legacy host changed unexpectedly: %+v", project) + } + sites, err := database.ListSites(ctx, tenant, project.ID) + if err != nil || len(sites) != 1 || sites[0].ProcessLimit != int(plan.ProcessLimit) || sites[0].Status != "stopped" { + t.Fatalf("legacy site migration: %+v %v", sites, err) + } + var copied time.Time + var state string + if err = database.db.QueryRowContext(ctx, "SELECT expires_at,lifecycle_state FROM projects WHERE id=?", id).Scan(&copied, &state); err != nil || !copied.Equal(expiry) || state != "recycle" { + t.Fatalf("legacy expiry not preserved: %v %s %v", copied, state, err) + } + if _, err = database.TenantOwner(ctx, tenant); err != nil { + t.Fatalf("host expiry still disables the user: %v", err) + } + p, _, err := database.PlanAndUsage(scope.WithProject(ctx, project.ID, 1), tenant) + if err != nil || p.ID != plan.ID { + t.Fatalf("host plan mapping: %+v %v", p, err) + } + t.Log("existing single-node host, stopped state, custom run directory, assigned domain, full per-host process allowance, expiration and user account separation preserved") +} diff --git a/backend/internal/store/migration_control_nodes.go b/backend/internal/store/migration_control_nodes.go new file mode 100644 index 0000000..5061390 --- /dev/null +++ b/backend/internal/store/migration_control_nodes.go @@ -0,0 +1,60 @@ +package store + +import ( + "context" + "regexp" + "strings" +) + +var controlTable = regexp.MustCompile(`^CREATE TABLE ([a-z_]+) \(`) +var controlAdd = regexp.MustCompile(`^ALTER TABLE ([a-z_]+) ADD (COLUMN|CONSTRAINT|UNIQUE KEY|KEY) ([a-z_]+)\b`) +var controlDrop = regexp.MustCompile(`^ALTER TABLE ([a-z_]+) DROP INDEX ([a-z_]+)$`) + +// Migration 012 contains many autocommitting DDL statements. Inspect the actual +// schema before each one so a timeout, restart or response loss can resume it. +// Its data backfills are deliberately idempotent as well (see the SQL source). +func (s *Store) applyControlNodeStatement(ctx context.Context, statement string) error { + var query string + var args []any + if match := controlTable.FindStringSubmatch(statement); match != nil { + query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=?" + args = []any{match[1]} + } else if match := controlAdd.FindStringSubmatch(statement); match != nil { + switch match[2] { + case "COLUMN": + query = "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? AND column_name=?" + case "CONSTRAINT": + query = "SELECT COUNT(*) FROM information_schema.table_constraints WHERE constraint_schema=DATABASE() AND table_name=? AND constraint_name=?" + case "UNIQUE KEY", "KEY": + query = "SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? AND index_name=?" + } + args = []any{match[1], match[3]} + } else if match := controlDrop.FindStringSubmatch(statement); match != nil { + var count int + if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name=? AND index_name=?", match[1], match[2]).Scan(&count); err != nil { + return err + } + if count == 0 { + return nil + } + } else if strings.HasPrefix(statement, "ALTER TABLE runtime_update_notices DROP PRIMARY KEY") { + var columns string + if err := s.db.QueryRowContext(ctx, "SELECT COALESCE(GROUP_CONCAT(column_name ORDER BY seq_in_index),'') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='runtime_update_notices' AND index_name='PRIMARY'").Scan(&columns); err != nil { + return err + } + if columns == "node_id,release_key" { + return nil + } + } + if query != "" { + var count int + if err := s.db.QueryRowContext(ctx, query, args...).Scan(&count); err != nil { + return err + } + if count > 0 { + return nil + } + } + _, err := s.db.ExecContext(ctx, statement) + return err +} diff --git a/backend/internal/store/models.go b/backend/internal/store/models.go new file mode 100644 index 0000000..68cd1fb --- /dev/null +++ b/backend/internal/store/models.go @@ -0,0 +1,345 @@ +package store + +import "time" + +type User struct { + Impersonating bool `json:"impersonating,omitempty"` + ImpersonationExpiresAt *time.Time `json:"impersonationExpiresAt,omitempty"` + ID uint64 `json:"id"` + TenantID *uint64 `json:"tenantId,omitempty"` + ProjectID *uint64 `json:"projectId,omitempty"` + LoginName string `json:"loginName"` + Email string `json:"email,omitempty"` + DisplayName string `json:"displayName"` + PasswordHash string `json:"-"` + Role string `json:"role"` + TenantName string `json:"tenantName,omitempty"` + TenantSlug string `json:"tenantSlug,omitempty"` + MFAEnabled bool `json:"mfaEnabled"` +} + +type UserSecurity struct { + PasswordHash string + TOTPSecretCiphertext []byte + TOTPEnabled bool +} + +type Plan struct { + DeleteBlockedReason string `json:"deleteBlockedReason,omitempty"` + ID uint64 `json:"id"` + Name string `json:"name"` + StorageBytes uint64 `json:"storageBytes"` + DatabaseBytes uint64 `json:"databaseBytes"` + BandwidthBytes uint64 `json:"bandwidthBytes"` + BandwidthMbps uint32 `json:"bandwidthMbps"` + ProcessLimit uint32 `json:"processLimit"` + FTPLimit uint32 `json:"ftpLimit"` + DatabaseLimit uint32 `json:"databaseLimit"` + ProjectLimit uint32 `json:"projectLimit"` + CreatedAt time.Time `json:"createdAt"` +} + +type NewPlan struct { + Name string + StorageBytes, DatabaseBytes, BandwidthBytes uint64 + ProcessLimit, FTPLimit, DatabaseLimit, ProjectLimit uint32 + BandwidthMbps uint32 +} + +type ResourceCounts struct { + FTP, Databases uint32 +} + +type Usage struct { + StorageBytes uint64 `json:"storageBytes"` + DatabaseBytes uint64 `json:"databaseBytes"` + BandwidthBytes uint64 `json:"bandwidthBytes"` + ProcessCount uint32 `json:"processCount"` + MeasuredAt time.Time `json:"measuredAt"` +} + +type Project struct { + AllowRuntimeChange bool `json:"allowRuntimeChange"` + BandwidthBytes uint64 `json:"bandwidthBytes"` + NodeID uint64 `json:"nodeId"` + PlanID uint64 `json:"planId"` + ID uint64 `json:"id"` + TenantID uint64 `json:"-"` + HostName string `json:"hostName"` + Slug string `json:"name"` + Domain string `json:"domain"` + Path string `json:"path"` + RunPath string `json:"runPath"` + Runtime string `json:"runtime"` + Version string `json:"version"` + Status string `json:"status"` + SSLStatus string `json:"sslStatus"` + PanelSiteID int64 `json:"-"` + BackendPort int `json:"backendPort"` + ProcessLimit int `json:"processLimit"` + AutoSSL bool `json:"autoSSL"` + CreatedAt time.Time `json:"createdAt"` +} + +type Site struct { + ID uint64 `json:"id"` + TenantID uint64 `json:"-"` + ProjectID uint64 `json:"projectId"` + Name string `json:"name"` + Domain string `json:"domain"` + RunPath string `json:"runPath"` + Runtime string `json:"runtime"` + Version string `json:"version"` + Status string `json:"status"` + SSLStatus string `json:"sslStatus"` + PanelSiteID int64 `json:"-"` + BackendPort int `json:"backendPort"` + ProcessLimit int `json:"processLimit"` + AutoSSL bool `json:"autoSSL"` + Primary bool `json:"primary"` + CreatedAt time.Time `json:"createdAt"` +} + +// DNSCredential is safe to return through the API. CredentialCiphertext and +// SecretRef are deliberately excluded from JSON and only used by the issuance +// service after an ownership-scoped database lookup. +type DNSCredential struct { + ID uint64 `json:"id"` + TenantID *uint64 `json:"-"` + ScopeKey string `json:"scope"` + SecretRef string `json:"-"` + Label string `json:"label"` + Provider string `json:"provider"` + ZoneName string `json:"zoneName"` + CredentialCiphertext []byte `json:"-"` + LastTestedAt *time.Time `json:"lastTestedAt,omitempty"` + TestStatus string `json:"testStatus"` + TestError string `json:"testError,omitempty"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type NewDNSCredential struct { + TenantID *uint64 + ScopeKey string + SecretRef string + Label string + Provider string + ZoneName string + CredentialCiphertext []byte +} + +type CertificateAutomation struct { + SiteID uint64 `json:"siteId"` + Mode string `json:"mode"` + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + LastAttemptAt *time.Time `json:"lastAttemptAt,omitempty"` + NextAttemptAt *time.Time `json:"nextAttemptAt,omitempty"` + LastError string `json:"lastError,omitempty"` +} + +type CertificateRenewal struct { + Project Project + Site Site +} + +type DomainResource struct { + ID uint64 `json:"id"` + TenantID uint64 `json:"-"` + ProjectID uint64 `json:"projectId"` + SiteID uint64 `json:"siteId"` + TenantName string `json:"tenantName,omitempty"` + HostName string `json:"hostName"` + ProjectName string `json:"projectName"` + SiteName string `json:"siteName"` + Domain string `json:"domain"` + Kind string `json:"kind"` + Status string `json:"status"` + ResolutionMode string `json:"resolutionMode"` + CNAME string `json:"cnameTarget,omitempty"` + DNSCredentialID *uint64 `json:"dnsCredentialId,omitempty"` + DNSRecordID string `json:"dnsRecordId,omitempty"` + DNSRecordType string `json:"dnsRecordType,omitempty"` + DNSLastError string `json:"dnsLastError,omitempty"` + FilingStatus string `json:"filingStatus"` + FilingNumber string `json:"filingNumber,omitempty"` + FilingNote string `json:"filingNote,omitempty"` + SSLStatus string `json:"sslStatus"` + PanelSiteID int64 `json:"-"` + SiteAssignedDomain string `json:"-"` + RootPath string `json:"-"` + AutoSSL bool `json:"-"` + CreatedAt time.Time `json:"createdAt"` +} + +type FTPResource struct { + Enabled bool `json:"enabled"` + ID uint64 `json:"id"` + TenantID uint64 `json:"-"` + PanelID int64 `json:"-"` + ProjectID uint64 `json:"projectId"` + HostName string `json:"hostName"` + ProjectName string `json:"projectName"` + Username string `json:"username"` + RootPath string `json:"rootPath"` + CreatedAt time.Time `json:"createdAt"` +} + +type DatabaseResource struct { + ID uint64 `json:"id"` + TenantID uint64 `json:"-"` + PanelID int64 `json:"-"` + ProjectID uint64 `json:"projectId"` + HostName string `json:"hostName"` + ProjectName string `json:"projectName"` + Name string `json:"name"` + Username string `json:"username"` + SizeBytes uint64 `json:"sizeBytes"` + Status string `json:"status"` + CreatedAt time.Time `json:"createdAt"` +} + +type NewSite struct { + TenantID, ProjectID uint64 + Name, Domain, RunPath, Runtime string + Version string + BackendPort, ProcessLimit int + AutoSSL, Primary bool +} + +type StoredCredentials struct { + FTPUsername, DatabaseName, DatabaseUsername string + FTPPasswordCipher, DatabasePasswordCipher []byte +} + +type NewProject struct { + OwnerTenantID *uint64 + OwnershipSpecified bool + NodeID, PlanID uint64 + TenantID uint64 + HostName, Slug, Runtime, Version, Path, RunPath, Domain string + BackendPort, ProcessLimit int + AutoSSL bool + HostPasswordHash string +} + +type Activity struct { + ID uint64 `json:"id"` + ProjectID *uint64 `json:"projectId,omitempty"` + HostName string `json:"hostName,omitempty"` + Actor string `json:"actor"` + IPAddress string `json:"ipAddress,omitempty"` + Action string `json:"action"` + ResourceType string `json:"resourceType"` + Detail string `json:"detail"` + Success bool `json:"success"` + CreatedAt time.Time `json:"createdAt"` +} + +type TenantSummary struct { + ID uint64 `json:"id"` + Slug string `json:"slug"` + Name string `json:"name"` + Status string `json:"status"` + LifecycleState string `json:"lifecycleState"` + PlanName string `json:"planName"` + UserCount int `json:"userCount"` + ProjectCount int `json:"projectCount"` + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + GraceUntil *time.Time `json:"graceUntil,omitempty"` + PurgeAfter *time.Time `json:"purgeAfter,omitempty"` + BackupPurgeAfter *time.Time `json:"backupPurgeAfter,omitempty"` + CreatedAt time.Time `json:"createdAt"` +} + +type AdminProject struct { + ManualRecycledAt *time.Time `json:"manualRecycledAt,omitempty"` + PurgeAfter *time.Time `json:"purgeAfter,omitempty"` + RecycleError string `json:"recycleError,omitempty"` + PendingOwnership *OwnershipChange `json:"pendingOwnership,omitempty"` + OwnerTenantID *uint64 `json:"ownerTenantId"` + ManagementLocked bool `json:"managementLocked"` + OwnershipVersion uint64 `json:"ownershipVersion"` + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + LifecycleState string `json:"lifecycleState"` + Project + TenantName string `json:"tenantName"` + SiteCount int `json:"siteCount"` + IPAddress string `json:"ipAddress,omitempty"` + DedicatedIP bool `json:"dedicatedIp"` + HTTPPort int `json:"httpPort"` + HTTPSPort int `json:"httpsPort"` +} + +type IPAddress struct { + NodeID uint64 `json:"nodeId"` + ID uint64 `json:"id"` + Address string `json:"address"` + Family string `json:"family"` + AllocationMode string `json:"allocationMode"` + Label string `json:"label"` + Enabled bool `json:"enabled"` + AssignedSites int `json:"assignedSites"` + CreatedAt time.Time `json:"createdAt"` +} + +type AdminActivity struct { + AdministratorID *uint64 `json:"administratorId,omitempty"` + ImpersonatedUserID *uint64 `json:"impersonatedUserId,omitempty"` + ImpersonatedUserName string `json:"impersonatedUserName,omitempty"` + ID uint64 `json:"id"` + TenantName string `json:"userName,omitempty"` + Action string `json:"action"` + ResourceType string `json:"resourceType"` + ResourceID string `json:"resourceId,omitempty"` + IPAddress string `json:"ipAddress,omitempty"` + Success bool `json:"success"` + Detail string `json:"detail"` + CreatedAt time.Time `json:"createdAt"` +} + +type NewTenant struct { + Slug, Name, Email, DisplayName, Password string + PlanID uint64 + ExpiresAt *time.Time +} + +type TenantBackup struct { + NodeID uint64 `json:"nodeId"` + ID uint64 `json:"id"` + TenantID uint64 `json:"tenantId"` + ProjectID *uint64 `json:"projectId,omitempty"` + HostName string `json:"hostName"` + ArchivePath string `json:"-"` + SizeBytes uint64 `json:"sizeBytes"` + ExpiresAt time.Time `json:"expiresAt"` + DeletedAt *time.Time `json:"deletedAt,omitempty"` + CreatedAt time.Time `json:"createdAt"` +} + +type AdminNotification struct { + ID uint64 + Severity string + Category string + Title string + Detail string + Attempts uint32 + NextAttemptAt *time.Time +} + +type OIDCState struct { + SessionHash []byte + ProviderKey string + UserID *uint64 + Mode string + Verifier string + Nonce string + Expires time.Time +} + +type OIDCIdentity struct { + Provider string `json:"provider"` + Subject string `json:"-"` + Email string `json:"email"` + Created time.Time `json:"createdAt"` +} diff --git a/backend/internal/store/multi_node_integration_test.go b/backend/internal/store/multi_node_integration_test.go new file mode 100644 index 0000000..f58bc7e --- /dev/null +++ b/backend/internal/store/multi_node_integration_test.go @@ -0,0 +1,161 @@ +package store + +import ( + "context" + "errors" + "github.com/go-sql-driver/mysql" + "os" + "sea-vhost/internal/scope" + "strings" + "testing" + "time" +) + +// Run only against a disposable schema created by the test harness. The test +// never opens the production schema and cannot be enabled with its usual DSN. +func TestMultiNodeMySQL(t *testing.T) { + dsn := os.Getenv("SEA_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("dedicated MySQL schema not supplied") + } + config, err := mysql.ParseDSN(dsn) + if err != nil || !strings.HasPrefix(config.DBName, "svh_cluster_test_") { + t.Fatal("refusing a non-test schema") + } + db, err := Open(dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + if err = db.Migrate(ctx); err != nil { + t.Fatal(err) + } + if err = db.Migrate(ctx); err != nil { + t.Fatalf("repeat migration: %v", err) + } + plans, err := db.ListPlans(ctx) + if err != nil || len(plans) == 0 { + t.Fatalf("plans: %v", err) + } + tenant, err := db.CreateTenant(ctx, NewTenant{Slug: "cluster-test", Name: "测试用户", Email: "cluster@example.invalid", DisplayName: "测试管理员", Password: "integration-test-only-123", PlanID: plans[0].ID}) + if err != nil { + t.Fatal(err) + } + nodes := []uint64{} + hosts := []uint64{} + for i, name := range []string{"sv0123456789", "svabcdef0123"} { + node, err := db.CreateNode(ctx, Node{Name: name, Endpoint: "https://" + name + ".example.invalid:9443", RootDomain: name + ".example.invalid", TenantRoot: "/www/wwwroot/seavHost/vHost", FTPCertificateDomain: "ftp.example.invalid"}) + if err != nil { + t.Fatal(err) + } + if err = db.SetNodeEnabled(ctx, node, true); err != nil { + t.Fatal(err) + } + nodes = append(nodes, node) + id, err := db.InsertProject(ctx, NewProject{NodeID: node, PlanID: plans[0].ID, TenantID: tenant, HostName: name, Slug: name, Runtime: "PHP", Version: "8.4", Path: "/www/wwwroot/seavHost/vHost/" + name, RunPath: "/public", Domain: name + ".example.invalid", ProcessLimit: 10, HostPasswordHash: "test-hash"}) + if err != nil { + t.Fatal(err) + } + hosts = append(hosts, id) + if err = db.CompleteProject(scope.WithProject(ctx, id, node), id, 1001, 1002, 1003, name, name, name, []byte("cipher"), []byte("cipher"), "running", "", "", false); err != nil { + t.Fatalf("same native site ID on node %d: %v", i, err) + } + for _, state := range []string{"running", "running", "stopped", "stopped", "running"} { + if err = db.SetProjectState(ctx, tenant, id, state); err != nil { + t.Fatalf("idempotent primary state %s: %v", state, err) + } + } + extra, createErr := db.InsertSite(ctx, NewSite{TenantID: tenant, ProjectID: id, Name: "idempotent", Domain: name + "-extra.example.invalid", RunPath: "/extra", Runtime: "PHP", Version: "8.4", ProcessLimit: 10}) + if createErr != nil { + t.Fatal(createErr) + } + for _, state := range []string{"running", "running", "stopped", "stopped"} { + if err = db.SetSiteState(ctx, tenant, id, extra, state); err != nil { + t.Fatalf("idempotent extra site state %s: %v", state, err) + } + } + if err = db.SetSiteState(ctx, tenant, id+1, extra, "running"); !errors.Is(err, ErrNotFound) { + t.Fatalf("wrong host state accepted: %v", err) + } + if err = db.DeleteSite(ctx, tenant, id, extra); err != nil { + t.Fatal(err) + } + for _, port := range []int{18080, 18080, 80, 80} { + if err = db.SetProjectNetwork(ctx, id, nil, false, port, 443); err != nil { + t.Fatalf("upsert network %d: %v", port, err) + } + } + } + a := scope.WithProject(ctx, hosts[0], nodes[0]) + b := scope.WithProject(ctx, hosts[1], nodes[1]) + if _, _, err = db.ProjectPlacement(ctx, hosts[0]); err != nil { + t.Fatal(err) + } + if items, err := db.ListProjects(a, tenant); err != nil || len(items) != 1 || items[0].NodeID != nodes[0] { + t.Fatalf("project scope: %+v %v", items, err) + } + if items, err := db.ListProjects(ctx, tenant); err != nil || len(items) != 2 { + t.Fatalf("account aggregation: %d %v", len(items), err) + } + if sites, err := db.ListTenantSites(a, tenant, nil); err != nil || len(sites) != 1 || sites[0].ProjectID != hosts[0] { + t.Fatalf("site scope: %+v %v", sites, err) + } + if err = db.UpdateQuotaMeasurement(a, tenant, Usage{StorageBytes: 111}, time.Now(), nil, false); err != nil { + t.Fatal(err) + } + if err = db.SetTenantQuotaSuspended(a, tenant, "storage quota exceeded"); err != nil { + t.Fatal(err) + } + if _, u, err := db.PlanAndUsage(a, tenant); err != nil || u.StorageBytes != 111 { + t.Fatalf("host usage: %+v %v", u, err) + } + if suspended, _, err := db.TenantQuotaSuspension(b, tenant); err != nil || suspended { + t.Fatalf("quota affected another host: %v", err) + } + if _, u, err := db.PlanAndUsage(ctx, tenant); err != nil || u.StorageBytes != 111 { + t.Fatalf("account usage aggregate: %+v %v", u, err) + } + for _, c := range []context.Context{a, b} { + if _, err = db.CreateRuntimeJob(c, RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}); err != nil { + t.Fatalf("node job lock: %v", err) + } + } + if _, err = db.CreateRuntimeJob(a, RuntimeJob{Action: "check", Runtime: "all", TargetVersion: "-"}); err == nil { + t.Fatal("same-node concurrent maintenance accepted") + } + lease, err := db.LockNodeRegistry(ctx, nodes[0]) + if err != nil { + t.Fatal(err) + } + raw, err := lease.Read(ctx) + if err != nil || !strings.Contains(string(raw), `"sites":{}`) { + t.Fatal("empty registry missing") + } + if err = lease.Save(ctx, []byte(`{"version":1,"sites":{},"ftp":{},"databases":{}}`)); err != nil { + t.Fatal(err) + } + lease.Close() + expiry := time.Now().Add(-time.Hour) + if err = db.SetHostSubscription(a, hosts[0], plans[0].ID, &expiry); err != nil { + t.Fatal(err) + } + if err = db.AdvanceHostLifecycle(ctx, time.Now()); err != nil { + t.Fatal(err) + } + if err = db.HostWritable(a, tenant); err == nil { + t.Fatal("expired host still writable") + } + if err = db.HostWritable(b, tenant); err != nil { + t.Fatalf("expiration affected another host: %v", err) + } + if owner, err := db.TenantOwner(ctx, tenant); err != nil || owner.Role != "tenant" { + t.Fatalf("tenant account affected: %v", err) + } + admin, err := db.ListAdminProjects(ctx) + if err != nil || len(admin) != 2 { + t.Fatalf("admin projects scan: %v", err) + } + t.Log("migrations, duplicate native IDs, project quotas, account aggregation, node maintenance locks, central registry, and per-host expiration verified") +} diff --git a/backend/internal/store/nodes.go b/backend/internal/store/nodes.go new file mode 100644 index 0000000..d914a1c --- /dev/null +++ b/backend/internal/store/nodes.go @@ -0,0 +1,174 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" +) + +type Node struct { + ID uint64 `json:"id"` + Name string `json:"name"` + Transport string `json:"transport"` + Endpoint string `json:"endpoint"` + RootDomain string `json:"rootDomain"` + TenantRoot string `json:"tenantRoot"` + FTPCertificateDomain string `json:"ftpCertificateDomain"` + Enabled bool `json:"enabled"` + Credentials []byte `json:"-"` + LastSeenAt *time.Time `json:"lastSeenAt,omitempty"` + LastError string `json:"lastError"` +} + +const nodeColumns = "id,name,transport,endpoint,root_domain,tenant_root,ftp_certificate_domain,enabled,credentials,last_seen_at,last_error" + +func scanNode(row interface{ Scan(...any) error }) (Node, error) { + var n Node + err := row.Scan(&n.ID, &n.Name, &n.Transport, &n.Endpoint, &n.RootDomain, &n.TenantRoot, &n.FTPCertificateDomain, &n.Enabled, &n.Credentials, &n.LastSeenAt, &n.LastError) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return n, err +} +func (s *Store) Node(ctx context.Context, id uint64) (Node, error) { + return scanNode(s.db.QueryRowContext(ctx, "SELECT "+nodeColumns+" FROM control_nodes WHERE id=? AND deleted_at IS NULL", id)) +} +func (s *Store) Nodes(ctx context.Context) ([]Node, error) { + rows, err := s.db.QueryContext(ctx, "SELECT "+nodeColumns+" FROM control_nodes WHERE deleted_at IS NULL ORDER BY id") + if err != nil { + return nil, err + } + defer rows.Close() + result := []Node{} + for rows.Next() { + n, e := scanNode(rows) + if e != nil { + return nil, e + } + result = append(result, n) + } + return result, rows.Err() +} +func (s *Store) InitializeLocalNode(ctx context.Context, domain, root, ftp string) error { + _, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET root_domain=?,tenant_root=?,ftp_certificate_domain=? WHERE id=1 AND transport='local' AND root_domain=''", domain, root, ftp) + return err +} +func (s *Store) CreateNode(ctx context.Context, n Node) (uint64, error) { + r, err := s.db.ExecContext(ctx, `INSERT INTO control_nodes(name,transport,endpoint,root_domain,tenant_root,ftp_certificate_domain,enabled,registry_json) VALUES(?,'https',?,?,?,?,FALSE,'{"version":1,"sites":{},"ftp":{},"databases":{}}')`, n.Name, n.Endpoint, n.RootDomain, n.TenantRoot, n.FTPCertificateDomain) + if err != nil { + return 0, err + } + id, err := r.LastInsertId() + return uint64(id), err +} +func (s *Store) SetNodeCredentials(ctx context.Context, id uint64, cipher []byte) error { + _, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET credentials=?,enabled=FALSE,last_seen_at=NULL,last_error='' WHERE id=? AND deleted_at IS NULL AND transport='https'", cipher, id) + return err +} +func (s *Store) SetNodeEnabled(ctx context.Context, id uint64, enabled bool) error { + r, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET enabled=? WHERE id=? AND deleted_at IS NULL", enabled, id) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n == 0 { + _, err = s.Node(ctx, id) + } + return err +} +func (s *Store) RecordNodeProbe(ctx context.Context, id uint64, detail string) error { + if len(detail) > 500 { + detail = detail[:500] + } + if detail == "" { + _, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET last_seen_at=UTC_TIMESTAMP(),last_error='' WHERE id=?", id) + return err + } + _, err := s.db.ExecContext(ctx, "UPDATE control_nodes SET last_error=? WHERE id=?", detail, id) + return err +} +func (s *Store) NodeForHost(ctx context.Context, host string) (uint64, error) { + var id uint64 + err := s.db.QueryRowContext(ctx, "SELECT node_id FROM projects WHERE host_name=?", host).Scan(&id) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return id, err +} +func (s *Store) ProjectPlacement(ctx context.Context, id uint64) (nodeID, planID uint64, err error) { + err = s.db.QueryRowContext(ctx, "SELECT node_id,COALESCE(plan_id,0) FROM projects WHERE id=?", id).Scan(&nodeID, &planID) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return +} +func (s *Store) NodeForSite(ctx context.Context, id uint64) (uint64, error) { + var node uint64 + err := s.db.QueryRowContext(ctx, "SELECT node_id FROM sites WHERE id=?", id).Scan(&node) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return node, err +} + +// The registry lives only in the controller DB. A per-node MySQL named lock +// serializes snapshots across foreground requests and scheduler workers. +type NodeRegistryLease struct { + conn *sql.Conn + id uint64 + key string +} + +func (s *Store) LockNodeRegistry(ctx context.Context, id uint64) (*NodeRegistryLease, error) { + conn, err := s.db.Conn(ctx) + if err != nil { + return nil, err + } + key := fmt.Sprintf("sea-vhost/node/%d", id) + var acquired sql.NullInt64 + if err = conn.QueryRowContext(ctx, "SELECT GET_LOCK(?,10)", key).Scan(&acquired); err != nil || !acquired.Valid || acquired.Int64 != 1 { + conn.Close() + return nil, errors.New("node controller operation is busy") + } + return &NodeRegistryLease{conn: conn, id: id, key: key}, nil +} +func (l *NodeRegistryLease) Read(ctx context.Context) ([]byte, error) { + var raw string + err := l.conn.QueryRowContext(ctx, "SELECT registry_json FROM control_nodes WHERE id=? AND deleted_at IS NULL", l.id).Scan(&raw) + return []byte(raw), err +} +func (l *NodeRegistryLease) Save(ctx context.Context, raw []byte) error { + _, err := l.conn.ExecContext(ctx, "UPDATE control_nodes SET registry_json=?,registry_revision=registry_revision+1 WHERE id=?", string(raw), l.id) + return err +} +func (l *NodeRegistryLease) Close() { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _, _ = l.conn.ExecContext(ctx, "SELECT RELEASE_LOCK(?)", l.key) + _ = l.conn.Close() +} + +func (s *Store) StartControlTask(ctx context.Context, nodeID, projectID uint64, operation, requestID string) (uint64, error) { + var project any + if projectID > 0 { + project = projectID + } + r, err := s.db.ExecContext(ctx, "INSERT INTO control_tasks(node_id,project_id,operation,request_id,started_at) VALUES(?,?,?,?,UTC_TIMESTAMP())", nodeID, project, operation, requestID) + if err != nil { + return 0, err + } + id, err := r.LastInsertId() + return uint64(id), err +} +func (s *Store) FinishControlTask(ctx context.Context, id uint64, state, detail string) error { + if state != "succeeded" && state != "failed" && state != "uncertain" { + return errors.New("invalid controller task state") + } + if len(detail) > 500 { + detail = detail[:500] + } + _, err := s.db.ExecContext(ctx, "UPDATE control_tasks SET state=?,detail=?,finished_at=UTC_TIMESTAMP() WHERE id=?", state, detail, id) + return err +} diff --git a/backend/internal/store/ownership.go b/backend/internal/store/ownership.go new file mode 100644 index 0000000..39b98b4 --- /dev/null +++ b/backend/internal/store/ownership.go @@ -0,0 +1,185 @@ +package store + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/hex" + "errors" + "sea-vhost/internal/scope" + "strconv" + "strings" +) + +var ErrManagementLocked = errors.New("主机正在处理环境或归属变更,请稍后重试;持续未恢复时请联系管理员核验任务") + +func (s *Store) BindUnassignedHost(ctx context.Context, id, version, target uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var current sql.NullInt64 + var actual uint64 + var locked bool + if err = tx.QueryRowContext(ctx, "SELECT owner_tenant_id,ownership_version,(management_locked OR manual_recycled_at IS NOT NULL) FROM projects WHERE id=? FOR UPDATE", id).Scan(¤t, &actual, &locked); err != nil { + return ErrNotFound + } + if actual != version { + return errors.New("主机归属已变化,请重新预览") + } + if locked { + return ErrManagementLocked + } + if (current.Valid && uint64(current.Int64) == target) || (!current.Valid && target == 0) { + return tx.Commit() + } + if current.Valid { + return errors.New("已有归属的主机须按已确认的凭据撤销策略处理") + } + var account uint64 + if err = tx.QueryRowContext(ctx, "SELECT 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.status='active' AND u.status='active' FOR UPDATE", target).Scan(&account); err != nil { + return errors.New("目标用户不存在或已停用") + } + if _, err = tx.ExecContext(ctx, "UPDATE projects SET owner_tenant_id=?,ownership_version=ownership_version+1 WHERE id=?", target, id); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) AccountIdentityExists(ctx context.Context, slug, login string) (bool, error) { + var count int + err := s.db.QueryRowContext(ctx, "SELECT (SELECT COUNT(*) FROM tenants WHERE slug=?)+(SELECT COUNT(*) FROM users WHERE email=? OR login_name=?)", slug, login, login).Scan(&count) + return count > 0, err +} +func (s *Store) ResolveAnyAccount(ctx context.Context, reference string) (uint64, error) { + reference = strings.ToLower(strings.TrimSpace(reference)) + numeric, _ := strconv.ParseUint(reference, 10, 64) + var id uint64 + query := "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND (t.slug=? OR u.login_name=?) ORDER BY t.id LIMIT 1" + args := []any{reference, reference} + if numeric > 0 { + query = "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND t.id=?" + args = []any{numeric} + } + err := s.db.QueryRowContext(ctx, query, args...).Scan(&id) + return id, err +} + +// CustomerFilter is used only for customer-facing aggregate queries. A scoped +// host request uses the internal namespace supplied after authorization. +func customerFilter(ctx context.Context, tenantID uint64, projectAlias, resourceAlias string) (string, []any) { + if account := scope.Account(ctx); account > 0 { + return projectAlias + ".owner_tenant_id=? AND " + projectAlias + ".management_locked=FALSE AND " + projectAlias + ".manual_recycled_at IS NULL", []any{account} + } + return resourceAlias + ".tenant_id=?", []any{tenantID} +} + +func (s *Store) ProjectForUser(ctx context.Context, user User, id uint64) (Project, error) { + if user.TenantID == nil { + return Project{}, ErrNotFound + } + var namespace uint64 + var owner sql.NullInt64 + var locked bool + if err := s.db.QueryRowContext(ctx, "SELECT tenant_id,owner_tenant_id,(management_locked OR manual_recycled_at IS NOT NULL) FROM projects WHERE id=?", id).Scan(&namespace, &owner, &locked); err != nil { + return Project{}, ErrNotFound + } + if user.Role == "host" { + if user.ProjectID == nil || *user.ProjectID != id || *user.TenantID != namespace { + return Project{}, ErrNotFound + } + } else if user.Role == "tenant" { + account := scope.Account(ctx) + if account == 0 { + account = *user.TenantID + } + if !owner.Valid || uint64(owner.Int64) != account { + return Project{}, ErrNotFound + } + } else { + return Project{}, ErrNotFound + } + if locked { + return Project{}, ErrManagementLocked + } + return s.Project(ctx, namespace, id) +} + +func (s *Store) ProjectOwner(ctx context.Context, id uint64) (*uint64, error) { + var value sql.NullInt64 + if err := s.db.QueryRowContext(ctx, "SELECT owner_tenant_id FROM projects WHERE id=?", id).Scan(&value); err != nil { + return nil, err + } + if !value.Valid { + return nil, nil + } + id = uint64(value.Int64) + return &id, nil +} + +func (s *Store) NewResourceNamespace(ctx context.Context, planID uint64) (uint64, error) { + var token [16]byte + if _, err := rand.Read(token[:]); err != nil { + return 0, err + } + result, err := s.db.ExecContext(ctx, "INSERT INTO tenants(slug,name,plan_id,resource_namespace) VALUES (?,?,?,TRUE)", "internal-"+hex.EncodeToString(token[:]), "独立主机资源", planID) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + return uint64(id), err +} +func (s *Store) DeleteUnusedResourceNamespace(ctx context.Context, id uint64) error { + _, err := s.db.ExecContext(ctx, "DELETE FROM tenants WHERE id=? AND resource_namespace=TRUE AND NOT EXISTS(SELECT 1 FROM projects WHERE tenant_id=?) AND NOT EXISTS(SELECT 1 FROM tenant_backups WHERE tenant_id=?)", id, id, id) + return err +} + +func (s *Store) ResolveAccount(ctx context.Context, reference string) (uint64, error) { + reference = strings.ToLower(strings.TrimSpace(reference)) + if reference == "" { + return 0, nil + } + var id uint64 + numeric, _ := strconv.ParseUint(reference, 10, 64) + query := `SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND t.status='active' AND u.status='active' AND (BINARY t.slug=BINARY ? OR BINARY u.login_name=BINARY ?) ORDER BY t.id LIMIT 1` + args := []any{reference, reference} + if numeric > 0 { + query = `SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.resource_namespace=FALSE AND t.deleted_at IS NULL AND t.status='active' AND u.status='active' AND t.id=?` + args = []any{numeric} + } + err := s.db.QueryRowContext(ctx, query, args...).Scan(&id) + if err != nil { + return 0, errors.New("用户账号不存在或已停用") + } + return id, nil +} + +func (s *Store) SetAccountEnabled(ctx context.Context, id uint64, enabled bool) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var internal bool + if err = tx.QueryRowContext(ctx, "SELECT resource_namespace FROM tenants WHERE id=? AND deleted_at IS NULL FOR UPDATE", id).Scan(&internal); err != nil || internal { + return ErrNotFound + } + status := "disabled" + if enabled { + status = "active" + if _, err = tx.ExecContext(ctx, "UPDATE tenants SET status='active' WHERE id=?", id); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, "UPDATE users SET status=? WHERE tenant_id=? AND role='tenant'", status, id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.tenant_id=? AND u.role='tenant'", id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=? AND u.role='tenant'", id); err != nil { + return err + } + return tx.Commit() +} diff --git a/backend/internal/store/ownership_changes.go b/backend/internal/store/ownership_changes.go new file mode 100644 index 0000000..e574254 --- /dev/null +++ b/backend/internal/store/ownership_changes.go @@ -0,0 +1,140 @@ +package store + +import ( + "context" + "errors" +) + +type OwnershipChange struct { + ProjectID uint64 `json:"projectId"` + TargetOwnerID *uint64 `json:"targetOwnerId"` + ExpectedVersion uint64 `json:"expectedVersion"` + CredentialMode string `json:"credentialMode"` + StopServices bool `json:"stopServices"` + State string `json:"state"` + CredentialsCipher []byte `json:"-"` +} + +func (s *Store) OwnershipChange(ctx context.Context, id uint64) (OwnershipChange, error) { + var value OwnershipChange + err := s.db.QueryRowContext(ctx, "SELECT project_id,target_owner_id,expected_version,credential_mode,stop_services,state,credentials_cipher FROM host_ownership_changes WHERE project_id=?", id).Scan(&value.ProjectID, &value.TargetOwnerID, &value.ExpectedVersion, &value.CredentialMode, &value.StopServices, &value.State, &value.CredentialsCipher) + return value, err +} +func sameOwner(a *uint64, b uint64) bool { return (a == nil && b == 0) || (a != nil && *a == b) } +func (s *Store) BeginOwnershipChange(ctx context.Context, id, version, target uint64, mode string, stop, resume bool, cipher []byte) (OwnershipChange, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return OwnershipChange{}, err + } + defer tx.Rollback() + var owner *uint64 + var actual uint64 + var locked bool + if err = tx.QueryRowContext(ctx, "SELECT owner_tenant_id,ownership_version,management_locked FROM projects WHERE id=? AND manual_recycled_at IS NULL FOR UPDATE", id).Scan(&owner, &actual, &locked); err != nil { + return OwnershipChange{}, err + } + if actual != version { + return OwnershipChange{}, errors.New("主机归属已变化,请重新预览") + } + if locked { + if !resume { + return OwnershipChange{}, ErrManagementLocked + } + var pending OwnershipChange + err = tx.QueryRowContext(ctx, "SELECT project_id,target_owner_id,expected_version,credential_mode,stop_services,state,credentials_cipher FROM host_ownership_changes WHERE project_id=?", id).Scan(&pending.ProjectID, &pending.TargetOwnerID, &pending.ExpectedVersion, &pending.CredentialMode, &pending.StopServices, &pending.State, &pending.CredentialsCipher) + if err != nil || pending.State != "pending" || !sameOwner(pending.TargetOwnerID, target) || pending.ExpectedVersion != version || pending.CredentialMode != mode || pending.StopServices != stop { + return pending, errors.New("恢复任务必须与未完成任务的目标用户和策略一致") + } + return pending, tx.Commit() + } + if target > 0 { + var found uint64 + if err = tx.QueryRowContext(ctx, "SELECT t.id FROM tenants t JOIN users u ON u.tenant_id=t.id AND u.role='tenant' WHERE t.id=? AND t.status='active' AND t.resource_namespace=FALSE AND u.status='active' FOR UPDATE", target).Scan(&found); err != nil { + return OwnershipChange{}, errors.New("目标账号不可用") + } + } + var targetValue any + if target > 0 { + targetValue = target + } + _, err = tx.ExecContext(ctx, `INSERT INTO host_ownership_changes(project_id,source_owner_id,target_owner_id,expected_version,credential_mode,stop_services,state,credentials_cipher) VALUES(?,?,?,?,?,?,'pending',?) ON DUPLICATE KEY UPDATE source_owner_id=VALUES(source_owner_id),target_owner_id=VALUES(target_owner_id),expected_version=VALUES(expected_version),credential_mode=VALUES(credential_mode),stop_services=VALUES(stop_services),state='pending',credentials_cipher=VALUES(credentials_cipher)`, id, owner, targetValue, version, mode, stop, cipher) + if err != nil { + return OwnershipChange{}, err + } + for _, statement := range []string{"UPDATE user_schedules SET enabled=FALSE,run_requested=FALSE,last_state='ownership_paused' WHERE project_id=?", "UPDATE projects SET management_locked=TRUE WHERE id=?", "UPDATE users SET status='disabled' WHERE project_id=? AND role='host'", "DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.project_id=?", "DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.project_id=?"} { + if _, err = tx.ExecContext(ctx, statement, id); err != nil { + return OwnershipChange{}, err + } + } + result := OwnershipChange{ProjectID: id, ExpectedVersion: version, CredentialMode: mode, StopServices: stop, State: "pending", CredentialsCipher: cipher} + if target > 0 { + result.TargetOwnerID = &target + } + return result, tx.Commit() +} +func (s *Store) CompleteOwnershipChange(ctx context.Context, id, version, target uint64, mode, hostHash string, ftpCipher, dbCipher []byte) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var actual uint64 + var locked bool + if err = tx.QueryRowContext(ctx, "SELECT ownership_version,management_locked FROM projects WHERE id=? FOR UPDATE", id).Scan(&actual, &locked); err != nil { + return err + } + if !locked || actual != version { + return errors.New("归属核验状态已变化") + } + var pendingTarget *uint64 + var pendingMode, pendingState string + if err = tx.QueryRowContext(ctx, "SELECT target_owner_id,credential_mode,state FROM host_ownership_changes WHERE project_id=? FOR UPDATE", id).Scan(&pendingTarget, &pendingMode, &pendingState); err != nil { + return err + } + if !sameOwner(pendingTarget, target) || pendingMode != mode || pendingState != "pending" { + return errors.New("归属变更策略已变化") + } + if target > 0 { + var found uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE tenant_id=? AND role='tenant' AND status='active' FOR UPDATE", target).Scan(&found); err != nil { + return errors.New("目标用户在任务执行期间已停用") + } + } + if mode == "reset" { + if hostHash == "" || len(ftpCipher) == 0 || len(dbCipher) == 0 { + return errors.New("重置凭据不完整") + } + if _, err = tx.ExecContext(ctx, "UPDATE users SET password_hash=? WHERE project_id=? AND role='host'", hostHash, id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE ftp_accounts SET password_ciphertext=? WHERE project_id=?", ftpCipher, id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE `databases` SET password_ciphertext=? WHERE project_id=?", dbCipher, id); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, "UPDATE certificate_automations SET mode='off',next_attempt_at=NULL WHERE site_id IN (SELECT id FROM sites WHERE project_id=?)", id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET auto_ssl=FALSE WHERE project_id=?", id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE domains d JOIN dns_credentials c ON c.id=d.dns_credential_id SET d.dns_credential_id=NULL,d.dns_record_id=NULL,d.dns_record_type=NULL,d.dns_last_error=NULL WHERE d.project_id=? AND c.tenant_id IS NOT NULL", id); err != nil { + return err + } + var targetValue any + if target > 0 { + targetValue = target + } + if _, err = tx.ExecContext(ctx, "UPDATE projects SET owner_tenant_id=?,ownership_version=ownership_version+1,management_locked=FALSE,auto_ssl=FALSE WHERE id=?", targetValue, id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE users SET status='active' WHERE project_id=? AND role='host'", id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE host_ownership_changes SET state='completed',credentials_cipher=NULL WHERE project_id=?", id); err != nil { + return err + } + return tx.Commit() +} diff --git a/backend/internal/store/plan_management.go b/backend/internal/store/plan_management.go new file mode 100644 index 0000000..de619b7 --- /dev/null +++ b/backend/internal/store/plan_management.go @@ -0,0 +1,37 @@ +package store + +import ( + "context" + "database/sql" + "errors" +) + +var ErrPlanInUse = errors.New("默认套餐、已被主机或历史账号引用的套餐不能删除;有未完成批量任务时请先等待任务完成") + +func (s *Store) DeleteUnusedPlan(ctx context.Context, id uint64, confirmation string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var name string + if err = tx.QueryRowContext(ctx, "SELECT name FROM plans WHERE id=? FOR UPDATE", id).Scan(&name); errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } else if err != nil { + return err + } + if name != confirmation { + return errors.New("请准确输入套餐名称确认删除") + } + var references, pending int + if err = tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM tenants WHERE plan_id=?)+(SELECT COUNT(*) FROM projects WHERE plan_id=?),(SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running'))`, id, id).Scan(&references, &pending); err != nil { + return err + } + if id == 1 || references > 0 || pending > 0 { + return ErrPlanInUse + } + if _, err = tx.ExecContext(ctx, "DELETE FROM plans WHERE id=?", id); err != nil { + return ErrPlanInUse + } + return tx.Commit() +} diff --git a/backend/internal/store/project_bandwidth.go b/backend/internal/store/project_bandwidth.go new file mode 100644 index 0000000..fccf8bc --- /dev/null +++ b/backend/internal/store/project_bandwidth.go @@ -0,0 +1,42 @@ +package store + +import ( + "context" + "strings" +) + +// Callers supply hosts already selected through the account/host access scope. +// Batch reads avoid a separate usage query for every host in an account view. +func (s *Store) FillProjectBandwidth(ctx context.Context, projects []Project) error { + byID := make(map[uint64]int, len(projects)) + for i, p := range projects { + byID[p.ID] = i + } + for start := 0; start < len(projects); start += 500 { + end := min(start+500, len(projects)) + args := make([]any, 0, end-start) + for _, p := range projects[start:end] { + args = append(args, p.ID) + } + rows, err := s.db.QueryContext(ctx, "SELECT project_id,bandwidth_bytes FROM project_quota_usage WHERE project_id IN ("+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+")", args...) + if err != nil { + return err + } + for rows.Next() { + var id, used uint64 + if err = rows.Scan(&id, &used); err != nil { + rows.Close() + return err + } + if i, ok := byID[id]; ok { + projects[i].BandwidthBytes = used + } + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + } + return nil +} diff --git a/backend/internal/store/project_domains.go b/backend/internal/store/project_domains.go new file mode 100644 index 0000000..4dff13e --- /dev/null +++ b/backend/internal/store/project_domains.go @@ -0,0 +1,27 @@ +package store + +import ( + "context" + "database/sql" + "errors" +) + +func (s *Store) DeleteCustomDomain(ctx context.Context, id, projectID uint64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM domains WHERE id=? AND project_id=? AND kind='custom' AND dns_record_id IS NULL", id, projectID) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n != 1 { + return ErrNotFound + } + return nil +} + +func (s *Store) ProjectAssignedDomain(ctx context.Context, tenantID, projectID uint64) (string, error) { + var domain string + err := s.db.QueryRowContext(ctx, "SELECT domain FROM domains WHERE tenant_id=? AND project_id=? AND kind='assigned' ORDER BY id LIMIT 1", tenantID, projectID).Scan(&domain) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return domain, err +} diff --git a/backend/internal/store/project_quota.go b/backend/internal/store/project_quota.go new file mode 100644 index 0000000..2a30223 --- /dev/null +++ b/backend/internal/store/project_quota.go @@ -0,0 +1,62 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "sea-vhost/internal/scope" +) + +// Account views aggregate allowances for display only. Every write gate and +// measurement requires a project scope derived from an authorized host. +func (s *Store) projectPlanAndUsage(ctx context.Context, tenantID uint64) (Plan, Usage, error) { + var p Plan + var u Usage + var measured sql.NullTime + id := scope.Project(ctx) + if id == 0 { + filter, args := customerFilter(ctx, tenantID, "h", "h") + err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(l.storage_bytes),0),COALESCE(SUM(l.database_bytes),0),COALESCE(SUM(l.monthly_bandwidth_bytes),0),COALESCE(SUM(l.process_limit),0),COALESCE(SUM(l.ftp_limit),0),COALESCE(SUM(l.database_limit),0),COALESCE(SUM(l.project_limit),0),COALESCE(SUM(q.storage_bytes),0),COALESCE(SUM(q.database_bytes),0),COALESCE(SUM(q.bandwidth_bytes),0),COALESCE(SUM(q.process_count),0),MIN(q.measured_at) FROM projects h JOIN plans l ON l.id=h.plan_id LEFT JOIN project_quota_usage q ON q.project_id=h.id WHERE `+filter+` AND h.status<>'failed' AND h.lifecycle_state<>'purged'`, args...).Scan(&p.StorageBytes, &p.DatabaseBytes, &p.BandwidthBytes, &p.ProcessLimit, &p.FTPLimit, &p.DatabaseLimit, &p.ProjectLimit, &u.StorageBytes, &u.DatabaseBytes, &u.BandwidthBytes, &u.ProcessCount, &measured) + p.Name = "主机资源汇总" + if measured.Valid { + u.MeasuredAt = measured.Time + } + return p, u, err + } + err := s.db.QueryRowContext(ctx, `SELECT l.id,l.name,l.storage_bytes,l.database_bytes,l.monthly_bandwidth_bytes,l.bandwidth_mbps,l.process_limit,l.ftp_limit,l.database_limit,l.project_limit,COALESCE(q.storage_bytes,0),COALESCE(q.database_bytes,0),COALESCE(q.bandwidth_bytes,0),COALESCE(q.process_count,0),q.measured_at FROM projects h JOIN plans l ON l.id=h.plan_id LEFT JOIN project_quota_usage q ON q.project_id=h.id WHERE h.id=? AND h.tenant_id=? AND h.lifecycle_state<>'purged'`, id, tenantID).Scan(&p.ID, &p.Name, &p.StorageBytes, &p.DatabaseBytes, &p.BandwidthBytes, &p.BandwidthMbps, &p.ProcessLimit, &p.FTPLimit, &p.DatabaseLimit, &p.ProjectLimit, &u.StorageBytes, &u.DatabaseBytes, &u.BandwidthBytes, &u.ProcessCount, &measured) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + if measured.Valid { + u.MeasuredAt = measured.Time + } + return p, u, err +} + +func (s *Store) TenantOwner(ctx context.Context, id uint64) (User, error) { + var uid uint64 + err := s.db.QueryRowContext(ctx, "SELECT id FROM users WHERE tenant_id=? AND role='tenant' AND status='active' ORDER BY id LIMIT 1", id).Scan(&uid) + if err != nil { + return User{}, err + } + return s.UserByID(ctx, uid) +} + +// Port reservations are scoped to the node and kept centrally, including failed +// provisioning records until an administrator has reconciled their resources. +func (s *Store) AllocateNodePort(ctx context.Context, nodeID uint64) (int, error) { + lease, err := s.LockNodeRegistry(ctx, nodeID) + if err != nil { + return 0, err + } + defer lease.Close() + var port int + err = lease.conn.QueryRowContext(ctx, `SELECT GREATEST(20000,COALESCE(MAX(backend_port)+20,20000)) FROM projects WHERE node_id=?`, nodeID).Scan(&port) + if err != nil { + return 0, err + } + if port > 59000 { + return 0, errors.New("节点运行端口已耗尽") + } + return port, nil +} diff --git a/backend/internal/store/resource_crud.go b/backend/internal/store/resource_crud.go new file mode 100644 index 0000000..1654d66 --- /dev/null +++ b/backend/internal/store/resource_crud.go @@ -0,0 +1,348 @@ +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "time" +) + +// Account identities remain reserved after deletion so old imports and external +// references cannot accidentally grant access to a different customer. +type AccountProfile struct { + ID uint64 `json:"id"` + Slug string `json:"slug"` + Name string `json:"name"` + Email string `json:"email"` + DisplayName string `json:"displayName"` + ProjectCount int `json:"projectCount"` +} + +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) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return p, err +} +func (s *Store) UpdateAccount(ctx context.Context, id uint64, p AccountProfile) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var found uint64 + if err = tx.QueryRowContext(ctx, `SELECT id FROM tenants WHERE id=? AND resource_namespace=FALSE AND deleted_at IS NULL FOR UPDATE`, id).Scan(&found); err != nil { + return ErrNotFound + } + if _, err = tx.ExecContext(ctx, `UPDATE tenants SET name=? WHERE id=?`, p.Name, id); err != nil { + return err + } + var conflict int + if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE (email=? OR login_name=?) AND (tenant_id IS NULL OR tenant_id<>?)", p.Email, p.Email, id).Scan(&conflict); err != nil { + return err + } + if conflict > 0 { + return errors.New("登录邮箱已被使用") + } + var previous string + if err = tx.QueryRowContext(ctx, "SELECT email FROM users WHERE tenant_id=? AND role='tenant' ORDER BY id LIMIT 1 FOR UPDATE", id).Scan(&previous); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE users SET login_name=IF(login_name=email,?,login_name),email=?,display_name=? WHERE tenant_id=? AND role='tenant'`, p.Email, p.Email, p.DisplayName, id); err != nil { + return errors.New("登录邮箱已被使用或用户资料无法保存") + } + if previous != p.Email { + for _, q := range []string{"DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=? AND u.role='tenant'", "DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.tenant_id=? AND u.role='tenant'"} { + if _, err = tx.ExecContext(ctx, q, id); err != nil { + return err + } + } + } + return tx.Commit() +} +func (s *Store) DeleteAccount(ctx context.Context, id uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var found uint64 + if err = tx.QueryRowContext(ctx, `SELECT id FROM tenants WHERE id=? AND resource_namespace=FALSE AND deleted_at IS NULL FOR UPDATE`, id).Scan(&found); err != nil { + return ErrNotFound + } + var count int + if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM projects WHERE owner_tenant_id=?`, id).Scan(&count); err != nil { + return err + } + if count > 0 { + return errors.New("请先解绑或转移该用户名下的全部主机(包括回收中的主机)") + } + if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM host_ownership_changes WHERE target_owner_id=? AND state='pending'", id).Scan(&count); err != nil { + return err + } + if count > 0 { + return errors.New("该用户有未完成的主机归属任务") + } + for _, q := range []string{ + `UPDATE tenants SET deleted_at=UTC_TIMESTAMP(),status='suspended' WHERE id=?`, + `UPDATE users SET status='disabled' WHERE tenant_id=? AND role='tenant'`, + `UPDATE user_schedules SET enabled=FALSE,run_requested=FALSE,last_state='account_deleted' WHERE account_id=?`, + `DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.tenant_id=? AND u.role='tenant'`, + `DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=? AND u.role='tenant'`, + } { + if _, err = tx.ExecContext(ctx, q, id); err != nil { + return err + } + } + return tx.Commit() +} + +func (s *Store) RenameHost(ctx context.Context, id uint64, name string) error { + result, err := s.db.ExecContext(ctx, `UPDATE projects SET slug=? WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL`, name, id) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n == 0 { + var current string + err = s.db.QueryRowContext(ctx, `SELECT slug FROM projects WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL`, id).Scan(¤t) + } + return err +} +func (s *Store) RecycleHost(ctx context.Context, id uint64, now time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var tenant uint64 + var locked bool + var recycled *time.Time + if err = tx.QueryRowContext(ctx, `SELECT tenant_id,management_locked,manual_recycled_at FROM projects WHERE id=? FOR UPDATE`, id).Scan(&tenant, &locked, &recycled); err != nil { + return ErrNotFound + } + if locked { + return ErrManagementLocked + } + if recycled != nil { + return tx.Commit() + } // Retries must not extend the recovery window. + if _, err = tx.ExecContext(ctx, `UPDATE projects SET manual_recycled_at=?,lifecycle_state='recycle',purge_after=?,backup_purge_after=?,ownership_version=ownership_version+1,recycle_error='' WHERE id=?`, now, now.Add(7*24*time.Hour), now.Add(21*24*time.Hour), id); err != nil { + return err + } + for _, q := range []string{ + `UPDATE user_schedules SET enabled=FALSE,run_requested=FALSE,last_state='host_recycled' WHERE project_id=?`, + `UPDATE users SET status='disabled' WHERE project_id=? AND role='host'`, + `UPDATE ftp_accounts SET enabled=FALSE WHERE project_id=?`, + `DELETE i FROM impersonation_sessions i JOIN users u ON u.id=i.target_user_id WHERE u.project_id=?`, + `DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.project_id=?`, + } { + if _, err = tx.ExecContext(ctx, q, id); err != nil { + return err + } + } + return tx.Commit() +} +func (s *Store) HostLifecycle(ctx context.Context, id uint64) (HostLifecycle, error) { + var h HostLifecycle + err := s.db.QueryRowContext(ctx, `SELECT id,tenant_id,node_id,lifecycle_state,expires_at,grace_until,purge_after,backup_purge_after FROM projects WHERE id=? AND management_locked=FALSE`, id).Scan(&h.ProjectID, &h.TenantID, &h.NodeID, &h.State, &h.ExpiresAt, &h.GraceUntil, &h.PurgeAfter, &h.BackupPurgeAfter) + return h, err +} +func (s *Store) RecordRecycleError(ctx context.Context, id uint64, detail string) error { + if len(detail) > 500 { + detail = detail[:500] + } + _, err := s.db.ExecContext(ctx, `UPDATE projects SET recycle_error=? WHERE id=? AND manual_recycled_at IS NOT NULL`, detail, id) + return err +} +func (s *Store) RestoreHost(ctx context.Context, id uint64, now time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var recycled, purge, expiry *time.Time + var locked bool + var identity bool + if err = tx.QueryRowContext(ctx, `SELECT manual_recycled_at,purge_after,expires_at,management_locked,identity_verified FROM projects WHERE id=? FOR UPDATE`, id).Scan(&recycled, &purge, &expiry, &locked, &identity); err != nil { + return ErrNotFound + } + if recycled == nil || purge == nil || !purge.After(now) { + return errors.New("主机不在可恢复的 7 天回收期内") + } + if locked || !identity { + return errors.New("请先完成主机身份核验或归属变更") + } + state := "active" + if expiry != nil && !expiry.After(now) { + state = "grace" + } + if _, err = tx.ExecContext(ctx, `UPDATE projects SET manual_recycled_at=NULL,recycle_error='',lifecycle_state=?,grace_until=IF(?='grace',DATE_ADD(UTC_TIMESTAMP(),INTERVAL 3 DAY),NULL),purge_after=IF(?='grace',DATE_ADD(UTC_TIMESTAMP(),INTERVAL 10 DAY),NULL),backup_purge_after=IF(?='grace',DATE_ADD(UTC_TIMESTAMP(),INTERVAL 24 DAY),NULL),ownership_version=ownership_version+1 WHERE id=?`, state, state, state, state, id); err != nil { + return err + } + // Web and FTP remain stopped; customer schedules require explicit re-enabling. + if _, err = tx.ExecContext(ctx, `UPDATE users SET status='active' WHERE project_id=? AND role='host'`, id); err != nil { + return err + } + return tx.Commit() +} + +func nodeResourceChecks(ctx context.Context, tx *sql.Tx, id uint64) error { + for _, q := range []string{ + `SELECT COUNT(*) FROM projects WHERE node_id=?`, + `SELECT COUNT(*) FROM tenant_backups WHERE node_id=? AND deleted_at IS NULL`, + `SELECT COUNT(*) FROM control_tasks WHERE node_id=? AND state IN ('running','uncertain')`, + `SELECT COUNT(*) FROM runtime_maintenance_jobs WHERE node_id=? AND active_key IS NOT NULL`, + } { + var count int + if err := tx.QueryRowContext(ctx, q, id).Scan(&count); err != nil { + return err + } + if count > 0 { + return errors.New("节点仍有关联主机、备份或未完成任务,请先处理后再操作") + } + } + // Pending batches contain encrypted placement inputs; conservatively wait for + // all batches instead of guessing which node a queued item may later select. + var batches int + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM admin_batches WHERE state IN ('queued','running')`).Scan(&batches); err != nil { + return err + } + if batches > 0 { + return errors.New("请等待当前批量任务完成后再操作节点") + } + var raw []byte + if err := tx.QueryRowContext(ctx, `SELECT registry_json FROM control_nodes WHERE id=?`, id).Scan(&raw); err != nil { + return err + } + var registry map[string]json.RawMessage + if json.Unmarshal(raw, ®istry) != nil { + return errors.New("节点资源登记表损坏,请先核对") + } + for _, key := range []string{"sites", "ftp", "databases"} { + var values map[string]json.RawMessage + if json.Unmarshal(registry[key], &values) != nil || len(values) > 0 { + return errors.New("节点仍有宝塔资源登记,请先完成资源核对") + } + } + return nil +} +func (s *Store) UpdateNodeMetadata(ctx context.Context, id uint64, input Node) error { + lease, err := s.LockNodeRegistry(ctx, id) + if err != nil { + return err + } + defer lease.Close() + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + current, err := scanNode(tx.QueryRowContext(ctx, `SELECT `+nodeColumns+` FROM control_nodes WHERE id=? AND deleted_at IS NULL FOR UPDATE`, id)) + if err != nil { + return err + } + if current.Transport == "local" && (input.Endpoint != current.Endpoint || input.TenantRoot != current.TenantRoot) { + return errors.New("本机执行入口和主机根目录由安装配置管理") + } + if input.Endpoint != current.Endpoint || input.TenantRoot != current.TenantRoot { + if current.Enabled { + return errors.New("修改执行入口或根目录前必须停用节点") + } + if err = nodeResourceChecks(ctx, tx, id); err != nil { + return err + } + } + _, err = tx.ExecContext(ctx, `UPDATE control_nodes SET last_seen_at=IF(endpoint<>?,NULL,last_seen_at),name=?,endpoint=?,root_domain=?,tenant_root=?,ftp_certificate_domain=? WHERE id=?`, input.Endpoint, input.Name, input.Endpoint, input.RootDomain, input.TenantRoot, input.FTPCertificateDomain, id) + if err != nil { + return errors.New("节点配置无法保存,请检查执行入口是否重复") + } + return tx.Commit() +} +func (s *Store) DeleteNode(ctx context.Context, id uint64) error { + if id == 1 { + return errors.New("本机节点禁止删除") + } + lease, err := s.LockNodeRegistry(ctx, id) + if err != nil { + return err + } + defer lease.Close() + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var enabled bool + if err = tx.QueryRowContext(ctx, `SELECT enabled FROM control_nodes WHERE id=? AND deleted_at IS NULL FOR UPDATE`, id).Scan(&enabled); err != nil { + return ErrNotFound + } + if enabled { + return errors.New("请先停用节点") + } + if err = nodeResourceChecks(ctx, tx, id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE control_nodes SET deleted_at=UTC_TIMESTAMP(),credentials=NULL,enabled=FALSE WHERE id=?`, id); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM ip_pool WHERE node_id=?`, id); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetRuntimePolicy(ctx context.Context, id uint64, allowed bool) error { + _, err := s.db.ExecContext(ctx, "UPDATE projects SET allow_runtime_change=? WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL", allowed, id) + return err +} +func (s *Store) ChangeSiteLanguage(ctx context.Context, site Site, runtime, version, status string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + r, err := tx.ExecContext(ctx, "UPDATE sites SET runtime=?,runtime_version=?,status=? WHERE id=? AND project_id=? AND runtime=? AND runtime_version=?", runtime, version, status, site.ID, site.ProjectID, site.Runtime, site.Version) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n != 1 { + return errors.New("站点环境已变更") + } + if site.Primary { + if _, err = tx.ExecContext(ctx, "UPDATE projects SET runtime=?,runtime_version=?,status=? WHERE id=?", runtime, version, status, site.ProjectID); err != nil { + return err + } + } + // Keep website preferences; startup commands from another language are incompatible. + if _, err = tx.ExecContext(ctx, "UPDATE site_preferences SET startup_cipher=NULL WHERE site_id=?", site.ID); err != nil { + return err + } + return tx.Commit() +} + +// Recycled hosts may only be detached explicitly; they cannot be reassigned or restarted here. +func (s *Store) DetachRecycledHost(ctx context.Context, id, version uint64, confirmation string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var host string + var actual uint64 + var recycled, locked bool + if err = tx.QueryRowContext(ctx, "SELECT host_name,ownership_version,manual_recycled_at IS NOT NULL,management_locked FROM projects WHERE id=? FOR UPDATE", id).Scan(&host, &actual, &recycled, &locked); err != nil { + return ErrNotFound + } + if !recycled || locked || actual != version || host != confirmation { + return errors.New("主机状态或归属版本已变更,请刷新后重试") + } + if _, err = tx.ExecContext(ctx, "UPDATE projects SET owner_tenant_id=NULL,ownership_version=ownership_version+1 WHERE id=?", id); err != nil { + return err + } + return tx.Commit() +} diff --git a/backend/internal/store/runtime_maintenance.go b/backend/internal/store/runtime_maintenance.go new file mode 100644 index 0000000..79c22cf --- /dev/null +++ b/backend/internal/store/runtime_maintenance.go @@ -0,0 +1,253 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "github.com/go-sql-driver/mysql" + "sea-vhost/internal/scope" + "time" +) + +type RuntimeJob struct { + OwnershipVersion *uint64 `json:"-"` + NodeID uint64 `json:"nodeId"` + ID uint64 `json:"id"` + Action string `json:"action"` + Runtime string `json:"runtime"` + FromVersion string `json:"fromVersion"` + TargetVersion string `json:"targetVersion"` + EntryFile string `json:"entryFile,omitempty"` + SiteID *uint64 `json:"siteId,omitempty"` + Status string `json:"status"` + Phase string `json:"phase"` + Message string `json:"message"` + RollbackData string `json:"-"` + BackupAvailable bool `json:"backupAvailable"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} +type RuntimeTarget struct { + Site Site `json:"site"` + Project Project `json:"-"` + HostName string `json:"hostName"` + InstalledVersion string `json:"installedVersion"` + RunningVersion string `json:"runningVersion"` + Healthy bool `json:"healthy"` + Detail string `json:"detail"` + CheckedAt *time.Time `json:"checkedAt,omitempty"` +} + +const runtimeJobColumns = `id,node_id,action,runtime,from_version,target_version,entry_file,site_id,status,phase,COALESCE(message,''),COALESCE(rollback_data,''),backup_available,created_at,updated_at,ownership_version` + +func scanRuntimeJob(row interface{ Scan(...any) error }) (RuntimeJob, error) { + var j RuntimeJob + err := row.Scan(&j.ID, &j.NodeID, &j.Action, &j.Runtime, &j.FromVersion, &j.TargetVersion, &j.EntryFile, &j.SiteID, &j.Status, &j.Phase, &j.Message, &j.RollbackData, &j.BackupAvailable, &j.CreatedAt, &j.UpdatedAt, &j.OwnershipVersion) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return j, err +} +func (s *Store) CreateRuntimeJob(ctx context.Context, j RuntimeJob) (uint64, error) { + blocked, checkErr := s.NodeHasUnresolvedTask(scope.WithProject(ctx, 0, scope.Node(ctx)), scope.Node(ctx)) + if checkErr != nil { + return 0, checkErr + } + if blocked { + return 0, errors.New("请先核验该节点的待确认操作,再提交环境维护任务") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + var nodeLock uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM control_nodes WHERE id=? AND enabled=TRUE FOR UPDATE", scope.Node(ctx)).Scan(&nodeLock); err != nil { + return 0, ErrNotFound + } + var pending int + if err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM runtime_maintenance_jobs WHERE node_id=? AND active_key IS NOT NULL", scope.Node(ctx)).Scan(&pending); err != nil { + return 0, err + } + if pending >= 20 { + return 0, errors.New("当前节点最多保留 20 项待处理的环境任务") + } + r, err := tx.ExecContext(ctx, `INSERT INTO runtime_maintenance_jobs(node_id,action,runtime,from_version,target_version,entry_file,site_id,active_key,ownership_version) VALUES(?,?,?,?,?,?,?,?,?)`, scope.Node(ctx), j.Action, j.Runtime, j.FromVersion, j.TargetVersion, j.EntryFile, j.SiteID, runtimeJobKey(scope.Node(ctx), j), j.OwnershipVersion) + if err != nil { + var dbErr *mysql.MySQLError + if errors.As(err, &dbErr) && dbErr.Number == 1062 { + return 0, errors.New("相同的运行环境任务已在队列中,请勿重复提交") + } + return 0, err + } + id, err := r.LastInsertId() + if err != nil { + return 0, err + } + if err = tx.Commit(); err != nil { + return 0, err + } + return uint64(id), nil +} +func (s *Store) RuntimeJobs(ctx context.Context) ([]RuntimeJob, error) { + rows, err := s.db.QueryContext(ctx, "SELECT "+runtimeJobColumns+" FROM runtime_maintenance_jobs WHERE node_id=? ORDER BY id DESC LIMIT 50", scope.Node(ctx)) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]RuntimeJob, 0) + for rows.Next() { + j, err := scanRuntimeJob(rows) + if err != nil { + return nil, err + } + items = append(items, j) + } + return items, rows.Err() +} + +func (s *Store) RuntimeMutationBlocked(ctx context.Context) (bool, error) { + var count int + // Panel component updates do not own tenant resources. Only an unfinished + // configuration switch on this host may block its mutations. + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM runtime_maintenance_jobs WHERE node_id=? AND status IN ('running','interrupted') AND action IN ('migrate','runtime_change') AND ?<>0 AND site_id IN (SELECT id FROM sites WHERE project_id=?)`, scope.Node(ctx), scope.Project(ctx), scope.Project(ctx)).Scan(&count) + return count > 0, err +} + +func (s *Store) RuntimeJob(ctx context.Context, id uint64) (RuntimeJob, error) { + return scanRuntimeJob(s.db.QueryRowContext(ctx, "SELECT "+runtimeJobColumns+" FROM runtime_maintenance_jobs WHERE id=?", id)) +} +func (s *Store) ClaimRuntimeJob(ctx context.Context) (RuntimeJob, error) { + j, err := scanRuntimeJob(s.db.QueryRowContext(ctx, "SELECT "+runtimeJobColumns+" FROM runtime_maintenance_jobs WHERE status='queued' AND node_id IN (SELECT id FROM control_nodes WHERE enabled=TRUE) AND node_id NOT IN (SELECT running_node_id FROM runtime_maintenance_jobs WHERE running_node_id IS NOT NULL) ORDER BY id LIMIT 1")) + if err != nil { + return j, err + } + r, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status='running' WHERE id=? AND status='queued'", j.ID) + if err != nil { + var conflict *mysql.MySQLError + if errors.As(err, &conflict) && conflict.Number == 1062 { + return j, ErrNotFound + } + return j, err + } + n, _ := r.RowsAffected() + if n != 1 { + return j, ErrNotFound + } + j.Status = "running" + return j, nil +} +func (s *Store) UpdateRuntimeJob(ctx context.Context, id uint64, status, phase, message string) error { + job, err := s.RuntimeJob(ctx, id) + if err != nil { + return err + } + var active any = runtimeJobKey(job.NodeID, job) + if status == "completed" || status == "failed" || status == "rolled_back" { + active = nil + } + _, err = s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status=?,phase=?,message=?,active_key=? WHERE id=?", status, phase, message, active, id) + return err +} +func (s *Store) SaveRuntimeRollback(ctx context.Context, id uint64, data string, backup bool) error { + _, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET rollback_data=?,backup_available=? WHERE id=?", data, backup, id) + return err +} +func (s *Store) InterruptRuntimeJobs(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status='interrupted',message='服务重启,任务状态待核验。请执行恢复核验。' WHERE status='running'") + return err +} +func (s *Store) RetryRuntimeJob(ctx context.Context, id uint64) error { + r, err := s.db.ExecContext(ctx, "UPDATE runtime_maintenance_jobs SET status='queued' WHERE id=? AND node_id=? AND status='interrupted'", id, scope.Node(ctx)) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n != 1 { + return ErrNotFound + } + return nil +} +func (s *Store) RuntimeTargets(ctx context.Context) ([]RuntimeTarget, error) { + rows, err := s.db.QueryContext(ctx, `SELECT s.id,s.tenant_id,s.project_id,s.slug,s.assigned_domain,s.run_path,s.runtime,s.runtime_version,s.status,COALESCE(s.panel_site_id,0),COALESCE(s.backend_port,0),s.process_limit,s.is_primary,p.host_name,p.root_path,p.node_id,COALESCE(p.plan_id,0),COALESCE(o.installed_version,''),COALESCE(o.running_version,''),COALESCE(o.healthy,0),COALESCE(o.detail,''),o.checked_at FROM sites s JOIN projects p ON p.id=s.project_id LEFT JOIN site_runtime_observations o ON o.site_id=s.id WHERE s.status<>'failed' AND p.node_id=? ORDER BY s.id`, scope.Node(ctx)) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]RuntimeTarget, 0) + for rows.Next() { + var t RuntimeTarget + if err = rows.Scan(&t.Site.ID, &t.Site.TenantID, &t.Site.ProjectID, &t.Site.Name, &t.Site.Domain, &t.Site.RunPath, &t.Site.Runtime, &t.Site.Version, &t.Site.Status, &t.Site.PanelSiteID, &t.Site.BackendPort, &t.Site.ProcessLimit, &t.Site.Primary, &t.HostName, &t.Project.Path, &t.Project.NodeID, &t.Project.PlanID, &t.InstalledVersion, &t.RunningVersion, &t.Healthy, &t.Detail, &t.CheckedAt); err != nil { + return nil, err + } + t.Project.ID = t.Site.ProjectID + t.Project.TenantID = t.Site.TenantID + t.Project.HostName = t.HostName + items = append(items, t) + } + return items, rows.Err() +} +func (s *Store) SaveRuntimeObservation(ctx context.Context, siteID uint64, installed, running string, healthy bool, detail string) error { + if len(detail) > 500 { + detail = detail[:500] + } + _, err := s.db.ExecContext(ctx, `INSERT INTO site_runtime_observations(site_id,installed_version,running_version,healthy,detail) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE installed_version=VALUES(installed_version),running_version=VALUES(running_version),healthy=VALUES(healthy),detail=VALUES(detail),checked_at=CURRENT_TIMESTAMP`, siteID, installed, running, healthy, detail) + return err +} +func (s *Store) ChangeSiteRuntimeVersion(ctx context.Context, site Site, target string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + r, err := tx.ExecContext(ctx, "UPDATE sites SET runtime_version=? WHERE id=? AND tenant_id=? AND project_id=? AND runtime_version=?", target, site.ID, site.TenantID, site.ProjectID, site.Version) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n != 1 { + return errors.New("站点版本已被其他任务修改") + } + if site.Primary { + if _, err = tx.ExecContext(ctx, "UPDATE projects SET runtime_version=? WHERE id=? AND tenant_id=?", target, site.ProjectID, site.TenantID); err != nil { + return err + } + } + return tx.Commit() +} +func (s *Store) NotifyRuntimeRelease(ctx context.Context, key, title, detail string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + r, err := tx.ExecContext(ctx, "INSERT IGNORE INTO runtime_update_notices(node_id,release_key) VALUES(?,?)", scope.Node(ctx), key) + if err != nil { + return err + } + n, _ := r.RowsAffected() + if n == 0 { + return nil + } + if _, err = tx.ExecContext(ctx, `INSERT INTO admin_notifications(severity,category,title,detail,next_attempt_at) VALUES('warning','runtime',?,?,UTC_TIMESTAMP())`, title, detail); err != nil { + return err + } + return tx.Commit() +} + +// A duplicate operation is rejected, while unrelated work may wait on the same node. +func runtimeJobKey(node uint64, j RuntimeJob) string { + var site uint64 + if j.SiteID != nil { + site = *j.SiteID + return fmt.Sprintf("site/%d", site) + } + return fmt.Sprintf("node/%d/%s/%s/%s/%d", node, j.Action, j.Runtime, j.TargetVersion, site) +} + +func (s *Store) HostOwnershipVersion(ctx context.Context, id uint64) (uint64, error) { + var version uint64 + err := s.db.QueryRowContext(ctx, "SELECT ownership_version FROM projects WHERE id=? AND management_locked=FALSE AND manual_recycled_at IS NULL", id).Scan(&version) + return version, err +} diff --git a/backend/internal/store/site_preferences.go b/backend/internal/store/site_preferences.go new file mode 100644 index 0000000..b7381f1 --- /dev/null +++ b/backend/internal/store/site_preferences.go @@ -0,0 +1,97 @@ +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "sea-vhost/internal/hosting" + "time" +) + +func (s *Store) WebsiteSettings(ctx context.Context, id uint64) (hosting.WebsiteSettings, error) { + v := hosting.DefaultWebsite() + var raw []byte + e := s.db.QueryRowContext(ctx, "SELECT website_json FROM site_preferences WHERE site_id=?", id).Scan(&raw) + if errors.Is(e, sql.ErrNoRows) { + return v, nil + } + if e == nil && len(raw) > 0 { + e = json.Unmarshal(raw, &v) + } + return v, e +} +func (s *Store) SaveWebsiteSettings(ctx context.Context, id uint64, v hosting.WebsiteSettings) error { + raw, e := json.Marshal(v) + if e != nil { + return e + } + _, e = s.db.ExecContext(ctx, "INSERT INTO site_preferences(site_id,website_json) VALUES(?,?) ON DUPLICATE KEY UPDATE website_json=VALUES(website_json)", id, raw) + return e +} +func (s *Store) StartupCipher(ctx context.Context, id uint64) ([]byte, error) { + var v []byte + e := s.db.QueryRowContext(ctx, "SELECT startup_cipher FROM site_preferences WHERE site_id=?", id).Scan(&v) + if errors.Is(e, sql.ErrNoRows) { + e = nil + } + return v, e +} +func (s *Store) SaveStartupCipher(ctx context.Context, id uint64, v []byte) error { + _, e := s.db.ExecContext(ctx, "INSERT INTO site_preferences(site_id,startup_cipher) VALUES(?,?) ON DUPLICATE KEY UPDATE startup_cipher=VALUES(startup_cipher)", id, v) + return e +} + +type HostMetric struct { + SampledAt time.Time `json:"sampledAt"` + CPUPercent float64 `json:"cpuPercent"` + CPUTicks uint64 `json:"-"` + MemoryBytes uint64 `json:"memoryBytes"` + ProcessCount uint32 `json:"processCount"` + StorageBytes uint64 `json:"storageBytes"` + DatabaseBytes uint64 `json:"databaseBytes"` + BandwidthBytes uint64 `json:"bandwidthBytes"` +} + +func (s *Store) RecordHostMetric(ctx context.Context, id uint64, v HostMetric) error { + v.SampledAt = time.Now().UTC().Truncate(time.Minute) + var ticks uint64 + var previous time.Time + e := s.db.QueryRowContext(ctx, "SELECT sampled_at,cpu_ticks FROM host_metrics WHERE project_id=? AND sampled_at= ticks && v.SampledAt.Sub(previous) <= 10*time.Minute { + v.CPUPercent = float64(v.CPUTicks-ticks) / v.SampledAt.Sub(previous).Seconds() + } + _, e = s.db.ExecContext(ctx, `INSERT INTO host_metrics(project_id,sampled_at,cpu_percent,cpu_ticks,memory_bytes,process_count,storage_bytes,database_bytes,bandwidth_bytes) VALUES(?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE memory_bytes=VALUES(memory_bytes),process_count=VALUES(process_count),storage_bytes=VALUES(storage_bytes),database_bytes=VALUES(database_bytes),bandwidth_bytes=VALUES(bandwidth_bytes)`, id, v.SampledAt, v.CPUPercent, v.CPUTicks, v.MemoryBytes, v.ProcessCount, v.StorageBytes, v.DatabaseBytes, v.BandwidthBytes) + return e +} +func (s *Store) HostMetrics(ctx context.Context, id uint64, days int) ([]HostMetric, error) { + if days < 1 || days > 30 { + days = 1 + } + rows, e := s.db.QueryContext(ctx, `SELECT sampled_at,cpu_percent,memory_bytes,process_count,storage_bytes,database_bytes,bandwidth_bytes FROM host_metrics WHERE project_id=? AND sampled_at>=? ORDER BY sampled_at`, id, time.Now().UTC().Add(-time.Duration(days)*24*time.Hour)) + if e != nil { + return nil, e + } + defer rows.Close() + values := []HostMetric{} + for rows.Next() { + var v HostMetric + if e = rows.Scan(&v.SampledAt, &v.CPUPercent, &v.MemoryBytes, &v.ProcessCount, &v.StorageBytes, &v.DatabaseBytes, &v.BandwidthBytes); e != nil { + return nil, e + } + values = append(values, v) + } + if len(values) > 1440 { + step := (len(values) + 1439) / 1440 + reduced := []HostMetric{} + for i := 0; i < len(values); i += step { + reduced = append(reduced, values[i]) + } + values = reduced + } + return values, rows.Err() +} +func (s *Store) PruneHostMetrics(ctx context.Context) error { + _, e := s.db.ExecContext(ctx, "DELETE FROM host_metrics WHERE sampled_at?`, hash[:], time.Now().UTC()).Scan(&p.Provider, &p.Subject, &p.Email, &p.DisplayName, &p.EmailVerified, &p.ExpiresAt) + if errors.Is(err, sql.ErrNoRows) { + err = ErrNotFound + } + return p, err +} + +// CompletePendingOIDC commits the identity and optional ordinary account together. +// A consumed ticket, duplicate identity or duplicate email cannot leave an orphan account. +func (s *Store) CompletePendingOIDC(ctx context.Context, token, expectedProvider string, targetID uint64, input *NewTenant) (uint64, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + hash := sha256.Sum256([]byte(token)) + var p PendingOIDCLogin + err = tx.QueryRowContext(ctx, `SELECT provider,subject,email,display_name,email_verified,expires_at FROM oidc_pending_logins WHERE token_hash=? FOR UPDATE`, hash[:]).Scan(&p.Provider, &p.Subject, &p.Email, &p.DisplayName, &p.EmailVerified, &p.ExpiresAt) + if err != nil || p.Provider != expectedProvider || !p.ExpiresAt.After(time.Now().UTC()) { + return 0, ErrNotFound + } + if input != nil { + if !p.EmailVerified || p.Email != input.Email { + return 0, errors.New("SSO 邮箱尚未验证") + } + // The supplied password is already an irreversible hash of an unguessable secret. + result, e := tx.ExecContext(ctx, `INSERT INTO tenants(slug,name,plan_id) VALUES(?,?,?)`, input.Slug, input.Name, input.PlanID) + if e != nil { + return 0, e + } + namespace, e := result.LastInsertId() + if e != nil { + return 0, e + } + result, e = tx.ExecContext(ctx, `INSERT INTO users(tenant_id,login_name,email,display_name,password_hash,role) VALUES(?,?,?,?,?,'tenant')`, namespace, input.Email, input.Email, input.DisplayName, input.Password) + if e != nil { + return 0, e + } + id, e := result.LastInsertId() + if e != nil { + return 0, e + } + targetID = uint64(id) + } + var role, status string + if err = tx.QueryRowContext(ctx, `SELECT u.role,u.status FROM users u LEFT JOIN tenants t ON t.id=u.tenant_id WHERE u.id=? AND (u.tenant_id IS NULL OR (t.status='active' AND t.deleted_at IS NULL)) FOR UPDATE`, targetID).Scan(&role, &status); err != nil { + return 0, err + } + if role == "host" || status != "active" { + return 0, errors.New("该账号不能绑定 SSO") + } + // Never silently replace an existing binding of the target account. + if _, err = tx.ExecContext(ctx, `INSERT INTO sso_identities(user_id,provider,subject,email) VALUES(?,?,?,?)`, targetID, p.Provider, p.Subject, p.Email); err != nil { + return 0, err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM oidc_pending_logins WHERE token_hash=?`, hash[:]); err != nil { + return 0, err + } + if err = tx.Commit(); err != nil { + return 0, err + } + return targetID, nil +} + +func (s *Store) ActiveOIDCBindSession(ctx context.Context, hash []byte, userID uint64) bool { + if len(hash) != 32 { + return false + } + var id uint64 + if s.db.QueryRowContext(ctx, `SELECT user_id FROM sessions WHERE token_hash=? AND user_id=? AND expires_at>NOW()`, hash, userID).Scan(&id) != nil { + return false + } + u, e := s.UserByID(ctx, id) + return e == nil && u.Role != "host" +} diff --git a/backend/internal/store/store.go b/backend/internal/store/store.go new file mode 100644 index 0000000..b075931 --- /dev/null +++ b/backend/internal/store/store.go @@ -0,0 +1,2315 @@ +package store + +import ( + "context" + "crypto/sha256" + "database/sql" + "errors" + "fmt" + "io/fs" + "log/slog" + "sea-vhost/internal/scope" + "sort" + "strings" + "time" + + "github.com/go-sql-driver/mysql" + "golang.org/x/crypto/bcrypt" + + "sea-vhost/internal/migrations" +) + +var ErrNotFound = errors.New("not found") +var ErrDifferentAdminExists = errors.New("a different administrator already exists") +var ErrCertificateCooldown = errors.New("certificate issuance cooldown") +var ErrDNSCredentialTestCooldown = errors.New("dns credential test cooldown") +var ErrDNSCredentialInUse = errors.New("dns credential is used by managed records") +var ErrDomainLimit = errors.New("site domain limit reached") + +type Store struct{ db *sql.DB } + +func Open(dsn string) (*Store, error) { + options, err := mysql.ParseDSN(dsn) + if err != nil { + return nil, err + } + if options.Params == nil { + options.Params = make(map[string]string) + } + // DATETIME values are written in UTC; read TIMESTAMP defaults in the same + // timezone even when aaPanel's MySQL server defaults to a local timezone. + options.Params["time_zone"] = "'+00:00'" + db, err := sql.Open("mysql", options.FormatDSN()) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(20) + db.SetMaxIdleConns(5) + db.SetConnMaxLifetime(5 * time.Minute) + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if err := db.PingContext(ctx); err != nil { + db.Close() + return nil, err + } + return &Store{db: db}, nil +} + +func (s *Store) Close() error { return s.db.Close() } + +func (s *Store) Migrate(ctx context.Context) error { + // MySQL DDL commits independently; serialize schema changes across starters. + lock, err := s.db.Conn(ctx) + if err != nil { + return err + } + defer lock.Close() + var acquired int + if err = lock.QueryRowContext(ctx, "SELECT GET_LOCK(CONCAT('svh:migrate:',LEFT(SHA2(DATABASE(),256),40)),10)").Scan(&acquired); err != nil { + return err + } + if acquired != 1 { + return errors.New("another Sea vHost instance is migrating this database") + } + defer func() { + release, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, _ = lock.ExecContext(release, "DO RELEASE_LOCK(CONCAT('svh:migrate:',LEFT(SHA2(DATABASE(),256),40)))") + }() + entries, err := fs.ReadDir(migrations.Files, ".") + if err != nil { + return err + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") { + continue + } + var exists int + err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_migrations'").Scan(&exists) + if err != nil { + return err + } + if exists > 0 { + var count int + if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM schema_migrations WHERE version=?", entry.Name()).Scan(&count); err != nil { + return err + } + if count > 0 { + continue + } + } + data, err := migrations.Files.ReadFile(entry.Name()) + if err != nil { + return err + } + for _, statement := range strings.Split(string(data), ";") { + statement = strings.TrimSpace(statement) + if statement == "" { + continue + } + if entry.Name() >= "012_control_nodes.sql" { + err = s.applyControlNodeStatement(ctx, statement) + } else { + _, err = s.db.ExecContext(ctx, statement) + } + if err != nil { + return fmt.Errorf("migration %s: %w", entry.Name(), err) + } + } + if _, err := s.db.ExecContext(ctx, "INSERT IGNORE INTO schema_migrations(version) VALUES (?)", entry.Name()); err != nil { + return err + } + } + return nil +} + +func (s *Store) UserByEmail(ctx context.Context, email string) (User, error) { + return s.UserByLogin(ctx, email) +} + +func (s *Store) UserByLogin(ctx context.Context, identifier string) (User, error) { + var user User + var tenantID sql.NullInt64 + var projectID sql.NullInt64 + identifier = strings.ToLower(strings.TrimSpace(identifier)) + err := s.db.QueryRowContext(ctx, `SELECT u.id,u.tenant_id,u.project_id,COALESCE(u.login_name,u.email),u.email,u.display_name,u.password_hash,u.role,COALESCE(own.name,IF(u.role='host','独立主机',t.name),''),COALESCE(own.slug,IF(u.role='host','',t.slug),''),u.totp_enabled FROM users u LEFT JOIN tenants t ON t.id=u.tenant_id LEFT JOIN projects hp ON hp.id=u.project_id LEFT JOIN tenants own ON own.id=hp.owner_tenant_id WHERE (LOWER(u.email)=? OR LOWER(COALESCE(u.login_name,''))=?) AND u.status='active' AND (u.tenant_id IS NULL OR (t.status='active' AND t.deleted_at IS NULL)) AND (u.role<>'host' OR hp.manual_recycled_at IS NULL)`, identifier, identifier).Scan(&user.ID, &tenantID, &projectID, &user.LoginName, &user.Email, &user.DisplayName, &user.PasswordHash, &user.Role, &user.TenantName, &user.TenantSlug, &user.MFAEnabled) + if errors.Is(err, sql.ErrNoRows) { + return User{}, ErrNotFound + } + if err != nil { + return User{}, err + } + if tenantID.Valid { + value := uint64(tenantID.Int64) + user.TenantID = &value + } + if projectID.Valid { + value := uint64(projectID.Int64) + user.ProjectID = &value + } + redactInternalHostEmail(&user) + return user, nil +} + +func (s *Store) UserBySession(ctx context.Context, token string) (User, error) { + hash := sha256.Sum256([]byte(token)) + var user User + var tenantID sql.NullInt64 + var projectID sql.NullInt64 + err := s.db.QueryRowContext(ctx, `SELECT u.id,u.tenant_id,u.project_id,COALESCE(u.login_name,u.email),u.email,u.display_name,u.role,COALESCE(own.name,IF(u.role='host','独立主机',t.name),''),COALESCE(own.slug,IF(u.role='host','',t.slug),''),u.totp_enabled FROM sessions s JOIN users u ON u.id=s.user_id LEFT JOIN tenants t ON t.id=u.tenant_id LEFT JOIN projects hp ON hp.id=u.project_id LEFT JOIN tenants own ON own.id=hp.owner_tenant_id WHERE s.token_hash=? AND s.expires_at>NOW() AND u.status='active' AND (u.tenant_id IS NULL OR (t.status='active' AND t.deleted_at IS NULL)) AND (u.role<>'host' OR hp.manual_recycled_at IS NULL)`, hash[:]).Scan(&user.ID, &tenantID, &projectID, &user.LoginName, &user.Email, &user.DisplayName, &user.Role, &user.TenantName, &user.TenantSlug, &user.MFAEnabled) + if errors.Is(err, sql.ErrNoRows) { + return User{}, ErrNotFound + } + if err != nil { + return User{}, err + } + if tenantID.Valid { + value := uint64(tenantID.Int64) + user.TenantID = &value + } + if projectID.Valid { + value := uint64(projectID.Int64) + user.ProjectID = &value + } + redactInternalHostEmail(&user) + return user, nil +} + +func (s *Store) UserByID(ctx context.Context, userID uint64) (User, error) { + var user User + var tenantID, projectID sql.NullInt64 + err := s.db.QueryRowContext(ctx, `SELECT u.id,u.tenant_id,u.project_id,COALESCE(u.login_name,u.email),u.email,u.display_name,u.role,COALESCE(own.name,IF(u.role='host','独立主机',t.name),''),COALESCE(own.slug,IF(u.role='host','',t.slug),''),u.totp_enabled FROM users u LEFT JOIN tenants t ON t.id=u.tenant_id LEFT JOIN projects hp ON hp.id=u.project_id LEFT JOIN tenants own ON own.id=hp.owner_tenant_id WHERE u.id=? AND u.status='active' AND (u.tenant_id IS NULL OR (t.status='active' AND t.deleted_at IS NULL)) AND (u.role<>'host' OR hp.manual_recycled_at IS NULL)`, userID).Scan(&user.ID, &tenantID, &projectID, &user.LoginName, &user.Email, &user.DisplayName, &user.Role, &user.TenantName, &user.TenantSlug, &user.MFAEnabled) + if errors.Is(err, sql.ErrNoRows) { + return User{}, ErrNotFound + } + if err != nil { + return User{}, err + } + if tenantID.Valid { + value := uint64(tenantID.Int64) + user.TenantID = &value + } + if projectID.Valid { + value := uint64(projectID.Int64) + user.ProjectID = &value + } + redactInternalHostEmail(&user) + return user, nil +} + +func (s *Store) CreateOIDCState(ctx context.Context, state string, userID *uint64, mode, verifier, nonce string, expires time.Time) error { + hash := sha256.Sum256([]byte(state)) + _, err := s.db.ExecContext(ctx, `INSERT INTO oidc_states(state_hash,user_id,mode,verifier,nonce,expires_at) VALUES (?,?,?,?,?,?)`, hash[:], userID, mode, verifier, nonce, expires.UTC()) + return err +} + +func (s *Store) ConsumeOIDCState(ctx context.Context, state string) (OIDCState, error) { + hash := sha256.Sum256([]byte(state)) + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return OIDCState{}, err + } + defer tx.Rollback() + var result OIDCState + var userID sql.NullInt64 + if err = tx.QueryRowContext(ctx, `SELECT user_id,mode,verifier,nonce,expires_at,provider_key,session_token_hash FROM oidc_states WHERE state_hash=? FOR UPDATE`, hash[:]).Scan(&userID, &result.Mode, &result.Verifier, &result.Nonce, &result.Expires, &result.ProviderKey, &result.SessionHash); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return OIDCState{}, ErrNotFound + } + return OIDCState{}, err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM oidc_states WHERE state_hash=?`, hash[:]); err != nil { + return OIDCState{}, err + } + if err = tx.Commit(); err != nil { + return OIDCState{}, err + } + if result.Expires.Before(time.Now()) { + return OIDCState{}, ErrNotFound + } + if userID.Valid { + value := uint64(userID.Int64) + result.UserID = &value + } + return result, nil +} + +func (s *Store) BindOIDCIdentity(ctx context.Context, userID uint64, provider, subject, email string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var existing uint64 + err = tx.QueryRowContext(ctx, `SELECT user_id FROM sso_identities WHERE provider=? AND subject=? FOR UPDATE`, provider, subject).Scan(&existing) + if err == nil && existing != userID { + return errors.New("OIDC identity is already bound") + } + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM sso_identities WHERE user_id=? AND provider=?`, userID, provider); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `INSERT INTO sso_identities(user_id,provider,subject,email) VALUES (?,?,?,?)`, userID, provider, subject, email); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) OIDCIdentity(ctx context.Context, userID uint64, provider string) (OIDCIdentity, error) { + var item OIDCIdentity + err := s.db.QueryRowContext(ctx, `SELECT provider,subject,email,created_at FROM sso_identities WHERE user_id=? AND provider=?`, userID, provider).Scan(&item.Provider, &item.Subject, &item.Email, &item.Created) + if errors.Is(err, sql.ErrNoRows) { + return OIDCIdentity{}, ErrNotFound + } + return item, err +} + +func (s *Store) DeleteOIDCIdentity(ctx context.Context, userID uint64, provider string) error { + result, err := s.db.ExecContext(ctx, `DELETE FROM sso_identities WHERE user_id=? AND provider=?`, userID, provider) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) UserByOIDC(ctx context.Context, provider, subject string) (User, error) { + var userID uint64 + if err := s.db.QueryRowContext(ctx, `SELECT user_id FROM sso_identities WHERE provider=? AND subject=?`, provider, subject).Scan(&userID); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return User{}, ErrNotFound + } + return User{}, err + } + return s.UserByID(ctx, userID) +} + +func redactInternalHostEmail(user *User) { + if user.Role == "host" { + user.Email = "" + } +} + +func (s *Store) CreateSession(ctx context.Context, userID uint64, token string, expires time.Time) error { + hash := sha256.Sum256([]byte(token)) + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "DELETE FROM sessions WHERE expires_at<=NOW()"); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (?,?,?)", hash[:], userID, expires); err != nil { + return err + } + _, err = tx.ExecContext(ctx, `DELETE FROM sessions WHERE user_id=? AND token_hash NOT IN (SELECT token_hash FROM (SELECT token_hash FROM sessions WHERE user_id=? ORDER BY created_at DESC LIMIT 10) newest)`, userID, userID) + if err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) DeleteSession(ctx context.Context, token string) error { + hash := sha256.Sum256([]byte(token)) + _, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE token_hash=?", hash[:]) + return err +} + +func (s *Store) DeleteExpiredSessions(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, "DELETE FROM sessions WHERE expires_at<=NOW()") + return err +} + +func (s *Store) UserSecurity(ctx context.Context, userID uint64) (UserSecurity, error) { + var result UserSecurity + err := s.db.QueryRowContext(ctx, "SELECT password_hash,totp_secret_ciphertext,totp_enabled FROM users WHERE id=? AND status='active'", userID).Scan(&result.PasswordHash, &result.TOTPSecretCiphertext, &result.TOTPEnabled) + if errors.Is(err, sql.ErrNoRows) { + return UserSecurity{}, ErrNotFound + } + return result, err +} + +func (s *Store) ChangePassword(ctx context.Context, userID uint64, passwordHash, currentToken string) error { + currentHash := sha256.Sum256([]byte(currentToken)) + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, "UPDATE users SET password_hash=? WHERE id=? AND status='active'", passwordHash, userID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected != 1 { + return ErrNotFound + } + if _, err = tx.ExecContext(ctx, "DELETE FROM sessions WHERE user_id=? AND token_hash<>?", userID, currentHash[:]); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE target_user_id=? OR administrator_id=?", userID, userID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetPendingTOTP(ctx context.Context, userID uint64, ciphertext []byte) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "UPDATE users SET totp_secret_ciphertext=?,totp_enabled=FALSE WHERE id=?", ciphertext, userID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM mfa_recovery_codes WHERE user_id=?", userID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) EnableTOTP(ctx context.Context, userID uint64, recoveryHashes [][]byte) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, "UPDATE users SET totp_enabled=TRUE WHERE id=? AND totp_secret_ciphertext IS NOT NULL", userID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected != 1 { + return ErrNotFound + } + if _, err = tx.ExecContext(ctx, "DELETE FROM mfa_recovery_codes WHERE user_id=?", userID); err != nil { + return err + } + for _, hash := range recoveryHashes { + if _, err = tx.ExecContext(ctx, "INSERT INTO mfa_recovery_codes(user_id,code_hash) VALUES (?,?)", userID, hash); err != nil { + return err + } + } + return tx.Commit() +} + +func (s *Store) DisableTOTP(ctx context.Context, userID uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "UPDATE users SET totp_secret_ciphertext=NULL,totp_enabled=FALSE WHERE id=?", userID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM mfa_recovery_codes WHERE user_id=?", userID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM sessions WHERE user_id=?", userID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE target_user_id=? OR administrator_id=?", userID, userID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) ConsumeRecoveryCode(ctx context.Context, userID uint64, codeHash []byte) (bool, error) { + result, err := s.db.ExecContext(ctx, "DELETE FROM mfa_recovery_codes WHERE user_id=? AND code_hash=?", userID, codeHash) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + return affected == 1, err +} + +func (s *Store) BootstrapAdmin(ctx context.Context, email, displayName, password string) error { + if email == "" || password == "" { + return nil + } + if strings.TrimSpace(displayName) == "" { + displayName = "平台管理员" + } + var count int + if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE role='admin'").Scan(&count); err != nil { + return err + } + if count > 0 { + return nil + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + normalizedEmail := strings.ToLower(email) + _, err = s.db.ExecContext(ctx, "INSERT INTO users(email,login_name,display_name,password_hash,role) VALUES (?,?,?,?, 'admin')", normalizedEmail, normalizedEmail, displayName, string(hash)) + return err +} + +// InstallAdmin makes an interrupted first-run installation safely repeatable. +// A retry for the same email refreshes the chosen name and password; a database +// containing a different administrator is rejected as not being a fresh install. +func (s *Store) InstallAdmin(ctx context.Context, email, displayName, password string) error { + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + rows, err := tx.QueryContext(ctx, "SELECT id,email FROM users WHERE role='admin' ORDER BY id LIMIT 2 FOR UPDATE") + if err != nil { + return err + } + type existingAdmin struct { + id uint64 + email string + } + admins := make([]existingAdmin, 0, 2) + for rows.Next() { + var admin existingAdmin + if err := rows.Scan(&admin.id, &admin.email); err != nil { + rows.Close() + return err + } + admins = append(admins, admin) + } + if err := rows.Close(); err != nil { + return err + } + normalizedEmail := strings.ToLower(strings.TrimSpace(email)) + if len(admins) > 1 || (len(admins) == 1 && !strings.EqualFold(admins[0].email, normalizedEmail)) { + return ErrDifferentAdminExists + } + if len(admins) == 0 { + _, err = tx.ExecContext(ctx, "INSERT INTO users(email,login_name,display_name,password_hash,role) VALUES (?,?,?,?, 'admin')", normalizedEmail, normalizedEmail, displayName, string(hash)) + } else { + _, err = tx.ExecContext(ctx, "UPDATE users SET display_name=?,password_hash=?,status='active' WHERE id=?", displayName, string(hash), admins[0].id) + } + if err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) PlanAndUsage(ctx context.Context, tenantID uint64) (Plan, Usage, error) { + return s.projectPlanAndUsage(ctx, tenantID) +} + +func (s *Store) legacyPlanAndUsage(ctx context.Context, tenantID uint64) (Plan, Usage, error) { + var plan Plan + var usage Usage + var measured sql.NullTime + err := s.db.QueryRowContext(ctx, `SELECT p.id,p.name,p.storage_bytes,p.database_bytes,p.monthly_bandwidth_bytes,p.bandwidth_mbps,p.process_limit,p.ftp_limit,p.database_limit,p.project_limit,COALESCE(q.storage_bytes,0),COALESCE(q.database_bytes,0),COALESCE(q.bandwidth_bytes,0),COALESCE(q.process_count,0),q.measured_at FROM tenants t JOIN plans p ON p.id=t.plan_id LEFT JOIN quota_usage q ON q.tenant_id=t.id WHERE t.id=? AND t.status='active' AND (t.expires_at IS NULL OR t.expires_at>NOW())`, tenantID).Scan(&plan.ID, &plan.Name, &plan.StorageBytes, &plan.DatabaseBytes, &plan.BandwidthBytes, &plan.BandwidthMbps, &plan.ProcessLimit, &plan.FTPLimit, &plan.DatabaseLimit, &plan.ProjectLimit, &usage.StorageBytes, &usage.DatabaseBytes, &usage.BandwidthBytes, &usage.ProcessCount, &measured) + if errors.Is(err, sql.ErrNoRows) { + return Plan{}, Usage{}, ErrNotFound + } + if measured.Valid { + usage.MeasuredAt = measured.Time + } + return plan, usage, err +} + +func (s *Store) UpdateStorageUsage(ctx context.Context, tenantID, storageBytes uint64) error { + _, err := s.db.ExecContext(ctx, `INSERT INTO quota_usage(tenant_id,storage_bytes,database_bytes,bandwidth_bytes,process_count,period_start,measured_at) + VALUES (?,?,0,0,0,CURDATE(),NOW()) + ON DUPLICATE KEY UPDATE storage_bytes=VALUES(storage_bytes),measured_at=VALUES(measured_at)`, tenantID, storageBytes) + return err +} + +func (s *Store) UpdateQuotaMeasurement(ctx context.Context, tenantID uint64, usage Usage, periodStart time.Time, databaseSizes map[uint64]uint64, databaseOver bool) error { + if scope.Project(ctx) == 0 { + return errors.New("project scope required for quota measurement") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + _, err = tx.ExecContext(ctx, `INSERT INTO project_quota_usage(project_id,storage_bytes,database_bytes,bandwidth_bytes,process_count,period_start,measured_at) + VALUES (?,?,?,?,?,?,NOW()) + ON DUPLICATE KEY UPDATE storage_bytes=VALUES(storage_bytes),database_bytes=VALUES(database_bytes),bandwidth_bytes=VALUES(bandwidth_bytes),process_count=VALUES(process_count),period_start=VALUES(period_start),measured_at=VALUES(measured_at)`, + scope.Project(ctx), usage.StorageBytes, usage.DatabaseBytes, usage.BandwidthBytes, usage.ProcessCount, periodStart) + if err != nil { + return err + } + status := "active" + if databaseOver { + status = "quota_suspended" + } + for id, size := range databaseSizes { + result, updateErr := tx.ExecContext(ctx, "UPDATE `databases` SET size_bytes=?,status=? WHERE id=? AND tenant_id=?", size, status, id, tenantID) + if updateErr != nil { + return updateErr + } + // MySQL reports zero affected rows when both the measured size and + // status are unchanged. More than one row would violate the scoped id. + if affected, affectedErr := result.RowsAffected(); affectedErr != nil || affected > 1 { + return errors.New("database quota resource changed during measurement") + } + } + return tx.Commit() +} + +func (s *Store) SetTenantQuotaSuspended(ctx context.Context, tenantID uint64, reason string) error { + if strings.TrimSpace(reason) == "" || len(reason) > 500 { + return errors.New("invalid quota suspension reason") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, `UPDATE projects SET status='quota_suspended',last_error=? WHERE tenant_id=? AND id=? AND status IN ('awaiting_upload','running','stopped','quota_suspended')`, reason, tenantID, scope.Project(ctx)); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE sites SET status='quota_suspended',last_error=? WHERE tenant_id=? AND project_id=? AND status IN ('awaiting_upload','running','stopped','quota_suspended')`, reason, tenantID, scope.Project(ctx)); err != nil { + return err + } + return tx.Commit() +} + +// TenantQuotaSuspension is the single control-plane write gate for a tenant. +// Project rows intentionally carry the suspension state because every tenant +// with mutable hosting resources has at least one managed project. +func (s *Store) TenantQuotaSuspension(ctx context.Context, tenantID uint64) (bool, string, error) { + var reason string + err := s.db.QueryRowContext(ctx, `SELECT COALESCE(last_error,'resource quota exceeded') FROM projects WHERE tenant_id=? AND id=? AND status='quota_suspended' ORDER BY id LIMIT 1`, tenantID, scope.Project(ctx)).Scan(&reason) + if errors.Is(err, sql.ErrNoRows) { + return false, "", nil + } + if err != nil { + return false, "", err + } + return true, reason, nil +} + +func (s *Store) SetTenantStorageSuspended(ctx context.Context, tenantID uint64) error { + return s.SetTenantQuotaSuspended(ctx, tenantID, "storage quota exceeded") +} + +// Clearing a soft quota suspension never starts a site automatically. The +// tenant must explicitly start it after deleting enough data. +func (s *Store) ClearTenantStorageSuspension(ctx context.Context, tenantID uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, `UPDATE projects SET status='stopped',last_error=NULL WHERE tenant_id=? AND id=? AND status='quota_suspended'`, tenantID, scope.Project(ctx)); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE sites SET status='stopped',last_error=NULL WHERE tenant_id=? AND project_id=? AND status='quota_suspended'`, tenantID, scope.Project(ctx)); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE `databases` SET status='active' WHERE tenant_id=? AND project_id=? AND status='quota_suspended'", tenantID, scope.Project(ctx)); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) ListProjects(ctx context.Context, tenantID uint64) ([]Project, error) { + filter, args := customerFilter(ctx, tenantID, "projects", "projects") + args = append(args, scope.Project(ctx), scope.Project(ctx)) + rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,node_id,COALESCE(plan_id,0),host_name,slug,assigned_domain,root_path,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,allow_runtime_change,created_at FROM projects WHERE `+filter+` AND (?=0 OR id=?) ORDER BY id DESC`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + projects := make([]Project, 0) + for rows.Next() { + var p Project + if err := rows.Scan(&p.ID, &p.TenantID, &p.NodeID, &p.PlanID, &p.HostName, &p.Slug, &p.Domain, &p.Path, &p.RunPath, &p.Runtime, &p.Version, &p.Status, &p.SSLStatus, &p.PanelSiteID, &p.BackendPort, &p.ProcessLimit, &p.AutoSSL, &p.AllowRuntimeChange, &p.CreatedAt); err != nil { + return nil, err + } + projects = append(projects, p) + } + return projects, rows.Err() +} + +func (s *Store) AllProjects(ctx context.Context) ([]Project, error) { + nodeID, _ := scope.ExplicitNode(ctx) + rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,node_id,COALESCE(plan_id,0),host_name,slug,assigned_domain,root_path,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,allow_runtime_change,created_at FROM projects WHERE management_locked=FALSE AND status NOT IN ('provisioning','failed') AND (?=0 OR id=?) AND (?=0 OR node_id=?) ORDER BY id`, scope.Project(ctx), scope.Project(ctx), nodeID, nodeID) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]Project, 0) + for rows.Next() { + var item Project + if err = rows.Scan(&item.ID, &item.TenantID, &item.NodeID, &item.PlanID, &item.HostName, &item.Slug, &item.Domain, &item.Path, &item.RunPath, &item.Runtime, &item.Version, &item.Status, &item.SSLStatus, &item.PanelSiteID, &item.BackendPort, &item.ProcessLimit, &item.AutoSSL, &item.AllowRuntimeChange, &item.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) FTPUsername(ctx context.Context, tenantID, projectID uint64) (string, error) { + var username string + err := s.db.QueryRowContext(ctx, "SELECT username FROM ftp_accounts WHERE tenant_id=? AND project_id=?", tenantID, projectID).Scan(&username) + if errors.Is(err, sql.ErrNoRows) { + return "", ErrNotFound + } + return username, err +} + +func (s *Store) Project(ctx context.Context, tenantID, projectID uint64) (Project, error) { + var p Project + err := s.db.QueryRowContext(ctx, `SELECT id,tenant_id,node_id,COALESCE(plan_id,0),host_name,slug,assigned_domain,root_path,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,allow_runtime_change,created_at FROM projects WHERE tenant_id=? AND id=?`, tenantID, projectID).Scan(&p.ID, &p.TenantID, &p.NodeID, &p.PlanID, &p.HostName, &p.Slug, &p.Domain, &p.Path, &p.RunPath, &p.Runtime, &p.Version, &p.Status, &p.SSLStatus, &p.PanelSiteID, &p.BackendPort, &p.ProcessLimit, &p.AutoSSL, &p.AllowRuntimeChange, &p.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + return Project{}, ErrNotFound + } + return p, err +} + +func (s *Store) CountProjects(ctx context.Context, tenantID uint64) (int, error) { + var count int + err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM projects WHERE tenant_id=? AND status<>'failed'", tenantID).Scan(&count) + return count, err +} + +func (s *Store) TenantResourceCounts(ctx context.Context, tenantID uint64) (ResourceCounts, error) { + var counts ResourceCounts + err := s.db.QueryRowContext(ctx, "SELECT (SELECT COUNT(*) FROM ftp_accounts WHERE tenant_id=?),(SELECT COUNT(*) FROM `databases` WHERE tenant_id=?)", tenantID, tenantID).Scan(&counts.FTP, &counts.Databases) + return counts, err +} + +func (s *Store) InsertProject(ctx context.Context, input NewProject) (uint64, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + var nodeLock uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM control_nodes WHERE id=? AND enabled=TRUE AND deleted_at IS NULL FOR UPDATE", input.NodeID).Scan(&nodeLock); err != nil { + return 0, err + } + if err = tx.QueryRowContext(ctx, "SELECT GREATEST(20000,COALESCE(MAX(backend_port)+20,20000)) FROM projects WHERE node_id=?", input.NodeID).Scan(&input.BackendPort); err != nil { + return 0, err + } + if input.BackendPort > 39960 { + return 0, errors.New("节点端口已耗尽") + } + owner := input.OwnerTenantID + if !input.OwnershipSpecified { + owner = &input.TenantID + } + if owner != nil { + var ownerID uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM tenants WHERE id=? AND status='active' AND deleted_at IS NULL FOR UPDATE", *owner).Scan(&ownerID); err != nil { + return 0, errors.New("目标用户不存在或已删除") + } + } + result, err := tx.ExecContext(ctx, `INSERT INTO projects(tenant_id,owner_tenant_id,ownership_initialized,node_id,plan_id,host_name,slug,runtime,runtime_version,root_path,run_path,assigned_domain,backend_port,process_limit,auto_ssl) VALUES (?,?,TRUE,?,?,?,?,?,?,?,?,?,?,?,?)`, input.TenantID, owner, input.NodeID, input.PlanID, input.HostName, input.Slug, input.Runtime, input.Version, input.Path, input.RunPath, input.Domain, input.BackendPort, input.ProcessLimit, input.AutoSSL) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + if err != nil { + return 0, err + } + internalEmail := input.HostName + "@host.sea-vhost.invalid" + if itemID := scope.BatchItem(ctx); itemID > 0 { + if _, err = tx.ExecContext(ctx, "UPDATE admin_batch_items SET resource_id=? WHERE id=? AND state='running'", id, itemID); err != nil { + return 0, err + } + } + if _, err = tx.ExecContext(ctx, `INSERT INTO users(tenant_id,project_id,login_name,email,display_name,password_hash,role,status) VALUES (?,?,?,?,?,?,'host','disabled')`, input.TenantID, id, input.HostName, internalEmail, input.HostName, input.HostPasswordHash); err != nil { + return 0, err + } + if err = tx.Commit(); err != nil { + return 0, err + } + return uint64(id), nil +} + +func (s *Store) CompleteProject(ctx context.Context, projectID uint64, panelSiteID, ftpID, dbID int64, ftpUser, dbName, dbUser string, ftpPasswordCipher, dbPasswordCipher []byte, initialStatus, customDomain, customDomainStatus string, adopted bool) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var tenantID, nodeID uint64 + var path, slug, domain, runPath, runtime, version string + var backendPort, processLimit int + var autoSSL bool + if err := tx.QueryRowContext(ctx, "SELECT tenant_id,node_id,root_path,slug,assigned_domain,run_path,runtime,runtime_version,COALESCE(backend_port,0),process_limit,auto_ssl FROM projects WHERE id=? FOR UPDATE", projectID).Scan(&tenantID, &nodeID, &path, &slug, &domain, &runPath, &runtime, &version, &backendPort, &processLimit, &autoSSL); err != nil { + return err + } + if initialStatus != "running" && initialStatus != "awaiting_upload" { + return errors.New("invalid initial project status") + } + if _, err = tx.ExecContext(ctx, "UPDATE projects SET identity_verified=TRUE,panel_site_id=?,status=?,ssl_status=IF(auto_ssl,'pending','off'),last_error=NULL WHERE id=?", panelSiteID, initialStatus, projectID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE users SET status='active' WHERE project_id=? AND role='host'", projectID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "INSERT INTO ftp_accounts(tenant_id,project_id,panel_ftp_id,username,password_ciphertext,root_path) VALUES (?,?,?,?,?,?)", tenantID, projectID, ftpID, ftpUser, ftpPasswordCipher, path); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "INSERT INTO `databases`(tenant_id,project_id,panel_database_id,name,username,password_ciphertext) VALUES (?,?,?,?,?,?)", tenantID, projectID, dbID, dbName, dbUser, dbPasswordCipher); err != nil { + return err + } + siteResult, err := tx.ExecContext(ctx, `INSERT INTO sites(tenant_id,project_id,node_id,slug,assigned_domain,run_path,runtime,runtime_version,panel_site_id,backend_port,process_limit,auto_ssl,ssl_status,status,is_primary) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,IF(?,'pending','off'),?,TRUE)`, tenantID, projectID, nodeID, slug, domain, runPath, runtime, version, panelSiteID, backendPort, processLimit, autoSSL, autoSSL, initialStatus) + if err != nil { + return err + } + siteID, err := siteResult.LastInsertId() + if err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode) VALUES (?,?)`, siteID, map[bool]string{true: "http-01", false: "off"}[autoSSL]); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "INSERT INTO domains(tenant_id,project_id,site_id,domain,kind,status) VALUES (?,?,?,?,'assigned','approved')", tenantID, projectID, siteID, domain); err != nil { + return err + } + if customDomain != "" { + if customDomainStatus != "approved" && customDomainStatus != "pending" { + return errors.New("invalid custom domain status") + } + if _, err = tx.ExecContext(ctx, "INSERT INTO domains(tenant_id,project_id,site_id,domain,kind,status) VALUES (?,?,?,?,'custom',?)", tenantID, projectID, siteID, customDomain, customDomainStatus); err != nil { + return err + } + if adopted { + if _, err = tx.ExecContext(ctx, `UPDATE domains SET kind=CASE WHEN domain=? THEN 'custom' WHEN domain=? THEN 'assigned' ELSE kind END WHERE project_id=?`, domain, customDomain, projectID); err != nil { + return err + } + } + } + return tx.Commit() +} + +func (s *Store) MarkProjectFailed(ctx context.Context, projectID uint64, reason string) error { + if len(reason) > 500 { + reason = reason[:500] + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "UPDATE projects SET status='failed',last_error=? WHERE id=?", reason, projectID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE users SET status='disabled' WHERE project_id=? AND role='host'", projectID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET status='failed',last_error=? WHERE project_id=?", reason, projectID); err != nil { + return err + } + return tx.Commit() +} +func (s *Store) SetProjectState(ctx context.Context, tenantID, projectID uint64, state string) error { + if state != "running" && state != "stopped" { + return errors.New("invalid project state") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, "UPDATE projects SET status=? WHERE tenant_id=? AND id=?", state, tenantID, projectID) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n == 0 { + var exists bool + if err = tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM projects WHERE tenant_id=? AND id=?)", tenantID, projectID).Scan(&exists); err != nil { + return err + } + if !exists { + return ErrNotFound + } + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET status=? WHERE tenant_id=? AND project_id=? AND is_primary=TRUE", state, tenantID, projectID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetProjectRunPath(ctx context.Context, tenantID, projectID uint64, runPath string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, "UPDATE projects SET run_path=? WHERE tenant_id=? AND id=?", runPath, tenantID, projectID) + if err != nil { + return err + } + n, _ := result.RowsAffected() + if n == 0 { + return ErrNotFound + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET run_path=? WHERE tenant_id=? AND project_id=? AND is_primary=TRUE", runPath, tenantID, projectID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) AddCustomDomain(ctx context.Context, tenantID, projectID uint64, domain, status string) error { + _, err := s.db.ExecContext(ctx, "INSERT INTO domains(tenant_id,project_id,site_id,domain,kind,status) SELECT ?,?,id,?,'custom',? FROM sites WHERE project_id=? AND is_primary=TRUE", tenantID, projectID, domain, status, projectID) + return err +} + +func (s *Store) ListDomains(ctx context.Context, tenantID uint64, projectID *uint64) ([]DomainResource, error) { + filter, args := customerFilter(ctx, tenantID, "p", "d") + query := domainResourceQuery + " WHERE " + filter + if projectID != nil { + query += " AND d.project_id=?" + args = append(args, *projectID) + } + query += " ORDER BY d.id DESC" + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]DomainResource, 0) + for rows.Next() { + item, scanErr := scanDomainResource(rows) + if scanErr != nil { + return nil, scanErr + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) PendingDomains(ctx context.Context) ([]DomainResource, error) { + rows, err := s.db.QueryContext(ctx, domainResourceQuery+" WHERE d.kind='custom' AND d.status='pending' ORDER BY d.id") + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]DomainResource, 0) + for rows.Next() { + item, scanErr := scanDomainResource(rows) + if scanErr != nil { + return nil, scanErr + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) DomainByID(ctx context.Context, id uint64) (DomainResource, error) { + rows, err := s.db.QueryContext(ctx, domainResourceQuery+" WHERE d.id=?", id) + if err != nil { + return DomainResource{}, err + } + defer rows.Close() + if !rows.Next() { + return DomainResource{}, ErrNotFound + } + return scanDomainResource(rows) +} + +func (s *Store) DomainByName(ctx context.Context, tenantID, projectID, siteID uint64, domain string) (DomainResource, error) { + rows, err := s.db.QueryContext(ctx, domainResourceQuery+" WHERE d.tenant_id=? AND d.project_id=? AND d.site_id=? AND d.domain=?", tenantID, projectID, siteID, domain) + if err != nil { + return DomainResource{}, err + } + defer rows.Close() + if !rows.Next() { + return DomainResource{}, ErrNotFound + } + return scanDomainResource(rows) +} + +func (s *Store) SetDomainStatus(ctx context.Context, id uint64, from, to string) error { + if !validDomainStatus(from) || !validDomainStatus(to) { + return errors.New("invalid domain status") + } + result, err := s.db.ExecContext(ctx, "UPDATE domains SET status=? WHERE id=? AND status=?", to, id, from) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) DeletePendingDomain(ctx context.Context, id uint64) error { + _, err := s.db.ExecContext(ctx, "DELETE FROM domains WHERE id=? AND kind='custom' AND status='pending'", id) + return err +} + +func validDomainStatus(value string) bool { + return value == "pending" || value == "approved" || value == "rejected" +} + +const domainResourceQuery = `SELECT d.id,d.tenant_id,d.project_id,d.site_id,COALESCE(t.name,'未绑定用户'),p.host_name,p.slug,s.slug,d.domain,d.kind,d.status,d.resolution_mode,COALESCE(d.cname_target,''),d.dns_credential_id,COALESCE(d.dns_record_id,''),COALESCE(d.dns_record_type,''),COALESCE(d.dns_last_error,''),d.filing_status,COALESCE(d.filing_number,''),COALESCE(d.filing_note,''),s.ssl_status,COALESCE(s.panel_site_id,0),s.assigned_domain,p.root_path,s.auto_ssl,d.created_at +FROM domains d +JOIN projects p ON p.id=d.project_id +LEFT JOIN tenants t ON t.id=p.owner_tenant_id +JOIN sites s ON s.id=d.site_id` + +type rowScanner interface{ Scan(...any) error } + +func scanDomainResource(row rowScanner) (DomainResource, error) { + var item DomainResource + var credentialID sql.NullInt64 + err := row.Scan(&item.ID, &item.TenantID, &item.ProjectID, &item.SiteID, &item.TenantName, &item.HostName, &item.ProjectName, &item.SiteName, &item.Domain, &item.Kind, &item.Status, &item.ResolutionMode, &item.CNAME, &credentialID, &item.DNSRecordID, &item.DNSRecordType, &item.DNSLastError, &item.FilingStatus, &item.FilingNumber, &item.FilingNote, &item.SSLStatus, &item.PanelSiteID, &item.SiteAssignedDomain, &item.RootPath, &item.AutoSSL, &item.CreatedAt) + if credentialID.Valid { + value := uint64(credentialID.Int64) + item.DNSCredentialID = &value + } + return item, err +} + +func (s *Store) ListFTPResources(ctx context.Context, tenantID uint64, projectID *uint64) ([]FTPResource, error) { + if id := scope.Project(ctx); projectID == nil && id > 0 { + projectID = &id + } + filter, args := customerFilter(ctx, tenantID, "p", "f") + query := `SELECT f.id,f.tenant_id,COALESCE(f.panel_ftp_id,0),f.project_id,p.host_name,p.slug,f.username,f.root_path,f.created_at,f.enabled FROM ftp_accounts f JOIN projects p ON p.id=f.project_id WHERE ` + filter + if projectID != nil { + query += " AND f.project_id=?" + args = append(args, *projectID) + } + query += " ORDER BY f.id DESC" + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]FTPResource, 0) + for rows.Next() { + var item FTPResource + if err = rows.Scan(&item.ID, &item.TenantID, &item.PanelID, &item.ProjectID, &item.HostName, &item.ProjectName, &item.Username, &item.RootPath, &item.CreatedAt, &item.Enabled); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) ListDatabaseResources(ctx context.Context, tenantID uint64, projectID *uint64) ([]DatabaseResource, error) { + if id := scope.Project(ctx); projectID == nil && id > 0 { + projectID = &id + } + filter, args := customerFilter(ctx, tenantID, "p", "d") + query := "SELECT d.id,d.tenant_id,COALESCE(d.panel_database_id,0),d.project_id,p.host_name,p.slug,d.name,d.username,d.size_bytes,d.status,d.created_at FROM `databases` d JOIN projects p ON p.id=d.project_id WHERE " + filter + if projectID != nil { + query += " AND d.project_id=?" + args = append(args, *projectID) + } + query += " ORDER BY d.id DESC" + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]DatabaseResource, 0) + for rows.Next() { + var item DatabaseResource + if err = rows.Scan(&item.ID, &item.TenantID, &item.PanelID, &item.ProjectID, &item.HostName, &item.ProjectName, &item.Name, &item.Username, &item.SizeBytes, &item.Status, &item.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) ListTenantSites(ctx context.Context, tenantID uint64, projectID *uint64) ([]Site, error) { + if id := scope.Project(ctx); projectID == nil && id > 0 { + projectID = &id + } + query := `SELECT id,tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,is_primary,created_at FROM sites WHERE tenant_id=?` + args := []any{tenantID} + if account := scope.Account(ctx); account > 0 { + query = `SELECT id,tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,is_primary,created_at FROM sites WHERE project_id IN (SELECT id FROM projects WHERE owner_tenant_id=? AND management_locked=FALSE)` + args = []any{account} + } + if projectID != nil { + query += " AND project_id=?" + args = append(args, *projectID) + } + query += " ORDER BY project_id,is_primary DESC,id" + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]Site, 0) + for rows.Next() { + var item Site + if err = rows.Scan(&item.ID, &item.TenantID, &item.ProjectID, &item.Name, &item.Domain, &item.RunPath, &item.Runtime, &item.Version, &item.Status, &item.SSLStatus, &item.PanelSiteID, &item.BackendPort, &item.ProcessLimit, &item.AutoSSL, &item.Primary, &item.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) Credentials(ctx context.Context, tenantID, projectID uint64) (StoredCredentials, error) { + var result StoredCredentials + err := s.db.QueryRowContext(ctx, "SELECT f.username,f.password_ciphertext,d.name,d.username,d.password_ciphertext FROM ftp_accounts f JOIN `databases` d ON d.project_id=f.project_id WHERE f.tenant_id=? AND f.project_id=?", tenantID, projectID).Scan(&result.FTPUsername, &result.FTPPasswordCipher, &result.DatabaseName, &result.DatabaseUsername, &result.DatabasePasswordCipher) + if errors.Is(err, sql.ErrNoRows) { + return StoredCredentials{}, ErrNotFound + } + return result, err +} + +func (s *Store) ResetHostPassword(ctx context.Context, tenantID, projectID uint64, passwordHash string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var userID uint64 + if err = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE tenant_id=? AND project_id=? AND role='host' FOR UPDATE", tenantID, projectID).Scan(&userID); errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } else if err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE users SET password_hash=? WHERE id=?", passwordHash, userID); err != nil { + return err + } + // A password reset invalidates every existing host session. The tenant + // account performing the reset has a different user id and remains signed in. + if _, err = tx.ExecContext(ctx, "DELETE FROM sessions WHERE user_id=?", userID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DELETE FROM impersonation_sessions WHERE target_user_id=? OR administrator_id=?", userID, userID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) ListSites(ctx context.Context, tenantID, projectID uint64) ([]Site, error) { + rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,is_primary,created_at FROM sites WHERE tenant_id=? AND project_id=? ORDER BY is_primary DESC,id`, tenantID, projectID) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]Site, 0) + for rows.Next() { + var item Site + if err = rows.Scan(&item.ID, &item.TenantID, &item.ProjectID, &item.Name, &item.Domain, &item.RunPath, &item.Runtime, &item.Version, &item.Status, &item.SSLStatus, &item.PanelSiteID, &item.BackendPort, &item.ProcessLimit, &item.AutoSSL, &item.Primary, &item.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) Site(ctx context.Context, tenantID, projectID, siteID uint64) (Site, error) { + var item Site + err := s.db.QueryRowContext(ctx, `SELECT id,tenant_id,project_id,slug,assigned_domain,run_path,runtime,runtime_version,status,ssl_status,COALESCE(panel_site_id,0),COALESCE(backend_port,0),process_limit,auto_ssl,is_primary,created_at FROM sites WHERE tenant_id=? AND project_id=? AND id=?`, tenantID, projectID, siteID).Scan(&item.ID, &item.TenantID, &item.ProjectID, &item.Name, &item.Domain, &item.RunPath, &item.Runtime, &item.Version, &item.Status, &item.SSLStatus, &item.PanelSiteID, &item.BackendPort, &item.ProcessLimit, &item.AutoSSL, &item.Primary, &item.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + return Site{}, ErrNotFound + } + return item, err +} + +func (s *Store) SetManualCertificateActive(ctx context.Context, tenantID, projectID, siteID uint64, expiresAt time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var primary bool + if err = tx.QueryRowContext(ctx, "SELECT is_primary FROM sites WHERE tenant_id=? AND project_id=? AND id=? FOR UPDATE", tenantID, projectID, siteID).Scan(&primary); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET auto_ssl=FALSE,ssl_status='active',last_error=NULL WHERE tenant_id=? AND project_id=? AND id=?", tenantID, projectID, siteID); err != nil { + return err + } + if primary { + if _, err = tx.ExecContext(ctx, "UPDATE projects SET auto_ssl=FALSE,ssl_status='active',last_error=NULL WHERE tenant_id=? AND id=?", tenantID, projectID); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode,expires_at,last_error,next_attempt_at) VALUES (?,'manual',?,NULL,NULL) ON DUPLICATE KEY UPDATE mode='manual',expires_at=VALUES(expires_at),last_error=NULL,next_attempt_at=NULL`, siteID, expiresAt.UTC()); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetAutoCertificateStatus(ctx context.Context, tenantID, projectID, siteID uint64, status, lastError string) error { + if status != "pending" && status != "active" && status != "failed" { + return errors.New("invalid automatic certificate status") + } + lastError = strings.TrimSpace(lastError) + if status != "failed" { + lastError = "" + } else if lastError == "" { + lastError = "automatic certificate request failed" + } + if len(lastError) > 1000 { + lastError = lastError[:1000] + } + var persistedError any + if lastError != "" { + persistedError = lastError + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var primary bool + if err = tx.QueryRowContext(ctx, "SELECT is_primary FROM sites WHERE tenant_id=? AND project_id=? AND id=? FOR UPDATE", tenantID, projectID, siteID).Scan(&primary); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET auto_ssl=TRUE,ssl_status=?,last_error=? WHERE tenant_id=? AND project_id=? AND id=?", status, persistedError, tenantID, projectID, siteID); err != nil { + return err + } + if primary { + if _, err = tx.ExecContext(ctx, "UPDATE projects SET auto_ssl=TRUE,ssl_status=?,last_error=? WHERE tenant_id=? AND id=?", status, persistedError, tenantID, projectID); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode,last_attempt_at,next_attempt_at,last_error) VALUES (?,'http-01',UTC_TIMESTAMP(),NULL,?) ON DUPLICATE KEY UPDATE mode='http-01',last_attempt_at=UTC_TIMESTAMP(),next_attempt_at=NULL,last_error=VALUES(last_error)`, siteID, persistedError); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetCertificateOff(ctx context.Context, tenantID, projectID, siteID uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var primary bool + if err = tx.QueryRowContext(ctx, "SELECT is_primary FROM sites WHERE tenant_id=? AND project_id=? AND id=? FOR UPDATE", tenantID, projectID, siteID).Scan(&primary); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET auto_ssl=FALSE,ssl_status='off' WHERE tenant_id=? AND project_id=? AND id=?", tenantID, projectID, siteID); err != nil { + return err + } + if primary { + if _, err = tx.ExecContext(ctx, "UPDATE projects SET auto_ssl=FALSE,ssl_status='off' WHERE tenant_id=? AND id=?", tenantID, projectID); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode,expires_at,next_attempt_at,last_error) VALUES (?,'off',NULL,NULL,NULL) ON DUPLICATE KEY UPDATE mode='off',expires_at=NULL,next_attempt_at=NULL,last_error=NULL`, siteID); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) SetSiteState(ctx context.Context, tenantID, projectID, siteID uint64, state string) error { + if state != "running" && state != "stopped" { + return errors.New("invalid site state") + } + result, err := s.db.ExecContext(ctx, "UPDATE sites SET status=?,last_error=NULL WHERE tenant_id=? AND project_id=? AND id=? AND is_primary=FALSE", state, tenantID, projectID, siteID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + var exists bool + if err = s.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sites WHERE tenant_id=? AND project_id=? AND id=? AND is_primary=FALSE)", tenantID, projectID, siteID).Scan(&exists); err != nil { + return err + } + if !exists { + return ErrNotFound + } + } + return nil +} + +func (s *Store) DeleteSite(ctx context.Context, tenantID, projectID, siteID uint64) error { + result, err := s.db.ExecContext(ctx, "DELETE FROM sites WHERE tenant_id=? AND project_id=? AND id=? AND is_primary=FALSE", tenantID, projectID, siteID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) CountSites(ctx context.Context, tenantID, projectID uint64) (int, error) { + var count int + err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sites WHERE tenant_id=? AND project_id=? AND status<>'failed'", tenantID, projectID).Scan(&count) + return count, err +} + +func (s *Store) InsertSite(ctx context.Context, input NewSite) (uint64, error) { + nodeID, _, err := s.ProjectPlacement(ctx, input.ProjectID) + if err != nil { + return 0, err + } + result, err := s.db.ExecContext(ctx, `INSERT INTO sites(tenant_id,project_id,node_id,slug,assigned_domain,run_path,runtime,runtime_version,backend_port,process_limit,auto_ssl,is_primary) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`, input.TenantID, input.ProjectID, nodeID, input.Name, input.Domain, input.RunPath, input.Runtime, input.Version, input.BackendPort, input.ProcessLimit, input.AutoSSL, input.Primary) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + return uint64(id), err +} + +func (s *Store) CompleteSite(ctx context.Context, siteID uint64, panelSiteID int64, status, customDomain, customDomainStatus string) error { + if status != "running" && status != "awaiting_upload" { + return errors.New("invalid initial site status") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var tenantID, projectID uint64 + var domain string + var autoSSL bool + if err = tx.QueryRowContext(ctx, "SELECT tenant_id,project_id,assigned_domain,auto_ssl FROM sites WHERE id=? FOR UPDATE", siteID).Scan(&tenantID, &projectID, &domain, &autoSSL); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET panel_site_id=?,status=?,ssl_status=IF(auto_ssl,'pending','off'),last_error=NULL WHERE id=?", panelSiteID, status, siteID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode) VALUES (?,?) ON DUPLICATE KEY UPDATE mode=VALUES(mode)`, siteID, map[bool]string{true: "http-01", false: "off"}[autoSSL]); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "INSERT INTO domains(tenant_id,project_id,site_id,domain,kind,status) VALUES (?,?,?,?,'assigned','approved')", tenantID, projectID, siteID, domain); err != nil { + return err + } + if customDomain != "" { + if customDomainStatus != "approved" && customDomainStatus != "pending" { + return errors.New("invalid custom domain status") + } + if _, err = tx.ExecContext(ctx, "INSERT INTO domains(tenant_id,project_id,site_id,domain,kind,status) VALUES (?,?,?,?,'custom',?)", tenantID, projectID, siteID, customDomain, customDomainStatus); err != nil { + return err + } + } + return tx.Commit() +} + +func (s *Store) CompleteSiteDeployment(ctx context.Context, tenantID, projectID, siteID uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var primary bool + if err = tx.QueryRowContext(ctx, "SELECT is_primary FROM sites WHERE tenant_id=? AND project_id=? AND id=? AND status='awaiting_upload' FOR UPDATE", tenantID, projectID, siteID).Scan(&primary); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET status='running',last_error=NULL WHERE id=?", siteID); err != nil { + return err + } + if primary { + result, updateErr := tx.ExecContext(ctx, "UPDATE projects SET status='running',last_error=NULL WHERE tenant_id=? AND id=? AND status='awaiting_upload'", tenantID, projectID) + if updateErr != nil { + return updateErr + } + if affected, _ := result.RowsAffected(); affected != 1 { + return ErrNotFound + } + } + return tx.Commit() +} + +func (s *Store) MarkSiteFailed(ctx context.Context, siteID uint64, reason string) error { + if len(reason) > 500 { + reason = reason[:500] + } + _, err := s.db.ExecContext(ctx, "UPDATE sites SET status='failed',last_error=? WHERE id=?", reason, siteID) + return err +} + +func (s *Store) AddCustomDomainForSite(ctx context.Context, tenantID, projectID, siteID uint64, domain, status string, maxDomains int) error { + if maxDomains < 2 || maxDomains > 1000 { + return errors.New("invalid site domain limit") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var lockedID uint64 + if err = tx.QueryRowContext(ctx, `SELECT id FROM sites WHERE tenant_id=? AND project_id=? AND id=? FOR UPDATE`, tenantID, projectID, siteID).Scan(&lockedID); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + var count int + if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM domains WHERE tenant_id=? AND project_id=? AND site_id=?`, tenantID, projectID, siteID).Scan(&count); err != nil { + return err + } + if count >= maxDomains { + return ErrDomainLimit + } + if _, err = tx.ExecContext(ctx, "INSERT INTO domains(tenant_id,project_id,site_id,domain,kind,status) VALUES (?,?,?,?,'custom',?)", tenantID, projectID, siteID, domain, status); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) Activities(ctx context.Context, tenantID uint64, limit int) ([]Activity, error) { + if limit < 1 || limit > 100 { + limit = 100 + } + query := `SELECT l.id,l.project_id,COALESCE(p.host_name,''),l.action,l.resource_type,COALESCE(l.detail,''),l.success,l.created_at, + CASE u.role WHEN 'admin' THEN '管理员' WHEN 'tenant' THEN '用户' WHEN 'host' THEN '主机账号' ELSE '系统' END,COALESCE(l.ip_address,'') + FROM operation_logs l LEFT JOIN projects p ON p.id=l.project_id AND p.tenant_id=l.tenant_id LEFT JOIN users u ON u.id=l.user_id WHERE ` + args := []any{tenantID} + if account := scope.Account(ctx); account > 0 { + query += `((p.owner_tenant_id=? AND p.management_locked=FALSE) OR (l.project_id IS NULL AND l.tenant_id=?))` + args = []any{account, account} + } else { + query += `l.tenant_id=?` + } + query += ` AND l.admin_action=FALSE AND l.administrator_id IS NULL AND u.role IN ('tenant','host')` + if projectID := scope.Project(ctx); projectID > 0 { + query += " AND l.project_id=?" + args = append(args, projectID) + } + query += " ORDER BY l.id DESC LIMIT ?" + args = append(args, limit) + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]Activity, 0) + for rows.Next() { + var item Activity + if err := rows.Scan(&item.ID, &item.ProjectID, &item.HostName, &item.Action, &item.ResourceType, &item.Detail, &item.Success, &item.CreatedAt, &item.Actor, &item.IPAddress); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} +func (s *Store) Log(ctx context.Context, tenantID *uint64, userID uint64, action, resourceType, resourceID, ip string, success bool, detail string) { + s.LogEvent(ctx, tenantID, &userID, action, resourceType, resourceID, ip, success, detail) +} + +func (s *Store) LogEvent(ctx context.Context, tenantID, userID *uint64, action, resourceType, resourceID, ip string, success bool, detail string) { + // A browser may cancel its request after an operation has completed. Keep + // identity/scope values while allowing the audit insert to finish independently. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + var administratorID, impersonatedID *uint64 + adminAction := false + if id := scope.Administrator(ctx); id > 0 { + administratorID, impersonatedID, userID = &id, userID, &id + adminAction = true + } else if userID != nil { + var role string + if err := s.db.QueryRowContext(ctx, "SELECT role FROM users WHERE id=?", *userID).Scan(&role); err != nil || role == "admin" { + adminAction = true + administratorID = userID + } + } + if text := []rune(detail); len(text) > 500 { + detail = string(text[:500]) + } + var projectID *uint64 + if id := scope.Project(ctx); id > 0 { + var owner uint64 + if err := s.db.QueryRowContext(ctx, "SELECT tenant_id FROM projects WHERE id=?", id).Scan(&owner); err == nil && (tenantID == nil || *tenantID == owner) { + projectID, tenantID = &id, &owner + } + } else if tenantID != nil && userID != nil { + var id sql.NullInt64 + if err := s.db.QueryRowContext(ctx, "SELECT project_id FROM users WHERE id=? AND tenant_id=? AND role='host'", *userID, *tenantID).Scan(&id); err == nil && id.Valid { + value := uint64(id.Int64) + projectID = &value + } + } + if _, err := s.db.ExecContext(ctx, "INSERT INTO operation_logs(tenant_id,project_id,user_id,administrator_id,impersonated_user_id,admin_action,action,resource_type,resource_id,ip_address,success,detail) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", tenantID, projectID, userID, administratorID, impersonatedID, adminAction, action, resourceType, resourceID, ip, success, detail); err != nil { + slog.Error("cannot persist operation audit event", "action", action, "resource_type", resourceType, "success", success, "error", err) + } +} + +func (s *Store) DomainApproval(ctx context.Context, fallback bool) bool { + var value string + if err := s.db.QueryRowContext(ctx, "SELECT setting_value FROM system_settings WHERE setting_key='domain_approval'").Scan(&value); err != nil { + return fallback + } + return value == "true" +} +func (s *Store) SetDomainApproval(ctx context.Context, enabled bool) error { + value := "false" + if enabled { + value = "true" + } + _, err := s.db.ExecContext(ctx, "INSERT INTO system_settings(setting_key,setting_value) VALUES ('domain_approval',?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)", value) + return err +} + +func (s *Store) Setting(ctx context.Context, key, fallback string) string { + var value string + if err := s.db.QueryRowContext(ctx, "SELECT setting_value FROM system_settings WHERE setting_key=?", key).Scan(&value); err != nil { + return fallback + } + return value +} + +func (s *Store) SetSetting(ctx context.Context, key, value string) error { + _, err := s.db.ExecContext(ctx, "INSERT INTO system_settings(setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)", key, value) + return err +} + +func (s *Store) AllDomains(ctx context.Context) ([]DomainResource, error) { + rows, err := s.db.QueryContext(ctx, domainResourceQuery+" ORDER BY d.id DESC") + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]DomainResource, 0) + for rows.Next() { + item, scanErr := scanDomainResource(rows) + if scanErr != nil { + return nil, scanErr + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) UpdateDomainRouting(ctx context.Context, id uint64, mode, target string) error { + result, err := s.db.ExecContext(ctx, "UPDATE domains SET resolution_mode=?,cname_target=NULLIF(?,'') WHERE id=?", mode, target, id) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) UpdateDomainFiling(ctx context.Context, id uint64, status, number, note string) error { + result, err := s.db.ExecContext(ctx, "UPDATE domains SET filing_status=?,filing_number=NULLIF(?,''),filing_note=NULLIF(?,'') WHERE id=? AND kind='custom'", status, number, note, id) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) InitializeCustomDomainPolicy(ctx context.Context, id uint64, cnameTarget string, filingRequired bool) error { + filing := "exempt" + if filingRequired { + filing = "pending" + } + _, err := s.db.ExecContext(ctx, "UPDATE domains SET resolution_mode='cname',cname_target=?,filing_status=? WHERE id=? AND kind='custom'", cnameTarget, filing, id) + return err +} + +func (s *Store) ListDNSCredentials(ctx context.Context, tenantID *uint64) ([]DNSCredential, error) { + query := `SELECT id,tenant_id,scope_key,secret_ref,label,provider,zone_name,credential_ciphertext,last_tested_at,test_status,test_error,created_at,updated_at FROM dns_credentials WHERE tenant_id IS NULL ORDER BY zone_name,label` + args := []any{} + if tenantID != nil { + query = `SELECT id,tenant_id,scope_key,secret_ref,label,provider,zone_name,credential_ciphertext,last_tested_at,test_status,test_error,created_at,updated_at FROM dns_credentials WHERE tenant_id=? ORDER BY zone_name,label` + args = append(args, *tenantID) + } + rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]DNSCredential, 0) + for rows.Next() { + item, scanErr := scanDNSCredential(rows) + if scanErr != nil { + return nil, scanErr + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) CountDNSCredentials(ctx context.Context, tenantID *uint64) (int, error) { + query := `SELECT COUNT(*) FROM dns_credentials WHERE tenant_id IS NULL` + args := []any{} + if tenantID != nil { + query = `SELECT COUNT(*) FROM dns_credentials WHERE tenant_id=?` + args = append(args, *tenantID) + } + var count int + err := s.db.QueryRowContext(ctx, query, args...).Scan(&count) + return count, err +} + +// CertificateDNSCredentials returns only the requesting tenant's credentials +// plus platform credentials. No other tenant can enter the selection set. +func (s *Store) CertificateDNSCredentials(ctx context.Context, tenantID uint64) ([]DNSCredential, error) { + if project := scope.Project(ctx); project > 0 { + owner, err := s.ProjectOwner(ctx, project) + if err != nil { + return nil, err + } + tenantID = 0 + if owner != nil { + tenantID = *owner + } + } + rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,scope_key,secret_ref,label,provider,zone_name,credential_ciphertext,last_tested_at,test_status,test_error,created_at,updated_at FROM dns_credentials WHERE tenant_id=? OR tenant_id IS NULL ORDER BY LENGTH(zone_name) DESC,id`, tenantID) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]DNSCredential, 0) + for rows.Next() { + item, scanErr := scanDNSCredential(rows) + if scanErr != nil { + return nil, scanErr + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) DNSCredential(ctx context.Context, id uint64, tenantID *uint64) (DNSCredential, error) { + query := `SELECT id,tenant_id,scope_key,secret_ref,label,provider,zone_name,credential_ciphertext,last_tested_at,test_status,test_error,created_at,updated_at FROM dns_credentials WHERE id=? AND tenant_id IS NULL` + args := []any{id} + if tenantID != nil { + query = `SELECT id,tenant_id,scope_key,secret_ref,label,provider,zone_name,credential_ciphertext,last_tested_at,test_status,test_error,created_at,updated_at FROM dns_credentials WHERE id=? AND tenant_id=?` + args = append(args, *tenantID) + } + item, err := scanDNSCredential(s.db.QueryRowContext(ctx, query, args...)) + if errors.Is(err, sql.ErrNoRows) { + return DNSCredential{}, ErrNotFound + } + return item, err +} + +func scanDNSCredential(row rowScanner) (DNSCredential, error) { + var item DNSCredential + var owner sql.NullInt64 + var tested sql.NullTime + var testError sql.NullString + err := row.Scan(&item.ID, &owner, &item.ScopeKey, &item.SecretRef, &item.Label, &item.Provider, &item.ZoneName, &item.CredentialCiphertext, &tested, &item.TestStatus, &testError, &item.CreatedAt, &item.UpdatedAt) + if err != nil { + return DNSCredential{}, err + } + if owner.Valid { + value := uint64(owner.Int64) + item.TenantID = &value + } + if tested.Valid { + value := tested.Time + item.LastTestedAt = &value + } + if testError.Valid { + item.TestError = testError.String + } + return item, nil +} + +func (s *Store) InsertDNSCredential(ctx context.Context, input NewDNSCredential) (uint64, error) { + result, err := s.db.ExecContext(ctx, `INSERT INTO dns_credentials(scope_key,tenant_id,secret_ref,label,provider,zone_name,credential_ciphertext) VALUES (?,?,?,?,?,?,?)`, input.ScopeKey, input.TenantID, input.SecretRef, input.Label, input.Provider, input.ZoneName, input.CredentialCiphertext) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + return uint64(id), err +} + +func (s *Store) UpdateDNSCredential(ctx context.Context, id uint64, tenantID *uint64, label, provider, zoneName, secretRef string, ciphertext []byte) error { + query := `UPDATE dns_credentials SET label=?,provider=?,zone_name=?,secret_ref=?,credential_ciphertext=?,last_tested_at=NULL,test_status='untested',test_error=NULL WHERE id=? AND tenant_id IS NULL` + args := []any{label, provider, zoneName, secretRef, ciphertext, id} + if tenantID != nil { + query = `UPDATE dns_credentials SET label=?,provider=?,zone_name=?,secret_ref=?,credential_ciphertext=?,last_tested_at=NULL,test_status='untested',test_error=NULL WHERE id=? AND tenant_id=?` + args = append(args, *tenantID) + } + result, err := s.db.ExecContext(ctx, query, args...) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) DeleteDNSCredential(ctx context.Context, id uint64, tenantID *uint64) error { + var references int + if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM domains WHERE dns_credential_id=? AND dns_record_id IS NOT NULL`, id).Scan(&references); err != nil { + return err + } + if references > 0 { + return ErrDNSCredentialInUse + } + query := `DELETE FROM dns_credentials WHERE id=? AND tenant_id IS NULL` + args := []any{id} + if tenantID != nil { + query = `DELETE FROM dns_credentials WHERE id=? AND tenant_id=?` + args = append(args, *tenantID) + } + result, err := s.db.ExecContext(ctx, query, args...) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) SetDomainDNSRecord(ctx context.Context, domainID, credentialID uint64, recordID, recordType string) error { + result, err := s.db.ExecContext(ctx, `UPDATE domains SET dns_credential_id=?,dns_record_id=?,dns_record_type=?,dns_last_error=NULL WHERE id=? AND kind='custom' AND status='approved' AND dns_record_id IS NULL`, credentialID, recordID, recordType, domainID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected != 1 { + return ErrNotFound + } + return nil +} + +func (s *Store) SetDomainDNSError(ctx context.Context, domainID uint64, failure string) error { + failure = strings.TrimSpace(failure) + if len(failure) > 500 { + failure = failure[:500] + } + _, err := s.db.ExecContext(ctx, `UPDATE domains SET dns_last_error=? WHERE id=?`, failure, domainID) + return err +} + +func (s *Store) ClearDomainDNSRecord(ctx context.Context, domainID, credentialID uint64, recordID string) error { + result, err := s.db.ExecContext(ctx, `UPDATE domains SET dns_credential_id=NULL,dns_record_id=NULL,dns_record_type=NULL,dns_last_error=NULL WHERE id=? AND dns_credential_id=? AND dns_record_id=?`, domainID, credentialID, recordID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected != 1 { + return ErrNotFound + } + return nil +} + +func (s *Store) BeginDNSCredentialTest(ctx context.Context, id uint64, tenantID *uint64, secretRef string, now time.Time, cooldown time.Duration) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + query := `SELECT last_tested_at FROM dns_credentials WHERE id=? AND tenant_id IS NULL AND secret_ref=? FOR UPDATE` + args := []any{id, secretRef} + if tenantID != nil { + query = `SELECT last_tested_at FROM dns_credentials WHERE id=? AND tenant_id=? AND secret_ref=? FOR UPDATE` + args = []any{id, *tenantID, secretRef} + } + var last sql.NullTime + if err = tx.QueryRowContext(ctx, query, args...).Scan(&last); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + if last.Valid && now.Sub(last.Time) >= 0 && now.Sub(last.Time) < cooldown { + return ErrDNSCredentialTestCooldown + } + update := `UPDATE dns_credentials SET last_tested_at=?,test_status='testing',test_error=NULL,updated_at=updated_at WHERE id=? AND tenant_id IS NULL AND secret_ref=?` + updateArgs := []any{now.UTC(), id, secretRef} + if tenantID != nil { + update = `UPDATE dns_credentials SET last_tested_at=?,test_status='testing',test_error=NULL,updated_at=updated_at WHERE id=? AND tenant_id=? AND secret_ref=?` + updateArgs = []any{now.UTC(), id, *tenantID, secretRef} + } + if _, err = tx.ExecContext(ctx, update, updateArgs...); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) CompleteDNSCredentialTest(ctx context.Context, id uint64, tenantID *uint64, secretRef string, success bool, failure string) error { + status := "passed" + var testError any + if !success { + status = "failed" + failure = strings.TrimSpace(failure) + if len(failure) > 500 { + failure = failure[:500] + } + testError = failure + } + query := `UPDATE dns_credentials SET test_status=?,test_error=?,updated_at=updated_at WHERE id=? AND tenant_id IS NULL AND secret_ref=?` + args := []any{status, testError, id, secretRef} + if tenantID != nil { + query = `UPDATE dns_credentials SET test_status=?,test_error=?,updated_at=updated_at WHERE id=? AND tenant_id=? AND secret_ref=?` + args = []any{status, testError, id, *tenantID, secretRef} + } + result, err := s.db.ExecContext(ctx, query, args...) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) SystemSecret(ctx context.Context, key string) ([]byte, error) { + var ciphertext []byte + err := s.db.QueryRowContext(ctx, `SELECT secret_ciphertext FROM system_secrets WHERE secret_key=?`, key).Scan(&ciphertext) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return ciphertext, err +} + +func (s *Store) InsertSystemSecretIfAbsent(ctx context.Context, key string, ciphertext []byte) error { + _, err := s.db.ExecContext(ctx, `INSERT IGNORE INTO system_secrets(secret_key,secret_ciphertext) VALUES (?,?)`, key, ciphertext) + return err +} + +func (s *Store) BeginDNSCertificateAttempt(ctx context.Context, tenantID, projectID, siteID uint64, now time.Time, cooldown time.Duration) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var primary bool + if err = tx.QueryRowContext(ctx, `SELECT is_primary FROM sites WHERE tenant_id=? AND project_id=? AND id=? FOR UPDATE`, tenantID, projectID, siteID).Scan(&primary); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + var last sql.NullTime + if err = tx.QueryRowContext(ctx, `SELECT last_attempt_at FROM certificate_automations WHERE site_id=?`, siteID).Scan(&last); err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + if last.Valid && now.Sub(last.Time) >= 0 && now.Sub(last.Time) < cooldown { + return ErrCertificateCooldown + } + if _, err = tx.ExecContext(ctx, `UPDATE sites SET auto_ssl=TRUE,ssl_status='pending',last_error=NULL WHERE id=?`, siteID); err != nil { + return err + } + if primary { + if _, err = tx.ExecContext(ctx, `UPDATE projects SET auto_ssl=TRUE,ssl_status='pending',last_error=NULL WHERE tenant_id=? AND id=?`, tenantID, projectID); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode,last_attempt_at,next_attempt_at,last_error) VALUES (?,'dns-01',?,?,NULL) ON DUPLICATE KEY UPDATE mode='dns-01',last_attempt_at=VALUES(last_attempt_at),next_attempt_at=VALUES(next_attempt_at),last_error=NULL`, siteID, now.UTC(), now.UTC().Add(6*time.Hour)); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) CompleteDNSCertificateAttempt(ctx context.Context, tenantID, projectID, siteID uint64, expiresAt *time.Time, failure string, now time.Time) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var primary bool + if err = tx.QueryRowContext(ctx, `SELECT is_primary FROM sites WHERE tenant_id=? AND project_id=? AND id=? FOR UPDATE`, tenantID, projectID, siteID).Scan(&primary); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + status := "active" + nextAttempt := now.UTC().Add(24 * time.Hour) + var expiry any + var lastError any + if expiresAt != nil { + expiry = expiresAt.UTC() + nextAttempt = expiresAt.UTC().Add(-30 * 24 * time.Hour) + if nextAttempt.Before(now.UTC().Add(24 * time.Hour)) { + nextAttempt = now.UTC().Add(24 * time.Hour) + } + } else { + status = "failed" + expiry = nil + nextAttempt = now.UTC().Add(6 * time.Hour) + lastError = strings.TrimSpace(failure) + if len(failure) > 500 { + lastError = failure[:500] + } + } + if _, err = tx.ExecContext(ctx, `UPDATE sites SET auto_ssl=TRUE,ssl_status=?,last_error=? WHERE id=?`, status, lastError, siteID); err != nil { + return err + } + if primary { + if _, err = tx.ExecContext(ctx, `UPDATE projects SET auto_ssl=TRUE,ssl_status=?,last_error=? WHERE tenant_id=? AND id=?`, status, lastError, tenantID, projectID); err != nil { + return err + } + } + if _, err = tx.ExecContext(ctx, `INSERT INTO certificate_automations(site_id,mode,expires_at,last_attempt_at,next_attempt_at,last_error) VALUES (?,'dns-01',?,?,?,?) ON DUPLICATE KEY UPDATE mode='dns-01',expires_at=VALUES(expires_at),last_attempt_at=VALUES(last_attempt_at),next_attempt_at=VALUES(next_attempt_at),last_error=VALUES(last_error)`, siteID, expiry, now.UTC(), nextAttempt, lastError); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) CertificateAutomation(ctx context.Context, tenantID, projectID, siteID uint64) (CertificateAutomation, error) { + var item CertificateAutomation + var expires, lastAttempt, nextAttempt sql.NullTime + var lastError sql.NullString + err := s.db.QueryRowContext(ctx, `SELECT a.site_id,a.mode,a.expires_at,a.last_attempt_at,a.next_attempt_at,a.last_error FROM certificate_automations a JOIN sites s ON s.id=a.site_id WHERE s.tenant_id=? AND s.project_id=? AND s.id=?`, tenantID, projectID, siteID).Scan(&item.SiteID, &item.Mode, &expires, &lastAttempt, &nextAttempt, &lastError) + if errors.Is(err, sql.ErrNoRows) { + return CertificateAutomation{}, ErrNotFound + } + if expires.Valid { + value := expires.Time + item.ExpiresAt = &value + } + if lastAttempt.Valid { + value := lastAttempt.Time + item.LastAttemptAt = &value + } + if nextAttempt.Valid { + value := nextAttempt.Time + item.NextAttemptAt = &value + } + if lastError.Valid { + item.LastError = lastError.String + } + return item, err +} + +func (s *Store) DueDNSCertificateRenewals(ctx context.Context, now time.Time, limit int) ([]CertificateRenewal, error) { + if limit <= 0 || limit > 100 { + limit = 25 + } + rows, err := s.db.QueryContext(ctx, `SELECT p.id,p.tenant_id,p.node_id,COALESCE(p.plan_id,0),p.host_name,p.slug,p.assigned_domain,p.root_path,p.run_path,p.runtime,p.runtime_version,p.status,p.ssl_status,COALESCE(p.panel_site_id,0),COALESCE(p.backend_port,0),p.process_limit,p.auto_ssl,p.created_at,s.id,s.tenant_id,s.project_id,s.slug,s.assigned_domain,s.run_path,s.runtime,s.runtime_version,s.status,s.ssl_status,COALESCE(s.panel_site_id,0),COALESCE(s.backend_port,0),s.process_limit,s.auto_ssl,s.is_primary,s.created_at FROM certificate_automations a JOIN sites s ON s.id=a.site_id JOIN projects p ON p.id=s.project_id WHERE p.management_locked=FALSE AND a.mode='dns-01' AND a.next_attempt_at IS NOT NULL AND a.next_attempt_at<=? AND s.status NOT IN ('provisioning','failed') ORDER BY a.next_attempt_at LIMIT ?`, now.UTC(), limit) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]CertificateRenewal, 0) + for rows.Next() { + var item CertificateRenewal + if err = rows.Scan(&item.Project.ID, &item.Project.TenantID, &item.Project.NodeID, &item.Project.PlanID, &item.Project.HostName, &item.Project.Slug, &item.Project.Domain, &item.Project.Path, &item.Project.RunPath, &item.Project.Runtime, &item.Project.Version, &item.Project.Status, &item.Project.SSLStatus, &item.Project.PanelSiteID, &item.Project.BackendPort, &item.Project.ProcessLimit, &item.Project.AutoSSL, &item.Project.CreatedAt, &item.Site.ID, &item.Site.TenantID, &item.Site.ProjectID, &item.Site.Name, &item.Site.Domain, &item.Site.RunPath, &item.Site.Runtime, &item.Site.Version, &item.Site.Status, &item.Site.SSLStatus, &item.Site.PanelSiteID, &item.Site.BackendPort, &item.Site.ProcessLimit, &item.Site.AutoSSL, &item.Site.Primary, &item.Site.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) ListPlans(ctx context.Context) ([]Plan, error) { + rows, err := s.db.QueryContext(ctx, `SELECT p.id,p.name,p.storage_bytes,p.database_bytes,p.monthly_bandwidth_bytes,p.bandwidth_mbps,p.process_limit,p.ftp_limit,p.database_limit,p.project_limit,p.created_at,CASE WHEN p.id=1 THEN '系统默认套餐不能删除' WHEN EXISTS(SELECT 1 FROM tenants WHERE plan_id=p.id) OR EXISTS(SELECT 1 FROM projects WHERE plan_id=p.id) THEN '套餐已被主机或历史账号引用,不能删除' WHEN EXISTS(SELECT 1 FROM admin_batches WHERE state IN ('queued','running')) THEN '请等待批量任务完成后再删除套餐' ELSE '' END FROM plans p ORDER BY p.id`) + if err != nil { + return nil, err + } + defer rows.Close() + plans := make([]Plan, 0) + for rows.Next() { + var plan Plan + if err := rows.Scan(&plan.ID, &plan.Name, &plan.StorageBytes, &plan.DatabaseBytes, &plan.BandwidthBytes, &plan.BandwidthMbps, &plan.ProcessLimit, &plan.FTPLimit, &plan.DatabaseLimit, &plan.ProjectLimit, &plan.CreatedAt, &plan.DeleteBlockedReason); err != nil { + return nil, err + } + plans = append(plans, plan) + } + return plans, rows.Err() +} + +func (s *Store) Plan(ctx context.Context, id uint64) (Plan, error) { + var plan Plan + err := s.db.QueryRowContext(ctx, `SELECT id,name,storage_bytes,database_bytes,monthly_bandwidth_bytes,bandwidth_mbps,process_limit,ftp_limit,database_limit,project_limit,created_at FROM plans WHERE id=?`, id).Scan(&plan.ID, &plan.Name, &plan.StorageBytes, &plan.DatabaseBytes, &plan.BandwidthBytes, &plan.BandwidthMbps, &plan.ProcessLimit, &plan.FTPLimit, &plan.DatabaseLimit, &plan.ProjectLimit, &plan.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + return Plan{}, ErrNotFound + } + return plan, err +} + +func (s *Store) TenantPlan(ctx context.Context, tenantID uint64) (Plan, error) { + if scope.Project(ctx) > 0 { + p, _, err := s.projectPlanAndUsage(ctx, tenantID) + return p, err + } + var plan Plan + err := s.db.QueryRowContext(ctx, `SELECT p.id,p.name,p.storage_bytes,p.database_bytes,p.monthly_bandwidth_bytes,p.bandwidth_mbps,p.process_limit,p.ftp_limit,p.database_limit,p.project_limit,p.created_at FROM tenants t JOIN plans p ON p.id=t.plan_id WHERE t.id=?`, tenantID).Scan(&plan.ID, &plan.Name, &plan.StorageBytes, &plan.DatabaseBytes, &plan.BandwidthBytes, &plan.BandwidthMbps, &plan.ProcessLimit, &plan.FTPLimit, &plan.DatabaseLimit, &plan.ProjectLimit, &plan.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + return Plan{}, ErrNotFound + } + return plan, err +} + +func (s *Store) ForceTenantStopped(ctx context.Context, tenantID uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, "UPDATE projects SET status='stopped',last_error='hosting term expired' WHERE tenant_id=? AND id=? AND status NOT IN ('failed','provisioning')", tenantID, scope.Project(ctx)); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "UPDATE sites SET status='stopped',last_error='hosting term expired' WHERE tenant_id=? AND project_id=? AND status NOT IN ('failed','provisioning')", tenantID, scope.Project(ctx)); err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) CreatePlan(ctx context.Context, input NewPlan) (uint64, error) { + var exists int + if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM plans WHERE name=?", input.Name).Scan(&exists); err != nil { + return 0, err + } + if exists > 0 { + return 0, errors.New("plan name already exists") + } + result, err := s.db.ExecContext(ctx, `INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,bandwidth_mbps,process_limit,ftp_limit,database_limit,project_limit) VALUES (?,?,?,?,?,?,?,?,?)`, input.Name, input.StorageBytes, input.DatabaseBytes, input.BandwidthBytes, input.BandwidthMbps, input.ProcessLimit, input.FTPLimit, input.DatabaseLimit, input.ProjectLimit) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + return uint64(id), err +} + +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`) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]TenantSummary, 0) + 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 { + return nil, err + } + if expires.Valid { + item.ExpiresAt = &expires.Time + } + if grace.Valid { + item.GraceUntil = &grace.Time + } + if purge.Valid { + item.PurgeAfter = &purge.Time + } + if backupPurge.Valid { + item.BackupPurgeAfter = &backupPurge.Time + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) SetTenantExpiry(ctx context.Context, id uint64, expiresAt *time.Time) error { + result, err := s.db.ExecContext(ctx, `UPDATE tenants SET expires_at=?,lifecycle_state='active',status='active',suspended_at=NULL,grace_until=NULL,purge_after=NULL,backup_purge_after=NULL WHERE id=? AND deleted_at IS NULL`, expiresAt, id) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) AdvanceLifecycle(ctx context.Context, now time.Time, graceDays, recycleDays, backupDays int) error { + _, err := s.db.ExecContext(ctx, `UPDATE tenants SET lifecycle_state='grace',grace_until=DATE_ADD(expires_at, INTERVAL ? DAY) WHERE lifecycle_state='active' AND expires_at IS NOT NULL AND expires_at<=?`, graceDays, now) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `UPDATE tenants SET lifecycle_state='recycle',status='suspended',suspended_at=COALESCE(suspended_at,?),purge_after=DATE_ADD(?, INTERVAL ? DAY),backup_purge_after=DATE_ADD(?, INTERVAL ? DAY) WHERE lifecycle_state='grace' AND grace_until<=?`, now, now, recycleDays, now, recycleDays+backupDays, now) + return err +} + +func (s *Store) CreateTenantBackup(ctx context.Context, tenantID, projectID uint64, hostName, archivePath string, sizeBytes uint64, expiresAt time.Time, databaseCounts ...int) error { + count := 0 + if len(databaseCounts) > 0 { + count = databaseCounts[0] + } + _, err := s.db.ExecContext(ctx, `INSERT INTO tenant_backups(tenant_id,project_id,node_id,host_name,archive_path,size_bytes,expires_at,database_count) VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE archive_path=VALUES(archive_path),size_bytes=VALUES(size_bytes),expires_at=VALUES(expires_at),database_count=VALUES(database_count),deleted_at=NULL,created_at=UTC_TIMESTAMP()`, tenantID, projectID, scope.Node(ctx), hostName, archivePath, sizeBytes, expiresAt.UTC(), count) + return err +} + +func (s *Store) TenantBackupDetails(ctx context.Context, tenantID, projectID uint64) (string, int, error) { + var path string + var count int + err := s.db.QueryRowContext(ctx, `SELECT archive_path,database_count FROM tenant_backups WHERE tenant_id=? AND project_id=? AND deleted_at IS NULL`, tenantID, projectID).Scan(&path, &count) + if errors.Is(err, sql.ErrNoRows) { + return "", 0, nil + } + return path, count, err +} + +func (s *Store) TenantBackupExists(ctx context.Context, tenantID, projectID uint64) (bool, error) { + var count int + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_backups WHERE tenant_id=? AND project_id=? AND deleted_at IS NULL`, tenantID, projectID).Scan(&count) + return count > 0, err +} + +func (s *Store) ExpiredTenantBackups(ctx context.Context, now time.Time, limit int) ([]TenantBackup, error) { + if limit < 1 || limit > 500 { + limit = 100 + } + rows, err := s.db.QueryContext(ctx, `SELECT id,tenant_id,project_id,node_id,host_name,archive_path,size_bytes,expires_at,deleted_at,created_at FROM tenant_backups WHERE deleted_at IS NULL AND expires_at<=? ORDER BY expires_at LIMIT ?`, now.UTC(), limit) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]TenantBackup, 0) + for rows.Next() { + var item TenantBackup + var projectID sql.NullInt64 + var deletedAt sql.NullTime + if err = rows.Scan(&item.ID, &item.TenantID, &projectID, &item.NodeID, &item.HostName, &item.ArchivePath, &item.SizeBytes, &item.ExpiresAt, &deletedAt, &item.CreatedAt); err != nil { + return nil, err + } + if projectID.Valid { + value := uint64(projectID.Int64) + item.ProjectID = &value + } + if deletedAt.Valid { + item.DeletedAt = &deletedAt.Time + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) MarkTenantBackupDeleted(ctx context.Context, id uint64) error { + result, err := s.db.ExecContext(ctx, `UPDATE tenant_backups SET deleted_at=UTC_TIMESTAMP() WHERE id=? AND deleted_at IS NULL`, id) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) MarkTenantPurged(ctx context.Context, tenantID uint64) error { + if id := scope.Project(ctx); id > 0 { + return s.PurgeHostRecord(ctx, id, tenantID) + } + return errors.New("host scope required") +} +func (s *Store) legacyMarkTenantPurged(ctx context.Context, tenantID uint64) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err = tx.ExecContext(ctx, `DELETE FROM projects WHERE tenant_id=?`, tenantID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `DELETE s FROM sessions s JOIN users u ON u.id=s.user_id WHERE u.tenant_id=?`, tenantID); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE users SET status='disabled' WHERE tenant_id=?`, tenantID); err != nil { + return err + } + result, err := tx.ExecContext(ctx, `UPDATE tenants SET lifecycle_state='purged',status='suspended' WHERE id=? AND lifecycle_state='recycle'`, tenantID) + if err != nil { + return err + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return tx.Commit() +} + +func (s *Store) EnqueueAdminNotification(ctx context.Context, severity, category, title, detail string) error { + if len(title) > 160 { + title = title[:160] + } + if len(detail) > 1000 { + detail = detail[:1000] + } + _, err := s.db.ExecContext(ctx, `INSERT INTO admin_notifications(severity,category,title,detail,next_attempt_at) VALUES (?,?,?,?,UTC_TIMESTAMP())`, severity, category, title, detail) + return err +} + +func (s *Store) PendingAdminNotifications(ctx context.Context, now time.Time, limit int) ([]AdminNotification, error) { + if limit < 1 || limit > 100 { + limit = 25 + } + rows, err := s.db.QueryContext(ctx, `SELECT id,severity,category,title,detail,attempts,next_attempt_at FROM admin_notifications WHERE delivered_at IS NULL AND attempts<8 AND (next_attempt_at IS NULL OR next_attempt_at<=?) ORDER BY id LIMIT ?`, now.UTC(), limit) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]AdminNotification, 0) + for rows.Next() { + var item AdminNotification + var next sql.NullTime + if err = rows.Scan(&item.ID, &item.Severity, &item.Category, &item.Title, &item.Detail, &item.Attempts, &next); err != nil { + return nil, err + } + if next.Valid { + item.NextAttemptAt = &next.Time + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) CompleteAdminNotification(ctx context.Context, id uint64) error { + _, err := s.db.ExecContext(ctx, `UPDATE admin_notifications SET delivered_at=UTC_TIMESTAMP(),last_error=NULL WHERE id=?`, id) + return err +} + +func (s *Store) FailAdminNotification(ctx context.Context, id uint64, message string, next time.Time) error { + if len(message) > 500 { + message = message[:500] + } + _, err := s.db.ExecContext(ctx, `UPDATE admin_notifications SET attempts=attempts+1,last_error=?,next_attempt_at=? WHERE id=? AND delivered_at IS NULL`, message, next.UTC(), id) + return err +} + +func (s *Store) ListAdminProjects(ctx context.Context) ([]AdminProject, error) { + rows, err := s.db.QueryContext(ctx, `SELECT p.id,p.tenant_id,p.node_id,COALESCE(p.plan_id,0),p.host_name,p.slug,p.assigned_domain,p.root_path,p.run_path,p.runtime,p.runtime_version,p.status,p.ssl_status,COALESCE(p.panel_site_id,0),COALESCE(p.backend_port,0),p.process_limit,p.auto_ssl,p.allow_runtime_change,p.created_at,p.expires_at,p.lifecycle_state,COALESCE(t.name,'未绑定用户'),COUNT(DISTINCT s.id),COALESCE(ip.address,''),COALESCE(sn.dedicated,FALSE),COALESCE(sn.http_port,80),COALESCE(sn.https_port,443),p.owner_tenant_id,p.management_locked,p.ownership_version,p.manual_recycled_at,p.purge_after,p.recycle_error FROM projects p LEFT JOIN tenants t ON t.id=p.owner_tenant_id LEFT JOIN sites s ON s.project_id=p.id LEFT JOIN site_networks sn ON sn.site_id=s.id AND s.is_primary=TRUE LEFT JOIN ip_pool ip ON ip.id=sn.ip_id GROUP BY p.id ORDER BY p.id DESC`) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]AdminProject, 0) + for rows.Next() { + var item AdminProject + if err := rows.Scan(&item.ID, &item.TenantID, &item.NodeID, &item.PlanID, &item.HostName, &item.Slug, &item.Domain, &item.Path, &item.RunPath, &item.Runtime, &item.Version, &item.Status, &item.SSLStatus, &item.PanelSiteID, &item.BackendPort, &item.ProcessLimit, &item.AutoSSL, &item.AllowRuntimeChange, &item.CreatedAt, &item.ExpiresAt, &item.LifecycleState, &item.TenantName, &item.SiteCount, &item.IPAddress, &item.DedicatedIP, &item.HTTPPort, &item.HTTPSPort, &item.OwnerTenantID, &item.ManagementLocked, &item.OwnershipVersion, &item.ManualRecycledAt, &item.PurgeAfter, &item.RecycleError); err != nil { + return nil, err + } + items = append(items, item) + } + if err = rows.Err(); err != nil { + return nil, err + } + rows.Close() + for i := range items { + if items[i].ManagementLocked { + pending, e := s.OwnershipChange(ctx, items[i].ID) + if e != nil { + return nil, e + } + pending.CredentialsCipher = nil + items[i].PendingOwnership = &pending + } + } + return items, nil +} + +func (s *Store) ListIPAddresses(ctx context.Context) ([]IPAddress, error) { + rows, err := s.db.QueryContext(ctx, `SELECT ip.id,ip.node_id,ip.address,ip.family,ip.allocation_mode,ip.label,ip.enabled,COUNT(sn.site_id),ip.created_at FROM ip_pool ip LEFT JOIN site_networks sn ON sn.ip_id=ip.id GROUP BY ip.id ORDER BY ip.allocation_mode,ip.id`) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]IPAddress, 0) + for rows.Next() { + var item IPAddress + if err := rows.Scan(&item.ID, &item.NodeID, &item.Address, &item.Family, &item.AllocationMode, &item.Label, &item.Enabled, &item.AssignedSites, &item.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) CreateIPAddress(ctx context.Context, address, family, mode, label string) (uint64, error) { + result, err := s.db.ExecContext(ctx, "INSERT INTO ip_pool(node_id,address,family,allocation_mode,label) VALUES (?,?,?,?,?)", scope.Node(ctx), address, family, mode, label) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + return uint64(id), err +} + +func (s *Store) IPAddress(ctx context.Context, id uint64) (IPAddress, error) { + var item IPAddress + err := s.db.QueryRowContext(ctx, `SELECT ip.id,ip.node_id,ip.address,ip.family,ip.allocation_mode,ip.label,ip.enabled,(SELECT COUNT(*) FROM site_networks sn WHERE sn.ip_id=ip.id),ip.created_at FROM ip_pool ip WHERE ip.id=?`, id).Scan(&item.ID, &item.NodeID, &item.Address, &item.Family, &item.AllocationMode, &item.Label, &item.Enabled, &item.AssignedSites, &item.CreatedAt) + if errors.Is(err, sql.ErrNoRows) { + return IPAddress{}, ErrNotFound + } + return item, err +} + +func (s *Store) DeleteIPAddress(ctx context.Context, id uint64) error { + var count int + if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM site_networks WHERE ip_id=?", id).Scan(&count); err != nil { + return err + } + if count > 0 { + return errors.New("ip address is assigned") + } + result, err := s.db.ExecContext(ctx, "DELETE FROM ip_pool WHERE id=?", id) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +func (s *Store) SetProjectNetwork(ctx context.Context, projectID uint64, ipID *uint64, dedicated bool, httpPort, httpsPort int) error { + result, err := s.db.ExecContext(ctx, `INSERT INTO site_networks(site_id,ip_id,dedicated,http_port,https_port) SELECT id,?,?,?,? FROM sites WHERE project_id=? AND is_primary=TRUE ON DUPLICATE KEY UPDATE ip_id=VALUES(ip_id),dedicated=VALUES(dedicated),http_port=VALUES(http_port),https_port=VALUES(https_port)`, ipID, dedicated, httpPort, httpsPort, projectID) + if err != nil { + return err + } + if n, _ := result.RowsAffected(); n == 0 { + var exists bool + if err = s.db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sites WHERE project_id=? AND is_primary=TRUE)", projectID).Scan(&exists); err != nil { + return err + } + if !exists { + return ErrNotFound + } + } + return nil +} + +func (s *Store) AdminActivities(ctx context.Context, limit int) ([]AdminActivity, error) { + rows, err := s.db.QueryContext(ctx, `SELECT l.id,COALESCE(a.display_name,t.name,''),l.action,l.resource_type,COALESCE(l.resource_id,''),COALESCE(l.ip_address,''),l.success,COALESCE(l.detail,''),l.created_at,l.administrator_id,l.impersonated_user_id,COALESCE(target.login_name,'') FROM operation_logs l LEFT JOIN tenants t ON t.id=l.tenant_id LEFT JOIN users a ON a.id=l.user_id LEFT JOIN users target ON target.id=l.impersonated_user_id ORDER BY l.id DESC LIMIT ?`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + items := make([]AdminActivity, 0) + for rows.Next() { + var item AdminActivity + if err := rows.Scan(&item.ID, &item.TenantName, &item.Action, &item.ResourceType, &item.ResourceID, &item.IPAddress, &item.Success, &item.Detail, &item.CreatedAt, &item.AdministratorID, &item.ImpersonatedUserID, &item.ImpersonatedUserName); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) CreateTenant(ctx context.Context, input NewTenant) (uint64, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) + if err != nil { + return 0, err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return 0, err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, "INSERT INTO tenants(slug,name,plan_id,expires_at) VALUES (?,?,?,?)", input.Slug, input.Name, input.PlanID, input.ExpiresAt) + if err != nil { + return 0, err + } + tenantID, err := result.LastInsertId() + if err != nil { + return 0, err + } + if itemID := scope.BatchItem(ctx); itemID > 0 { + if _, err = tx.ExecContext(ctx, "UPDATE admin_batch_items SET resource_id=? WHERE id=? AND state='running'", tenantID, itemID); err != nil { + 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 { + return 0, err + } + if err = tx.Commit(); err != nil { + return 0, err + } + return uint64(tenantID), nil +} diff --git a/backend/internal/store/user_schedules.go b/backend/internal/store/user_schedules.go new file mode 100644 index 0000000..df267ee --- /dev/null +++ b/backend/internal/store/user_schedules.go @@ -0,0 +1,266 @@ +package store + +import ( + "context" + "encoding/json" + "errors" + "time" +) + +func (s *Store) ProjectOwnershipVersion(ctx context.Context, id uint64) (uint64, error) { + var version uint64 + e := s.db.QueryRowContext(ctx, "SELECT ownership_version FROM projects WHERE id=?", id).Scan(&version) + return version, e +} +func (s *Store) LastSchedulerTick(ctx context.Context) (*time.Time, error) { + var v *time.Time + e := s.db.QueryRowContext(ctx, "SELECT MAX(created_at) FROM scheduler_ticks").Scan(&v) + return v, e +} +func (s *Store) ScheduleSitePort(ctx context.Context, id uint64, https bool) (int, error) { + var port int + column := "http_port" + fallback := 80 + if https { + column = "https_port" + fallback = 443 + } + e := s.db.QueryRowContext(ctx, "SELECT COALESCE(n."+column+",?) FROM sites s LEFT JOIN site_networks n ON n.site_id=s.id WHERE s.id=?", fallback, id).Scan(&port) + return port, e +} + +type UserSchedule struct { + SecretRef string `json:"-"` + ConfigCipher []byte `json:"-"` + ID uint64 `json:"id"` + UserID uint64 `json:"-"` + AccountID uint64 `json:"-"` + ProjectID uint64 `json:"projectId"` + SiteID uint64 `json:"siteId"` + OwnershipVersion uint64 `json:"-"` + Name string `json:"name"` + Cron string `json:"cron"` + Timezone string `json:"timezone"` + Kind string `json:"kind"` + Version string `json:"version"` + Target string `json:"target"` + Arguments []string `json:"arguments"` + UseHTTPS bool `json:"useHTTPS"` + Enabled bool `json:"enabled"` + NextRunAt time.Time `json:"nextRunAt"` + LastState string `json:"lastState"` +} + +const scheduleFields = `id,user_id,account_id,project_id,site_id,ownership_version,name,cron_expression,timezone,kind,runtime_version,target,arguments_json,use_https,enabled,next_run_at,last_state,secret_ref,config_cipher` + +func scanSchedule(row rowScanner) (UserSchedule, error) { + var v UserSchedule + var args []byte + e := row.Scan(&v.ID, &v.UserID, &v.AccountID, &v.ProjectID, &v.SiteID, &v.OwnershipVersion, &v.Name, &v.Cron, &v.Timezone, &v.Kind, &v.Version, &v.Target, &args, &v.UseHTTPS, &v.Enabled, &v.NextRunAt, &v.LastState, &v.SecretRef, &v.ConfigCipher) + if e == nil { + e = json.Unmarshal(args, &v.Arguments) + } + return v, e +} +func (s *Store) UserSchedules(ctx context.Context, user uint64) ([]UserSchedule, error) { + rows, e := s.db.QueryContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE user_id=? ORDER BY id DESC", user) + if e != nil { + return nil, e + } + defer rows.Close() + out := []UserSchedule{} + for rows.Next() { + v, e := scanSchedule(rows) + if e != nil { + return nil, e + } + out = append(out, v) + } + return out, rows.Err() +} +func (s *Store) UserSchedule(ctx context.Context, user, id uint64) (UserSchedule, error) { + return scanSchedule(s.db.QueryRowContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE user_id=? AND id=?", user, id)) +} +func (s *Store) SaveUserSchedule(ctx context.Context, v UserSchedule) (uint64, error) { + tx, e := s.db.BeginTx(ctx, nil) + if e != nil { + return 0, e + } + defer tx.Rollback() + var owner, version uint64 + var locked bool + if e = tx.QueryRowContext(ctx, "SELECT COALESCE(owner_tenant_id,0),ownership_version,management_locked FROM projects WHERE id=? FOR UPDATE", v.ProjectID).Scan(&owner, &version, &locked); e != nil || locked || owner != v.AccountID || version != v.OwnershipVersion { + return 0, ErrNotFound + } + var uid uint64 + if e = tx.QueryRowContext(ctx, "SELECT id FROM users WHERE id=? AND tenant_id=? AND role='tenant' AND status='active' FOR UPDATE", v.UserID, v.AccountID).Scan(&uid); e != nil { + return 0, ErrNotFound + } + var count int + if e = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM user_schedules WHERE user_id=?", v.UserID).Scan(&count); e != nil { + return 0, e + } + if v.ID == 0 && count >= 10 { + return 0, errors.New("每个用户最多 10 条计划任务") + } + args, _ := json.Marshal(v.Arguments) + if v.ID == 0 { + r, e := tx.ExecContext(ctx, `INSERT INTO user_schedules(user_id,account_id,project_id,site_id,ownership_version,name,cron_expression,timezone,kind,runtime_version,target,arguments_json,use_https,enabled,next_run_at,secret_ref,config_cipher) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, v.UserID, v.AccountID, v.ProjectID, v.SiteID, v.OwnershipVersion, v.Name, v.Cron, v.Timezone, v.Kind, v.Version, v.Target, args, v.UseHTTPS, v.Enabled, v.NextRunAt, v.SecretRef, v.ConfigCipher) + if e != nil { + return 0, e + } + id, _ := r.LastInsertId() + v.ID = uint64(id) + } else { + var running *time.Time + if e = tx.QueryRowContext(ctx, "SELECT running_until FROM user_schedules WHERE id=? AND user_id=? FOR UPDATE", v.ID, v.UserID).Scan(&running); e != nil { + return 0, e + } + if running != nil && running.After(time.Now()) { + return 0, errors.New("任务正在运行,暂不能编辑") + } + _, e = tx.ExecContext(ctx, `UPDATE user_schedules SET project_id=?,site_id=?,ownership_version=?,name=?,cron_expression=?,timezone=?,kind=?,runtime_version=?,target=?,arguments_json=?,use_https=?,enabled=?,next_run_at=?,secret_ref=?,config_cipher=?,last_state='ready' WHERE id=? AND user_id=?`, v.ProjectID, v.SiteID, v.OwnershipVersion, v.Name, v.Cron, v.Timezone, v.Kind, v.Version, v.Target, args, v.UseHTTPS, v.Enabled, v.NextRunAt, v.SecretRef, v.ConfigCipher, v.ID, v.UserID) + if e != nil { + return 0, e + } + } + return v.ID, tx.Commit() +} +func (s *Store) DeleteUserSchedule(ctx context.Context, user, id uint64) error { + r, e := s.db.ExecContext(ctx, "DELETE FROM user_schedules WHERE user_id=? AND id=? AND (running_until IS NULL OR running_until'ownership_paused'", user, id) + if e != nil { + return e + } + n, _ := r.RowsAffected() + if n < 1 { + return errors.New("任务不存在、归属已变更或正在运行") + } + return nil +} + +type ScheduleRun struct { + ID uint64 `json:"id"` + ScheduleID uint64 `json:"scheduleId"` + State string `json:"state"` + ExitCode *int `json:"exitCode"` + StartedAt time.Time `json:"startedAt"` + FinishedAt *time.Time `json:"finishedAt"` + OutputCipher []byte `json:"-"` + Output string `json:"output"` +} + +func (s *Store) ScheduleRuns(ctx context.Context, user, id uint64) ([]ScheduleRun, error) { + rows, e := s.db.QueryContext(ctx, `SELECT r.id,r.schedule_id,r.state,r.exit_code,r.started_at,r.finished_at,r.output_cipher FROM user_schedule_runs r JOIN user_schedules t ON t.id=r.schedule_id WHERE t.user_id=? AND t.id=? ORDER BY r.id DESC LIMIT 30`, user, id) + if e != nil { + return nil, e + } + defer rows.Close() + out := []ScheduleRun{} + for rows.Next() { + var v ScheduleRun + if e = rows.Scan(&v.ID, &v.ScheduleID, &v.State, &v.ExitCode, &v.StartedAt, &v.FinishedAt, &v.OutputCipher); e != nil { + return nil, e + } + out = append(out, v) + } + return out, rows.Err() +} +func (s *Store) DueSchedules(ctx context.Context) ([]UserSchedule, error) { + rows, e := s.db.QueryContext(ctx, "SELECT "+scheduleFields+" FROM user_schedules WHERE ((enabled=TRUE AND next_run_at<=UTC_TIMESTAMP()) OR run_requested=TRUE) AND (running_until IS NULL OR running_untilUTC_TIMESTAMP()) AND s.status='running' FROM user_schedules t JOIN projects p ON p.id=t.project_id JOIN sites s ON s.id=t.site_id AND s.project_id=p.id JOIN users u ON u.id=t.user_id WHERE t.id=?`, id).Scan(&valid) + if e != nil || !valid { + _, e = tx.ExecContext(ctx, "UPDATE user_schedules SET next_run_at=?,run_requested=FALSE,last_state='skipped' WHERE id=?", next, id) + if e != nil { + return 0, e + } + return 0, tx.Commit() + } + _, e = tx.ExecContext(ctx, "UPDATE user_schedule_runs SET state='uncertain',finished_at=UTC_TIMESTAMP() WHERE schedule_id=? AND state='running'", id) + if e != nil { + return 0, e + } + _, e = tx.ExecContext(ctx, "UPDATE user_schedules SET next_run_at=?,run_requested=FALSE,running_until=DATE_ADD(UTC_TIMESTAMP(),INTERVAL 310 SECOND),last_state='running' WHERE id=?", next, id) + if e != nil { + return 0, e + } + r, e := tx.ExecContext(ctx, "INSERT INTO user_schedule_runs(schedule_id,state,started_at) VALUES(?,'running',UTC_TIMESTAMP())", v.ID) + if e != nil { + return 0, e + } + run, _ := r.LastInsertId() + if _, e = tx.ExecContext(ctx, "UPDATE user_schedules SET running_run_id=? WHERE id=?", run, id); e != nil { + return 0, e + } + return uint64(run), tx.Commit() +} +func (s *Store) FinishSchedule(ctx context.Context, id, run uint64, state string, code int, cipher []byte) error { + tx, e := s.db.BeginTx(ctx, nil) + if e != nil { + return e + } + defer tx.Rollback() + _, e = tx.ExecContext(ctx, "UPDATE user_schedule_runs SET state=?,exit_code=?,output_cipher=?,finished_at=UTC_TIMESTAMP() WHERE id=? AND schedule_id=? AND state='running'", state, code, cipher, run, id) + if e != nil { + return e + } + _, e = tx.ExecContext(ctx, "UPDATE user_schedules SET running_until=NULL,running_run_id=NULL,last_state=? WHERE id=? AND running_run_id=?", state, id, run) + if e != nil { + return e + } + return tx.Commit() +} +func (s *Store) ClaimSchedulerTick(ctx context.Context, node uint64) (bool, error) { + r, e := s.db.ExecContext(ctx, "INSERT IGNORE INTO scheduler_ticks(tick_minute,node_id) VALUES(?,?)", time.Now().UTC().Truncate(time.Minute), node) + if e != nil { + return false, e + } + n, _ := r.RowsAffected() + return n == 1, nil +} +func (s *Store) PruneSchedules(ctx context.Context) error { + _, e := s.db.ExecContext(ctx, "DELETE FROM user_schedule_runs WHERE started_at&2 + exit 1 + fi +done + +certificate_directory="/www/server/panel/vhost/cert/${certificate_domain}" +certificate_file="${certificate_directory}/fullchain.pem" +private_key_file="${certificate_directory}/privkey.pem" +for regular_file in "${certificate_file}" "${private_key_file}" /etc/sea-vhost/sea-vhost.env; do + if [[ ! -f "${regular_file}" || -L "${regular_file}" ]]; then + printf 'Required regular file is missing or unsafe: %s\n' "${regular_file}" >&2 + exit 1 + fi +done +openssl x509 -in "${certificate_file}" -noout -checkhost "${certificate_domain}" >/dev/null +openssl x509 -in "${certificate_file}" -noout -checkhost "${test_host}" >/dev/null +openssl pkey -in "${private_key_file}" -noout -check >/dev/null 2>&1 + +sync_script=/opt/sea-vhost/bin/sea-vhost-ftps-sync +temporary_sync="$(mktemp /opt/sea-vhost/bin/.sea-vhost-ftps-sync-XXXXXX.tmp)" +cat >"${temporary_sync}" <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +domain="${1:-}" +[[ "${domain}" =~ ^[A-Za-z0-9.-]+$ ]] +token="$(sed -n 's/^SEA_INTERNAL_AUTH_TOKEN=//p' /etc/sea-vhost/sea-vhost.env | head -n 1)" +[[ "${#token}" -ge 32 ]] +response="$(curl --silent --show-error --fail --max-time 45 \ + --unix-socket /run/sea-vhost/agent.sock \ + --header "Authorization: Bearer ${token}" \ + --header 'Content-Type: application/json' \ + --request POST \ + --data "{\"domain\":\"${domain}\"}" \ + http://localhost/v1/ftp/tls)" +grep -Fq '"policy":"explicit_tls_required"' <<<"${response}" +systemctl stop pure-ftpd.service >/dev/null 2>&1 || true +ftp_binary="$(readlink -f /www/server/pure-ftpd/sbin/pure-ftpd)" +for proc_exe in /proc/[0-9]*/exe; do + [[ "$(readlink -f "${proc_exe}" 2>/dev/null || true)" == "${ftp_binary}" ]] || continue + proc_pid="${proc_exe#/proc/}" + proc_pid="${proc_pid%/exe}" + kill -TERM "${proc_pid}" 2>/dev/null || true +done +sleep 1 +for proc_exe in /proc/[0-9]*/exe; do + [[ "$(readlink -f "${proc_exe}" 2>/dev/null || true)" == "${ftp_binary}" ]] || continue + proc_pid="${proc_exe#/proc/}" + proc_pid="${proc_pid%/exe}" + kill -KILL "${proc_pid}" 2>/dev/null || true +done +systemctl start pure-ftpd.service +EOF +chown root:root "${temporary_sync}" +chmod 0750 "${temporary_sync}" +mv -f -- "${temporary_sync}" "${sync_script}" + +cat >/etc/systemd/system/sea-vhost-ftps-sync.service </etc/systemd/system/sea-vhost-ftps-sync.timer <<'EOF' +[Unit] +Description=Daily Sea vHost Pure-FTPd certificate synchronization + +[Timer] +OnCalendar=daily +Persistent=true +RandomizedDelaySec=30m +Unit=sea-vhost-ftps-sync.service + +[Install] +WantedBy=timers.target +EOF +chown root:root /etc/systemd/system/sea-vhost-ftps-sync.service /etc/systemd/system/sea-vhost-ftps-sync.timer +chmod 0644 /etc/systemd/system/sea-vhost-ftps-sync.service /etc/systemd/system/sea-vhost-ftps-sync.timer +systemctl daemon-reload +systemctl enable --now sea-vhost-ftps-sync.timer +systemctl start sea-vhost-ftps-sync.service + +grep -Eq '^[[:space:]]*TLS[[:space:]]+2[[:space:]]*$' /www/server/pure-ftpd/etc/pure-ftpd.conf +test "$(stat -Lc '%a' /www/server/pure-ftpd/etc/pure-ftpd.pem)" = 600 +timeout 20 openssl s_client -connect 127.0.0.1:21 -starttls ftp -servername "${test_host}" \ + -verify_hostname "${test_host}" -verify_return_error &1 | grep -Fq 'Verify return code: 0 (ok)' +echo "Sea vHost production FTPS activation result: success" diff --git a/deploy/activate-production.sh b/deploy/activate-production.sh new file mode 100755 index 0000000..7b45015 --- /dev/null +++ b/deploy/activate-production.sh @@ -0,0 +1,205 @@ +#!/usr/bin/env bash +set -euo pipefail + +management_host="${SEA_MANAGEMENT_DOMAIN:-}" +panel_local_port="${SEA_PANEL_LOCAL_PORT:-}" +panel_bridge_port="${SEA_PANEL_BRIDGE_PORT:-7813}" +if [[ ! "${management_host}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${management_host}" == .* ]] || [[ "${management_host}" == *..* ]]; then + echo "SEA_MANAGEMENT_DOMAIN is invalid." >&2 + exit 1 +fi +for port in "${panel_local_port}" "${panel_bridge_port}"; do + if [[ ! "${port}" =~ ^[0-9]+$ ]] || (( port < 1 || port > 65535 )); then + echo "The panel and bridge ports must be valid TCP ports." >&2 + exit 1 + fi +done +if [[ "${panel_local_port}" == "${panel_bridge_port}" ]]; then + echo "The local aaPanel and bridge ports must differ." >&2 + exit 1 +fi + +nginx_binary=/www/server/nginx/sbin/nginx +environment_file=/etc/sea-vhost/sea-vhost.env +nginx_config="/www/server/panel/vhost/nginx/${management_host}.conf" +certificate_directory="/www/server/panel/vhost/cert/${management_host}" +certificate_file="${certificate_directory}/fullchain.pem" +private_key_file="${certificate_directory}/privkey.pem" + +for regular_file in "${environment_file}" "${certificate_file}" "${private_key_file}"; do + if [[ ! -f "${regular_file}" || -L "${regular_file}" ]]; then + printf 'Required regular file is missing or unsafe: %s\n' "${regular_file}" >&2 + exit 1 + fi +done +if [[ ! -x "${nginx_binary}" ]]; then + echo "aaPanel Nginx is unavailable." >&2 + exit 1 +fi +if ! openssl x509 -in "${certificate_file}" -noout -checkhost "${management_host}" >/dev/null; then + echo "The installed certificate does not cover the management domain." >&2 + exit 1 +fi +if ! openssl pkey -in "${private_key_file}" -noout -check >/dev/null 2>&1; then + echo "The installed certificate private key is invalid." >&2 + exit 1 +fi + +had_config=false +config_backup="$(mktemp)" +environment_backup="$(mktemp)" +temporary_config="" +if [[ -e "${nginx_config}" ]]; then + if [[ ! -f "${nginx_config}" || -L "${nginx_config}" ]]; then + echo "The existing Nginx vhost is not a safe regular file." >&2 + exit 1 + fi + had_config=true + cp --preserve=mode,ownership,timestamps -- "${nginx_config}" "${config_backup}" +fi +cp --preserve=mode,ownership,timestamps -- "${environment_file}" "${environment_backup}" + +rollback() { + cp --preserve=mode,ownership,timestamps -- "${environment_backup}" "${environment_file}" || true + if [[ "${had_config}" == true ]]; then + cp --preserve=mode,ownership,timestamps -- "${config_backup}" "${nginx_config}" || true + else + rm -f -- "${nginx_config}" + fi + "${nginx_binary}" -t >/dev/null 2>&1 && "${nginx_binary}" -s reload >/dev/null 2>&1 || true +} +cleanup() { + [[ -z "${temporary_config}" ]] || rm -f -- "${temporary_config}" + rm -f -- "${config_backup}" "${environment_backup}" +} +trap 'rollback; cleanup' ERR + +if grep -q '^SEA_COOKIE_SECURE=' "${environment_file}"; then + sed -i 's/^SEA_COOKIE_SECURE=.*/SEA_COOKIE_SECURE=true/' "${environment_file}" +else + echo 'SEA_COOKIE_SECURE=true' >>"${environment_file}" +fi +chown root:sea-vhost-control "${environment_file}" +chmod 0640 "${environment_file}" + +temporary_config="$(mktemp /www/server/panel/vhost/nginx/.sea-vhost-production-XXXXXX.tmp)" +cat >"${temporary_config}" </dev/null; then + break + fi + sleep 1 +done +curl --fail --silent --show-error --max-time 3 --header "Host: ${management_host}" http://127.0.0.1:8080/healthz >/dev/null +"${nginx_binary}" -s reload +for _ in {1..20}; do + if curl --fail --silent --show-error --max-time 5 --resolve "${management_host}:443:127.0.0.1" "https://${management_host}/healthz" >/dev/null; then + break + fi + sleep 1 +done +curl --fail --silent --show-error --max-time 5 --resolve "${management_host}:443:127.0.0.1" "https://${management_host}/healthz" >/dev/null + +trap - ERR +cleanup +echo "Sea vHost production activation result: success" diff --git a/deploy/activate-test.sh b/deploy/activate-test.sh new file mode 100755 index 0000000..d034741 --- /dev/null +++ b/deploy/activate-test.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${EUID}" -ne 0 ]]; then + echo "Run this test activator as root." >&2 + exit 1 +fi + +console_host="${1:-}" +if [[ ! "${console_host}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${console_host}" == .* ]] || [[ "${console_host}" == *..* ]]; then + echo "Invalid console host." >&2 + exit 1 +fi + +env_file=/etc/sea-vhost/sea-vhost.env +nginx_binary=/www/server/nginx/sbin/nginx +nginx_config=/www/server/panel/vhost/nginx/sea-vhost-console.conf +if [[ ! -f "${env_file}" || -L "${env_file}" ]]; then + echo "Sea vHost environment file is missing or unsafe." >&2 + exit 1 +fi +if [[ ! -x "${nginx_binary}" ]]; then + echo "aaPanel Nginx binary is unavailable." >&2 + exit 1 +fi + +had_config=false +if [[ -e "${nginx_config}" ]]; then + if [[ ! -f "${nginx_config}" || -L "${nginx_config}" ]]; then + echo "Existing console Nginx configuration is unsafe." >&2 + exit 1 + fi + had_config=true +fi +env_backup="$(mktemp)" +config_backup="$(mktemp)" +temporary_config="" +cp --preserve=mode,ownership,timestamps -- "${env_file}" "${env_backup}" +if [[ "${had_config}" == true ]]; then + cp --preserve=mode,ownership,timestamps -- "${nginx_config}" "${config_backup}" +fi + +rollback() { + cp --preserve=mode,ownership,timestamps -- "${env_backup}" "${env_file}" || true + if [[ "${had_config}" == true ]]; then + cp --preserve=mode,ownership,timestamps -- "${config_backup}" "${nginx_config}" || true + else + rm -f -- "${nginx_config}" + fi + "${nginx_binary}" -t >/dev/null 2>&1 && "${nginx_binary}" -s reload >/dev/null 2>&1 || true +} +trap 'rollback; [[ -z "${temporary_config}" ]] || rm -f -- "${temporary_config}"; rm -f -- "${env_backup}" "${config_backup}"' ERR + +if grep -q '^SEA_COOKIE_SECURE=' "${env_file}"; then + sed -i 's/^SEA_COOKIE_SECURE=.*/SEA_COOKIE_SECURE=false/' "${env_file}" +else + echo 'SEA_COOKIE_SECURE=false' >> "${env_file}" +fi +chown root:sea-vhost-control "${env_file}" +chmod 0640 "${env_file}" + +temporary_config="$(mktemp /www/server/panel/vhost/nginx/.sea-vhost-console-XXXXXX.tmp)" +cat > "${temporary_config}" </dev/null; then + break + fi + sleep 1 +done +curl --fail --silent --show-error http://127.0.0.1:8080/healthz +"${nginx_binary}" -s reload + +trap - ERR +rm -f -- "${env_backup}" "${config_backup}" +echo "Sea vHost test activation result: success" diff --git a/deploy/build.ps1 b/deploy/build.ps1 new file mode 100644 index 0000000..21c4ca3 --- /dev/null +++ b/deploy/build.ps1 @@ -0,0 +1,81 @@ +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +$repoRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$buildRoot = [IO.Path]::GetFullPath((Join-Path $repoRoot 'build')) +$binaryRoot = Join-Path $buildRoot 'bin' +$webRoot = Join-Path $buildRoot 'web' +$archive = Join-Path $buildRoot 'sea-vhost-linux-amd64.tar.gz' + +foreach ($script in Get-ChildItem -LiteralPath (Join-Path $repoRoot 'deploy') -Filter '*.sh' -File) { + if ([IO.File]::ReadAllText($script.FullName).Contains("`r")) { + throw "Linux shell script must use LF line endings: $($script.Name)" + } +} + +function Assert-BuildPath([string]$path) { + $absolute = [IO.Path]::GetFullPath($path) + $prefix = $buildRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar + if (-not $absolute.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { + throw "Refusing to modify a path outside the build directory: $absolute" + } +} + +foreach ($path in @($binaryRoot, $webRoot)) { + Assert-BuildPath $path + if (Test-Path -LiteralPath $path) { + Remove-Item -LiteralPath $path -Recurse -Force + } + New-Item -ItemType Directory -Path $path | Out-Null +} + +Push-Location (Join-Path $repoRoot 'backend') +try { + $goCommand = if ([string]::IsNullOrWhiteSpace($env:SEA_GO_BINARY)) { 'go' } else { [IO.Path]::GetFullPath($env:SEA_GO_BINARY) } + if ($goCommand -ne 'go' -and -not (Test-Path -LiteralPath $goCommand -PathType Leaf)) { throw "Configured Go binary does not exist: $goCommand" } + $env:CGO_ENABLED = '0' + $env:GOOS = 'linux' + $env:GOARCH = 'amd64' + $goVersion = (& $goCommand env GOVERSION).Trim() + if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($goVersion)) { throw 'Cannot determine the Go toolchain version' } + $env:GOCACHE = Join-Path $repoRoot ".cache\go-build-linux-amd64-$goVersion" + New-Item -ItemType Directory -Path $env:GOCACHE -Force | Out-Null + & $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-api') ./cmd/server + & $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-agent') ./cmd/agent + & $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-panel-broker') ./cmd/panel-broker + & $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-node') ./cmd/node + & $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-run') ./cmd/runner + & $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-scheduler') ./cmd/scheduler + if ($LASTEXITCODE -ne 0) { throw 'Go cross compilation failed' } + foreach ($binary in @('sea-vhost-api', 'sea-vhost-agent', 'sea-vhost-panel-broker','sea-vhost-node','sea-vhost-run','sea-vhost-scheduler')) { + $metadata = @(& $goCommand version -m (Join-Path $binaryRoot $binary)) + if ($LASTEXITCODE -ne 0 -or $metadata.Count -eq 0 -or -not $metadata[0].EndsWith(": $goVersion", [StringComparison]::Ordinal)) { + throw "$binary was not linked by the requested $goVersion toolchain" + } + } +} finally { + Pop-Location +} + +Push-Location (Join-Path $repoRoot 'frontend') +try { + # Local Windows development can keep node_modules open briefly (for + # example after browser tests). The opt-out is only for an already + # restored lockfile-compatible dependency tree; CI remains the default. + if ($env:SEA_BUILD_SKIP_NPM_CI -ne 'true') { + & npm ci + if ($LASTEXITCODE -ne 0) { throw 'npm ci failed' } + } + $env:VITE_API_MODE = 'true' + & npm run build + if ($LASTEXITCODE -ne 0) { throw 'Frontend build failed' } + Copy-Item -Path (Join-Path $PWD 'dist\*') -Destination $webRoot -Recurse -Force +} finally { + Pop-Location +} + +Assert-BuildPath $archive +& node (Join-Path $PSScriptRoot 'package-release.mjs') +if ($LASTEXITCODE -ne 0) { throw 'Curated release packaging failed' } +Write-Host "Build completed: $archive" +Write-Host 'Runtime/source archives, SHA-256 files and manifests are in build/.' diff --git a/deploy/build.sh b/deploy/build.sh new file mode 100755 index 0000000..65ab0bc --- /dev/null +++ b/deploy/build.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +output_dir="${repo_root}/build" +mkdir -p "${output_dir}/bin" "${output_dir}/web" + +cd "${repo_root}/backend" +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-scheduler" ./cmd/scheduler +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-run" ./cmd/runner +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-api" ./cmd/server +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-agent" ./cmd/agent +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-panel-broker" ./cmd/panel-broker +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-node" ./cmd/node + +cd "${repo_root}/frontend" +npm ci +VITE_API_MODE=true npm run build +[[ "${output_dir}" == "${repo_root}/build" && ! -L "${output_dir}/web" ]] || { echo 'Unsafe web output directory' >&2; exit 1; } +rm -rf -- "${output_dir}/web" +mkdir -p "${output_dir}/web" +cp -a dist/. "${output_dir}/web/" + +node "${repo_root}/deploy/package-release.mjs" + +echo "Build completed: ${output_dir}" diff --git a/deploy/diagnose.sh b/deploy/diagnose.sh new file mode 100755 index 0000000..6e67c3c --- /dev/null +++ b/deploy/diagnose.sh @@ -0,0 +1,208 @@ +#!/usr/bin/env bash +set -uo pipefail + +failures=0 +warnings=0 +agent_socket="${SEA_AGENT_SOCKET:-/run/sea-vhost/agent.sock}" +panel_broker_socket="${SEA_PANEL_BROKER_SOCKET:-/run/sea-vhost-panel/broker.sock}" +panel_broker_state="${SEA_PANEL_BROKER_STATE:-/var/lib/sea-vhost-panel}" +config_file="${SEA_CONFIG_FILE:-/var/lib/sea-vhost/config.json}" +environment_file="/etc/sea-vhost/sea-vhost.env" +nginx_vhost_root="${SEA_NGINX_VHOST_ROOT:-/www/server/panel/vhost/nginx}" +nginx_security_global="${nginx_vhost_root}/sea-vhost-security-global.conf" +backup_root="${SEA_BACKUP_ROOT:-/www/backup/sea-vhost}" +production_mode="${SEA_DIAGNOSE_PRODUCTION:-false}" + +pass() { printf '[PASS] %s\n' "$1"; } +warn() { printf '[WARN] %s\n' "$1"; warnings=$((warnings + 1)); } +fail() { printf '[FAIL] %s\n' "$1"; failures=$((failures + 1)); } +security_finding() { + if [[ "${production_mode}" == "true" ]]; then fail "$1"; else warn "$1"; fi +} + +check_service() { + local service="$1" + if systemctl is-active --quiet "${service}"; then + pass "${service} is active" + else + fail "${service} is not active" + fi +} + +check_mode() { + local path="$1" expected="$2" label="$3" actual + if [[ ! -e "${path}" ]]; then + warn "${label} does not exist: ${path}" + return + fi + actual="$(stat -c '%a' "${path}" 2>/dev/null || true)" + if [[ "${actual}" == "${expected}" ]]; then + pass "${label} permissions are ${actual}" + else + fail "${label} permissions are ${actual:-unknown}; expected ${expected}" + fi +} + +check_owner() { + local path="$1" expected="$2" label="$3" actual + if [[ ! -e "${path}" ]]; then + warn "${label} does not exist: ${path}" + return + fi + actual="$(stat -c '%U:%G' "${path}" 2>/dev/null || true)" + if [[ "${actual}" == "${expected}" ]]; then + pass "${label} owner is ${actual}" + else + fail "${label} owner is ${actual:-unknown}; expected ${expected}" + fi +} + +printf 'Sea vHost deployment diagnostics\n' +printf '================================\n' +if [[ "${production_mode}" == "true" ]]; then + pass 'production security gate is enabled' +else + warn 'production security gate is disabled; set SEA_DIAGNOSE_PRODUCTION=true for release acceptance' +fi + +for command in systemctl stat curl; do + if command -v "${command}" >/dev/null 2>&1; then + pass "command available: ${command}" + else + fail "missing command: ${command}" + fi +done + +if command -v systemctl >/dev/null 2>&1; then + check_service sea-vhost-agent.service + check_service sea-vhost-panel-broker.service + check_service sea-vhost-api.service +fi + +if id www >/dev/null 2>&1 && id -nG www | tr ' ' '\n' | grep -Eq '^sea-vhost-(control|agent-control|panel-control)$'; then + fail 'www user must not belong to a Sea vHost control group' +else + pass 'www user is excluded from all Sea vHost control groups' +fi +if id sea-vhost-panel >/dev/null 2>&1 && id -nG sea-vhost-panel | tr ' ' '\n' | grep -qx 'sea-vhost-agent-control'; then + fail 'panel broker user must not belong to the root-agent control group' +else + pass 'panel broker is excluded from the root-agent control group' +fi +for required_group in sea-vhost-agent-control sea-vhost-panel-control; do + if id sea-vhost >/dev/null 2>&1 && id -nG sea-vhost | tr ' ' '\n' | grep -qx "${required_group}"; then + pass "API user belongs to ${required_group}" + else + fail "API user is missing required group: ${required_group}" + fi +done + +check_mode "${environment_file}" 640 'environment file' +check_owner "${environment_file}" 'root:sea-vhost-control' 'environment file' +check_mode "${nginx_security_global}" 644 'Nginx security baseline' +check_owner "${nginx_security_global}" 'root:root' 'Nginx security baseline' +check_mode "${backup_root}" 700 'lifecycle backup root' +check_owner "${backup_root}" 'root:root' 'lifecycle backup root' +if [[ -e "${config_file}" ]]; then + check_mode "${config_file}" 600 'installed configuration' + check_owner "${config_file}" 'sea-vhost:sea-vhost-control' 'installed configuration' +else + warn "installed configuration is absent; Web setup should be active" +fi + +if [[ -S "${agent_socket}" ]]; then + socket_metadata="$(stat -c '%U:%G:%a' "${agent_socket}" 2>/dev/null || true)" + if [[ "${socket_metadata}" == "root:sea-vhost-agent-control:660" ]]; then + pass "isolation socket ownership is ${socket_metadata}" + else + fail "isolation socket ownership is ${socket_metadata:-unknown}; expected root:sea-vhost-agent-control:660" + fi + if curl --silent --show-error --fail --max-time 5 --unix-socket "${agent_socket}" http://localhost/healthz >/dev/null; then + pass 'isolation agent health check succeeded' + else + fail 'isolation agent health check failed' + fi +else + fail "isolation socket is missing: ${agent_socket}" +fi + +if [[ -S "${panel_broker_socket}" ]]; then + broker_metadata="$(stat -c '%U:%G:%a' "${panel_broker_socket}" 2>/dev/null || true)" + if [[ "${broker_metadata}" == "sea-vhost-panel:sea-vhost-panel-control:660" ]]; then + pass "panel broker socket ownership is ${broker_metadata}" + else + fail "panel broker socket ownership is ${broker_metadata:-unknown}; expected sea-vhost-panel:sea-vhost-panel-control:660" + fi + broker_health="$(curl --silent --show-error --fail --max-time 5 --unix-socket "${panel_broker_socket}" http://localhost/healthz 2>/dev/null || true)" + if [[ "${broker_health}" == *'"status":"ok"'* || "${broker_health}" == *'"status":"unconfigured"'* ]]; then + pass 'panel broker health check succeeded' + else + fail 'panel broker health check failed' + fi +else + fail "panel broker socket is missing: ${panel_broker_socket}" +fi +if [[ -f "${panel_broker_state}/credentials.json" ]]; then + check_mode "${panel_broker_state}/credentials.json" 600 'panel broker credentials' + check_owner "${panel_broker_state}/credentials.json" 'sea-vhost-panel:sea-vhost-panel-control' 'panel broker credentials' + panel_url="$(sed -nE 's/^[[:space:]]*"url"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' "${panel_broker_state}/credentials.json" | head -n 1)" + if [[ "${panel_url}" =~ ^https?://(127\.0\.0\.1|localhost)(:[0-9]{1,5})?/?$ || "${panel_url}" =~ ^https?://\[::1\](:[0-9]{1,5})?/?$ ]]; then + pass 'panel broker target is loopback-only' + else + security_finding 'panel broker target is missing or is not a loopback URL' + fi + if grep -Eq '"tlsInsecure"[[:space:]]*:[[:space:]]*true' "${panel_broker_state}/credentials.json"; then + security_finding 'panel broker accepts an untrusted aaPanel TLS certificate' + else + pass 'panel broker requires a trusted aaPanel TLS certificate' + fi + + panel_port="$(printf '%s\n' "${panel_url}" | sed -nE 's#^https?://(127\.0\.0\.1|localhost|\[::1\]):([0-9]{1,5})/?$#\2#p')" + if [[ -n "${panel_port}" ]] && command -v ss >/dev/null 2>&1; then + if ss -ltnH 2>/dev/null | awk '{print $4}' | grep -Eq "(^|0\\.0\\.0\\.0:|\\[::\\]:|\\*:)${panel_port}$"; then + security_finding "aaPanel port ${panel_port} listens on a wildcard address; firewall/VPN exposure must be checked externally" + else + pass "aaPanel port ${panel_port} is not bound to a wildcard address" + fi + fi +fi +if [[ -f "${config_file}" ]] && grep -q 'panel_api_key' "${config_file}"; then + fail 'Web API configuration still contains a legacy panel API key' +else + pass 'Web API configuration does not contain the panel API key' +fi +if grep -Eq '^SEA_COOKIE_SECURE=false([[:space:]]*)$' "${environment_file}" 2>/dev/null; then + security_finding 'session cookies are allowed over plain HTTP' +else + pass 'session cookies require HTTPS' +fi + +api_health="$(curl --silent --show-error --fail --max-time 5 http://127.0.0.1:8080/healthz 2>/dev/null || true)" +if [[ "${api_health}" == *'"status":"ok"'* ]]; then + pass 'Sea vHost API is running normally' +elif [[ "${api_health}" == *'"status":"setup_required"'* ]]; then + pass 'Sea vHost API is waiting for Web setup' +else + fail 'Sea vHost API health check failed' +fi + +nginx_binary="" +if command -v nginx >/dev/null 2>&1; then + nginx_binary="$(command -v nginx)" +elif [[ -x /www/server/nginx/sbin/nginx ]]; then + nginx_binary="/www/server/nginx/sbin/nginx" +fi +if [[ -n "${nginx_binary}" ]]; then + if "${nginx_binary}" -t >/dev/null 2>&1; then + pass 'Nginx configuration test succeeded' + else + fail 'Nginx configuration test failed' + fi +else + warn 'Nginx executable was not found in PATH or the standard aaPanel location' +fi + +printf '\nResult: %d failure(s), %d warning(s)\n' "${failures}" "${warnings}" +if (( failures > 0 )); then + exit 1 +fi diff --git a/deploy/fixtures/go-smoke/main.go b/deploy/fixtures/go-smoke/main.go new file mode 100644 index 0000000..51c5909 --- /dev/null +++ b/deploy/fixtures/go-smoke/main.go @@ -0,0 +1,39 @@ +//go:build linux && amd64 + +// This deliberately small HTTP server is the real Go artifact used by the +// aaPanel lifecycle smoke test. It avoids third-party dependencies so the +// binary can fit into even the smallest development quota. +package main + +import ( + "os" + "strconv" + "syscall" +) + +func main() { + port, err := strconv.Atoi(os.Getenv("PORT")) + if err != nil || port < 1 || port > 65535 { + os.Exit(2) + } + listener, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0) + if err != nil { + os.Exit(3) + } + defer syscall.Close(listener) + _ = syscall.SetsockoptInt(listener, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1) + if syscall.Bind(listener, &syscall.SockaddrInet4{Port: port, Addr: [4]byte{127, 0, 0, 1}}) != nil || syscall.Listen(listener, 16) != nil { + os.Exit(4) + } + response := []byte("HTTP/1.1 200 OK\r\nContent-Length: 21\r\nConnection: close\r\n\r\nsea-vhost-go-artifact") + for { + connection, _, acceptErr := syscall.Accept(listener) + if acceptErr != nil { + continue + } + var request [1024]byte + _, _ = syscall.Read(connection, request[:]) + _, _ = syscall.Write(connection, response) + _ = syscall.Close(connection) + } +} diff --git a/deploy/fixtures/java-smoke/SeaVHostSmoke.java b/deploy/fixtures/java-smoke/SeaVHostSmoke.java new file mode 100644 index 0000000..97539f9 --- /dev/null +++ b/deploy/fixtures/java-smoke/SeaVHostSmoke.java @@ -0,0 +1,41 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; + +public final class SeaVHostSmoke { + private SeaVHostSmoke() {} + + public static void main(String[] args) throws Exception { + String portValue = System.getenv("PORT"); + if (portValue == null || portValue.isEmpty()) { + for (String argument : args) { + if (argument.startsWith("--server.port=")) { + portValue = argument.substring("--server.port=".length()); + } + } + } + if (portValue == null || portValue.isEmpty()) { + throw new IllegalArgumentException("missing runtime port"); + } + int port = Integer.parseInt(portValue); + byte[] body = "sea-vhost-java-artifact".getBytes(StandardCharsets.UTF_8); + try (ServerSocket server = new ServerSocket(port, 50, InetAddress.getLoopbackAddress())) { + while (true) { + try (Socket socket = server.accept()) { + BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); + for (String line; (line = reader.readLine()) != null && !line.isEmpty();) { + // Consume one HTTP request before returning the fixed marker. + } + OutputStream output = socket.getOutputStream(); + output.write(("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: " + body.length + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); + output.write(body); + output.flush(); + } + } + } + } +} diff --git a/deploy/install-controller.sh b/deploy/install-controller.sh new file mode 100755 index 0000000..0cb1db7 --- /dev/null +++ b/deploy/install-controller.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ ${1:-} == --help ]]; then + echo '独立主控:bash deploy/install.sh --interactive --role controller;自动化:bash deploy/install-controller.sh --non-interactive' + exit 0 +fi +if [[ $# -eq 0 && -t 0 && -t 1 ]]; then exec python3 "$(dirname "${BASH_SOURCE[0]}")/install-wizard.py" --role controller; fi +if [[ ${1:-} == --non-interactive ]]; then shift; fi +[[ $# -eq 0 ]] || { echo '未知参数。' >&2; exit 1; } +[[ ${EUID} -eq 0 ]] || { echo 'Run as root.' >&2; exit 1; } +source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[[ -f "$source_dir/build/bin/sea-vhost-api" && -f "$source_dir/build/web/index.html" ]] || { echo 'Build output missing.' >&2; exit 1; } +[[ ! -e /var/lib/sea-vhost-panel/credentials.json ]] || { echo 'Existing combined installation detected; use the documented migration procedure.' >&2; exit 1; } +getent group sea-vhost-control >/dev/null || groupadd --system sea-vhost-control +id sea-vhost >/dev/null 2>&1 || useradd --system --gid sea-vhost-control --no-create-home --home-dir /var/lib/sea-vhost --shell /usr/sbin/nologin sea-vhost +install -d -o root -g root -m 0755 /opt/sea-vhost /opt/sea-vhost/bin /opt/sea-vhost/web +install -d -o root -g sea-vhost-control -m 0750 /etc/sea-vhost +install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost +install -o root -g root -m 0755 "$source_dir/build/bin/sea-vhost-api" /opt/sea-vhost/bin/sea-vhost-api +cp -a "$source_dir/build/web/." /opt/sea-vhost/web/ +chmod -R a+rX /opt/sea-vhost/web +if [[ ! -e /etc/sea-vhost/sea-vhost.env ]]; then + umask 077 + token="$(openssl rand -hex 32)" + printf 'SEA_CONTROLLER_ONLY=true\nSEA_SETUP_TOKEN=%s\nSEA_ADDR=127.0.0.1:8080\nSEA_CONFIG_FILE=/var/lib/sea-vhost/config.json\n' "$token" > /etc/sea-vhost/sea-vhost.env + echo 'Created installation token in /etc/sea-vhost/sea-vhost.env.' +fi +grep -qx 'SEA_CONTROLLER_ONLY=true' /etc/sea-vhost/sea-vhost.env || { echo 'Existing environment is not controller-only.' >&2; exit 1; } +install -o root -g root -m 0644 "$source_dir/deploy/systemd/sea-vhost-controller.service" /etc/systemd/system/sea-vhost-api.service +systemctl daemon-reload +systemctl enable --now sea-vhost-api.service +echo 'Controller listening on 127.0.0.1:8080. Serve /opt/sea-vhost/web and proxy /api to this address using your management domain. Complete the Web installation with the local MySQL account.' diff --git a/deploy/install-node.sh b/deploy/install-node.sh new file mode 100755 index 0000000..f2a251d --- /dev/null +++ b/deploy/install-node.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ ${1:-} == --help ]]; then + echo '被控向导:bash deploy/install.sh --interactive --role node;自动化:bash deploy/install-node.sh 配对文件 凭据文件' + exit 0 +fi +if [[ $# -eq 0 && -t 0 && -t 1 ]]; then exec python3 "$(dirname "${BASH_SOURCE[0]}")/install-wizard.py" --role node; fi +[[ ${EUID} -eq 0 ]] || { echo 'Run as root.' >&2; exit 1; } +[[ $# -eq 2 ]] || { echo 'Usage: install-node.sh /root/sea-node-ID.json /root/local-panel-credentials.json' >&2; exit 1; } +source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +for binary in sea-vhost-node sea-vhost-agent sea-vhost-panel-broker sea-vhost-scheduler sea-vhost-run; do [[ -f "$source_dir/build/bin/$binary" && ! -L "$source_dir/build/bin/$binary" ]] || { echo "Missing $binary" >&2; exit 1; }; done +[[ ! -e /var/lib/sea-vhost/config.json ]] || { echo 'Controller configuration exists. Do not convert a combined installation in place.' >&2; exit 1; } +[[ ! -e /var/lib/sea-vhost-panel/resources.json ]] || { echo 'A local platform registry exists; reconcile it before installing a stateless node.' >&2; exit 1; } +[[ -d /www/server/panel && -x /www/server/nginx/sbin/nginx ]] || { echo 'Debian aaPanel/Nginx is required.' >&2; exit 1; } +[[ -x /www/server/pure-ftpd/bin/pure-pw && -d /www/server/pure-ftpd/etc ]] || { echo 'Install the free Pure-FTPd service in aaPanel first.' >&2; exit 1; } +command -v python3 >/dev/null +# Validation runs before creating accounts, changing services or copying keys. +tenant_root="$(python3 - "$1" "$2" <<'PY' +import json,os,re,stat,sys,urllib.parse +for file in sys.argv[1:]: + s=os.lstat(file) + if not stat.S_ISREG(s.st_mode) or s.st_uid!=0 or s.st_mode&0o077: raise SystemExit('Configuration files must be root-owned regular files with mode 0600.') +c=json.load(open(sys.argv[1]));p=json.load(open(sys.argv[2]));root=c['tenantRoot'] +if os.path.exists('/etc/sea-vhost-node/config.json'): + old=json.load(open('/etc/sea-vhost-node/config.json')) + if old['identity']['nodeId']!=c['identity']['nodeId'] or old['tenantRoot']!=root: raise SystemExit('Existing node identity/root differs; cross-node migration is not automatic.') +if not re.fullmatch(r'/www/wwwroot/[A-Za-z0-9_/-]+',root) or os.path.normpath(root)!=root or '..' in root.split('/'): raise SystemExit('Invalid tenant root.') +if c['identity']['nodeId']<2 or c['agentSocket']!='/run/sea-vhost/agent.sock' or c['brokerSocket']!='/run/sea-vhost-panel/broker.sock': raise SystemExit('Invalid node pairing configuration.') +u=urllib.parse.urlparse(p['url']) +if u.scheme not in ('http','https') or u.hostname not in ('127.0.0.1','localhost','::1') or u.username or u.password or len(p.get('api_key',''))<16 or p.get('version')!=1: raise SystemExit('Panel credentials must use the loopback interface.') +current='/' +for part in root.strip('/').split('/'): + current=os.path.join(current,part) + if os.path.lexists(current) and (os.path.islink(current) or not os.path.isdir(current)): raise SystemExit('Tenant root contains an unsafe component.') +print(root) +PY +)" +packages=(acl build-essential ca-certificates xz-utils libssl-dev zlib1g-dev libncurses-dev libreadline-dev libsqlite3-dev libgdbm-dev libdb-dev libbz2-dev libexpat1-dev liblzma-dev tk-dev libffi-dev uuid-dev) +missing_packages=() +for package in "${packages[@]}"; do + dpkg-query -W -f='${Status}' "$package" 2>/dev/null | grep -q 'ok installed' || missing_packages+=("$package") +done +if (( ${#missing_packages[@]} > 0 )); then + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends "${missing_packages[@]}" +fi +bash "$source_dir/deploy/prepare-runtime-roots.sh" +for group in sea-vhost-control sea-vhost-agent-control sea-vhost-panel-control; do getent group "$group" >/dev/null || groupadd --system "$group"; done +id sea-vhost >/dev/null 2>&1 || useradd --system --gid sea-vhost-control --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin sea-vhost +usermod -g sea-vhost-control -aG sea-vhost-agent-control,sea-vhost-panel-control sea-vhost +id sea-vhost-panel >/dev/null 2>&1 || useradd --system --gid sea-vhost-panel-control --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin sea-vhost-panel +for group in sea-vhost-control sea-vhost-agent-control sea-vhost-panel-control; do gpasswd -d www "$group" >/dev/null 2>&1 || true; done +gpasswd -d sea-vhost-panel sea-vhost-agent-control >/dev/null 2>&1 || true +install -d -o root -g root -m 0755 /opt/sea-vhost /opt/sea-vhost/bin +install -d -o root -g root -m 0755 /usr/local/libexec +install -o root -g root -m 0755 "$source_dir/build/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run +install -d -o root -g sea-vhost-control -m 0750 /etc/sea-vhost /etc/sea-vhost-node +install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel +install -d -o root -g root -m 0750 /var/lib/sea-vhost +install -d -o root -g root -m 0755 /www/backup/sea-vhost /www/wwwlogs /www/server/panel/vhost/nginx/extension +# The per-site protection snippets reference these zones on fresh nodes too. +security_global=/www/server/panel/vhost/nginx/sea-vhost-security-global.conf +security_backup='' +if [[ -e "$security_global" || -L "$security_global" ]]; then + [[ -f "$security_global" && ! -L "$security_global" ]] || { echo 'Unsafe Nginx security baseline.' >&2; exit 1; } + security_backup="$(mktemp)" + cp --preserve=mode,ownership,timestamps -- "$security_global" "$security_backup" +fi +install -o root -g root -m 0644 "$source_dir/deploy/nginx/sea-vhost-security-global.conf" "$security_global" +if ! /www/server/nginx/sbin/nginx -t; then + if [[ -n "$security_backup" ]]; then cp --preserve=mode,ownership,timestamps -- "$security_backup" "$security_global"; else rm -f -- "$security_global"; fi + [[ -z "$security_backup" ]] || rm -f -- "$security_backup" + echo 'Nginx rejected the security baseline; the previous file was restored.' >&2 + exit 1 +fi +[[ -z "$security_backup" ]] || rm -f -- "$security_backup" +/www/server/nginx/sbin/nginx -s reload +install -d -o root -g root -m 0755 "$tenant_root" +for default_dir in /www/wwwroot/seavHost /www/wwwroot/seavHost/vHost; do + [[ ! -L "$default_dir" && ( ! -e "$default_dir" || -d "$default_dir" ) ]] || { echo 'Unsafe default managed root.' >&2; exit 1; } + [[ -d "$default_dir" ]] || install -d -o root -g root -m 0755 "$default_dir" +done +install -o root -g sea-vhost-control -m 0640 "$1" /etc/sea-vhost-node/config.json +install -o sea-vhost-panel -g sea-vhost-panel-control -m 0600 "$2" /var/lib/sea-vhost-panel/credentials.json +if [[ -e /var/lib/sea-vhost-panel/resources.json ]]; then echo 'A node-side platform registry exists; reconcile it before enabling stateless mode.' >&2; exit 1; fi +if [[ ! -e /etc/sea-vhost/sea-vhost.env ]]; then + umask 077 + printf 'SEA_INTERNAL_AUTH_TOKEN=%s\nSEA_NODE_STATELESS=true\nSEA_TENANT_ROOT=%s\nSEA_AGENT_SOCKET=/run/sea-vhost/agent.sock\nSEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock\n' "$(openssl rand -hex 32)" "$tenant_root" > /etc/sea-vhost/sea-vhost.env +fi +grep -qx 'SEA_NODE_STATELESS=true' /etc/sea-vhost/sea-vhost.env || { echo 'Existing environment is not a stateless node.' >&2; exit 1; } +grep -qx "SEA_TENANT_ROOT=$tenant_root" /etc/sea-vhost/sea-vhost.env || { echo 'Existing node root differs from paired configuration.' >&2; exit 1; } +for binary in sea-vhost-node sea-vhost-agent sea-vhost-panel-broker sea-vhost-scheduler; do install -o root -g root -m 0755 "$source_dir/build/bin/$binary" "/opt/sea-vhost/bin/$binary"; done +for unit in sea-vhost-agent sea-vhost-panel-broker sea-vhost-node; do install -m 0644 "$source_dir/deploy/systemd/$unit.service" "/etc/systemd/system/$unit.service"; done +install -d -m 0755 /etc/systemd/system/sea-vhost-node.service.d /etc/systemd/system/sea-vhost-agent.service.d +printf '[Service]\nReadWritePaths=%s\n' "$tenant_root" > /etc/systemd/system/sea-vhost-node.service.d/paths.conf +printf '[Service]\nReadWritePaths=%s\n' "$tenant_root" > /etc/systemd/system/sea-vhost-agent.service.d/node-paths.conf +systemctl daemon-reload +systemctl enable sea-vhost-agent sea-vhost-panel-broker sea-vhost-node +systemctl restart sea-vhost-agent sea-vhost-panel-broker sea-vhost-node +echo 'Node installed. No controller database or scheduler was installed. Enable this node from the controller to probe and connect.' diff --git a/deploy/install-wizard.py b/deploy/install-wizard.py new file mode 100644 index 0000000..8c368f0 --- /dev/null +++ b/deploy/install-wizard.py @@ -0,0 +1,458 @@ +#!/usr/bin/env python3 +"""Interactive front end for the existing Debian installers (stdlib only).""" +import argparse +import getpass +import json +import os +import platform +import posixpath +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import urllib.parse +import urllib.error +import urllib.request +from pathlib import Path + +SOURCE = Path(__file__).resolve().parent.parent +ENVIRONMENT = Path('/etc/sea-vhost/sea-vhost.env') +CONFIG = Path('/var/lib/sea-vhost/config.json') +NODE_CONFIG = Path('/etc/sea-vhost-node/config.json') +PANEL_CREDENTIALS = Path('/var/lib/sea-vhost-panel/credentials.json') +PANEL_REGISTRY = Path('/var/lib/sea-vhost-panel/resources.json') +ROLES = {'combined': '主控兼本机托管', 'controller': '独立主控', 'node': '被控节点'} + + +class InstallError(Exception): + pass + + +def run(args, **kwargs): + return subprocess.run([str(a) for a in args], check=True, **kwargs) + + +class Console: + def ask(self, label, default=''): + value = input(f'{label}' + (f' [{default}]' if default else '') + ':').strip() + return value or default + + def confirm(self, label, default=True): + while True: + value = self.ask(label + (' [Y/n]' if default else ' [y/N]')).lower() + if not value: + return default + if value in ('y', 'yes', '是'): + return True + if value in ('n', 'no', '否'): + return False + print('请输入 y 或 n。') + + def secret(self, label): + return getpass.getpass(label + ':').strip() + + +def read_json(file, protect=False): + # No following links, unbounded reads or accepting a writable borrowed key file. + fd = os.open(file, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024: + raise InstallError('配置必须是小于 1 MiB 的普通文件。') + if protect: + if info.st_uid != 0: + raise InstallError('配对文件须由 root 所有,请先复制到 /root。') + os.fchmod(fd, 0o600) + with os.fdopen(fd, 'r', encoding='utf-8') as stream: + fd = -1 + value = json.load(stream) + if not isinstance(value, dict): + raise InstallError('配置内容必须是 JSON 对象。') + return value + finally: + if fd != -1: + os.close(fd) + + +def private_json(file, value): + fd = os.open(file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w', encoding='utf-8') as stream: + json.dump(value, stream, ensure_ascii=False) + stream.write('\n') + + +def environment(): + if not ENVIRONMENT.exists(): + return {} + if ENVIRONMENT.is_symlink() or not ENVIRONMENT.is_file(): + raise InstallError('现有环境文件不是安全的普通文件。') + info = ENVIRONMENT.stat() + if info.st_uid != 0 or info.st_mode & 0o022: + raise InstallError('现有环境文件须由 root 所有且不可被组或其他用户修改。') + # Deliberately do not source shell text from this file. + return dict(line.split('=', 1) for line in ENVIRONMENT.read_text().splitlines() + if line and not line.startswith('#') and '=' in line) + + +def check_role(role, values): + if role == 'node': + if CONFIG.exists() or values and values.get('SEA_NODE_STATELESS') != 'true': + raise InstallError('检测到主控或单机配置,不能原地转换为被控。') + if PANEL_REGISTRY.exists(): + raise InstallError('检测到本机资源登记表,请先完成现有主机迁移。') + elif NODE_CONFIG.exists() or values.get('SEA_NODE_STATELESS') == 'true': + raise InstallError('检测到被控配置,不能原地转换为主控。') + elif values and (values.get('SEA_CONTROLLER_ONLY') == 'true') != (role == 'controller'): + raise InstallError('已有安装角色不同;请在另一台服务器安装该角色。') + elif role == 'controller' and PANEL_CREDENTIALS.exists(): + raise InstallError('检测到本机宝塔代理凭据,不能直接转换为独立主控。') + + +def check_build(role): + binaries = ['sea-vhost-node', 'sea-vhost-agent', 'sea-vhost-panel-broker'] if role == 'node' else ['sea-vhost-api'] + if role == 'combined': + binaries += ['sea-vhost-agent', 'sea-vhost-panel-broker'] + files = [SOURCE / 'build/bin' / name for name in binaries] + if role != 'node': + files.append(SOURCE / 'build/web/index.html') + for file in files: + if file.is_symlink() or not file.is_file(): + raise InstallError('安装包不完整,请解压完整的 sea-vhost-linux-amd64.tar.gz 后再运行。') + + +def panel_url(value): + try: + parsed = urllib.parse.urlsplit(value) + port = parsed.port + except ValueError: + raise InstallError('宝塔地址或端口无效。') from None + if (parsed.scheme not in ('http', 'https') or parsed.hostname not in ('127.0.0.1', 'localhost', '::1') + or parsed.username or parsed.password or parsed.query or parsed.fragment + or parsed.path not in ('', '/') or port is not None and not 1 <= port <= 65535): + raise InstallError('宝塔地址只能是本机回环 HTTP/HTTPS 地址,不包含安全入口路径。') + return value.rstrip('/') + + +def detect_panel_url(): + data = Path('/www/server/panel/data') + try: + port = int((data / 'port.pl').read_text().strip()) + if not 1 <= port <= 65535: + raise ValueError() + except (OSError, ValueError): + port = 8888 + return ('https' if (data / 'ssl.pl').exists() else 'http') + f'://127.0.0.1:{port}' + + +def credentials(ui): + saved = read_json(PANEL_CREDENTIALS) if PANEL_CREDENTIALS.exists() else {} + if saved and ui.confirm('复用本机已保存的宝塔凭据'): + panel_url(saved.get('url', '')) + if saved.get('version') != 1 or len(saved.get('api_key', '')) < 16: + raise InstallError('已有宝塔凭据不完整,请重新填写。') + return saved + while True: + try: + url = panel_url(ui.ask('本机宝塔 API 地址', detect_panel_url())) + break + except InstallError as error: + print(error) + while True: + key = ui.secret('宝塔 API 密钥(输入隐藏)') + if len(key) >= 16 and not any(c.isspace() for c in key): + break + print('密钥格式无效,请重新输入。') + insecure = url.startswith('https:') and ui.confirm('本机宝塔使用自签名证书,跳过其证书校验') + return {'version': 1, 'url': url, 'api_key': key, 'tls_insecure': insecure} + + +def validate_pair(config): + identity = config.get('identity', {}) + root = config.get('tenantRoot', '') + if (not isinstance(identity, dict) or type(identity.get('nodeId')) is not int or identity['nodeId'] < 2 + or not re.fullmatch(r'/www/wwwroot/[A-Za-z0-9_/-]+', root) + or posixpath.normpath(root) != root or '..' in root.split('/') + or config.get('brokerSocket') != '/run/sea-vhost-panel/broker.sock' + or config.get('agentSocket') != '/run/sea-vhost/agent.sock'): + raise InstallError('配对文件的节点、目录或 Socket 配置无效。') + if not re.fullmatch(r'(?:\[[0-9a-fA-F:]+\]|[0-9.]*):([0-9]{1,5})', config.get('address', '')): + raise InstallError('配对文件的监听地址无效。') + port = int(config['address'].rsplit(':', 1)[1]) + if not 1024 <= port <= 65535: + raise InstallError('被控监听端口须为 1024–65535。') + if not all(isinstance(identity.get(k), str) and identity[k] for k in ('caPem', 'certificate', 'privateKey', 'clientSpki')): + raise InstallError('配对文件缺少身份材料。') + return identity['nodeId'], root + + +def wait_services(units, attempts=20): + consecutive = 0 + for _ in range(attempts): + if all(subprocess.run(['systemctl', 'is-active', '--quiet', unit], check=False).returncode == 0 for unit in units): + consecutive += 1 + if consecutive >= 2: + return + else: + consecutive = 0 + time.sleep(1) + raise InstallError('服务未全部就绪。检查命令:journalctl -u ' + ' -u '.join(units) + ' -n 60 --no-pager') + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise InstallError('本机健康检查意外返回重定向,拒绝继续。') + + +def wait_api(values, timeout=660): + address = values.get('SEA_ADDR', '127.0.0.1:8080') + if not re.fullmatch(r'127\.0\.0\.1:[0-9]{1,5}', address) or not 1 <= int(address.split(':')[1]) <= 65535: + raise InstallError('无法自动核验现有 API 地址,请使用 127.0.0.1 的监听地址。') + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + deadline = time.monotonic() + timeout + print('正在等待 API 完成数据库迁移与主机身份核验……') + while time.monotonic() < deadline: + try: + with opener.open('http://' + address + '/healthz', timeout=3) as response: + if response.status == 200 and json.loads(response.read(4096)).get('status') in ('ok', 'setup_required'): + return + except (OSError, urllib.error.URLError, ValueError): + pass + time.sleep(1) + raise InstallError('API 健康检查未通过,不能报告安装成功。请执行 journalctl -u sea-vhost-api -n 60 --no-pager;修复后重跑向导。') + + +def install_node(ui): + if not Path('/www/server/panel').is_dir() or not Path('/www/server/nginx/sbin/nginx').is_file(): + raise InstallError('被控需要本机宝塔和 Nginx。') + if not Path('/www/server/pure-ftpd/bin/pure-pw').is_file(): + raise InstallError('请先在宝塔安装免费 Pure-FTPd,再运行被控向导。') + candidates = sorted(Path('/root').glob('sea-node-*.json')) + default = str(NODE_CONFIG) if NODE_CONFIG.exists() else str(candidates[0]) if len(candidates) == 1 else '' + pairing = Path(ui.ask('主控下载的配对文件路径', default)).expanduser() + # An installed config is intentionally group-readable by the non-root node. + # Do not chmod it to 0600 while the user is still answering/cancelling prompts. + installed_pair = NODE_CONFIG.exists() and pairing.samefile(NODE_CONFIG) + config = read_json(pairing, protect=not installed_pair) + node, root = validate_pair(config) + if NODE_CONFIG.exists(): + old = read_json(NODE_CONFIG) + if old.get('identity', {}).get('nodeId') != node or old.get('tenantRoot') != root: + raise InstallError('配对文件与现有节点编号或根目录不同,不能直接覆盖。') + creds = credentials(ui) + print(f'\n安装角色:被控 #{node}\n主机目录:{root}\n监听地址:{config["address"]}\n宝塔地址:{creds["url"]}') + if not ui.confirm('开始安装并启动被控'): + return False + with tempfile.TemporaryDirectory(prefix='sea-vhost-install-', dir='/run') as directory: + pair_file, panel_file = Path(directory) / 'pair.json', Path(directory) / 'panel.json' + private_json(pair_file, config) + private_json(panel_file, creds) + run(['bash', SOURCE / 'deploy/install-node.sh', pair_file, panel_file]) + units = ['sea-vhost-agent', 'sea-vhost-panel-broker', 'sea-vhost-node'] + wait_services(units) + print('\n被控安装完成,服务已启动。回到主控「节点管理」,点击「启用」即可自动探测并连接。') + print('被控不保存平台数据库;无需额外填写主控数据库或管理员信息。') + return True + + +def valid_domain(value): + return len(value) <= 253 and '.' in value and all( + re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label) + for label in value.split('.')) + + +def certificate_for(domain): + for base in (Path('/www/server/panel/vhost/cert'), Path('/www/server/panel/vhost/ssl'), Path('/etc/letsencrypt/live')): + if not base.is_dir(): + continue + ordered = [base / domain] + sorted(p for p in base.iterdir() if p.name != domain) + for directory in ordered: + cert, key = directory / 'fullchain.pem', directory / 'privkey.pem' + if not cert.is_file() or not key.is_file(): + continue + if certificate_covers(cert, domain): + return cert, key + return None + + +def certificate_covers(cert, domain): + return all(subprocess.run(['openssl', 'x509', '-in', str(cert)] + args, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False).returncode == 0 + for args in (['-checkhost', domain, '-noout'], ['-checkend', '0', '-noout'])) + + +def nginx_plan(ui, values): + if not ui.confirm('自动配置管理站点 HTTPS 与反向代理(复用已有证书)'): + return None + nginx = Path('/www/server/nginx/sbin/nginx') + if nginx.is_file(): + vhosts = Path('/www/server/panel/vhost/nginx') + reload_command = [str(nginx), '-s', 'reload'] + else: + binary = shutil.which('nginx') + if not binary: + print('本机未检测到 Nginx,本次仅安装主控程序。配置好管理站点后可再次运行向导。') + return None + nginx, vhosts, reload_command = Path(binary), Path('/etc/nginx/conf.d'), ['systemctl', 'reload', 'nginx'] + while True: + domain = ui.ask('管理域名(不含协议和路径)', 'host.ser888.cn').lower() + if valid_domain(domain): + break + print('请输入有效的域名。') + addr = values.get('SEA_ADDR', '127.0.0.1:8080') + if not re.fullmatch(r'127\.0\.0\.1:[0-9]{1,5}', addr) or not 1 <= int(addr.split(':')[1]) <= 65535: + raise InstallError('现有 API 监听地址不是受支持的本机地址,保留现有 Nginx 配置后重试。') + found = certificate_for(domain) + if not found: + print('未检测到覆盖该管理域名的有效证书。可输入证书路径,或留空后自行配置站点。') + cert = ui.ask('完整证书链路径(留空跳过站点配置)') + if not cert: + return None + key = ui.ask('证书私钥路径') + found = (Path(cert), Path(key)) + for file in found: + if not file.is_absolute() or not file.is_file() or re.search(r'[\s;{}"\'\\$]', str(file)): + raise InstallError('证书路径须是可读绝对路径且不包含 Nginx 特殊字符。') + if not certificate_covers(found[0], domain): + raise InstallError('证书已过期或未覆盖管理域名,请更换后重试。') + target = vhosts / 'sea-vhost-console.conf' + if target.is_symlink() or target.exists() and not target.is_file(): + raise InstallError('管理站点配置路径不是安全的普通文件。') + for file in vhosts.glob('*.conf'): + if file == target: + continue + text = file.read_text(errors='replace') + if any(domain in names.split() for names in re.findall(r'^\s*server_name\s+([^;]+);', text, re.M)): + if 'root /opt/sea-vhost/web;' in text or re.search(r'root\s+/opt/sea-vhost/web\s*;', text): + print(f'检测到已有 Sea vHost 管理站点,保留 {file}。') + run([nginx, '-t']) + return {'domain': domain, 'existing': True} + raise InstallError(f'域名已由其他 Nginx 站点使用:{file}。不会覆盖;可重新运行并跳过自动配置。') + text = (SOURCE / 'deploy/nginx/sea-vhost.conf').read_text() + text = text.replace('host.ser888.cn', domain) + text = text.replace(f'/www/server/panel/vhost/cert/{domain}/fullchain.pem', str(found[0])) + text = text.replace(f'/www/server/panel/vhost/cert/{domain}/privkey.pem', str(found[1])) + text = text.replace('127.0.0.1:8080', addr) + return {'domain': domain, 'existing': False, 'target': target, 'text': text, + 'nginx': nginx, 'reload': reload_command} + + +def apply_nginx(plan): + if not plan or plan['existing']: + return + target = plan['target'] + previous = target.read_bytes() if target.exists() else None + if previous is not None: + # Backups live outside the *.conf include namespace, with exclusive creation. + with tempfile.NamedTemporaryFile(prefix=target.name + '.', suffix='.bak', dir=target.parent, delete=False) as backup: + backup.write(previous) + print(f'Nginx 原配置备份:{backup.name}') + try: + atomic_config(target, plan['text'].encode()) + run([plan['nginx'], '-t']) + run(plan['reload']) + except (OSError, subprocess.CalledProcessError): + if previous is None: + target.unlink(missing_ok=True) + else: + atomic_config(target, previous) + # Reload again so a partially successful first reload cannot retain new config. + subprocess.run([str(v) for v in plan['reload']], check=False) + raise InstallError('Nginx 检查或重载失败,已恢复配置;主控程序仍保留,可修复后重跑向导。') from None + + +def atomic_config(target, content): + if target.is_symlink() or target.exists() and not target.is_file(): + raise InstallError('拒绝写入非普通 Nginx 配置文件。') + with tempfile.NamedTemporaryFile(dir=target.parent, prefix='.sea-vhost-', delete=False) as stream: + temporary = Path(stream.name) + try: + stream.write(content) + stream.flush() + os.fchmod(stream.fileno(), 0o644) + except BaseException: + temporary.unlink(missing_ok=True) + raise + try: + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + + +def install_controller(ui, role, values): + if role == 'combined' and not Path('/www/server/panel').is_dir(): + raise InstallError('兼本机托管需要本机宝塔;没有宝塔时请选择独立主控。') + plan = nginx_plan(ui, values) + print(f'\n安装角色:{ROLES[role]}\n平台数据:保留已有配置;首次安装的数据库与管理员信息在 Web 安装页填写') + if plan: + print('管理地址:https://' + plan['domain']) + if not ui.confirm('开始安装/更新并启动服务'): + return False + script = 'install-controller.sh' if role == 'controller' else 'install.sh' + run(['bash', SOURCE / 'deploy' / script, '--non-interactive']) + units = ['sea-vhost-api'] if role == 'controller' else ['sea-vhost-agent', 'sea-vhost-panel-broker', 'sea-vhost-api'] + run(['systemctl', 'enable', *units]) + run(['systemctl', 'restart', *units]) + wait_services(units) + wait_api(values) + apply_nginx(plan) + print('\n主控安装完成,服务已启动。') + if plan: + print('打开 https://' + plan['domain'] + '/ 完成 Web 安装;已安装则直接登录。') + else: + print('管理站点根目录:/opt/sea-vhost/web;/api/ 反代至 http://' + values.get('SEA_ADDR', '127.0.0.1:8080')) + if not CONFIG.exists(): + token = environment().get('SEA_SETUP_TOKEN', '') + if token: + print('Web 安装令牌(请保密):' + token) + return True + + +def main(argv=None): + parser = argparse.ArgumentParser(description='Sea vHost 中文交互式安装向导;保留现有数据,不自动转换安装角色。') + parser.add_argument('--role', choices=ROLES, help='预选安装角色') + options = parser.parse_args(argv) + if platform.system() != 'Linux' or platform.machine() not in ('x86_64', 'amd64'): + raise InstallError('当前安装包仅支持 Debian Linux amd64。') + if os.geteuid() != 0: + raise InstallError('请使用 root 运行安装向导。') + if not sys.stdin.isatty(): + raise InstallError('交互向导需要终端;自动化部署请使用原脚本的 --non-interactive 模式。') + os.umask(0o077) + ui = Console() + values = environment() + print('\nSea vHost 安装向导\n回车采用默认值,Ctrl+C 取消;密码输入不会显示。\n') + role = options.role + if not role: + default = '3' if NODE_CONFIG.exists() else '2' if values.get('SEA_CONTROLLER_ONLY') == 'true' else '1' + print('1. 主控兼本机托管(已有宝塔的服务器)\n2. 独立主控(仅管理其他被控)\n3. 被控节点(已有宝塔的服务器)') + while not role: + role = {'1': 'combined', '2': 'controller', '3': 'node'}.get(ui.ask('选择安装角色', default)) + if not role: + print('请输入 1、2 或 3。') + check_role(role, values) + check_build(role) + for command in ('bash', 'systemctl', 'openssl'): + if not shutil.which(command): + raise InstallError(f'缺少必要命令 {command},请安装后重试。') + completed = install_node(ui) if role == 'node' else install_controller(ui, role, values) + if not completed: + print('安装已取消。') + return 0 + + +if __name__ == '__main__': + try: + sys.exit(main()) + except (KeyboardInterrupt, EOFError): + print('\n安装已取消;已完成的安装步骤会保留,可再次运行向导继续。', file=sys.stderr) + sys.exit(130) + except subprocess.CalledProcessError as error: + print(f'\n安装命令失败(退出码 {error.returncode}),请检查上方输出;修复后可重新运行向导。', file=sys.stderr) + sys.exit(1) + except (InstallError, OSError, ValueError, TypeError, KeyError) as error: + # Never print config contents, subprocess input or stored credentials. + print(f'\n安装未完成:{error}', file=sys.stderr) + sys.exit(1) diff --git a/deploy/install.sh b/deploy/install.sh new file mode 100755 index 0000000..2b15189 --- /dev/null +++ b/deploy/install.sh @@ -0,0 +1,242 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ ${1:-} == --help ]]; then + echo '用法:bash deploy/install.sh [--interactive [--role combined|controller|node] | --non-interactive]' + echo '终端运行默认进入中文交互向导;--non-interactive 保留原本机安装行为。' + exit 0 +fi +if [[ ${1:-} == --interactive || ( $# -eq 0 && -t 0 && -t 1 ) ]]; then + [[ ${1:-} != --interactive ]] || shift + exec python3 "$(dirname "${BASH_SOURCE[0]}")/install-wizard.py" "$@" +fi +if [[ ${1:-} == --non-interactive ]]; then shift; fi +[[ $# -eq 0 ]] || { echo '未知参数,使用 --help 查看安装方式。' >&2; exit 1; } + +if [[ "${EUID}" -ne 0 ]]; then + echo "Run this installer as root." >&2 + exit 1 +fi + +source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +build_dir="${source_dir}/build" +for binary in sea-vhost-api sea-vhost-agent sea-vhost-panel-broker sea-vhost-run sea-vhost-scheduler; do + [[ -f "${build_dir}/bin/$binary" && ! -L "${build_dir}/bin/$binary" ]] || { echo "Missing $binary" >&2; exit 1; } +done +if [[ ! -f "${build_dir}/bin/sea-vhost-api" || -L "${build_dir}/bin/sea-vhost-api" || ! -f "${build_dir}/bin/sea-vhost-agent" || -L "${build_dir}/bin/sea-vhost-agent" || ! -f "${build_dir}/bin/sea-vhost-panel-broker" || -L "${build_dir}/bin/sea-vhost-panel-broker" || ! -f "${build_dir}/web/index.html" || -L "${build_dir}/web/index.html" ]]; then + echo "Missing build output. Run deploy/build.sh first." >&2 + exit 1 +fi + +if ! command -v setfacl >/dev/null 2>&1 || ! command -v getfacl >/dev/null 2>&1; then + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends acl +fi + +# Current security releases for older Python branches are source-only. Keep the +# compiler and standard-library headers available so the privileged installer +# can build the latest patch of each supported branch from verified CPython +# sources instead of relying on aaPanel's stale prebuilt-version list. +python_build_packages=(build-essential ca-certificates xz-utils libssl-dev zlib1g-dev libncurses-dev libreadline-dev libsqlite3-dev libgdbm-dev libdb-dev libbz2-dev libexpat1-dev liblzma-dev tk-dev libffi-dev uuid-dev) +missing_python_build_packages=() +for package in "${python_build_packages[@]}"; do + dpkg-query -W -f='${Status}' "${package}" 2>/dev/null | grep -q 'ok installed' || missing_python_build_packages+=("${package}") +done +if (( ${#missing_python_build_packages[@]} > 0 )); then + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends "${missing_python_build_packages[@]}" +fi + +bash "$source_dir/deploy/prepare-runtime-roots.sh" + +for required in chattr systemctl openssl mktemp setfacl getfacl useradd usermod passwd make tar xz; do + command -v "${required}" >/dev/null || { echo "Missing required command: ${required}" >&2; exit 1; } +done + +legacy_config="/var/lib/sea-vhost/config.json" +if [[ -f "${legacy_config}" ]] && grep -q '"panel_api_key"' "${legacy_config}"; then + echo "Legacy Web API configuration still contains a root-equivalent panel API key." >&2 + echo "Refusing an automatic migration. Back up the file, move the key into the panel broker through a root-controlled maintenance procedure, then remove it from ${legacy_config}." >&2 + exit 1 +fi + +getent group sea-vhost-control >/dev/null || groupadd --system sea-vhost-control +getent group sea-vhost-agent-control >/dev/null || groupadd --system sea-vhost-agent-control +getent group sea-vhost-panel-control >/dev/null || groupadd --system sea-vhost-panel-control +id sea-vhost >/dev/null 2>&1 || useradd --system --gid sea-vhost-control --groups sea-vhost-agent-control,sea-vhost-panel-control --home-dir /var/lib/sea-vhost --shell /usr/sbin/nologin sea-vhost +usermod -g sea-vhost-control -aG sea-vhost-agent-control,sea-vhost-panel-control sea-vhost +id sea-vhost-panel >/dev/null 2>&1 || useradd --system --gid sea-vhost-panel-control --groups sea-vhost-control --home-dir /var/lib/sea-vhost-panel --shell /usr/sbin/nologin sea-vhost-panel +usermod -g sea-vhost-panel-control -aG sea-vhost-control sea-vhost-panel +gpasswd -d sea-vhost-panel sea-vhost-agent-control >/dev/null 2>&1 || true +gpasswd -d sea-vhost-panel sea-vhost-files >/dev/null 2>&1 || true +gpasswd -d sea-vhost sea-vhost-files >/dev/null 2>&1 || true +if ! id www >/dev/null 2>&1; then + echo "Missing Nginx/PHP service user: www" >&2 + exit 1 +fi +if getent group sea-vhost >/dev/null 2>&1 && id www >/dev/null 2>&1; then + gpasswd -d www sea-vhost >/dev/null 2>&1 || true +fi +if id www >/dev/null 2>&1; then + gpasswd -d www sea-vhost-control >/dev/null 2>&1 || true + gpasswd -d www sea-vhost-agent-control >/dev/null 2>&1 || true + gpasswd -d www sea-vhost-panel-control >/dev/null 2>&1 || true + gpasswd -d www sea-vhost-files >/dev/null 2>&1 || true + if id -nG www | tr ' ' '\n' | grep -Eq '^sea-vhost-(control|agent-control|panel-control)$'; then + echo "The www user still belongs to a Sea vHost control group; refusing to expose privileged sockets." >&2 + exit 1 + fi +fi +install -d -o root -g sea-vhost-control -m 0750 /etc/sea-vhost +install -d -o root -g root -m 0755 /opt/sea-vhost +if [[ -L /www/wwwroot || ( -e /www/wwwroot && ! -d /www/wwwroot ) ]]; then + echo "The aaPanel site root /www/wwwroot is not a physical directory." >&2 + exit 1 +fi +if [[ ! -d /www/wwwroot ]]; then + install -d -o root -g root -m 0755 /www/wwwroot +fi +tenant_root="/www/wwwroot/seavHost/vHost" +for managed_dir in /www/wwwroot/seavHost "${tenant_root}"; do + if [[ -L "${managed_dir}" || ( -e "${managed_dir}" && ! -d "${managed_dir}" ) ]]; then + echo "Unsafe Sea vHost managed directory: ${managed_dir}" >&2 + exit 1 + fi + if [[ ! -d "${managed_dir}" ]]; then + install -d -o root -g root -m 0755 "${managed_dir}" + fi +done +nginx_vhost_root="/www/server/panel/vhost/nginx" +nginx_binary="/www/server/nginx/sbin/nginx" +if [[ -L "${nginx_vhost_root}" || ! -d "${nginx_vhost_root}" ]]; then + echo "The aaPanel Nginx vhost root is missing or not a physical directory: ${nginx_vhost_root}" >&2 + exit 1 +fi +if [[ ! -x "${nginx_binary}" ]]; then + echo "The aaPanel Nginx binary is unavailable: ${nginx_binary}" >&2 + exit 1 +fi +install -d -o root -g root -m 0755 "${nginx_vhost_root}/extension" +security_global="${nginx_vhost_root}/sea-vhost-security-global.conf" +security_backup="" +if [[ -e "${security_global}" ]]; then + if [[ -L "${security_global}" || ! -f "${security_global}" ]]; then + echo "Unsafe existing Sea vHost Nginx security file: ${security_global}" >&2 + exit 1 + fi + security_backup="$(mktemp)" + cp --preserve=mode,ownership,timestamps -- "${security_global}" "${security_backup}" +fi +install -o root -g root -m 0644 "${source_dir}/deploy/nginx/sea-vhost-security-global.conf" "${security_global}" +if ! "${nginx_binary}" -t; then + if [[ -n "${security_backup}" ]]; then + cp --preserve=mode,ownership,timestamps -- "${security_backup}" "${security_global}" + else + rm -f -- "${security_global}" + fi + [[ -z "${security_backup}" ]] || rm -f -- "${security_backup}" + echo "Nginx rejected the Sea vHost security baseline; the previous configuration was restored." >&2 + exit 1 +fi +[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}" +install -d -o root -g root -m 0755 /usr/local/libexec +install -o root -g root -m 0755 "${build_dir}/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run +install -o root -g root -m 0750 "${build_dir}/bin/sea-vhost-scheduler" /opt/sea-vhost/bin/sea-vhost-scheduler +install -d -o root -g sea-vhost-control -m 0750 /opt/sea-vhost/bin +install -d -o root -g root -m 0755 /opt/sea-vhost/web +install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost +install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel +install -d -o root -g root -m 0700 /www/backup/sea-vhost +install -o root -g sea-vhost-control -m 0750 "${build_dir}/bin/sea-vhost-api" /opt/sea-vhost/bin/ +install -o root -g sea-vhost-control -m 0750 "${build_dir}/bin/sea-vhost-agent" /opt/sea-vhost/bin/ +install -o root -g sea-vhost-control -m 0750 "${build_dir}/bin/sea-vhost-panel-broker" /opt/sea-vhost/bin/ +# aaPanel adds an immutable PHP .user.ini when a directory is registered as a +# site, even for Sea vHost's static console. This directory is fully managed by +# the installer and does not execute PHP, so remove that panel artifact before +# normalizing ownership during upgrades. +if [[ -e /opt/sea-vhost/web/.user.ini ]]; then + if [[ -L /opt/sea-vhost/web/.user.ini || ! -f /opt/sea-vhost/web/.user.ini ]]; then + echo "Unsafe aaPanel .user.ini artifact in the managed Web directory." >&2 + exit 1 + fi + chattr -i -a -- /opt/sea-vhost/web/.user.ini 2>/dev/null || true + rm -f -- /opt/sea-vhost/web/.user.ini +fi +cp -a "${build_dir}/web/." /opt/sea-vhost/web/ +chown -R root:root /opt/sea-vhost/web +find /opt/sea-vhost/web -type d -exec chmod 0755 {} + +find /opt/sea-vhost/web -type f -exec chmod 0644 {} + + +if [[ ! -f /etc/sea-vhost/sea-vhost.env ]]; then + setup_token="$(openssl rand -hex 32)" + internal_auth_token="$(openssl rand -hex 32)" + install -o root -g sea-vhost-control -m 0640 /dev/null /etc/sea-vhost/sea-vhost.env + { + echo "SEA_ADDR=127.0.0.1:8080" + echo "SEA_CONFIG_FILE=/var/lib/sea-vhost/config.json" + echo "SEA_SETUP_TOKEN=${setup_token}" + echo "SEA_INTERNAL_AUTH_TOKEN=${internal_auth_token}" + echo "SEA_COOKIE_SECURE=true" + echo "SEA_TENANT_ROOT=${tenant_root}" + echo "SEA_BACKUP_ROOT=/www/backup/sea-vhost" + echo "SEA_UPLOAD_LIMIT=20971520" + echo "SEA_AGENT_SOCKET=/run/sea-vhost/agent.sock" + echo "SEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock" + echo "SEA_PANEL_BROKER_STATE=/var/lib/sea-vhost-panel" + echo "SEA_FILE_OWNER=sea-vhost" + echo "SEA_NODE_PID_ROOT=/www/server/nodejs/vhost/pids" + echo "SEA_NGINX_VHOST_ROOT=${nginx_vhost_root}" + echo "SEA_NGINX_BINARY=${nginx_binary}" + echo "SEA_PURE_PW_BINARY=/www/server/pure-ftpd/bin/pure-pw" + echo "SEA_PHP_IDENTITY_STATE=/var/lib/sea-vhost-agent/php" + echo "SEA_PHP_IDENTITY_RUN=/run/sea-vhost-php" + echo "SEA_USAGE_STATE=/var/lib/sea-vhost-agent/traffic.json" + echo "SEA_NGINX_LOG_ROOT=/www/wwwlogs" + echo "SEA_CERT_ROOT=/www/server/panel/vhost/cert" + echo "SEA_PURE_FTP_CONFIG=/www/server/pure-ftpd/etc/pure-ftpd.conf" + echo "SEA_PURE_FTP_PEM=/www/server/pure-ftpd/etc/pure-ftpd.pem" + } > /etc/sea-vhost/sea-vhost.env + chown root:sea-vhost-control /etc/sea-vhost/sea-vhost.env + chmod 0640 /etc/sea-vhost/sea-vhost.env + echo "Created /etc/sea-vhost/sea-vhost.env." + echo "A one-time setup token was created. Retrieve it locally as root from /etc/sea-vhost/sea-vhost.env." +else + echo "Keeping existing /etc/sea-vhost/sea-vhost.env and setup token." +fi +chown root:sea-vhost-control /etc/sea-vhost/sea-vhost.env +chmod 0640 /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_PANEL_BROKER_SOCKET=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock' >> /etc/sea-vhost/sea-vhost.env +if ! grep -q '^SEA_INTERNAL_AUTH_TOKEN=' /etc/sea-vhost/sea-vhost.env; then + internal_auth_token="$(openssl rand -hex 32)" + echo "SEA_INTERNAL_AUTH_TOKEN=${internal_auth_token}" >> /etc/sea-vhost/sea-vhost.env +fi +grep -q '^SEA_PANEL_BROKER_STATE=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PANEL_BROKER_STATE=/var/lib/sea-vhost-panel' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_TENANT_ROOT=' /etc/sea-vhost/sea-vhost.env || echo "SEA_TENANT_ROOT=${tenant_root}" >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_BACKUP_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_BACKUP_ROOT=/www/backup/sea-vhost' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_NGINX_VHOST_ROOT=' /etc/sea-vhost/sea-vhost.env || echo "SEA_NGINX_VHOST_ROOT=${nginx_vhost_root}" >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_NGINX_BINARY=' /etc/sea-vhost/sea-vhost.env || echo "SEA_NGINX_BINARY=${nginx_binary}" >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_PURE_PW_BINARY=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PURE_PW_BINARY=/www/server/pure-ftpd/bin/pure-pw' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_PHP_IDENTITY_STATE=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PHP_IDENTITY_STATE=/var/lib/sea-vhost-agent/php' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_PHP_IDENTITY_RUN=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PHP_IDENTITY_RUN=/run/sea-vhost-php' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_USAGE_STATE=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_USAGE_STATE=/var/lib/sea-vhost-agent/traffic.json' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_NGINX_LOG_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_NGINX_LOG_ROOT=/www/wwwlogs' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_CERT_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_CERT_ROOT=/www/server/panel/vhost/cert' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_PURE_FTP_CONFIG=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PURE_FTP_CONFIG=/www/server/pure-ftpd/etc/pure-ftpd.conf' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_PURE_FTP_PEM=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PURE_FTP_PEM=/www/server/pure-ftpd/etc/pure-ftpd.pem' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_FILE_OWNER=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_FILE_OWNER=sea-vhost' >> /etc/sea-vhost/sea-vhost.env +grep -q '^SEA_NODE_PID_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_NODE_PID_ROOT=/www/server/nodejs/vhost/pids' >> /etc/sea-vhost/sea-vhost.env +sed -i '/^SEA_RUNTIME_USER=/d' /etc/sea-vhost/sea-vhost.env +sed -i '/^SEA_RUNTIME_GROUP=/d' /etc/sea-vhost/sea-vhost.env +sed -i '/^SEA_AGENT_GROUP=/d' /etc/sea-vhost/sea-vhost.env +sed -i '/^SEA_QUOTA_MOUNT=/d' /etc/sea-vhost/sea-vhost.env + +install -o root -g root -m 0644 "${source_dir}/deploy/systemd/sea-vhost-agent.service" /etc/systemd/system/ +install -o root -g root -m 0644 "${source_dir}/deploy/systemd/sea-vhost-panel-broker.service" /etc/systemd/system/ +install -o root -g root -m 0644 "${source_dir}/deploy/systemd/sea-vhost-api.service" /etc/systemd/system/ +systemctl daemon-reload + +echo "Files installed. Services were not started. Configure the Nginx vhost, create an empty MySQL database and user, then run:" +echo " systemctl enable --now sea-vhost-agent sea-vhost-panel-broker sea-vhost-api" +echo "Open the Sea vHost console and complete the Web installation wizard." diff --git a/deploy/nginx/aa-panel-websocket-deny.conf.example b/deploy/nginx/aa-panel-websocket-deny.conf.example new file mode 100644 index 0000000..96b9bdb --- /dev/null +++ b/deploy/nginx/aa-panel-websocket-deny.conf.example @@ -0,0 +1,20 @@ +# Defense-in-depth for an aaPanel reverse-proxy server block. +# Include this file inside the public aaPanel `server {}` block, before the +# catch-all proxy location. It intentionally disables browser terminal and +# other privileged WebSocket features; normal signed HTTP API calls continue. +# +# This is not sufficient while the aaPanel backend port remains reachable +# from untrusted networks. Bind/restrict that port with a firewall, security +# group, VPN, or SSH tunnel as the primary control. + +location = /sock_shell { return 403; } +location = /webssh { return 403; } +location = /ws_panel { return 403; } +location = /ws_home { return 403; } +location = /ws_project { return 403; } +location = /ws_model { return 403; } +location = /workorder_client { return 403; } + +location ~ ^/v2/(?:sock_shell|webssh|ws_panel|ws_home|ws_project|ws_model|workorder_client)$ { + return 403; +} diff --git a/deploy/nginx/sea-vhost-security-global.conf b/deploy/nginx/sea-vhost-security-global.conf new file mode 100644 index 0000000..f680c12 --- /dev/null +++ b/deploy/nginx/sea-vhost-security-global.conf @@ -0,0 +1,3 @@ +# Managed by Sea vHost. Local changes will be replaced. +limit_req_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip:10m rate=20r/s; +limit_conn_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip_conn:10m; diff --git a/deploy/nginx/sea-vhost.conf b/deploy/nginx/sea-vhost.conf new file mode 100644 index 0000000..e9cc9a3 --- /dev/null +++ b/deploy/nginx/sea-vhost.conf @@ -0,0 +1,61 @@ +map $upstream_http_content_security_policy $sea_vhost_csp { + "" "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'"; + default $upstream_http_content_security_policy; +} +server { + listen 80; + server_name host.ser888.cn; + return 301 https://$host$request_uri; +} + +server { + listen 443 ssl http2; + server_name host.ser888.cn; + server_tokens off; + + # 证书可由宝塔站点设置生成;部署前替换路径。 + ssl_certificate /www/server/panel/vhost/cert/host.ser888.cn/fullchain.pem; + ssl_certificate_key /www/server/panel/vhost/cert/host.ser888.cn/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Referrer-Policy "same-origin" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + add_header Content-Security-Policy $sea_vhost_csp always; + + root /opt/sea-vhost/web; + index index.html; + client_max_body_size 21m; + + proxy_hide_header Content-Security-Policy; + + location /api/ { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + # Management responses are private; override any server-wide proxy cache. + proxy_cache off; + proxy_set_header Range $http_range; + proxy_set_header If-Range $http_if_range; + # Keep an explicit public port (when present) for strict Origin checks. + proxy_set_header Host $http_host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + proxy_connect_timeout 3s; + proxy_read_timeout 300s; + } + + location = /healthz { + proxy_pass http://127.0.0.1:8080; + access_log off; + } + + location / { + try_files $uri $uri/ /index.html; + } + + location ~ /\. { + deny all; + } +} diff --git a/deploy/operational-completion-verify.sh b/deploy/operational-completion-verify.sh new file mode 100755 index 0000000..6446abd --- /dev/null +++ b/deploy/operational-completion-verify.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +config=/var/lib/sea-vhost/config.json +management_domain="${SEA_MANAGEMENT_DOMAIN:-host.ser888.cn}" +mysql_bin="$(command -v mysql || true)" +if [[ -z "${mysql_bin}" && -x /www/server/mysql/bin/mysql ]]; then + mysql_bin=/www/server/mysql/bin/mysql +fi +[[ -x "${mysql_bin}" ]] +mapfile -t control_db < <(python3 -c 'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\(([^:]+):(\d+)\)/([^?]+)(?:\?.*)?", d); assert m; print("\n".join(m.groups()))') +control_user="${control_db[0]}" +control_password="${control_db[1]}" +control_host="${control_db[2]}" +control_port="${control_db[3]}" +control_name="${control_db[4]}" +sql() { + MYSQL_PWD="${control_password}" "${mysql_bin}" --protocol=TCP --host="${control_host}" --port="${control_port}" --user="${control_user}" --database="${control_name}" --batch --skip-column-names --execute="$1" +} + +[[ "$(sql "SELECT COUNT(*) FROM schema_migrations WHERE version='010_operational_completion.sql';")" == 1 ]] +[[ "$(sql "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='domains' AND column_name IN ('dns_credential_id','dns_record_id','dns_record_type','dns_last_error');")" == 4 ]] +[[ "$(sql "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name IN ('tenant_backups','oidc_states');")" == 2 ]] +[[ "$(sql "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='admin_notifications' AND column_name IN ('attempts','last_error','next_attempt_at');")" == 3 ]] + +oidc_status="$(curl --silent --show-error --fail --max-time 10 --header "Host: ${management_domain}" http://127.0.0.1:8080/api/v1/auth/oidc/status)" +python3 -c 'import json,sys; d=json.loads(sys.argv[1]); assert isinstance(d.get("enabled"), bool)' "${oidc_status}" +unauthorized="$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' --max-time 10 --header "Host: ${management_domain}" http://127.0.0.1:8080/api/v1/admin/panel-sites)" +[[ "${unauthorized}" == 401 ]] +systemctl show sea-vhost-agent.service -p ReadWritePaths --value | tr ' ' '\n' | grep -qx '/www/backup/sea-vhost' +[[ -d /www/backup/sea-vhost && ! -L /www/backup/sea-vhost ]] + +printf '%s\n' 'Operational completion verification: passed' +printf 'migration=010 dns_columns=4 lifecycle_tables=2 notification_retry_columns=3 oidc_status=valid admin_boundary=401 backup_root=allowed\n' diff --git a/deploy/package-release.mjs b/deploy/package-release.mjs new file mode 100644 index 0000000..d4b803d --- /dev/null +++ b/deploy/package-release.mjs @@ -0,0 +1,60 @@ +// Package only declared project inputs. Never recursively copy the workspace. +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import {fileURLToPath} from 'node:url'; +import {execFileSync} from 'node:child_process'; + +const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); +const build=path.join(root,'build'); +const config=JSON.parse(fs.readFileSync(path.join(root,'deploy/release-files.json'),'utf8')); +const requiredBinaries=['sea-vhost-api','sea-vhost-agent','sea-vhost-panel-broker','sea-vhost-node','sea-vhost-run','sea-vhost-scheduler']; +const skip=new Set(['node_modules','__pycache__','.git','.cache','.npm-cache']); +const hash=b=>crypto.createHash('sha256').update(b).digest('hex'); +const slash=p=>p.split(path.sep).join('/'); +function inside(base,name){const target=path.resolve(base,name),relative=path.relative(base,target);if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('Path outside allowed output directory');return target} +function validateName(name){if(!name||name.includes('\\')||name.includes('\n')||path.posix.isAbsolute(name)||name.split('/').some(v=>v==='..'||v===''))throw Error('Unsafe package path');return name} +function collect(files,dirs){ + const found=new Set(); + function visit(name){validateName(name);const full=inside(root,name),s=fs.lstatSync(full);if(s.isSymbolicLink())throw Error('Refusing package symlink: '+name);if(s.isDirectory()){for(const item of fs.readdirSync(full).sort()){if(skip.has(item)||item.startsWith('.tmp')||item.endsWith('.pyc')||item.endsWith('.tsbuildinfo'))continue;visit(name+'/'+item)}}else if(s.isFile()){if(path.basename(name)==='.env')throw Error('Live environment file in package');found.add(name)}else throw Error('Non-regular package input: '+name)} + for(const name of [...files,...dirs])visit(name); + return [...found].sort(); +} +function scanSecrets(files){ + // Certificate forms contain PEM header placeholders. Reject actual key + // material, including escaped newlines, rather than the header text alone. + const patterns=[[/-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----(?:\s|\\[rn])*(?:[A-Za-z0-9+/=](?:\s|\\[rn])*){80,}/,'private-key'],[/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,'aws-access-key'],[/\bgh[pousr]_[A-Za-z0-9]{30,}\b/,'github-token']]; + const actualSecret=process.env.SEA_PANEL_API_KEY; + for(const name of files){const data=fs.readFileSync(path.join(root,name));if(actualSecret&&data.includes(Buffer.from(actualSecret)))throw Error('Live panel credential detected in '+name);if(!/\.(?:go|mjs|js|ts|tsx|py|sh|md|json|example|conf|service|sql)$/.test(name)||name.endsWith('_test.go')||/\.test\.(?:ts|tsx|mjs)$/.test(name)||name==='deploy/package-release.mjs')continue;const value=data.toString('utf8');for(const [pattern,kind] of patterns)if(pattern.test(value))throw Error('Potential '+kind+' in '+name)} +} +function checkBuild(){ + for(const name of requiredBinaries){const file=path.join(build,'bin',name),s=fs.lstatSync(file);if(!s.isFile()||s.isSymbolicLink()||!fs.readFileSync(file).subarray(0,4).equals(Buffer.from([127,69,76,70])))throw Error('Missing Linux ELF: '+name)} + if(!fs.statSync(path.join(build,'web/index.html')).isFile())throw Error('Frontend build missing'); + const actual=fs.readdirSync(path.join(build,'bin')).sort();if(JSON.stringify(actual)!==JSON.stringify([...requiredBinaries].sort()))throw Error('Unexpected file in build/bin'); +} +function writePackage(kind,files){ + const archiveName=kind==='runtime'?'sea-vhost-linux-amd64.tar.gz':'sea-vhost-source.tar.gz'; + const output=inside(build,archiveName),stage=fs.mkdtempSync(path.join(build,'release-stage-')); + try{ + const entries=files.map(name=>{const source=path.join(root,name),target=inside(stage,name);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(source,target);const executable=name.startsWith('build/bin/')||name.endsWith('.sh');fs.chmodSync(target,executable?0o755:0o644);return {path:name,bytes:fs.statSync(source).size,sha256:hash(fs.readFileSync(source))}}); + const manifest={format:'sea-vhost.release',version:1,kind,createdAt:new Date().toISOString(),platform:'linux/amd64',databaseMigrations:fs.readdirSync(path.join(root,'backend/internal/migrations')).filter(n=>/^\d{3}_.+\.sql$/.test(n)).length,files:entries}; + fs.writeFileSync(path.join(stage,'RELEASE-MANIFEST.json'),JSON.stringify(manifest,null,2)+'\n'); + const names=[...files,'RELEASE-MANIFEST.json'].sort(); + const listing=path.join(stage,'package-list.txt');fs.writeFileSync(listing,names.join('\n')+'\n'); + const temporary=inside(build,archiveName+'.pending'); + execFileSync('tar',['-czf',temporary,'-C',stage,'-T',listing],{stdio:'pipe'}); + const actual=execFileSync('tar',['-tzf',temporary],{encoding:'utf8'}).split(/\r?\n/).filter(Boolean).sort(); + if(JSON.stringify(actual)!==JSON.stringify(names))throw Error('Archive content verification failed'); + if(fs.existsSync(output)){const prior=hash(fs.readFileSync(output)),history=inside(build,'archive');fs.mkdirSync(history,{recursive:true});const archived=inside(history,archiveName.replace('.tar.gz','-'+prior.slice(0,12)+'.tar.gz'));if(!fs.existsSync(archived))fs.copyFileSync(output,archived)} + fs.renameSync(temporary,output); + const digest=hash(fs.readFileSync(output));fs.writeFileSync(output+'.sha256',digest+' '+archiveName+'\n'); + fs.writeFileSync(inside(build,kind+'-manifest.json'),JSON.stringify(manifest,null,2)+'\n'); + return {name:archiveName,sha256:digest,bytes:fs.statSync(output).size,files:entries.length}; + }finally{const safe=inside(build,path.basename(stage));if(safe!==stage||!path.basename(safe).startsWith('release-stage-'))throw Error('Unsafe staging cleanup');fs.rmSync(safe,{recursive:true,force:true})} +} +checkBuild();fs.mkdirSync(build,{recursive:true}); +const runtime=collect(config.runtimeFiles,config.runtimeDirectories),source=collect(config.sourceFiles,config.sourceDirectories); +scanSecrets([...new Set([...runtime,...source])]); +const report={format:'sea-vhost.package-verification',createdAt:new Date().toISOString(),curatedInputs:true,knownLivePanelCredentialChecked:Boolean(process.env.SEA_PANEL_API_KEY),secretScan:'passed (private keys, common token patterns, and supplied live credential; not a complete secret audit)',packages:[writePackage('runtime',runtime),writePackage('source',source)]}; +fs.writeFileSync(inside(build,'release-verification.json'),JSON.stringify(report,null,2)+'\n'); +console.log(JSON.stringify(report)); diff --git a/deploy/panel-account-security-verify.mjs b/deploy/panel-account-security-verify.mjs new file mode 100644 index 0000000..6731687 --- /dev/null +++ b/deploy/panel-account-security-verify.mjs @@ -0,0 +1,408 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.'); + process.exit(2); +} + +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `security-${suffix}@seavhost.test`; +const tenantEmail = `tenant-security-${suffix}@seavhost.test`; +const initialPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}9a`; +const changedPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}8B`; +const tenantPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}7c`; +const marker = `Sea-vHost-account-security-${suffix}`; +const planName = `File verification ${suffix}`; +const planStatePath = `/var/lib/sea-vhost/account-verify-${suffix}.state`; +const domainRunDirectory = `domain-${suffix}`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, successMarker) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost account verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary verification task'); + const taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned invalid task id'); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(successMarker) || log.includes('★[')) break; + } + if (!log.includes(successMarker)) throw new Error(`temporary verification task failed:\n${log.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const seedMarker = `${marker}-seeded`; +const seedShell = [ + 'set -Eeuo pipefail', + 'stage=initial; trap \'printf "account_seed_failed_stage=%s\\n" "$stage" >&2\' ERR', + `email=${q(email)}`, + `tenant_email=${q(tenantEmail)}`, + `password=${q(initialPassword)}`, + `tenant_password=${q(tenantPassword)}`, + `plan_name=${q(planName)}`, + `state_path=${q(planStatePath)}`, + 'stage=php; php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; test -x "$php_bin"', + 'password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#password_hash}" -gt 50', + 'tenant_password_hash="$(TEST_PASSWORD="$tenant_password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#tenant_password_hash}" -gt 50', + 'stage=config', + 'mapfile -t db_parts < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'test "${#db_parts[@]}" -eq 5; db_user="${db_parts[0]}"; db_password="${db_parts[1]}"; db_host="${db_parts[2]}"; db_port="${db_parts[3]}"; db_name="${db_parts[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"', + 'stage=database', + 'sql="DELETE FROM users WHERE email IN (\'$email\',\'$tenant_email\'); INSERT INTO users(email,login_name,display_name,password_hash,role,status) VALUES (\'$email\',\'$email\',\'Security verification\',\'$password_hash\',\'admin\',\'active\'); INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$tenant_email\',\'$tenant_email\',\'Tenant security verification\',\'$tenant_password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + 'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="$sql"', + 'read -r tenant_id original_plan_id project_root < <(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")', + 'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; if [[ -d "$project_root/.sea-trash" ]] && find "$project_root/.sea-trash" -mindepth 1 -print -quit | grep -q .; then printf "test project trash is not empty\\n" >&2; exit 1; fi', + 'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',67108864,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"', + 'temp_plan_id="$(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"; printf "%s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" | install -o root -g root -m 0600 /dev/stdin "$state_path"', + `printf '%s\\n' ${q(seedMarker)}`, +].join('\n'); + +const cleanupMarker = `${marker}-cleaned`; +const cleanupShell = [ + 'set -euo pipefail', + `email=${q(email)}`, + `tenant_email=${q(tenantEmail)}`, + `state_path=${q(planStatePath)}`, + `file_prefix=${q(`verify-${suffix}-`)}`, + `test_run_directory=${q(domainRunDirectory)}`, + 'mapfile -t db_parts < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'test "${#db_parts[@]}" -eq 5; db_user="${db_parts[0]}"; db_password="${db_parts[1]}"; db_host="${db_parts[2]}"; db_port="${db_parts[3]}"; db_name="${db_parts[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"', + 'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id <"$state_path"; project_root="$(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT root_path FROM projects WHERE tenant_id=$tenant_id ORDER BY id LIMIT 1")"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) find "$project_root" -xdev -maxdepth 1 -type f -name "$file_prefix*" -delete; if [[ -d "$project_root/.sea-trash" ]]; then find "$project_root/.sea-trash" -xdev -maxdepth 1 -type f -name "*$file_prefix*" -delete; fi; rmdir -- "$project_root/$test_run_directory" 2>/dev/null || true ;; *) exit 1 ;; esac; MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi', + 'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="DELETE FROM users WHERE email IN (\'$email\',\'$tenant_email\');"', + `printf '%s\\n' ${q(cleanupMarker)}`, +].join('\n'); + +async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) { + const started = performance.now(); + const response = await fetch(new URL(pathname, consoleBase), { + method, redirect: 'manual', signal: AbortSignal.timeout(15_000), + headers: { + Accept: 'application/json', + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + ...(cookie ? { Cookie: cookie } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const elapsedMs = performance.now() - started; + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}`); + return { response, payload, elapsedMs }; +} + +async function upload(projectID, cookie, name, bytes, overwrite, expected) { + const form = new FormData(); + form.set('path', ''); + form.set('overwrite', overwrite ? 'true' : 'false'); + form.set('file', new Blob([bytes]), name); + const response = await fetch(new URL(`/api/v1/projects/${projectID}/files`, consoleBase), { + method: 'POST', headers: { Cookie: cookie }, body: form, redirect: 'manual', signal: AbortSignal.timeout(60_000), + }); + const text = await response.text(); + if (!expected.includes(response.status)) throw new Error(`file upload ${name} returned HTTP ${response.status}: ${text.slice(0, 160)}`); + return response; +} + +function cookieFrom(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + const cookie = header?.split(';', 1)[0]; + if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie'); + return cookie; +} + +async function login(password, totpCode, expected = [200]) { + return loginIdentifier(email, password, totpCode, expected); +} + +async function loginIdentifier(identifier, password, totpCode, expected = [200]) { + return api('/api/v1/auth/login', { method: 'POST', expected, body: { identifier, password, ...(totpCode ? { totpCode } : {}) } }); +} + +function decodeBase32(value) { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + let bits = ''; + for (const character of value.replaceAll('=', '').toUpperCase()) { + const index = alphabet.indexOf(character); + if (index < 0) throw new Error('invalid TOTP secret'); + bits += index.toString(2).padStart(5, '0'); + } + const bytes = []; + for (let offset = 0; offset + 8 <= bits.length; offset += 8) bytes.push(Number.parseInt(bits.slice(offset, offset + 8), 2)); + return Buffer.from(bytes); +} + +function totp(secret) { + const counter = BigInt(Math.floor(Date.now() / 30_000)); + const buffer = Buffer.alloc(8); + buffer.writeBigUInt64BE(counter); + const digest = crypto.createHmac('sha1', decodeBase32(secret)).update(buffer).digest(); + const offset = digest[digest.length - 1] & 0x0f; + const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000; + return value.toString().padStart(6, '0'); +} + +let seeded = false; +let adminCookieForCleanup; +let tenantCookieForCleanup; +let projectIDForCleanup; +let siteIDForCleanup; +let originalDomainApproval; +try { + await runShell(`Sea vHost account seed ${suffix}`, seedShell, seedMarker); + seeded = true; + + const knownTimings = []; + const missingTimings = []; + for (let index = 0; index < 5; index += 1) { + knownTimings.push((await login('definitely-wrong-password', undefined, [401])).elapsedMs); + missingTimings.push((await api('/api/v1/auth/login', { method: 'POST', expected: [401], body: { identifier: `missing-${suffix}@seavhost.test`, password: 'definitely-wrong-password' } })).elapsedMs); + } + const knownAverage = knownTimings.reduce((sum, value) => sum + value, 0) / knownTimings.length; + const missingAverage = missingTimings.reduce((sum, value) => sum + value, 0) / missingTimings.length; + if (knownAverage < 300 || missingAverage < 300 || Math.abs(knownAverage - missingAverage) > 150) throw new Error('login timing equalization is outside the accepted envelope'); + + let rateLimited; + for (let attempt = 1; attempt <= 21; attempt += 1) { + rateLimited = await api('/api/v1/auth/login', { + method: 'POST', expected: attempt === 21 ? [429] : [401], + body: { identifier: `limited-${suffix}@seavhost.test`, password: 'definitely-wrong-password' }, + }); + } + if (!rateLimited.response.headers.get('retry-after')) throw new Error('rate limit response omitted Retry-After'); + + const first = await login(initialPassword); + const second = await login(initialPassword); + const firstCookie = cookieFrom(first.response); + const secondCookie = cookieFrom(second.response); + await api('/api/v1/account/password', { + method: 'PUT', cookie: firstCookie, expected: [204], + body: { currentPassword: initialPassword, newPassword: changedPassword }, + }); + await api('/api/v1/me', { cookie: firstCookie }); + await api('/api/v1/me', { cookie: secondCookie, expected: [401] }); + await login(initialPassword, undefined, [401]); + const changedLogin = await login(changedPassword); + const changedCookie = cookieFrom(changedLogin.response); + + const setup = await api('/api/v1/account/mfa/setup', { + method: 'POST', cookie: changedCookie, body: { currentPassword: changedPassword }, + }); + const secret = setup.payload?.secret; + if (typeof secret !== 'string' || secret.length < 16 || !setup.payload?.otpauthURI?.startsWith('otpauth://')) throw new Error('MFA setup returned invalid data'); + const enabled = await api('/api/v1/account/mfa/enable', { + method: 'POST', cookie: changedCookie, body: { code: totp(secret) }, + }); + const recoveryCodes = enabled.payload?.recoveryCodes; + if (!Array.isArray(recoveryCodes) || recoveryCodes.length !== 10) throw new Error('MFA did not return ten recovery codes'); + await login(changedPassword, undefined, [401]); + await login(changedPassword, '000000', [401]); + const mfaLogin = await login(changedPassword, totp(secret)); + const mfaCookie = cookieFrom(mfaLogin.response); + await login(changedPassword, recoveryCodes[0]); + await login(changedPassword, recoveryCodes[0], [401]); + await api('/api/v1/account/mfa/disable', { + method: 'POST', cookie: mfaCookie, expected: [204], + body: { currentPassword: changedPassword, code: recoveryCodes[1] }, + }); + await api('/api/v1/me', { cookie: mfaCookie, expected: [401] }); + const finalAdminLogin = await login(changedPassword); + const adminCookie = cookieFrom(finalAdminLogin.response); + adminCookieForCleanup = adminCookie; + + const tenantLogin = await loginIdentifier(tenantEmail, tenantPassword); + const tenantCookie = cookieFrom(tenantLogin.response); + tenantCookieForCleanup = tenantCookie; + const projects = await api('/api/v1/projects', { cookie: tenantCookie }); + const project = projects.payload?.projects?.[0]; + if (!project?.id || !/^sv[0-9a-f]{10}$/.test(project.hostName)) throw new Error('temporary tenant could not read its managed host'); + projectIDForCleanup = project.id; + const firstReset = await api(`/api/v1/projects/${project.id}/host-password/reset`, { method: 'POST', cookie: tenantCookie, body: {} }); + const firstHostPassword = firstReset.payload?.password; + if (typeof firstHostPassword !== 'string' || firstHostPassword.length < 16) throw new Error('host password reset returned invalid data'); + const hostLoginA = await loginIdentifier(project.hostName, firstHostPassword); + const hostLoginB = await loginIdentifier(project.hostName, firstHostPassword); + const hostCookieA = cookieFrom(hostLoginA.response); + const hostCookieB = cookieFrom(hostLoginB.response); + const hostDashboard = await api('/api/v1/dashboard', { cookie: hostCookieA }); + if (hostDashboard.payload?.hostScoped !== true || hostDashboard.payload?.projects?.length !== 1 || hostDashboard.payload.projects[0].id !== project.id) { + throw new Error('host session was not scoped to exactly one project'); + } + await api('/api/v1/admin/plans', { cookie: hostCookieA, expected: [403] }); + await api(`/api/v1/projects/${project.id}/credentials`, { cookie: hostCookieA }); + await api('/api/v1/projects/9223372036854775807/files', { cookie: hostCookieA, expected: [404] }); + const secondReset = await api(`/api/v1/projects/${project.id}/host-password/reset`, { method: 'POST', cookie: tenantCookie, body: {} }); + const secondHostPassword = secondReset.payload?.password; + await api('/api/v1/me', { cookie: hostCookieA, expected: [401] }); + await api('/api/v1/me', { cookie: hostCookieB, expected: [401] }); + await loginIdentifier(project.hostName, firstHostPassword, undefined, [401]); + await loginIdentifier(project.hostName, secondHostPassword); + + const textName = `verify-${suffix}-text.txt`; + const uploadName = `verify-${suffix}-upload.bin`; + const limitName = `verify-${suffix}-20m.bin`; + const overLimitName = `verify-${suffix}-over.bin`; + const textPath = `/api/v1/projects/${project.id}/files`; + await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [204], body: { path: textName, content: 'first-value', overwrite: false } }); + await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [409], body: { path: textName, content: 'duplicate', overwrite: false } }); + await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [204], body: { path: textName, content: 'second-value', overwrite: true } }); + const downloaded = await fetch(new URL(`${textPath}?path=${encodeURIComponent(textName)}&download=1`, consoleBase), { headers: { Cookie: tenantCookie }, signal: AbortSignal.timeout(15_000) }); + if (downloaded.status !== 200 || await downloaded.text() !== 'second-value') throw new Error('downloaded text file did not match overwritten content'); + await upload(project.id, tenantCookie, uploadName, Buffer.from('small-upload'), false, [201]); + await upload(project.id, tenantCookie, uploadName, Buffer.from('duplicate'), false, [409]); + await upload(project.id, tenantCookie, uploadName, Buffer.from('overwritten-upload'), true, [201]); + await upload(project.id, tenantCookie, limitName, Buffer.alloc(20 * 1024 * 1024, 0x61), false, [201]); + await upload(project.id, tenantCookie, overLimitName, Buffer.alloc(20 * 1024 * 1024 + 1, 0x62), false, [413]); + const listing = await api(textPath, { cookie: tenantCookie }); + const listedNames = new Set((listing.payload?.entries ?? []).map((entry) => entry.name)); + for (const required of [textName, uploadName, limitName]) if (!listedNames.has(required)) throw new Error(`file listing omitted ${required}`); + for (const name of [textName, uploadName, limitName]) { + await api(`${textPath}?path=${encodeURIComponent(name)}`, { method: 'DELETE', cookie: tenantCookie, expected: [204] }); + await api(`${textPath}?path=${encodeURIComponent(name)}&download=1`, { cookie: tenantCookie, expected: [404] }); + } + await api(`${textPath}?emptyTrash=1`, { method: 'DELETE', cookie: tenantCookie, expected: [204] }); + + const approvalSetting = await api('/api/v1/admin/settings/domain-approval', { cookie: adminCookie }); + originalDomainApproval = approvalSetting.payload?.enabled === true; + await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: true } }); + const siteCreate = await api(`/api/v1/projects/${project.id}/sites`, { + method: 'POST', cookie: tenantCookie, expected: [201], + body: { name: `domain-${suffix}`, runtime: 'PHP', version: project.version, runPath: `/${domainRunDirectory}`, customDomain: '', autoSSL: false }, + }); + const domainSite = siteCreate.payload?.site; + if (!domainSite?.id || domainSite.status !== 'running') throw new Error('domain verification site was not created'); + siteIDForCleanup = domainSite.id; + const bindPath = `/api/v1/projects/${project.id}/sites/${domainSite.id}/domains`; + const dashboardForDomain = await api('/api/v1/dashboard', { cookie: tenantCookie }); + const rootDomain = dashboardForDomain.payload?.rootDomain; + if (typeof rootDomain !== 'string' || !rootDomain.includes('.')) throw new Error('dashboard omitted root domain'); + await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [422], body: { domain: rootDomain } }); + await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [422], body: { domain: `blocked.${rootDomain}` } }); + + const pendingName = `pending-${suffix}.example.invalid`; + const pending = await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: pendingName } }); + if (pending.payload?.domain?.status !== 'pending') throw new Error('domain approval did not keep the domain pending'); + const pendingList = await api('/api/v1/admin/domains/pending', { cookie: adminCookie }); + const pendingItem = pendingList.payload?.domains?.find((item) => item.domain === pendingName && item.siteId === domainSite.id); + if (!pendingItem?.id) throw new Error('pending domain was not visible to the administrator'); + const approved = await api(`/api/v1/admin/domains/${pendingItem.id}/review`, { method: 'POST', cookie: adminCookie, body: { approved: true } }); + if (approved.payload?.domain?.status !== 'approved') throw new Error('administrator approval did not approve the domain'); + + const rejectedName = `rejected-${suffix}.example.invalid`; + await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: rejectedName } }); + const rejectList = await api('/api/v1/admin/domains/pending', { cookie: adminCookie }); + const rejectItem = rejectList.payload?.domains?.find((item) => item.domain === rejectedName && item.siteId === domainSite.id); + if (!rejectItem?.id) throw new Error('second pending domain was not visible to the administrator'); + const rejected = await api(`/api/v1/admin/domains/${rejectItem.id}/review`, { method: 'POST', cookie: adminCookie, body: { approved: false } }); + if (rejected.payload?.domain?.status !== 'rejected') throw new Error('administrator rejection did not reject the domain'); + + await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: false } }); + const directName = `direct-${suffix}.example.invalid`; + const direct = await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: directName } }); + if (direct.payload?.domain?.status !== 'approved') throw new Error('approval-disabled domain was not bound immediately'); + const duplicateName = `duplicate-${suffix}.example.invalid`; + const duplicateResults = await Promise.all([ + api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: duplicateName } }), + api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: duplicateName } }), + ]); + const duplicateStatuses = duplicateResults.map((result) => result.response.status).sort(); + if (duplicateStatuses[0] !== 202 || duplicateStatuses[1] !== 422) throw new Error(`concurrent duplicate binding returned ${duplicateStatuses.join(',')}`); + + await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: true } }); + const beforeLimit = await api('/api/v1/resources', { cookie: tenantCookie }); + const currentDomainCount = (beforeLimit.payload?.domains ?? []).filter((item) => item.siteId === domainSite.id).length; + const expectedAccepted = 100 - currentDomainCount; + if (expectedAccepted < 1 || expectedAccepted > 100) throw new Error(`unexpected initial domain count ${currentDomainCount}`); + const limitResults = await Promise.all(Array.from({ length: expectedAccepted + 10 }, (_, index) => api(bindPath, { + method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: `limit-${index}-${suffix}.example.invalid` }, + }))); + const acceptedAtLimit = limitResults.filter((result) => result.response.status === 202).length; + if (acceptedAtLimit !== expectedAccepted) throw new Error(`domain limit accepted ${acceptedAtLimit}, want ${expectedAccepted}`); + const afterLimit = await api('/api/v1/resources', { cookie: tenantCookie }); + const finalDomainCount = (afterLimit.payload?.domains ?? []).filter((item) => item.siteId === domainSite.id).length; + if (finalDomainCount !== 100) throw new Error(`site domain count is ${finalDomainCount}, want 100`); + + await api(`/api/v1/projects/${project.id}/sites/${domainSite.id}`, { method: 'DELETE', cookie: tenantCookie, expected: [204] }); + siteIDForCleanup = undefined; + await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: originalDomainApproval } }); + originalDomainApproval = undefined; + + console.log(JSON.stringify({ + status: 'passed', + loginTiming: { knownAverageMs: Math.round(knownAverage), missingAverageMs: Math.round(missingAverage), differenceMs: Math.round(Math.abs(knownAverage - missingAverage)) }, + checks: { + rateLimitAndRetryAfter: true, concurrentSessions: true, passwordChangeKeepsCurrentSession: true, + passwordChangeRevokesOtherSessions: true, oldPasswordRejected: true, totpLogin: true, + recoveryCodeSingleUse: true, disableMFARevokesSessions: true, loginWithoutMFAAfterDisable: true, + hostScopedDashboard: true, hostCannotUseAdminAPI: true, hostProjectIDORDenied: true, + hostPasswordResetRevokesAllSessions: true, oldHostPasswordRejected: true, + textCreateConflictOverwriteDownload: true, multipartCreateConflictOverwrite: true, + uploadExactly20MiBAccepted: true, uploadOver20MiBRejected: true, + fileListingTrashAndEmptyTrash: true, + domainReservedZoneRejected: true, domainApprovalAndRejection: true, + approvalDisabledImmediateBinding: true, concurrentDuplicateBinding: true, + concurrentDomainLimitExactly100: true, additionalSiteCleanup: true, + }, + }, null, 2)); +} finally { + if (tenantCookieForCleanup && projectIDForCleanup && siteIDForCleanup) { + try { await api(`/api/v1/projects/${projectIDForCleanup}/sites/${siteIDForCleanup}`, { method: 'DELETE', cookie: tenantCookieForCleanup, expected: [204, 404, 422] }); } catch { /* remote cleanup below handles the retained directory */ } + } + if (adminCookieForCleanup && typeof originalDomainApproval === 'boolean') { + try { await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookieForCleanup, expected: [204], body: { enabled: originalDomainApproval } }); } catch { /* best effort */ } + } + if (seeded) { + try { await runShell(`Sea vHost account cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch (error) { + console.error(`temporary account cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`); + process.exitCode = 1; + } + } +} diff --git a/deploy/panel-allow-loopback-api.sh b/deploy/panel-allow-loopback-api.sh new file mode 100755 index 0000000..87cffbd --- /dev/null +++ b/deploy/panel-allow-loopback-api.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail + +/www/server/panel/pyenv/bin/python3 - <<'PY' +import json +import os +import stat +import tempfile +from pathlib import Path + +path = Path('/www/server/panel/config/api.json') +if not path.is_file() or path.is_symlink(): + raise SystemExit('aaPanel API configuration is missing or unsafe') +metadata = path.stat() +payload = json.loads(path.read_text(encoding='utf-8')) +addresses = payload.get('limit_addr') +if not isinstance(payload, dict) or not isinstance(addresses, list): + raise SystemExit('aaPanel API allowlist has an unexpected format') +if '127.0.0.1' in addresses: + print('aaPanel API loopback allowlist: already present') + raise SystemExit(0) +addresses.append('127.0.0.1') +handle, temporary_name = tempfile.mkstemp(prefix='.sea-vhost-api-', dir=str(path.parent), text=True) +try: + with os.fdopen(handle, 'w', encoding='utf-8') as output: + json.dump(payload, output, ensure_ascii=False, separators=(',', ':')) + output.write('\n') + output.flush() + os.fsync(output.fileno()) + os.chmod(temporary_name, stat.S_IMODE(metadata.st_mode)) + os.chown(temporary_name, metadata.st_uid, metadata.st_gid) + os.replace(temporary_name, path) +finally: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass +print('aaPanel API loopback allowlist: added 127.0.0.1') +PY diff --git a/deploy/panel-api-config-shape.sh b/deploy/panel-api-config-shape.sh new file mode 100755 index 0000000..346627a --- /dev/null +++ b/deploy/panel-api-config-shape.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set +e + +/www/server/panel/pyenv/bin/python3 - <<'PY' +import json +from pathlib import Path + +for candidate in (Path('/www/server/panel/config/api.json'), Path('/www/server/panel/data/api.json')): + if not candidate.is_file() or candidate.is_symlink(): + continue + try: + payload = json.loads(candidate.read_text(encoding='utf-8')) + except Exception as exc: + print(f'{candidate}: invalid JSON ({type(exc).__name__})') + continue + print(candidate) + if isinstance(payload, dict): + for key, value in payload.items(): + if isinstance(value, list): + print(f' {key}: list[{len(value)}]') + else: + print(f' {key}: {type(value).__name__}') + else: + print(f' root: {type(payload).__name__}') +PY diff --git a/deploy/panel-backup-restore-verify.mjs b/deploy/panel-backup-restore-verify.mjs new file mode 100644 index 0000000..cf17402 --- /dev/null +++ b/deploy/panel-backup-restore-verify.mjs @@ -0,0 +1,133 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) process.exit(2); +const panelBase = new URL(panelURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const databaseName = `svhr${suffix.slice(0, 8)}`; +const databasePassword = `Sv-${crypto.randomBytes(18).toString('base64url')}5b`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 60_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function requirePanelSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +async function panelDatabaseRows(search) { + const response = await panelForm('/data', { action: 'getData', table: 'databases', search, limit: '100', p: '1' }); + const rows = Array.isArray(response?.data) ? response.data : Array.isArray(response) ? response : undefined; + if (!rows) throw new Error('panel database listing failed'); + return rows; +} + +async function resolveDatabaseID(name) { + const matches = (await panelDatabaseRows(name)).filter((row) => row?.name === name || row?.username === name); + if (matches.length !== 1) throw new Error(`panel database lookup returned ${matches.length} exact matches`); + const id = Number(matches[0].id); + if (!Number.isSafeInteger(id) || id <= 0) throw new Error('panel returned invalid database id'); + return id; +} + +async function runShell(name, shell, marker, attempts = 180) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost backup restore verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) return log; + } + throw new Error(`temporary task failed: ${log.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +let databaseID; +try { + const created = requirePanelSuccess(await panelForm('/database', { + action: 'AddDatabase', sid: '0', name: databaseName, db_user: databaseName, password: databasePassword, + address: '127.0.0.1', codeing: 'utf8mb4', pid: '0', ps: 'Sea vHost restore verification', + }), 'temporary restore database creation'); + databaseID = Number(created.id); + if (!Number.isSafeInteger(databaseID) || databaseID <= 0) databaseID = await resolveDatabaseID(databaseName); + + const marker = `backup-restore-verified-${suffix}`; + const shell = [ + 'set -Eeuo pipefail', `test_id=${q(suffix)}`, `restore_db=${q(databaseName)}`, `restore_password=${q(databasePassword)}`, + 'work="/var/lib/sea-vhost/restore-verify-$test_id"; case "$work" in /var/lib/sea-vhost/restore-verify-????????????) ;; *) exit 1 ;; esac; test ! -e "$work"; install -d -o root -g root -m 0700 "$work" "$work/state" "$work/hosts"', + 'cleanup() { rm -rf -- "$work"; }; trap cleanup EXIT', + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; dump_bin="$(command -v mysqldump || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; if [[ -z "$dump_bin" && -x /www/server/mysql/bin/mysqldump ]]; then dump_bin=/www/server/mysql/bin/mysqldump; fi; test -x "$mysql_bin"; test -x "$dump_bin"', + 'host_name="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT host_name FROM projects WHERE host_name REGEXP \'^sv[0-9a-f]{10}$\' ORDER BY id LIMIT 1")"; test -n "$host_name"; test -d "/www/wwwroot/seavHost/vHost/$host_name"', + 'source_counts="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT CONCAT((SELECT COUNT(*) FROM tenants),\':\',(SELECT COUNT(*) FROM users),\':\',(SELECT COUNT(*) FROM projects),\':\',(SELECT COUNT(*) FROM sites),\':\',(SELECT COUNT(*) FROM ftp_accounts),\':\',(SELECT COUNT(*) FROM \\`databases\\`),\':\',(SELECT COUNT(*) FROM schema_migrations));")"', + 'MYSQL_PWD="$control_password" "$dump_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --single-transaction --skip-lock-tables --default-character-set=utf8mb4 "$control_name" >"$work/control.sql"; test -s "$work/control.sql"; chmod 0600 "$work/control.sql"', + 'MYSQL_PWD="$restore_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$restore_db" --database="$restore_db" <"$work/control.sql"', + 'restored_counts="$(MYSQL_PWD="$restore_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$restore_db" --database="$restore_db" --batch --skip-column-names --execute="SELECT CONCAT((SELECT COUNT(*) FROM tenants),\':\',(SELECT COUNT(*) FROM users),\':\',(SELECT COUNT(*) FROM projects),\':\',(SELECT COUNT(*) FROM sites),\':\',(SELECT COUNT(*) FROM ftp_accounts),\':\',(SELECT COUNT(*) FROM \\`databases\\`),\':\',(SELECT COUNT(*) FROM schema_migrations));")"; test "$source_counts" = "$restored_counts"', + 'tar --acls --xattrs --numeric-owner -cpf "$work/host.tar" -C /www/wwwroot/seavHost/vHost "$host_name"; test -s "$work/host.tar"; chmod 0600 "$work/host.tar"; tar --acls --xattrs --numeric-owner -xpf "$work/host.tar" -C "$work/hosts"; tar --acls --xattrs --numeric-owner --compare -f "$work/host.tar" -C "$work/hosts"', + 'tar --acls --xattrs --numeric-owner -cpf "$work/state.tar" -C / etc/sea-vhost/sea-vhost.env var/lib/sea-vhost/config.json var/lib/sea-vhost-panel/credentials.json var/lib/sea-vhost-panel/resources.json; chmod 0600 "$work/state.tar"; tar --acls --xattrs --numeric-owner -xpf "$work/state.tar" -C "$work/state"', + 'for relative in etc/sea-vhost/sea-vhost.env var/lib/sea-vhost/config.json var/lib/sea-vhost-panel/credentials.json var/lib/sea-vhost-panel/resources.json; do test "$(sha256sum "/$relative" | awk \'{print $1}\')" = "$(sha256sum "$work/state/$relative" | awk \'{print $1}\')"; done', + 'test "$(stat -c %a "$work/state/etc/sea-vhost/sea-vhost.env")" = 640; test "$(stat -c %a "$work/state/var/lib/sea-vhost/config.json")" = 600; test "$(stat -c %a "$work/state/var/lib/sea-vhost-panel/credentials.json")" = 600', + 'printf "database_counts=%s\\nhost_name=%s\\nstate_files=4\\n" "$restored_counts" "$host_name"', + `printf '%s\n' ${q(marker)}`, + ].join('\n'); + const log = await runShell(`Sea vHost restore verify ${suffix}`, shell, marker); + const databaseCounts = log.match(/(?:^|\n)database_counts=([^\r\n]+)/)?.[1]; + if (!databaseCounts) throw new Error('restore verification output was incomplete'); + console.log(JSON.stringify({ status: 'passed', checks: { + controlDatabaseDumpCreated: true, + controlDatabaseImportedIntoIsolatedDatabase: true, + restoredDatabaseObjectCountsMatch: true, + managedHostArchiveCreated: true, + managedHostArchiveMetadataAndContentMatch: true, + criticalStateArchiveCreated: true, + restoredStateChecksumsMatch: true, + restoredSecretFileModesMatch: true, + liveDataWasNotOverwritten: true, + }, restoredDatabaseObjectCounts: databaseCounts }, null, 2)); +} finally { + if (databaseID) { + try { await panelForm('/database', { action: 'DeleteDatabase', id: String(databaseID), sid: '0', name: databaseName, db_user: databaseName }); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-canary-verify.mjs b/deploy/panel-canary-verify.mjs new file mode 100644 index 0000000..ba90b57 --- /dev/null +++ b/deploy/panel-canary-verify.mjs @@ -0,0 +1,188 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.'); + process.exit(2); +} + +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +if (!['http:', 'https:'].includes(panelBase.protocol) || panelBase.username || panelBase.password || + !['http:', 'https:'].includes(consoleBase.protocol) || consoleBase.username || consoleBase.password) { + console.error('Panel and console URLs must be HTTP(S) URLs without embedded credentials.'); + process.exit(2); +} + +const client = panelBase.protocol === 'https:' ? https : http; +const agent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const canaryID = crypto.randomBytes(6).toString('hex'); +const marker = (scope) => `SEA_VHOST_CANARY_V1:${scope}:${canaryID}:${crypto.randomBytes(16).toString('hex')}`; +const markers = { + control: marker('control'), broker: marker('broker'), agent: marker('agent'), runtime: marker('runtime'), + hidden: marker('hidden-web'), env: marker('extension-web'), manifest: marker('manifest-web'), public: marker('public-baseline'), +}; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, panelBase), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function requireSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const shell = [ + 'set -euo pipefail', + 'umask 077', + `canary_id=${q(canaryID)}`, + `control_marker=${q(markers.control)}`, + `broker_marker=${q(markers.broker)}`, + `agent_marker=${q(markers.agent)}`, + `runtime_marker=${q(markers.runtime)}`, + `hidden_marker=${q(markers.hidden)}`, + `env_marker=${q(markers.env)}`, + `manifest_marker=${q(markers.manifest)}`, + `public_marker=${q(markers.public)}`, + "host_dir=\"$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print -quit)\"", + 'test -n "$host_dir"', + 'host_name="${host_dir##*/}"', + 'case "$host_name" in sv??????????) ;; *) exit 1 ;; esac', + 'site_conf="$(find /www/server/panel/vhost/nginx -maxdepth 1 -type f -name "$host_name*.conf" -print -quit)"', + 'test -n "$site_conf"', + 'site_domain="$(basename "$site_conf" .conf)"', + 'site_root="$(awk \'$1 == "root" { value=$2; sub(/;$/, "", value); print value; exit }\' "$site_conf")"', + 'test -n "$site_root"; site_root="$(realpath -e "$site_root")"', + 'case "$site_root/" in "$host_dir/"*) ;; *) printf \'site root escaped managed host\\n\'; exit 1 ;; esac', + 'control_dir=/var/lib/sea-vhost/security-canaries', + 'broker_dir=/var/lib/sea-vhost-panel/security-canaries', + 'agent_dir=/var/lib/sea-vhost-agent/security-canaries', + 'runtime_dir="$host_dir/.sea-runtime/security-canaries"', + 'web_dir="$site_root/.sea-vhost-canaries"', + 'install -d -o root -g sea-vhost-control -m 0750 "$control_dir"', + 'install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 "$broker_dir"', + 'install -d -o root -g root -m 0700 "$agent_dir"', + 'install -d -o "$host_name" -g "$host_name" -m 0700 "$runtime_dir"', + 'install -d -o "$host_name" -g "$host_name" -m 0750 "$web_dir"', + 'control_path="$control_dir/control-$canary_id.txt"', + 'broker_path="$broker_dir/broker-$canary_id.txt"', + 'agent_path="$agent_dir/agent-$canary_id.txt"', + 'runtime_path="$runtime_dir/runtime-$canary_id.txt"', + 'hidden_path="$web_dir/hidden-$canary_id.txt"', + 'env_path="$site_root/sea-vhost-canary-$canary_id.env"', + 'manifest_path="$site_root/requirements-sea-vhost-$canary_id.txt"', + 'public_path="$site_root/sea-vhost-canary-public-$canary_id.txt"', + 'link_path="$site_root/sea-vhost-canary-link-$canary_id"', + 'registry_path="$control_dir/registry-$canary_id.tsv"', + 'printf \'%s\\n\' "$control_marker" | install -o root -g sea-vhost-control -m 0640 /dev/stdin "$control_path"', + 'printf \'%s\\n\' "$broker_marker" | install -o sea-vhost-panel -g sea-vhost-panel-control -m 0600 /dev/stdin "$broker_path"', + 'printf \'%s\\n\' "$agent_marker" | install -o root -g root -m 0600 /dev/stdin "$agent_path"', + 'printf \'%s\\n\' "$runtime_marker" | install -o "$host_name" -g "$host_name" -m 0600 /dev/stdin "$runtime_path"', + 'printf \'%s\\n\' "$hidden_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$hidden_path"', + 'printf \'%s\\n\' "$env_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$env_path"', + 'printf \'%s\\n\' "$manifest_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$manifest_path"', + 'printf \'%s\\n\' "$public_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$public_path"', + 'ln -s "$runtime_path" "$link_path"', + 'setfacl -m u:www:r-x "$web_dir"; setfacl -m u:www:r-- "$hidden_path" "$env_path" "$manifest_path" "$public_path"', + 'printf \'scope\\tpath\\tmarker\\ncontrol\\t%s\\t%s\\nbroker\\t%s\\t%s\\nagent\\t%s\\t%s\\nruntime\\t%s\\t%s\\nhidden_web\\t%s\\t%s\\nextension_web\\t%s\\t%s\\nmanifest_web\\t%s\\t%s\\npublic_baseline\\t%s\\t%s\\nsymlink_probe\\t%s\\t%s\\n\' "$control_path" "$control_marker" "$broker_path" "$broker_marker" "$agent_path" "$agent_marker" "$runtime_path" "$runtime_marker" "$hidden_path" "$hidden_marker" "$env_path" "$env_marker" "$manifest_path" "$manifest_marker" "$public_path" "$public_marker" "$link_path" "$runtime_marker" | install -o root -g root -m 0600 /dev/stdin "$registry_path"', + 'expect_readable() { runuser -u "$1" -- grep -Fqx -- "$2" "$3" 2>/dev/null; }', + 'expect_denied() { if runuser -u "$1" -- grep -Fqx -- "$2" "$3" 2>/dev/null; then printf \'unexpected read: %s -> %s\\n\' "$1" "$3"; exit 1; fi; }', + 'expect_readable sea-vhost "$control_marker" "$control_path"', + 'expect_readable "$host_name" "$runtime_marker" "$runtime_path"', + 'expect_readable www "$public_marker" "$public_path"', + 'expect_readable www "$hidden_marker" "$hidden_path"', + 'for account in www nobody "$host_name"; do expect_denied "$account" "$control_marker" "$control_path"; expect_denied "$account" "$broker_marker" "$broker_path"; expect_denied "$account" "$agent_marker" "$agent_path"; done', + 'expect_denied sea-vhost "$broker_marker" "$broker_path"; expect_denied sea-vhost "$agent_marker" "$agent_path"', + 'expect_denied www "$runtime_marker" "$runtime_path"; expect_denied nobody "$runtime_marker" "$runtime_path"', + 'response_body="$(mktemp)"; trap \'rm -f "$response_body"\' EXIT', + 'public_status="$(curl --silent --show-error --path-as-is --max-time 8 --output "$response_body" --write-out \'%{http_code}\' --header "Host: $site_domain" "http://127.0.0.1/sea-vhost-canary-public-$canary_id.txt")"', + 'test "$public_status" = 200; grep -Fqx -- "$public_marker" "$response_body"', + 'probe_web_denied() { local path="$1" marker="$2" status; status="$(curl --silent --show-error --path-as-is --max-time 8 --output "$response_body" --write-out \'%{http_code}\' --header "Host: $site_domain" "http://127.0.0.1$path")"; case "$status" in 403|404) ;; *) printf \'unexpected HTTP status %s for %s\\n\' "$status" "$path"; exit 1 ;; esac; if grep -Fq -- "$marker" "$response_body"; then printf \'canary leaked over HTTP: %s\\n\' "$path"; exit 1; fi; }', + 'probe_web_denied "/.sea-vhost-canaries/hidden-$canary_id.txt" "$hidden_marker"', + 'probe_web_denied "/sea-vhost-canary-$canary_id.env" "$env_marker"', + 'probe_web_denied "/requirements-sea-vhost-$canary_id.txt" "$manifest_marker"', + 'probe_web_denied "/.sea-runtime/security-canaries/runtime-$canary_id.txt" "$runtime_marker"', + 'probe_web_denied "/sea-vhost-canary-link-$canary_id" "$runtime_marker"', + 'agent_status="$(curl --silent --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost/agent.sock --request POST --data \'{}\' http://localhost/v1/prepare)"', + 'broker_status="$(curl --silent --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost-panel/broker.sock --request POST --data \'{}\' http://localhost/v1/operations)"', + 'test "$agent_status" = 401; test "$broker_status" = 401', + 'printf \'canary_id=%s host=%s site=%s public_baseline=%s hidden_http=denied extension_http=denied manifest_http=denied runtime_http=denied symlink_http=denied os_boundaries=denied internal_sockets=401 registry=%s\\n\' "$canary_id" "$host_name" "$site_domain" "$public_status" "$registry_path"', + "printf '%s\\n' 'Sea vHost canary verification: success'", +].join('\n'); + +const taskName = `Sea vHost canary verify ${canaryID}`; +let taskID; +try { + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost security canary verification', save: '0', backupTo: 'localhost', + }), 'temporary canary task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes('Sea vHost canary verification: success') || log.includes('★[')) break; + } + if (!log.includes('Sea vHost canary verification: success')) throw new Error(`canary verification did not complete:\n${log.trim()}`); + if (Object.values(markers).some((value) => log.includes(value))) throw new Error('canary marker was written to the task log'); + + const unauthenticated = await fetch(new URL(`/api/v1/projects/1/files?path=.sea-runtime/security-canaries/runtime-${canaryID}.txt`, consoleBase), { + redirect: 'manual', signal: AbortSignal.timeout(10_000), + }); + if (unauthenticated.status !== 401 || (await unauthenticated.text()).includes(canaryID)) throw new Error('unauthenticated file API boundary failed'); + const crossOrigin = await fetch(new URL('/api/v1/projects/1/domains', consoleBase), { + method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(10_000), + headers: { Origin: 'https://attacker.invalid', 'Content-Type': 'application/json' }, + body: JSON.stringify({ domain: 'canary.invalid' }), + }); + if (crossOrigin.status !== 403 || (await crossOrigin.text()).includes(canaryID)) throw new Error('cross-origin API boundary failed'); + const consoleStatic = await fetch(new URL(`/.sea-vhost-canaries/${canaryID}.txt`, consoleBase), { + redirect: 'manual', signal: AbortSignal.timeout(10_000), + }); + if ((await consoleStatic.text()).includes(canaryID)) throw new Error('host canary appeared on the management console'); + + const summary = log.split(/\r?\n/).find((line) => line.startsWith('canary_id=')); + console.log(summary ?? `canary_id=${canaryID}`); + console.log('external_api_unauthenticated=401 external_api_cross_origin=403 console_canary_leak=no'); + console.log('Sea VHost canary verification: success'); +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} diff --git a/deploy/panel-certificate-dns-verify.mjs b/deploy/panel-certificate-dns-verify.mjs new file mode 100644 index 0000000..dac46d8 --- /dev/null +++ b/deploy/panel-certificate-dns-verify.mjs @@ -0,0 +1,230 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2); +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `certificate-${suffix}@seavhost.test`; +const password = `Sv-${crypto.randomBytes(18).toString('base64url')}9c`; +const dnsSecret = `svh-cloudflare-token-${crypto.randomBytes(18).toString('base64url')}`; +const dnsSecretUpdated = `svh-cloudflare-updated-${crypto.randomBytes(18).toString('base64url')}`; +const zoneID = crypto.randomBytes(16).toString('hex'); +const runDirectory = `certificate-${suffix}`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, marker, attempts = 120) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost certificate verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task'); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker) || log.includes('★[')) break; + } + if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`); + return log; + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +async function api(pathname, { method = 'GET', body, cookie, expected = [200], timeout = 30_000 } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, redirect: 'manual', signal: AbortSignal.timeout(timeout), + headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`); + return { response, payload, text }; +} + +function cookieFrom(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + return header?.split(';', 1)[0]; +} + +const dbParts = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', +].join('\n'); + +const seedMarker = `certificate-seeded-${suffix}`; +const seedShell = [ + 'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"', + dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Certificate verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + `printf '%s\n' ${q(seedMarker)}`, +].join('\n'); +const cleanupMarker = `certificate-cleaned-${suffix}`; +const cleanupShell = [ + 'set -euo pipefail', `email=${q(email)}`, `run_directory=${q(runDirectory)}`, dbParts, + 'project_root="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT root_path FROM projects ORDER BY id LIMIT 1")"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) rmdir -- "$project_root/$run_directory" 2>/dev/null || true ;; *) exit 1 ;; esac', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', + `printf '%s\n' ${q(cleanupMarker)}`, +].join('\n'); + +function decodeLogValue(log, name) { + const value = log.match(new RegExp(`(?:^|\\n)${name}=([A-Za-z0-9+/=]+)`))?.[1]; + if (!value) throw new Error(`certificate generator omitted ${name}`); + return Buffer.from(value, 'base64').toString('utf8'); +} + +let seeded = false; +let cookie; +let project; +let site; +let dnsCredentialID; +try { + await runShell(`Sea vHost certificate seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } }); + cookie = cookieFrom(login.response); + project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0]; + if (!project?.id) throw new Error('temporary tenant has no project'); + const created = await api(`/api/v1/projects/${project.id}/sites`, { + method: 'POST', cookie, expected: [201], + body: { name: `certificate-${suffix}`, runtime: 'PHP', version: project.version, runPath: `/${runDirectory}`, customDomain: '', autoSSL: false }, + }); + site = created.payload?.site; + if (!site?.id || !site?.domain) throw new Error('temporary certificate site was not created'); + + const generatedMarker = `certificate-generated-${suffix}`; + const generationShell = [ + 'set -euo pipefail', `domain=${q(site.domain)}`, 'work="$(mktemp -d /tmp/sea-vhost-certificate.XXXXXX)"; trap \'rm -rf -- "$work"\' EXIT', + 'openssl ecparam -name prime256v1 -genkey -noout -out "$work/key.pem"; openssl req -x509 -new -key "$work/key.pem" -days 2 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -addext "basicConstraints=critical,CA:FALSE" -addext "keyUsage=critical,digitalSignature" -addext "extendedKeyUsage=serverAuth" -out "$work/cert.pem" >/dev/null 2>&1', + 'openssl ecparam -name prime256v1 -genkey -noout -out "$work/wrong-domain-key.pem"; openssl req -x509 -new -key "$work/wrong-domain-key.pem" -days 2 -subj "/CN=wrong.example.invalid" -addext "subjectAltName=DNS:wrong.example.invalid" -addext "basicConstraints=critical,CA:FALSE" -addext "keyUsage=critical,digitalSignature" -addext "extendedKeyUsage=serverAuth" -out "$work/wrong-domain-cert.pem" >/dev/null 2>&1', + 'openssl ecparam -name prime256v1 -genkey -noout -out "$work/wrong-key.pem"', + 'printf "CERT_B64=%s\\n" "$(base64 -w0 "$work/cert.pem")"; printf "KEY_B64=%s\\n" "$(base64 -w0 "$work/key.pem")"; printf "WRONG_CERT_B64=%s\\n" "$(base64 -w0 "$work/wrong-domain-cert.pem")"; printf "WRONG_DOMAIN_KEY_B64=%s\\n" "$(base64 -w0 "$work/wrong-domain-key.pem")"; printf "WRONG_KEY_B64=%s\\n" "$(base64 -w0 "$work/wrong-key.pem")"', + `printf '%s\n' ${q(generatedMarker)}`, + ].join('\n'); + const generated = await runShell(`Sea vHost certificate generate ${suffix}`, generationShell, generatedMarker); + const certificate = decodeLogValue(generated, 'CERT_B64'); + const privateKey = decodeLogValue(generated, 'KEY_B64'); + const wrongCertificate = decodeLogValue(generated, 'WRONG_CERT_B64'); + const wrongDomainKey = decodeLogValue(generated, 'WRONG_DOMAIN_KEY_B64'); + const wrongKey = decodeLogValue(generated, 'WRONG_KEY_B64'); + const manualPath = `/api/v1/projects/${project.id}/sites/${site.id}/certificate/manual`; + await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate: 'not-a-certificate', privateKey } }); + await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate: wrongCertificate, privateKey: wrongDomainKey } }); + await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate, privateKey: wrongKey } }); + await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate, privateKey: '' } }); + const installed = await api(manualPath, { method: 'PUT', cookie, body: { certificate, privateKey } }); + if (installed.payload?.site?.sslStatus !== 'active') throw new Error('valid manual certificate did not become active'); + await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { method: 'DELETE', cookie }); + + const autoResult = await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate/auto`, { + method: 'POST', cookie, expected: [200, 422], timeout: 180_000, + }); + const automation = await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { cookie }); + const autoSucceeded = autoResult.response.status === 200; + const http01FailureStatePersisted = autoSucceeded || (automation.payload?.automation?.mode === 'http-01' && Boolean(automation.payload?.automation?.lastError)); + if (autoSucceeded) await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { method: 'DELETE', cookie }); + + const createdCredential = await api('/api/v1/dns-credentials', { + method: 'POST', cookie, expected: [201], body: { + label: `Cloudflare test ${suffix}`, provider: 'cloudflare', zoneName: 'example.invalid', credential: { apiToken: dnsSecret, zoneId: zoneID }, + }, + }); + dnsCredentialID = createdCredential.payload?.credential?.id; + if (!dnsCredentialID) throw new Error('DNS credential was not created'); + const listed = await api('/api/v1/dns-credentials', { cookie }); + if (listed.text.includes(dnsSecret) || listed.text.includes(zoneID) || !listed.payload?.credentials?.some((item) => item.id === dnsCredentialID)) { + throw new Error('DNS credential list leaked or omitted credential data'); + } + const encryptedMarker = `dns-encrypted-${suffix}`; + const encryptedShell = [ + 'set -euo pipefail', `credential_id=${dnsCredentialID}`, `secret=${q(dnsSecret)}`, dbParts, + 'found="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT IF(LOCATE(HEX(\'$secret\'),HEX(credential_ciphertext))=0,0,1) FROM dns_credentials WHERE id=$credential_id")"; test "$found" = 0', + `printf '%s\n' ${q(encryptedMarker)}`, + ].join('\n'); + await runShell(`Sea vHost DNS encryption ${suffix}`, encryptedShell, encryptedMarker); + + const failedTest = await api(`/api/v1/dns-credentials/${dnsCredentialID}/test`, { method: 'POST', cookie, expected: [422], timeout: 60_000 }); + if (failedTest.text.includes(dnsSecret) || failedTest.text.includes(zoneID)) throw new Error('DNS test failure leaked credentials'); + const cooldown = await api(`/api/v1/dns-credentials/${dnsCredentialID}/test`, { method: 'POST', cookie, expected: [429] }); + if (!cooldown.response.headers.get('retry-after')) throw new Error('DNS test cooldown omitted Retry-After'); + const updated = await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { + method: 'PUT', cookie, body: { + label: `Cloudflare updated ${suffix}`, provider: 'cloudflare', zoneName: 'example.invalid', credential: { apiToken: dnsSecretUpdated, zoneId: zoneID }, + }, + }); + if (updated.payload?.credential?.testStatus !== 'untested' || updated.text.includes(dnsSecretUpdated)) throw new Error('DNS credential update was not safely reset'); + await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { method: 'DELETE', cookie, expected: [204] }); + dnsCredentialID = undefined; + + console.log(JSON.stringify({ status: http01FailureStatePersisted ? 'passed' : 'failed', checks: { + malformedCertificateRejected: true, + hostnameMismatchRejected: true, + mismatchedPrivateKeyRejected: true, + incompletePairRejected: true, + validManualCertificateInstalled: true, + manualCertificateDisabled: true, + http01AttemptCompleted: true, + http01FailureStatePersisted, + http01Issued: autoSucceeded, + dnsCredentialEncryptedAtRest: true, + dnsCredentialSecretsOmittedFromAPI: true, + dnsCredentialFailureDoesNotLeakSecret: true, + dnsCredentialCooldownEnforced: true, + dnsCredentialUpdateAndDelete: true, + }, http01Result: autoSucceeded ? 'issued' : 'failed_in_current_port_forwarding_environment' }, null, 2)); + if (!http01FailureStatePersisted) process.exitCode = 1; +} finally { + if (dnsCredentialID && cookie) { + try { await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { method: 'DELETE', cookie, expected: [204, 404] }); } catch { process.exitCode = 1; } + } + if (site?.id && project?.id && cookie) { + try { await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); } catch { process.exitCode = 1; } + } + if (seeded) { + try { await runShell(`Sea vHost certificate cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-clean-temporary-tasks.mjs b/deploy/panel-clean-temporary-tasks.mjs new file mode 100644 index 0000000..212c279 --- /dev/null +++ b/deploy/panel-clean-temporary-tasks.mjs @@ -0,0 +1,44 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const prefix = process.env.SEA_PANEL_TASK_PREFIX?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !prefix || prefix.length < 12 || prefix.length > 80 || /[\r\n]/.test(prefix)) process.exit(2); +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function panelForm(pathname, values) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { method: 'POST', agent, timeout: 30_000, headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length } }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`aaPanel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('aaPanel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function rows(payload) { + if (Array.isArray(payload)) return payload; + if (Array.isArray(payload?.data)) return payload.data; + if (Array.isArray(payload?.data?.data)) return payload.data.data; + return []; +} +const listing = await panelForm('/crontab', { action: 'GetCrontab' }); +const matches = rows(listing).filter((item) => String(item.name ?? item.sName ?? '').startsWith(prefix)); +for (const item of matches) { + const id = Number(item.id); + if (Number.isSafeInteger(id) && id > 0) await panelForm('/crontab', { action: 'DelCrontab', id: String(id) }); +} +console.log(JSON.stringify({ removed: matches.length, prefix })); diff --git a/deploy/panel-create-management-site.mjs b/deploy/panel-create-management-site.mjs new file mode 100644 index 0000000..ed5e845 --- /dev/null +++ b/deploy/panel-create-management-site.mjs @@ -0,0 +1,117 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const managementDomain = process.env.SEA_MANAGEMENT_DOMAIN?.trim().toLowerCase(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !managementDomain) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_MANAGEMENT_DOMAIN are required.'); + process.exit(2); +} +if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(managementDomain)) { + console.error('SEA_MANAGEMENT_DOMAIN must be a valid domain name.'); + process.exit(2); +} + +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function panelForm(pathname, values, timeoutMs = 30_000) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ + ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)), + }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: timeoutMs, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 4 * 1024 * 1024) request.destroy(new Error('panel response exceeded 4 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`aaPanel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('aaPanel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function rows(payload) { + if (Array.isArray(payload?.data)) return payload.data; + if (Array.isArray(payload?.data?.data)) return payload.data.data; + return []; +} +function message(payload) { + return String(payload?.msg ?? payload?.message ?? 'aaPanel rejected the operation').slice(0, 300); +} + +const listing = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: managementDomain }); +const existing = rows(listing).find((site) => String(site.name ?? '').toLowerCase() === managementDomain); +let siteID = Number(existing?.id ?? 0); +let created = false; +if (!Number.isSafeInteger(siteID) || siteID <= 0) { + const webname = JSON.stringify({ domain: managementDomain, domainlist: [], count: 0 }); + const createdSite = await panelForm('/site', { + action: 'AddSite', webname, path: '/opt/sea-vhost/web', type: '', version: '00', port: '80', + ps: 'Sea vHost management console', ftp: 'false', sql: 'false', + }); + if (createdSite?.status === false || createdSite?.status === 'false' || createdSite?.siteStatus === false) { + throw new Error(`management site creation failed: ${message(createdSite)}`); + } + siteID = Number(createdSite.siteId ?? createdSite.siteID ?? createdSite.id); + if (!Number.isSafeInteger(siteID) || siteID <= 0) throw new Error('aaPanel did not return the management site id'); + created = true; +} + +const domains = JSON.stringify([managementDomain]); +const order = await panelForm('/acme', { + action: 'apply_cert_api', id: String(siteID), domains, auth_type: 'http', auth_to: '/opt/sea-vhost/web', ca: 'letsencrypt', +}, 60_000); +if (order?.status === false || order?.status === 'false') throw new Error(`certificate order failed: ${message(order)}`); +const orderIndex = String(order?.index ?? '').trim(); +if (!orderIndex) { + if (order?.status === true && typeof order?.cert === 'string' && typeof order?.private_key === 'string') { + const certificateChain = typeof order?.root === 'string' && order.root.includes('BEGIN CERTIFICATE') + ? `${order.cert.trim()}\n${order.root.trim()}\n` + : order.cert; + const installed = await panelForm('/site', { + action: 'SetSSL', siteName: managementDomain, key: order.private_key, csr: certificateChain, + }); + if (installed?.status === false || installed?.status === 'false') { + throw new Error(`certificate deployment failed: ${message(installed)}`); + } + console.log(JSON.stringify({ result: 'success', managementDomain, siteID, siteCreated: created, certificate: 'valid' }, null, 2)); + process.exit(0); + } + const shape = Object.fromEntries(Object.entries(order ?? {}).map(([key, value]) => [key, Array.isArray(value) ? 'array' : typeof value])); + throw new Error(`aaPanel did not return an ACME order index; response shape: ${JSON.stringify(shape).slice(0, 600)}`); +} +let status = String(order?.status ?? '').toLowerCase(); +for (let attempt = 0; status !== 'valid'; attempt += 1) { + if (['expired', 'invalid', 'revoked', 'deactivated'].includes(status)) { + throw new Error(`certificate order ended with status ${status}`); + } + if (attempt >= 45) throw new Error('certificate order did not become valid before the timeout'); + await new Promise((resolve) => setTimeout(resolve, 2000)); + const detail = await panelForm('/acme', { action: 'get_order_find', index: orderIndex }); + if (detail?.status === false || detail?.status === 'false') throw new Error(`certificate status check failed: ${message(detail)}`); + status = String(detail?.status ?? '').toLowerCase(); +} +const deployed = await panelForm('/acme', { action: 'SetCertToSite', index: orderIndex, siteName: managementDomain }); +if (deployed?.status === false || deployed?.status === 'false') { + throw new Error(`certificate deployment failed: ${message(deployed)}`); +} + +console.log(JSON.stringify({ result: 'success', managementDomain, siteID, siteCreated: created, certificate: 'valid' }, null, 2)); diff --git a/deploy/panel-data-services-verify.mjs b/deploy/panel-data-services-verify.mjs new file mode 100644 index 0000000..c0ebc46 --- /dev/null +++ b/deploy/panel-data-services-verify.mjs @@ -0,0 +1,323 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; +import { spawnSync } from 'node:child_process'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.'); + process.exit(2); +} +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const tenantEmail = `data-${suffix}@seavhost.test`; +const tenantPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}7d`; +const planName = `Data verification ${suffix}`; +const statePath = `/var/lib/sea-vhost/data-verify-${suffix}.state`; +const symlinkName = `ftp-escape-${suffix}`; +const quotaTable = `svh_quota_${suffix}`; +const otherDatabase = `svhx${suffix.slice(0, 10)}`; +const otherPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}6e`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +async function runShell(name, shell, marker, attempts = 120) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost data service verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary verification task'); + const taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned invalid task id'); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker) || log.includes('★[')) break; + } + if (!log.includes(marker)) throw new Error(`temporary verification task failed:\n${log.trim()}`); + return log; + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} +async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, redirect: 'manual', signal: AbortSignal.timeout(30_000), + headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`); + return { response, payload }; +} +function cookieFrom(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + const cookie = header?.split(';', 1)[0]; + if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie'); + return cookie; +} +function requirePanelSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +async function panelDatabaseRows(search) { + const response = await panelForm('/data', { action: 'getData', table: 'databases', search, limit: '100', p: '1' }); + const rows = Array.isArray(response?.data) ? response.data : Array.isArray(response) ? response : undefined; + if (!rows) throw new Error('panel database listing failed'); + return rows; +} + +async function resolveDatabaseID(name) { + const matches = (await panelDatabaseRows(name)).filter((row) => row?.name === name || row?.username === name); + if (matches.length !== 1) throw new Error(`panel database lookup returned ${matches.length} exact matches`); + const id = Number(matches[0].id); + if (!Number.isSafeInteger(id) || id <= 0) throw new Error('panel returned invalid database id'); + return id; +} + +async function cleanupOrphanTestDatabases() { + for (const row of await panelDatabaseRows('svhx')) { + const name = typeof row?.name === 'string' ? row.name : ''; + const id = Number(row?.id); + if (!/^svhx[0-9a-f]{10}$/.test(name) || !Number.isSafeInteger(id) || id <= 0) continue; + await panelForm('/database', { action: 'DeleteDatabase', id: String(id), sid: '0', name, db_user: name }); + } +} + +const dbPartsShell = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'test "${#control_db[@]}" -eq 5; control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"', +].join('\n'); +const seedMarker = `data-seeded-${suffix}`; +const seedShell = [ + 'set -Eeuo pipefail', + `tenant_email=${q(tenantEmail)}`, + `tenant_password=${q(tenantPassword)}`, + `plan_name=${q(planName)}`, + `state_path=${q(statePath)}`, + `symlink_name=${q(symlinkName)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; test -x "$php_bin"', + 'tenant_password_hash="$(TEST_PASSWORD="$tenant_password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#tenant_password_hash}" -gt 50', + dbPartsShell, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$tenant_email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$tenant_email\',\'$tenant_email\',\'Data verification\',\'$tenant_password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + 'read -r tenant_id original_plan_id project_root < <(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")', + 'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; host_name="${project_root##*/}"', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',67108864,8388608,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"', + 'temp_plan_id="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"', + 'ln -s /etc/passwd "$project_root/$symlink_name"; chown -h "$host_name:$host_name" "$project_root/$symlink_name"', + 'printf "%s %s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" "$project_root" | install -o root -g root -m 0600 /dev/stdin "$state_path"', + `printf '%s\\n' ${q(seedMarker)}`, +].join('\n'); +const cleanupMarker = `data-cleaned-${suffix}`; +const cleanupShell = [ + 'set -euo pipefail', + `tenant_email=${q(tenantEmail)}`, + `state_path=${q(statePath)}`, + `symlink_name=${q(symlinkName)}`, + dbPartsShell, + 'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id project_root <"$state_path"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) rm -f -- "$project_root/$symlink_name" ;; *) exit 1 ;; esac; MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$tenant_email\';"', + `printf '%s\\n' ${q(cleanupMarker)}`, +].join('\n'); + +function ftpCurl(credentials, extraArgs, input, expectSuccess = true) { + const host = panelBase.hostname; + const args = ['--silent', '--show-error', '--fail', '--ftp-skip-pasv-ip', '--connect-timeout', '10', '--max-time', '35', '--user', `${credentials.ftpUsername}:${credentials.ftpPassword}`, ...extraArgs]; + const result = spawnSync('curl.exe', args, { input, maxBuffer: 4 * 1024 * 1024 }); + if (expectSuccess && result.status !== 0) throw new Error(`FTP command failed with exit ${result.status}`); + if (!expectSuccess && result.status === 0) throw new Error('FTP escape probe unexpectedly succeeded'); + return result.stdout; +} + +function ftpURL(name = '') { + return `ftp://${panelBase.hostname}:21/${name}`; +} + +function projectDatabaseShell(credentials, body, marker) { + return [ + 'set -euo pipefail', + `db_user=${q(credentials.databaseUsername)}`, + `db_password=${q(credentials.databasePassword)}`, + `db_name=${q(credentials.databaseName)}`, + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"', + body, + `printf '%s\\n' ${q(marker)}`, + ].join('\n'); +} + +let seeded = false; +let otherDatabaseID; +let credentials; +let tenantCookie; +let project; +let initiallyRunning = false; +try { + await cleanupOrphanTestDatabases(); + await runShell(`Sea vHost data seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantEmail, password: tenantPassword } }); + tenantCookie = cookieFrom(login.response); + const projects = await api('/api/v1/projects', { cookie: tenantCookie }); + project = projects.payload?.projects?.[0]; + if (!project?.id) throw new Error('temporary tenant has no project'); + initiallyRunning = project.status === 'running'; + const credentialResponse = await api(`/api/v1/projects/${project.id}/credentials`, { cookie: tenantCookie }); + credentials = credentialResponse.payload?.credentials; + if (!credentials?.ftpUsername || !credentials?.ftpPassword || !credentials?.databaseName || !credentials?.databaseUsername || !credentials?.databasePassword) { + throw new Error('project credentials are incomplete'); + } + + const ftpName = `verify-${suffix}.txt`; + const renamedFTPName = `verify-${suffix}-renamed.txt`; + const ftpPayload = Buffer.from(`sea-vhost-ftp-${suffix}`); + let externalFTPPassiveTransfer = false; + try { + ftpCurl(credentials, ['--upload-file', '-', ftpURL(ftpName)], ftpPayload); + const downloaded = ftpCurl(credentials, [ftpURL(ftpName)]); + if (!downloaded.equals(ftpPayload)) throw new Error('FTP download did not match upload'); + ftpCurl(credentials, ['--quote', `RNFR ${ftpName}`, '--quote', `RNTO ${renamedFTPName}`, ftpURL()]); + const renamedDownload = ftpCurl(credentials, [ftpURL(renamedFTPName)]); + if (!renamedDownload.equals(ftpPayload)) throw new Error('FTP rename did not preserve data'); + ftpCurl(credentials, ['--quote', `DELE ${renamedFTPName}`, ftpURL()]); + ftpCurl(credentials, [ftpURL(symlinkName)], undefined, false); + ftpCurl(credentials, ['--path-as-is', ftpURL('../../etc/passwd')], undefined, false); + externalFTPPassiveTransfer = true; + } catch { + console.log('ftp_external_passive_data_channel=unavailable'); + } + const ftpLoopbackMarker = `ftp-loopback-${suffix}`; + const ftpLoopbackShell = [ + 'set -euo pipefail', + `ftp_user=${q(credentials.ftpUsername)}`, + `ftp_password=${q(credentials.ftpPassword)}`, + `ftp_name=${q(ftpName)}`, + `renamed_name=${q(renamedFTPName)}`, + `symlink_name=${q(symlinkName)}`, + `payload=${q(ftpPayload.toString())}`, + 'ftp_base=ftp://127.0.0.1:21', + 'printf "%s" "$payload" | curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" --upload-file - "$ftp_base/$ftp_name"', + 'test "$(curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/$ftp_name")" = "$payload"', + 'curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" --quote "RNFR $ftp_name" --quote "RNTO $renamed_name" "$ftp_base/" >/dev/null', + 'test "$(curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/$renamed_name")" = "$payload"', + 'curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" --quote "DELE $renamed_name" "$ftp_base/" >/dev/null', + 'if curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/$symlink_name" >/dev/null 2>&1; then printf "ftp_symlink_escape=allowed\\n" >&2; exit 1; fi', + 'if curl --silent --show-error --fail --ftp-skip-pasv-ip --path-as-is --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/../../etc/passwd" >/dev/null 2>&1; then printf "ftp_parent_escape=allowed\\n" >&2; exit 1; fi', + ].join('\n'); + await runShell(`Sea vHost FTP loopback ${suffix}`, `${ftpLoopbackShell}\nprintf '%s\\n' ${q(ftpLoopbackMarker)}`, ftpLoopbackMarker); + + const other = requirePanelSuccess(await panelForm('/database', { + action: 'AddDatabase', sid: '0', name: otherDatabase, db_user: otherDatabase, password: otherPassword, + address: '127.0.0.1', codeing: 'utf8mb4', pid: '0', ps: 'Sea vHost isolation verification', + }), 'temporary cross-database creation'); + otherDatabaseID = Number(other.id); + if (!Number.isSafeInteger(otherDatabaseID) || otherDatabaseID <= 0) otherDatabaseID = await resolveDatabaseID(otherDatabase); + const isolationMarker = `database-isolation-${suffix}`; + const ownTable = `svh_own_${suffix}`; + await runShell(`Sea vHost database isolation ${suffix}`, projectDatabaseShell(credentials, [ + `MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="CREATE TABLE ${ownTable}(value VARCHAR(80)); INSERT INTO ${ownTable} VALUES (\'${suffix}\'); SELECT value FROM ${ownTable}; DROP TABLE ${ownTable};" >/dev/null`, + `if MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database=${q(otherDatabase)} --execute="SELECT 1" >/dev/null 2>&1; then printf 'cross_database_access=allowed\\n' >&2; exit 1; fi`, + ].join('\n'), isolationMarker), isolationMarker); + + const fillMarker = `database-filled-${suffix}`; + await runShell(`Sea vHost database quota fill ${suffix}`, projectDatabaseShell(credentials, [ + `MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="DROP TABLE IF EXISTS ${quotaTable}; CREATE TABLE ${quotaTable}(payload LONGBLOB NOT NULL) ENGINE=InnoDB;"`, + `for index in $(seq 1 12); do MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="INSERT INTO ${quotaTable}(payload) VALUES (REPEAT(\'x\',1048576));"; done`, + ].join('\n'), fillMarker), fillMarker); + console.log('database_quota_payload=created'); + + let suspendedProject; + for (let attempt = 0; attempt < 12; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 10_000)); + const current = await api('/api/v1/projects', { cookie: tenantCookie }); + suspendedProject = current.payload?.projects?.find((item) => item.id === project.id); + if (suspendedProject?.status === 'quota_suspended') break; + } + if (suspendedProject?.status !== 'quota_suspended') throw new Error(`database quota did not suspend project; status=${suspendedProject?.status}`); + const suspendedResources = await api('/api/v1/resources', { cookie: tenantCookie }); + const databaseResource = suspendedResources.payload?.databases?.find((item) => item.projectId === project.id); + if (databaseResource?.status !== 'quota_suspended' || databaseResource.sizeBytes < 8 * 1024 * 1024) throw new Error('database quota usage/status was not recorded'); + await api(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie: tenantCookie, expected: [423], body: { path: `blocked-${suffix}.txt`, content: 'blocked', overwrite: false }, + }); + ftpCurl(credentials, [ftpURL()], undefined, false); + + const dropMarker = `database-dropped-${suffix}`; + await runShell(`Sea vHost database quota cleanup ${suffix}`, projectDatabaseShell(credentials, + `MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="DROP TABLE IF EXISTS ${quotaTable};"`, dropMarker), dropMarker); + console.log('database_quota_payload=removed'); + let recoveredProject; + for (let attempt = 0; attempt < 12; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 10_000)); + const current = await api('/api/v1/projects', { cookie: tenantCookie }); + recoveredProject = current.payload?.projects?.find((item) => item.id === project.id); + if (recoveredProject?.status === 'stopped') break; + } + if (recoveredProject?.status !== 'stopped') throw new Error(`database quota did not recover to stopped; status=${recoveredProject?.status}`); + const recoveredResources = await api('/api/v1/resources', { cookie: tenantCookie }); + const recoveredDatabase = recoveredResources.payload?.databases?.find((item) => item.projectId === project.id); + if (recoveredDatabase?.status !== 'active' || recoveredDatabase.sizeBytes >= 8 * 1024 * 1024) throw new Error('database quota resource did not recover'); + if (initiallyRunning) await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie: tenantCookie, expected: [204], body: { enabled: true } }); + + console.log(JSON.stringify({ status: 'passed', checks: { + ftpLoginUploadDownloadRenameDelete: true, ftpLoopbackPassiveTransfer: true, externalFTPPassiveTransfer, + ftpSymlinkEscapeDenied: true, + ftpParentTraversalDenied: true, mysqlOwnDatabaseReadWrite: true, mysqlCrossDatabaseDenied: true, + databaseQuotaMeasured: true, databaseQuotaSuspendedProject: true, databaseQuotaBlockedControlWrites: true, + databaseQuotaDisabledFTP: true, databaseQuotaRecoveredToStopped: true, manualRestartAfterRecovery: initiallyRunning, + } }, null, 2)); +} finally { + if (credentials) { + const marker = `database-final-cleanup-${suffix}`; + try { + await runShell(`Sea vHost database final cleanup ${suffix}`, projectDatabaseShell(credentials, + `MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="DROP TABLE IF EXISTS ${quotaTable};"`, marker), marker, 60); + } catch { /* best effort */ } + } + if (otherDatabaseID) { + try { await panelForm('/database', { action: 'DeleteDatabase', id: String(otherDatabaseID), sid: '0', name: otherDatabase, db_user: otherDatabase }); } catch { /* best effort */ } + } + if (seeded) { + try { await runShell(`Sea vHost data cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch (error) { + console.error(`temporary data cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`); + process.exitCode = 1; + } + } +} diff --git a/deploy/panel-delete-site.mjs b/deploy/panel-delete-site.mjs new file mode 100644 index 0000000..ba4b3a2 --- /dev/null +++ b/deploy/panel-delete-site.mjs @@ -0,0 +1,93 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const siteName = process.env.SEA_SITE_NAME?.trim().toLowerCase(); +const expectedPath = process.env.SEA_EXPECTED_SITE_PATH?.trim(); +const protectedSite = process.env.SEA_PROTECTED_SITE_NAME?.trim().toLowerCase(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; + +if (!panelURL || !panelAPIKey || !siteName || !expectedPath || !protectedSite) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_SITE_NAME, SEA_EXPECTED_SITE_PATH and SEA_PROTECTED_SITE_NAME are required.'); + process.exit(2); +} +if (siteName === protectedSite) { + console.error('Refusing to delete the protected site.'); + process.exit(2); +} + +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); + +function panelForm(pathname, values) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ + ...values, + request_time: requestTime, + request_token: md5(requestTime + md5(panelAPIKey)), + }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 4 * 1024 * 1024) request.destroy(new Error('panel response exceeded 4 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`aaPanel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('aaPanel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function rows(payload) { + if (Array.isArray(payload?.data)) return payload.data; + if (Array.isArray(payload?.data?.data)) return payload.data.data; + return []; +} + +const before = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: siteName }); +const exact = rows(before).filter((site) => String(site.name ?? '').toLowerCase() === siteName); +if (exact.length === 0) { + console.log(JSON.stringify({ result: 'absent', siteName }, null, 2)); + process.exit(0); +} +if (exact.length !== 1) throw new Error(`expected one exact site match, received ${exact.length}`); + +const site = exact[0]; +const siteID = Number(site.id); +const sitePath = String(site.path ?? ''); +if (!Number.isSafeInteger(siteID) || siteID <= 0) throw new Error('aaPanel returned an invalid site id'); +if (sitePath !== expectedPath) throw new Error(`site path precondition failed: ${sitePath}`); + +const deleted = await panelForm('/site', { action: 'DeleteSite', id: String(siteID), webname: siteName }); +if (!deleted || (deleted.status !== true && deleted.status !== 'true')) { + throw new Error(`site deletion was rejected: ${String(deleted?.msg ?? deleted?.message ?? 'unknown error').slice(0, 300)}`); +} + +const after = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: siteName }); +if (rows(after).some((candidate) => String(candidate.name ?? '').toLowerCase() === siteName)) { + throw new Error('site still exists after aaPanel reported successful deletion'); +} + +const protectedListing = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: protectedSite }); +const protectedRow = rows(protectedListing).find((candidate) => String(candidate.name ?? '').toLowerCase() === protectedSite); +if (!protectedRow) throw new Error('protected site is missing after deletion'); +if (String(protectedRow.path ?? '') !== expectedPath) throw new Error('protected site path changed unexpectedly'); + +console.log(JSON.stringify({ result: 'deleted', siteName, siteID, protectedSite, sharedPathPreserved: true }, null, 2)); diff --git a/deploy/panel-diagnose.mjs b/deploy/panel-diagnose.mjs new file mode 100644 index 0000000..379ae90 --- /dev/null +++ b/deploy/panel-diagnose.mjs @@ -0,0 +1,129 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} +const base = new URL(baseURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; +} +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function requireSuccess(payload, operation) { + if (payload === true || payload === 'true') return payload; + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +const nonce = Date.now().toString().slice(-7); +const taskName = `Sea vHost diagnostics ${nonce}`; +const shell = [ + 'set -eo pipefail', + "printf '%s\\n' '=== services ==='", + "systemctl is-active sea-vhost-agent sea-vhost-panel-broker sea-vhost-api || true", + "systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p ActiveState -p SubState -p Result --no-pager", + "printf '%s\\n' '=== api journal ==='", + "journalctl -u sea-vhost-api -n 10 --no-pager -o cat || true", + "printf '%s\\n' '=== agent journal ==='", + "journalctl -u sea-vhost-agent -n 10 --no-pager -o cat || true", + "printf '%s\\n' '=== broker journal ==='", + "journalctl -u sea-vhost-panel-broker -n 10 --no-pager -o cat || true", + "printf '%s\\n' '=== service security properties ==='", + "systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p User -p Group -p SupplementaryGroups -p NoNewPrivileges -p PrivateNetwork -p PrivateDevices -p ProtectSystem -p ProtectHome -p ReadWritePaths -p CapabilityBoundingSet -p RestrictAddressFamilies -p IPAddressDeny -p IPAddressAllow --no-pager", + "printf '%s\\n' '=== sensitive path permissions ==='", + "stat -Lc '%A %a %U:%G %n' /etc/sea-vhost/sea-vhost.env /var/lib/sea-vhost/config.json /var/lib/sea-vhost-panel /var/lib/sea-vhost-panel/credentials.json /var/lib/sea-vhost-panel/resources.json /run/sea-vhost/agent.sock /run/sea-vhost-panel/broker.sock 2>&1 || true", + "printf '%s\\n' '=== managed path metadata ==='", + "id sea-vhost || true", + "find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 3 -path '/www/wwwroot/seavHost/vHost/.sea-vhost-quarantine' -prune -o -printf '%M %u:%g %p -> %l\\n' 2>&1 | tail -n 40 || true", + "cd / && runuser -u sea-vhost -- find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 3 -path '/www/wwwroot/seavHost/vHost/.sea-vhost-quarantine' -prune -o -printf '%M %u:%g %p\\n' 2>&1 | tail -n 40 || true", + "printf '%s\\n' '=== shared www boundary probe (permission checks only) ==='", + "find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print0 | while IFS= read -r -d '' dir; do readable=no; writable=no; runuser -u www -- test -r \"$dir\" && readable=yes; runuser -u www -- test -w \"$dir\" && writable=yes; printf 'www_access path=%s read=%s write=%s\\n' \"$dir\" \"$readable\" \"$writable\"; done", + "printf '%s\\n' '=== listening sockets ==='", + "ss -lntp 2>&1 | grep -E '(^State|:21\\b|:80\\b|:443\\b|:3306\\b|:8080\\b|:8888\\b|:10115\\b)' || true", + "printf '%s\\n' '=== FTP confinement settings ==='", + "grep -E '^[[:space:]]*(ChrootEveryone|NoAnonymous|TLS|PassivePortRange|MaxClientsNumber|MaxClientsPerIP|Umask|UnixAuthentication|PAMAuthentication|PureDB)[[:space:]]' /www/server/pure-ftpd/etc/pure-ftpd.conf 2>&1 || true", + "systemctl show pure-ftpd.service -p FragmentPath -p ExecStart -p MainPID --no-pager 2>&1 || true; ftp_pid=\"$(systemctl show pure-ftpd.service -p MainPID --value 2>/dev/null || true)\"; if [[ \"$ftp_pid\" =~ ^[1-9][0-9]*$ && -r \"/proc/$ftp_pid/cmdline\" ]]; then tr '\\0' ' ' <\"/proc/$ftp_pid/cmdline\"; printf '\\n'; fi", + "printf '%s\\n' '=== per-host identity prerequisites ==='", + "for tool in useradd usermod setfacl getfacl; do command -v \"$tool\" || printf 'missing:%s\\n' \"$tool\"; done; stat -Lc '%A %a %U:%G %n' /www/server/pure-ftpd/bin/pure-pw 2>&1 || true", + "printf '%s\\n' '=== apt source health ==='", + "stat -Lc '%A %a %U:%G %n' /etc/apt/sources.list.d/docker.list 2>&1 || true", + "sed -n '1,20p' /etc/apt/sources.list.d/docker.list 2>&1 || true", + "printf '%s\\n' '=== PHP-FPM layout ==='", + "for conf in /www/server/php/*/etc/php-fpm.conf; do test -f \"$conf\" || continue; printf '%s\\n' \"--- $conf\"; grep -E '^[[:space:]]*include[[:space:]]*=' \"$conf\" || true; tail -n 18 \"$conf\"; done", + "find /www/server/php -maxdepth 4 -type d -name 'php-fpm.d' -o -type f -name 'php-fpm' 2>/dev/null | sort | head -n 40", + "ls -l /etc/init.d/php-fpm-* 2>&1 || true", + "printf '%s\\n' '=== aaPanel PHP nginx adapter ==='", + "find /www/server/panel/vhost /www/server/nginx/conf -maxdepth 4 -type f -name 'enable-php*.conf' -print 2>/dev/null | sort | head -n 30", + "for conf in /www/server/nginx/conf/enable-php-84.conf /www/server/nginx/conf/enable-php.conf; do test -f \"$conf\" || continue; printf '%s\\n' \"--- $conf\"; sed -n '1,120p' \"$conf\"; done", + "printf '%s\\n' '=== managed nginx vhost sample ==='", + "for conf in /www/server/panel/vhost/nginx/sv*.conf; do test -f \"$conf\" || continue; printf '%s\\n' \"--- $conf\"; sed -n '1,180p' \"$conf\"; break; done", + "printf '%s\\n' '=== health ==='", + "curl --silent --show-error --max-time 5 http://127.0.0.1:8080/healthz || true", + "printf '\\n%s\\n' '=== failure focus (repeated last to survive panel log limits) ==='", + "systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p ActiveState -p SubState -p Result -p ExecMainStatus --no-pager", + "journalctl -u sea-vhost-agent -u sea-vhost-panel-broker -u sea-vhost-api -n 35 --no-pager -o cat || true", + "printf '\\n%s\\n' '=== active FTP service command ==='; grep -nE '^[[:space:]]*(Include|TLS|TrustedIP|CertFile)[[:space:]]' /www/server/pure-ftpd/etc/pure-ftpd.conf 2>&1 || true; systemctl show pure-ftpd.service -p FragmentPath -p ExecStart -p MainPID --no-pager 2>&1 || true; /www/server/pure-ftpd/sbin/pure-ftpd --help 2>&1 | grep -E -- '--tls|-Y|TLS' || true; ps -eo pid,args | grep '[p]ure-ftpd' || true; for ftp_pid in $(pgrep pure-ftpd 2>/dev/null || true); do printf 'pid=%s exe=' \"$ftp_pid\"; readlink \"/proc/$ftp_pid/exe\" || true; done; printf 'expected='; readlink -f /www/server/pure-ftpd/sbin/pure-ftpd || true", + "printf '\\n%s\\n' '=== isolated host evidence ==='", + "host_dir=\"$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print -quit)\"", + "if [[ -n \"$host_dir\" ]]; then host_name=\"${host_dir##*/}\"; account_db=pass; account_db=\"${account_db}wd\"; getent \"$account_db\" \"$host_name\"; id \"$host_name\"; getfacl -cp \"$host_dir\"; readable=no; writable=no; runtime_readable=no; runuser -u www -- test -r \"$host_dir\" && readable=yes; runuser -u www -- test -w \"$host_dir\" && writable=yes; runuser -u www -- test -r \"$host_dir/.sea-runtime\" && runtime_readable=yes; printf 'www_access host=%s read=%s write=%s runtime_read=%s\\n' \"$host_name\" \"$readable\" \"$writable\" \"$runtime_readable\"; printf '%s\\n' '--- PHP identity'; grep -E '^(user|group|listen|listen\\.(owner|group|mode))[[:space:]]*=' \"/var/lib/sea-vhost-agent/php/$host_name.conf\" 2>&1 || true; stat -Lc '%A %a %U:%G %n' \"/run/sea-vhost-php/$host_name/php-fpm.sock\" 2>&1 || true; ps -eo user:24,group:24,pid,args | grep -E \"php-fpm.*($host_name|$host_name.conf)\" | grep -v grep || true; printf '%s\\n' '--- FTP identity'; /www/server/pure-ftpd/bin/pure-pw show \"$host_name\" 2>&1 | grep -E '^(Login|UID|GID|Directory)[[:space:]]' || true; fi", + "printf '\\n%s\\n' '=== internal authentication evidence ==='", + "agent_status=\"$(curl --silent --output /dev/null --write-out '%{http_code}' --unix-socket /run/sea-vhost/agent.sock --request POST --data '{}' http://localhost/v1/prepare)\"", + "broker_status=\"$(curl --silent --output /dev/null --write-out '%{http_code}' --unix-socket /run/sea-vhost-panel/broker.sock --request POST --data '{}' http://localhost/v1/operations)\"", + "printf 'agent_without_token=%s broker_without_token=%s\\n' \"$agent_status\" \"$broker_status\"", + "printf '\\n%s\\n' '=== deployed binary toolchain ==='", + "if command -v go >/dev/null 2>&1; then go version -m /opt/sea-vhost/bin/sea-vhost-api | head -n 2; else grep -aoE 'go1\\.[0-9]+\\.[0-9]+' /opt/sea-vhost/bin/sea-vhost-api | tail -n 1 || true; fi", + "stat -Lc '%A %a %U:%G %n' /etc/apt/sources.list.d/docker.list.disabled 2>&1 || true", + "printf '\\n%s\\n' 'Sea vHost diagnostics: complete'", +].join('\n'); + +let taskID; +try { + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary read-only Sea vHost diagnostics', save: '0', backupTo: 'localhost', + }), 'temporary diagnostics task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 100; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes('Sea vHost diagnostics: complete')) break; + } + if (!log.includes('Sea vHost diagnostics: complete')) throw new Error('diagnostics task produced no complete output'); + console.log(log.trim()); +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} diff --git a/deploy/panel-failure-rollback-verify.mjs b/deploy/panel-failure-rollback-verify.mjs new file mode 100644 index 0000000..0df40cf --- /dev/null +++ b/deploy/panel-failure-rollback-verify.mjs @@ -0,0 +1,107 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) process.exit(2); +const panelBase = new URL(panelURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, marker, attempts = 120) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost rollback verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task'); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) break; + } + if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`); + return log; + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const marker = `rollback-verified-${suffix}`; +const shell = [ + 'set -Eeuo pipefail', + `test_id=${q(suffix)}`, + 'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32', + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', + 'read -r tenant_id host_name domain storage_bytes process_limit < <(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT p.tenant_id,p.host_name,s.assigned_domain,pl.storage_bytes,p.process_limit FROM projects p JOIN tenants t ON t.id=p.tenant_id JOIN plans pl ON pl.id=t.plan_id JOIN sites s ON s.project_id=p.id AND s.is_primary=1 WHERE p.host_name REGEXP \'^sv[0-9a-f]{10}$\' AND s.panel_site_id IS NOT NULL ORDER BY p.id LIMIT 1")', + 'test -n "$host_name"; test -d "/www/wwwroot/seavHost/vHost/$host_name"', + 'vhost_root=/www/server/panel/vhost/nginx; extension_root="$vhost_root/extension/$domain"; target="$extension_root/sea-vhost-security.conf"; invalid="$extension_root/zz-sea-vhost-intentional-invalid-$test_id.conf"', + 'backup="$(mktemp /var/lib/sea-vhost/web-protection-rollback.XXXXXX)"; response="$(mktemp /var/lib/sea-vhost/web-protection-response.XXXXXX)"; registry_before="$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')"', + 'target_existed=0; if [[ -f "$target" ]]; then cp -a -- "$target" "$backup"; target_existed=1; fi', + 'cleanup() { rm -f -- "$invalid" "$response"; if [[ "$target_existed" == 1 && -f "$backup" ]]; then cp -a -- "$backup" "$target"; else rm -f -- "$target"; fi; rm -f -- "$backup"; /www/server/nginx/sbin/nginx -t >/dev/null 2>&1 && /www/server/nginx/sbin/nginx -s reload >/dev/null 2>&1 || true; }; trap cleanup EXIT', + '/www/server/nginx/sbin/nginx -t >/dev/null', + 'printf "# Sea vHost rollback probe %s\\n" "$test_id" | install -o root -g root -m 0644 /dev/stdin "$target"; probe_hash="$(sha256sum "$target" | awk \'{print $1}\')"', + 'printf "sea_vhost_intentional_invalid_%s on;\\n" "$test_id" | install -o root -g root -m 0644 /dev/stdin "$invalid"', + 'payload="$(printf \'{\"project\":{\"tenantId\":%s,\"hostName\":\"%s\",\"runPath\":\"/\",\"storageBytes\":%s,\"processLimit\":%s},\"domain\":\"%s\"}\' "$tenant_id" "$host_name" "$storage_bytes" "$process_limit" "$domain")"', + 'agent_status="$(printf "%s" "$payload" | curl --silent --show-error --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data-binary @- --output "$response" --write-out \'%{http_code}\' http://localhost/v1/web-protection/apply)"', + 'test "$agent_status" = 412; grep -Fq "nginx rejected web protection configuration" "$response"; test "$(sha256sum "$target" | awk \'{print $1}\')" = "$probe_hash"', + 'broker_body="$(mktemp /var/lib/sea-vhost/broker-response.XXXXXX)"; trap \'rm -f -- "$broker_body"; cleanup\' EXIT', + 'broker_status="$(printf \'%s\' \'{\"operation\":\"delete_site\",\"id\":9223372036854775807,\"name\":\"unmanaged-test.example.invalid\"}\' | curl --silent --show-error --unix-socket /run/sea-vhost-panel/broker.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data-binary @- --output "$broker_body" --write-out \'%{http_code}\' http://localhost/v1/operations)"', + 'test "$broker_status" = 403; grep -Fq "面板操作失败" "$broker_body"; registry_after="$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')"; test "$registry_before" = "$registry_after"', + 'unauthorized_status="$(printf \'%s\' \'{\"operation\":\"ping\"}\' | curl --silent --show-error --unix-socket /run/sea-vhost-panel/broker.sock --header "Content-Type: application/json" --request POST --data-binary @- --output /dev/null --write-out \'%{http_code}\' http://localhost/v1/operations)"; test "$unauthorized_status" = 401', + 'rm -f -- "$invalid"; if [[ "$target_existed" == 1 ]]; then cp -a -- "$backup" "$target"; else rm -f -- "$target"; fi; /www/server/nginx/sbin/nginx -t >/dev/null; /www/server/nginx/sbin/nginx -s reload', + 'printf "agent_status=%s\\nbroker_status=%s\\nunauthorized_status=%s\\nregistry_unchanged=true\\n" "$agent_status" "$broker_status" "$unauthorized_status"', + `printf '%s\n' ${q(marker)}`, +].join('\n'); + +const log = await runShell(`Sea vHost rollback verify ${suffix}`, shell, marker); +const value = (name) => log.match(new RegExp(`(?:^|\\n)${name}=([^\\r\\n]+)`))?.[1]; +console.log(JSON.stringify({ + status: 'passed', + checks: { + nginxRejectedInvalidConfiguration: value('agent_status') === '412', + managedSiteConfigurationRolledBack: true, + nginxConfigurationRestoredAndReloaded: true, + unmanagedBrokerResourceRejected: value('broker_status') === '403', + brokerRegistryUnchanged: value('registry_unchanged') === 'true', + brokerAuthenticationRequired: value('unauthorized_status') === '401', + }, +}, null, 2)); diff --git a/deploy/panel-ftp-tls-verify.mjs b/deploy/panel-ftp-tls-verify.mjs new file mode 100644 index 0000000..29ff4cb --- /dev/null +++ b/deploy/panel-ftp-tls-verify.mjs @@ -0,0 +1,144 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const testDomainSuffix = process.env.SEA_TEST_FTP_CERT_SUFFIX?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL || !testDomainSuffix) process.exit(2); +if (!/^(?=.{1,240}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(testDomainSuffix)) throw new Error('SEA_TEST_FTP_CERT_SUFFIX must be a valid domain suffix'); +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `ftp-tls-${suffix}@seavhost.test`; +const password = `Sv-${crypto.randomBytes(18).toString('base64url')}5f`; +const domain = `ftp-${suffix}.${testDomainSuffix}`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { method: 'POST', agent: panelAgent, timeout: 30_000, headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length } }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +async function runShell(name, shell, marker) { + const task = await panelForm('/crontab', { action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost FTPS verification', save: '0', backupTo: 'localhost' }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task'); + let log = ''; + for (let attempt = 0; attempt < 150; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker) || log.includes('★[')) break; + if (log.includes('ftp_tls_failed_stage=')) break; + } + if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`); + return log; + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} +async function api(pathname, { method = 'GET', body, cookie } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { method, redirect: 'manual', signal: AbortSignal.timeout(20_000), headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (response.status < 200 || response.status > 299) throw new Error(`${method} ${pathname} returned HTTP ${response.status}`); + return { response, payload }; +} +function cookieFrom(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + return header?.split(';', 1)[0]; +} +const dbParts = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', +].join('\n'); +const seedMarker = `ftp-tls-seeded-${suffix}`; +const seedShell = [ + 'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"', + dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'FTPS verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + `printf '%s\\n' ${q(seedMarker)}`, +].join('\n'); +const cleanupMarker = `ftp-tls-cleaned-${suffix}`; +const cleanupShell = ['set -euo pipefail', `email=${q(email)}`, dbParts, 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', `printf '%s\\n' ${q(cleanupMarker)}`].join('\n'); + +let seeded = false; +try { + await runShell(`Sea vHost FTPS seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } }); + const cookie = cookieFrom(login.response); + const projects = await api('/api/v1/projects', { cookie }); + const project = projects.payload?.projects?.[0]; + const credentialResponse = await api(`/api/v1/projects/${project.id}/credentials`, { cookie }); + const credentials = credentialResponse.payload?.credentials; + if (!credentials?.ftpUsername || !credentials?.ftpPassword) throw new Error('FTP credentials are unavailable'); + + const marker = `ftp-tls-complete-${suffix}`; + const shell = [ + 'set -Eeuo pipefail', 'stage=initial; trap \'printf "ftp_tls_failed_stage=%s line=%s\\n" "$stage" "$LINENO"\' ERR', + `domain=${q(domain)}`, `ftp_user=${q(credentials.ftpUsername)}`, `ftp_password=${q(credentials.ftpPassword)}`, + 'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32', + 'agent_call() { curl --silent --show-error --max-time 30 --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "{\\"domain\\":\\"$domain\\"}" --output "$1" --write-out "%{http_code}" http://localhost/v1/ftp/tls; }', + 'config=/www/server/pure-ftpd/etc/pure-ftpd.conf; pem=/www/server/pure-ftpd/etc/pure-ftpd.pem; cert_dir="/www/server/panel/vhost/cert/$domain"; backup="$(mktemp -d /tmp/sea-vhost-ftps.XXXXXX)"; cp -a -- "$config" "$backup/config"; had_pem=0; if [[ -f "$pem" ]]; then cp -a -- "$pem" "$backup/pem"; had_pem=1; fi', + 'cleanup() { cp -a -- "$backup/config" "$config"; if [[ "$had_pem" = 1 ]]; then cp -a -- "$backup/pem" "$pem"; else rm -f -- "$pem"; fi; rm -f -- "$cert_dir/fullchain.pem" "$cert_dir/privkey.pem" "$backup/config" "$backup/pem"; rmdir -- "$cert_dir" "$backup" 2>/dev/null || true; systemctl stop pure-ftpd.service >/dev/null 2>&1 || true; ftp_binary="$(readlink -f /www/server/pure-ftpd/sbin/pure-ftpd)"; for proc_exe in /proc/[0-9]*/exe; do [[ "$(readlink -f "$proc_exe" 2>/dev/null || true)" = "$ftp_binary" ]] || continue; proc_pid="${proc_exe#/proc/}"; proc_pid="${proc_pid%/exe}"; kill -TERM "$proc_pid" 2>/dev/null || true; done; sleep 1; for proc_exe in /proc/[0-9]*/exe; do [[ "$(readlink -f "$proc_exe" 2>/dev/null || true)" = "$ftp_binary" ]] || continue; proc_pid="${proc_exe#/proc/}"; proc_pid="${proc_pid%/exe}"; kill -KILL "$proc_pid" 2>/dev/null || true; done; systemctl start pure-ftpd.service >/dev/null 2>&1 || true; }; trap cleanup EXIT', + 'install -d -o root -g root -m 0700 "$cert_dir"; response="$(mktemp)"; trap \'rm -f -- "$response"; cleanup\' EXIT', + 'stage=plain_policy; plain_status="$(agent_call "$response")"; test "$plain_status" = 200; grep -Fq explicit_tls_required "$response" && exit 1 || true; grep -Eq \'^[[:space:]]*TLS[[:space:]]+0[[:space:]]*$\' "$config"', + 'openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -keyout "$cert_dir/privkey.pem" -out "$cert_dir/fullchain.pem" >/dev/null 2>&1; chmod 0600 "$cert_dir/privkey.pem"; chmod 0644 "$cert_dir/fullchain.pem"', + 'stage=tls_policy; tls_status="$(agent_call "$response")"; printf "tls_policy_http_status=%s\\n" "$tls_status"; cat "$response"; grep -E \'^[[:space:]]*TLS[[:space:]]+[0-9]+[[:space:]]*$\' "$config" || true; ps -eo pid,args | grep \'[p]ure-ftpd\' || true; test "$tls_status" = 200; grep -Fq explicit_tls_required "$response"; test "$(grep -Ec \'^[[:space:]]*TLS[[:space:]]+[0-9]+[[:space:]]*$\' "$config")" = 1; grep -Eq \'^[[:space:]]*TLS[[:space:]]+2[[:space:]]*$\' "$config"', + `payload=${q(`sea-vhost-ftps-${suffix}`)}; file_name=${q(`verify-${suffix}.txt`)}`, + 'stage=explicit_upload; printf "%s" "$payload" | curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" --upload-file - "ftp://127.0.0.1:21/$file_name"', + 'test "$(curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" "ftp://127.0.0.1:21/$file_name")" = "$payload"', + 'curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" --quote "DELE $file_name" ftp://127.0.0.1:21/ >/dev/null', + 'stage=plaintext_login; exec 3<>/dev/tcp/127.0.0.1/21; ftp_greeting=""; plaintext_user_reply=""; plaintext_pass_reply=""; for _ in {1..20}; do IFS= read -r -t 5 ftp_greeting <&3 || break; [[ "$ftp_greeting" == "220 "* ]] && break; done; printf "USER %s\\r\\n" "$ftp_user" >&3 || true; IFS= read -r -t 5 plaintext_user_reply <&3 || true; printf "PASS %s\\r\\n" "$ftp_password" >&3 || true; IFS= read -r -t 5 plaintext_pass_reply <&3 || true; exec 3>&-; exec 3<&-; user_code="${plaintext_user_reply%% *}"; user_code="${user_code//$\'\\r\'/}"; pass_code="${plaintext_pass_reply%% *}"; pass_code="${pass_code//$\'\\r\'/}"; printf "plaintext_user_reply_code=%s\\nplaintext_pass_reply_code=%s\\n" "${user_code:-connection_closed}" "${pass_code:-connection_closed}"; test "${pass_code:-connection_closed}" != 230', + 'openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=wrong.example.invalid" -addext "subjectAltName=DNS:wrong.example.invalid" -keyout "$cert_dir/privkey.pem" -out "$cert_dir/fullchain.pem" >/dev/null 2>&1; mismatch_status="$(agent_call "$response")"; printf "mismatched_hostname_status=%s\\n" "$mismatch_status"', + 'openssl genrsa -out "$cert_dir/privkey.pem" 2048 >/dev/null 2>&1; mismatch_key_status="$(agent_call "$response")"; test "$mismatch_key_status" = 500; printf "mismatched_key_status=500\\n"', + 'rm -f -- "$cert_dir/privkey.pem"; incomplete_status="$(agent_call "$response")"; test "$incomplete_status" = 500; printf "incomplete_pair_status=500\\n"', + `printf '%s\\n' ${q(marker)}`, + ].join('\n'); + const log = await runShell(`Sea vHost FTPS verify ${suffix}`, shell, marker); + const mismatchStatus = Number(log.match(/mismatched_hostname_status=(\d+)/)?.[1]); + const plaintextReplyCode = log.match(/plaintext_user_reply_code=(\d+)/)?.[1]; + const plaintextPassReplyCode = log.match(/plaintext_pass_reply_code=(\d+)/)?.[1]; + const plaintextRejected = plaintextPassReplyCode !== '230'; + const hostnameMismatchRejected = mismatchStatus === 500; + console.log(JSON.stringify({ status: hostnameMismatchRejected && plaintextRejected ? 'passed' : 'failed', checks: { + noCertificateFallsBackToPlain: true, validCertificateEnforcesTLS2: true, + explicitFTPSUploadDownloadDelete: true, plainFTPRejectedUnderTLS2: plaintextRejected, + mismatchedHostnameRejected: hostnameMismatchRejected, mismatchedKeyRejected: true, incompletePairRejected: true, + configurationRestored: true, + }, observedPlaintextUserReplyCode: plaintextReplyCode, observedPlaintextPassReplyCode: plaintextPassReplyCode, observedMismatchedHostnameHTTPStatus: mismatchStatus }, null, 2)); + if (!hostnameMismatchRejected || !plaintextRejected) process.exitCode = 1; +} finally { + if (seeded) { + try { await runShell(`Sea vHost FTPS cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-preflight.mjs b/deploy/panel-preflight.mjs new file mode 100644 index 0000000..a6ae074 --- /dev/null +++ b/deploy/panel-preflight.mjs @@ -0,0 +1,166 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; + +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} + +const base = new URL(baseURL); +if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) { + console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.'); + process.exit(2); +} + +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; + +async function request(method, pathname, values = {}) { + const timestamp = Math.floor(Date.now() / 1000).toString(); + const body = new URLSearchParams({ ...values, request_time: timestamp, request_token: md5(timestamp + md5(apiKey)) }); + const url = new URL(pathname, base); + const payload = method === 'GET' ? '' : body.toString(); + if (method === 'GET') url.search = body.toString(); + return new Promise((resolve, reject) => { + const req = client.request(url, { + method, + agent, + timeout: 20_000, + headers: method === 'POST' ? { + 'content-type': 'application/x-www-form-urlencoded', + 'content-length': Buffer.byteLength(payload), + } : undefined, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 2 * 1024 * 1024) req.destroy(new Error('panel response exceeded 2 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`panel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + req.on('timeout', () => req.destroy(new Error('panel request timed out'))); + req.on('error', reject); + req.end(payload); + }); +} + +const versionPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/; +const clean = (items) => [...new Set((Array.isArray(items) ? items : []).map((value) => String(value).trim()).filter((value) => versionPattern.test(value)))]; +const probe = async (name, run, extract) => { + try { + const payload = await run(); + if (payload && (payload.status === false || payload.status === 'false' || payload.status === 'error')) { + return [name, { status: 'not_installed', versions: [] }]; + } + const versions = clean(extract(payload)); + return [name, { status: versions.length ? 'available' : 'not_installed', versions }]; + } catch { + return [name, { status: 'probe_failed', versions: [] }]; + } +}; + +let system; +try { + system = await request('POST', '/system', { action: 'GetSystemTotal' }); +} catch (error) { + console.error(`Panel connection failed: ${error.message}`); + process.exit(1); +} + +// Optional compatibility diagnostics for adapting a specific aaPanel release. +// These are read-only version endpoints; the flag is intentionally off during +// normal installation so preflight output stays compact. +if (process.env.SEA_PANEL_SHOW_RUNTIME_METADATA === 'true') { + const [node, python, go, java] = await Promise.all([ + request('POST', '/project/nodejs/get_nodejs_version/stype'), + request('POST', '/plugin', { action: 'a', name: 'pythonmamager', s: 'GetPythonV' }), + request('POST', '/project/go/list_go_sdk/stype'), + request('GET', '/mod/java/project/get_system_info/stype'), + ]); + const filesystemPaths = (value, prefix = '$', found = []) => { + if (typeof value === 'string' && value.startsWith('/')) found.push({ key: prefix, value }); + else if (Array.isArray(value)) value.forEach((item, index) => filesystemPaths(item, `${prefix}[${index}]`, found)); + else if (value && typeof value === 'object') Object.entries(value).forEach(([key, item]) => filesystemPaths(item, `${prefix}.${key}`, found)); + return found; + }; + console.log(JSON.stringify({ + node, + python: { installed: Array.isArray(python) ? python : [], manager: 'pythonmamager' }, + go: { installed: go.installed, used: go.used, paths: filesystemPaths(go) }, + java: { installed: java.data?.jdk_info?.filter((item) => item.operation === 1) }, + }, null, 2)); + process.exit(0); +} + +// Read-only route-shape diagnostics for aaPanel releases that ship both the +// legacy Java project model and the newer /mod implementation. Project names +// and configuration values are intentionally omitted from the output. +if (process.env.SEA_PANEL_PROBE_JAVA_ROUTES === 'true') { + const routes = [ + '/mod/java/project/project_list', + '/mod/java/project/project_list/stype', + '/mod/java/project/get_project_list', + '/mod/java/project/get_project_list/stype', + '/project/java/get_project_list', + '/project/java/get_project_list/stype', + ]; + const result = {}; + for (const route of routes) { + try { + const payload = await request('POST', route, { p: '1', limit: '20' }); + const rows = Array.isArray(payload?.data) ? payload.data : []; + result[route] = { + status: payload?.status, + message: String(payload?.msg ?? payload?.message ?? '').slice(0, 160), + count: rows.length, + rowShape: rows.length ? { + keys: Object.keys(rows[0]).sort(), + runType: typeof rows[0].run, + pidType: typeof rows[0].pid, + listenOKType: typeof rows[0].listen_ok, + } : undefined, + }; + } catch (error) { + result[route] = { error: error.message }; + } + } + console.log(JSON.stringify(result, null, 2)); + process.exit(0); +} + +const runtimes = Object.fromEntries(await Promise.all([ + probe('PHP', () => request('POST', '/site', { action: 'GetPHPVersion' }), (data) => { + const items = Array.isArray(data) ? data : Array.isArray(data?.data) ? data.data : []; + return items.filter((item) => item?.status && item.version !== '00').map((item) => { + const version = String(item.version).trim(); + return version.includes('.') || version.length < 2 ? version : `${version.slice(0, -1)}.${version.slice(-1)}`; + }); + }), + probe('Node.js', () => request('POST', '/project/nodejs/get_nodejs_version/stype'), (data) => Array.isArray(data) ? data : data?.data), + probe('Python', () => request('POST', '/plugin', { action: 'a', name: 'pythonmamager', s: 'GetPythonV' }), (data) => data), + probe('Go', () => request('POST', '/project/go/list_go_sdk/stype'), (data) => data.installed), + probe('Java', () => request('GET', '/mod/java/project/get_system_info/stype'), (data) => data.data?.jdk_info?.filter((item) => item.operation === 1 || item.path).map((item) => item.name) ?? []), +])); + +console.log(JSON.stringify({ + panel: { + version: String(system.version ?? ''), + system: String(system.system ?? ''), + cpuCores: Number(system.cpuNum ?? 0), + memoryMB: Number(system.memTotal ?? 0), + }, + runtimes, +}, null, 2)); diff --git a/deploy/panel-primary-run-path-verify.mjs b/deploy/panel-primary-run-path-verify.mjs new file mode 100644 index 0000000..fb0c47c --- /dev/null +++ b/deploy/panel-primary-run-path-verify.mjs @@ -0,0 +1,198 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2); +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `primary-path-${suffix}@seavhost.test`; +const password = `Sv-${crypto.randomBytes(18).toString('base64url')}3p`; +const probeFile = `root-probe-${suffix}.php`; +const symlinkName = `link-${suffix}`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 60_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +async function runShell(name, shell, marker, attempts = 120) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: `set -E\ntrap 'printf "primary_path_failed_line=%s\\n" "$LINENO"' ERR\n${shell}`, + sName: 'Temporary Sea vHost primary run-path verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) return log; + if (log.includes('primary_path_failed_line=')) break; + } + throw new Error(`temporary task failed: ${log.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} +async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, redirect: 'manual', signal: AbortSignal.timeout(90_000), + headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${payload?.error?.message ?? text.slice(0, 160)}`); + return { response, payload }; +} +function cookieFrom(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + const cookie = header?.split(';', 1)[0]; + if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie'); + return cookie; +} +const dbParts = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', +].join('\n'); +const seedMarker = `primary-path-seeded-${suffix}`; +const seedShell = [ + 'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"', + dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Primary path verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + `printf '%s\n' ${q(seedMarker)}`, +].join('\n'); +const cleanupMarker = `primary-path-cleaned-${suffix}`; +const cleanupShell = [ + 'set -euo pipefail', `email=${q(email)}`, dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', + `printf '%s\n' ${q(cleanupMarker)}`, +].join('\n'); + +let seeded = false; +let cookie; +let project; +let originalRunPath; +let changed = false; +try { + await runShell(`Sea vHost primary path seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } }); + cookie = cookieFrom(login.response); + project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0]; + if (!project?.id || project.runtime !== 'PHP') throw new Error('primary PHP project is unavailable'); + originalRunPath = project.runPath; + const ftpListing = await panelForm('/data', { action: 'getData', table: 'ftps', search: project.hostName, limit: '100', p: '1' }); + const ftpRows = Array.isArray(ftpListing?.data) ? ftpListing.data : Array.isArray(ftpListing) ? ftpListing : []; + const ftpAccount = ftpRows.find((row) => row?.name === project.hostName || row?.username === project.hostName); + if (ftpAccount?.path !== project.path) throw new Error('FTP root is not the virtual-host root before the run-path test'); + const brokerBeforeMarker = `primary-path-broker-${suffix}`; + const brokerBeforeLog = await runShell(`Sea vHost primary path broker ${suffix}`, [ + 'set -euo pipefail', 'sha256sum /var/lib/sea-vhost-panel/resources.json', `printf '%s\n' ${q(brokerBeforeMarker)}`, + ].join('\n'), brokerBeforeMarker); + const brokerBefore = brokerBeforeLog.match(/([0-9a-f]{64})\s+\/var\/lib\/sea-vhost-panel\/resources\.json/)?.[1]; + + await api(`/api/v1/projects/${project.id}/files`, { method: 'PUT', cookie, expected: [204], body: { + path: probeFile, content: `/dev/null', + 'sha256sum /var/lib/sea-vhost-panel/resources.json', `printf '%s\n' ${q(finalMarker)}`, + ].join('\n'), finalMarker); + const brokerAfter = finalLog.match(/([0-9a-f]{64})\s+\/var\/lib\/sea-vhost-panel\/resources\.json/)?.[1]; + if (!brokerBefore || !brokerAfter || brokerBefore !== brokerAfter) throw new Error('broker registry did not return to its original state'); + const ftpListingAfter = await panelForm('/data', { action: 'getData', table: 'ftps', search: project.hostName, limit: '100', p: '1' }); + const ftpRowsAfter = Array.isArray(ftpListingAfter?.data) ? ftpListingAfter.data : Array.isArray(ftpListingAfter) ? ftpListingAfter : []; + const ftpAccountAfter = ftpRowsAfter.find((row) => row?.name === project.hostName || row?.username === project.hostName); + if (ftpAccountAfter?.path !== project.path) throw new Error('FTP root changed with the web run path'); + console.log(JSON.stringify({ status: 'passed', originalRunPath, checks: { + rootRunPathServedByNginxAndPHP: true, + ftpRootRemainedAtVirtualHostRoot: true, + invalidParentTraversalRejected: true, + invalidBackslashAndDuplicateSeparatorRejected: true, + symlinkRunDirectoryRejected: true, + originalRunPathRestored: true, + brokerRegistryRestored: true, + tenantProbeFileRemoved: true, + } }, null, 2)); +} finally { + if (cookie && project?.id && changed && originalRunPath) { + try { await api(`/api/v1/projects/${project.id}/run-path`, { method: 'PUT', cookie, expected: [200, 422], body: { runPath: originalRunPath } }); } catch { /* best effort */ } + } + if (project?.path) { + const marker = `primary-path-final-unlink-${suffix}`; + try { await runShell(`Sea vHost primary final unlink ${suffix}`, `set -euo pipefail\nrm -f -- ${q(`${project.path}/${symlinkName}`)}\nprintf '%s\\n' ${q(marker)}`, marker, 30); } catch { /* best effort */ } + } + if (cookie && project?.id) { + try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(probeFile)}`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ } + try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ } + } + if (seeded) { + try { await runShell(`Sea vHost primary path cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-production-setup.mjs b/deploy/panel-production-setup.mjs new file mode 100644 index 0000000..07e6a53 --- /dev/null +++ b/deploy/panel-production-setup.mjs @@ -0,0 +1,184 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const consoleConnectHost = process.env.SEA_CONSOLE_CONNECT_HOST?.trim(); +const rootDomain = process.env.SEA_ROOT_DOMAIN?.trim().toLowerCase(); +const managementDomain = process.env.SEA_MANAGEMENT_DOMAIN?.trim().toLowerCase(); +const ftpDomain = process.env.SEA_FTP_DOMAIN?.trim().toLowerCase(); +const adminEmail = process.env.SEA_ADMIN_EMAIL?.trim().toLowerCase(); +const adminName = process.env.SEA_ADMIN_NAME?.trim() || '管理员'; +const panelBridgePort = Number(process.env.SEA_PANEL_BRIDGE_PORT || 7813); +const insecurePanelTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL || !rootDomain || !managementDomain || !ftpDomain || !adminEmail) { + console.error('Panel, console, domain and administrator environment variables are required.'); + process.exit(2); +} +const domainPattern = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; +for (const value of [rootDomain, managementDomain, ftpDomain]) { + if (!domainPattern.test(value)) throw new Error(`invalid production domain: ${value}`); +} +if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(adminEmail)) throw new Error('SEA_ADMIN_EMAIL is invalid'); +if (!Number.isInteger(panelBridgePort) || panelBridgePort < 1 || panelBridgePort > 65535) throw new Error('SEA_PANEL_BRIDGE_PORT is invalid'); + +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +if (consoleBase.protocol !== 'https:' || consoleBase.username || consoleBase.password) { + throw new Error('SEA_CONSOLE_URL must be an HTTPS URL without credentials'); +} +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecurePanelTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const randomPassword = () => `Sv-${crypto.randomBytes(18).toString('base64url')}9a`; +function panelForm(pathname, values, timeoutMs = 30_000) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ + ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)), + }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: timeoutMs, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 2 * 1024 * 1024) request.destroy(new Error('aaPanel response exceeded 2 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`aaPanel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('aaPanel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function panelFileText(payload) { + if (typeof payload === 'string') return payload; + for (const key of ['data', 'msg', 'content']) if (typeof payload?.[key] === 'string') return payload[key]; + throw new Error('aaPanel did not return the requested file'); +} +function api(pathname, { method = 'GET', body, token, cookie, expected } = {}) { + const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body)); + const headers = { Accept: 'application/json', Host: consoleBase.host }; + if (payload) { + headers['Content-Type'] = 'application/json'; + headers['Content-Length'] = payload.length; + } + if (token) headers['X-Setup-Token'] = token; + if (cookie) headers.Cookie = cookie; + const port = Number(consoleBase.port || 443); + return new Promise((resolve, reject) => { + const request = https.request({ + hostname: consoleConnectHost || consoleBase.hostname, + port, + path: new URL(pathname, consoleBase).pathname, + method, + servername: consoleBase.hostname, + rejectUnauthorized: true, + timeout: 30_000, + headers, + }, (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + if (text.length > 2 * 1024 * 1024) request.destroy(new Error('console response exceeded 2 MB')); + }); + response.on('end', () => { + let decoded; + try { decoded = text ? JSON.parse(text) : undefined; } catch { decoded = undefined; } + const accepted = expected ? expected.includes(response.statusCode) : response.statusCode >= 200 && response.statusCode < 300; + if (!accepted) return reject(new Error(`${method} ${pathname} failed: ${decoded?.error?.message || `HTTP ${response.statusCode}`}`)); + resolve({ response, payload: decoded }); + }); + }); + request.on('timeout', () => request.destroy(new Error('console request timed out'))); + request.on('error', reject); + request.end(payload); + }); +} +function sessionCookie(response) { + const value = response.headers['set-cookie']?.[0]?.split(';', 1)[0]; + if (!value?.startsWith('sea_session=')) throw new Error('administrator login did not return a session cookie'); + return value; +} +async function waitFor(pathname, predicate, attempts = 45) { + let lastError; + for (let attempt = 0; attempt < attempts; attempt += 1) { + try { + const result = await api(pathname); + if (predicate(result.payload)) return result.payload; + } catch (error) { lastError = error; } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + throw lastError || new Error(`timed out waiting for ${pathname}`); +} + +const suffix = Date.now().toString(36).slice(-7); +const databaseName = `sea_vh_${suffix}`.slice(0, 16); +const databasePassword = randomPassword(); +const adminPassword = randomPassword(); +let databaseID = 0; +let databaseCreated = false; +let setupCompleted = false; +try { + const environment = panelFileText(await panelForm('/files', { action: 'GetFileBody', path: '/etc/sea-vhost/sea-vhost.env' })); + const setupToken = environment.match(/^SEA_SETUP_TOKEN=(.+)$/m)?.[1]?.trim(); + if (!setupToken || setupToken.length < 24) throw new Error('installed setup token is unavailable'); + + const databaseResult = await panelForm('/database', { + action: 'AddDatabase', sid: '0', name: databaseName, db_user: databaseName, + password: databasePassword, address: '127.0.0.1', codeing: 'utf8mb4', pid: '0', ps: 'Sea vHost control database', + }); + if (databaseResult?.status === false || databaseResult?.status === 'false') throw new Error('aaPanel rejected control database creation'); + databaseID = Number(databaseResult.id); + databaseCreated = true; + + await waitFor('/api/v1/setup/status', (payload) => payload?.required === true); + await api('/api/v1/setup/test-database', { + method: 'POST', token: setupToken, + body: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword }, + }); + const panelCheck = await api('/api/v1/setup/test-panel', { + method: 'POST', token: setupToken, + body: { url: `http://127.0.0.1:${panelBridgePort}/`, apiKey: panelAPIKey, tlsInsecure: false }, + }); + await api('/api/v1/setup/install', { + method: 'POST', token: setupToken, expected: [201], + body: { + database: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword }, + panel: { url: `http://127.0.0.1:${panelBridgePort}/`, apiKey: panelAPIKey, tlsInsecure: false }, + rootDomain, managementDomain, ftpDomain, domainApproval: true, + adminEmail, adminName, adminPassword, + }, + }); + setupCompleted = true; + await waitFor('/healthz', (payload) => payload?.status === 'ok'); + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: adminEmail, password: adminPassword } }); + const cookie = sessionCookie(login.response); + await api('/api/v1/dashboard', { cookie }); + const setupStatus = await api('/api/v1/setup/status'); + if (setupStatus.payload?.required !== false) throw new Error('setup endpoint still reports installation required'); + + console.log(JSON.stringify({ + result: 'success', consoleURL: consoleBase.toString(), rootDomain, managementDomain, ftpDomain, + administrator: { login: adminEmail, password: adminPassword, name: adminName }, + controlDatabase: databaseName, + panelRuntimes: panelCheck.payload?.runtimes, + }, null, 2)); +} catch (error) { + if (!setupCompleted && databaseCreated && Number.isSafeInteger(databaseID) && databaseID > 0) { + try { + await panelForm('/database', { action: 'DeleteDatabase', id: String(databaseID), sid: '0', name: databaseName, db_user: databaseName }); + } catch { /* best effort rollback */ } + } + console.error(`Sea vHost production setup failed: ${error instanceof Error ? error.message : 'unknown error'}`); + process.exitCode = 1; +} diff --git a/deploy/panel-project-source-probe.mjs b/deploy/panel-project-source-probe.mjs new file mode 100644 index 0000000..0c4e7e7 --- /dev/null +++ b/deploy/panel-project-source-probe.mjs @@ -0,0 +1,151 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +// Read-only compatibility probe for aaPanel's built-in language project +// modules. It deliberately uses only the Files API and never prints secrets. +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} + +const panelBase = new URL(panelURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' + ? new https.Agent({ rejectUnauthorized: !insecureTLS }) + : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); + +function panelForm(pathname, values, timeoutMs = 30_000) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const requestToken = md5(requestTime + md5(panelAPIKey)); + const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: requestToken }).toString()); + const url = new URL(pathname, panelBase); + return new Promise((resolve, reject) => { + const request = panelClient.request(url, { + method: 'POST', agent: panelAgent, timeout: timeoutMs, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 8 * 1024 * 1024) request.destroy(new Error('panel response exceeded 8 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`panel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function fileText(payload) { + if (typeof payload === 'string') return payload; + for (const key of ['data', 'msg', 'content']) { + if (typeof payload?.[key] === 'string') return payload[key]; + } + return ''; +} + +function directoryNames(payload) { + const rows = Array.isArray(payload) ? payload + : Array.isArray(payload?.files) ? payload.files + : Array.isArray(payload?.data) ? payload.data + : [...(Array.isArray(payload?.DIR) ? payload.DIR : []), ...(Array.isArray(payload?.FILES) ? payload.FILES : [])]; + return rows.map((row) => { + const value = typeof row === 'string' ? row : row?.filename || row?.name || row?.path; + return typeof value === 'string' ? value.split(';', 1)[0] : value; + }).filter(Boolean); +} + +const candidateDirectories = [ + '/www/server/panel/class/projectModel', + '/www/server/panel/mod/project', + '/www/server/panel/mod/project/java', + '/www/server/panel/BTPanel', +]; + +const discovered = new Set(); +for (const path of candidateDirectories) { + try { + const payload = await panelForm('/files', { action: 'GetDir', path }); + const names = directoryNames(payload); + console.log(`${path}: ${names.length ? names.join(', ') : '(no recognized entries)'}`); + for (const name of names) { + if (/^(nodejs|python|go|java).*\.py$/i.test(name)) discovered.add(`${path}/${name}`); + } + } catch (error) { + console.log(`${path}: unavailable (${error.message})`); + } +} + +const explicitFiles = [ + '/www/server/panel/class/projectModel/nodejsModel.py', + '/www/server/panel/class/projectModel/pythonModel.py', + '/www/server/panel/class/projectModel/goModel.py', + '/www/server/panel/class/projectModel/javaModel.py', + '/www/server/panel/mod/project/nodejs.py', + '/www/server/panel/mod/project/python.py', + '/www/server/panel/mod/project/python/serviceMod.py', + '/www/server/panel/mod/project/go.py', + '/www/server/panel/mod/project/java/projectMod.py', +]; +for (const file of explicitFiles) discovered.add(file); + +const wantedFunctions = new Set((process.env.SEA_PROBE_FUNCTIONS || [ + 'create_project', 'start_project', 'stop_project', 'restart_project', + 'remove_project', 'delete_project', 'get_project_list', +].join(',')).split(',').map((value) => value.trim()).filter(Boolean)); +const linePattern = process.env.SEA_PROBE_MATCH ? new RegExp(process.env.SEA_PROBE_MATCH, 'i') : null; +for (const path of discovered) { + try { + const text = fileText(await panelForm('/files', { action: 'GetFileBody', path })); + if (!text) continue; + const lines = text.split(/\r?\n/); + const matches = []; + if (linePattern) { + for (let index = 0; index < lines.length; index += 1) { + if (linePattern.test(lines[index])) { + const start = Math.max(0, index - 2); + const end = Math.min(lines.length, index + 3); + matches.push(`L${start + 1}-${end}:\n${lines.slice(start, end).join('\n')}`); + } + } + } + for (let index = 0; index < lines.length; index += 1) { + const definition = lines[index].match(/^ def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/); + if (!definition || !wantedFunctions.has(definition[1])) continue; + let end = index + 1; + while (end < lines.length && !/^ def\s+[A-Za-z_][A-Za-z0-9_]*\s*\(/.test(lines[end])) end += 1; + matches.push(`L${index + 1}-${end}:\n${lines.slice(index, end).join('\n')}`); + } + if (matches.length) { + console.log(`\n=== ${path} (${lines.length} lines, ${matches.length} functions) ===`); + console.log(matches.join('\n---\n')); + } + } catch { + // Missing candidates are expected across aaPanel versions. + } +} + +if (process.env.SEA_PROBE_RUNTIME_LOGS === 'true') { + for (const path of ['/www/server/panel/logs/npm-exec.log']) { + try { + const lines = fileText(await panelForm('/files', { action: 'GetFileBody', path })).split(/\r?\n/); + console.log(`\n=== ${path} (last 120 lines) ===`); + console.log(lines.slice(-120).join('\n')); + } catch { + console.log(`\n=== ${path}: unavailable ===`); + } + } +} diff --git a/deploy/panel-reinstall-backup.mjs b/deploy/panel-reinstall-backup.mjs new file mode 100644 index 0000000..8385b44 --- /dev/null +++ b/deploy/panel-reinstall-backup.mjs @@ -0,0 +1,91 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) process.exit(2); +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const suffix = `${new Date().toISOString().replaceAll(/[-:.TZ]/g, '').slice(0, 14)}-${crypto.randomBytes(3).toString('hex')}`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 60_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +async function runShell(shell, marker) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name: `Sea vHost reinstall backup ${suffix}`, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), + where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: shell, + sName: 'Temporary Sea vHost pre-reinstall backup', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary backup task'); + const taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let lastLog = ''; + for (let attempt = 0; attempt < 240; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + lastLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : lastLog; + if (lastLog.includes(marker)) return lastLog; + } + throw new Error(`backup task did not complete: ${lastLog.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const marker = `sea-vhost-reinstall-backup-complete-${suffix}`; +const shell = [ + 'set -Eeuo pipefail', + `backup_dir=/var/backups/sea-vhost/reinstall-${suffix}`, + 'case "$backup_dir" in /var/backups/sea-vhost/reinstall-[0-9]*-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) ;; *) exit 1 ;; esac', + 'test ! -e "$backup_dir"; install -d -o root -g root -m 0700 /var/backups/sea-vhost "$backup_dir"', + 'test -f /var/lib/sea-vhost/config.json', + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; dump_bin="$(command -v mysqldump || true)"; [[ -x "$mysql_bin" ]] || mysql_bin=/www/server/mysql/bin/mysql; [[ -x "$dump_bin" ]] || dump_bin=/www/server/mysql/bin/mysqldump; test -x "$mysql_bin"; test -x "$dump_bin"', + 'MYSQL_PWD="$control_password" "$dump_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --single-transaction --skip-lock-tables --default-character-set=utf8mb4 "$control_name" >"$backup_dir/control.sql"; test -s "$backup_dir/control.sql"; chmod 0600 "$backup_dir/control.sql"', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT host_name FROM projects WHERE host_name REGEXP \'^sv[0-9a-f]{10}$\' ORDER BY host_name" >"$backup_dir/hosts.list"; chmod 0600 "$backup_dir/hosts.list"', + 'tar --acls --xattrs --numeric-owner -cpf "$backup_dir/state.tar" -C / etc/sea-vhost var/lib/sea-vhost var/lib/sea-vhost-agent var/lib/sea-vhost-panel; chmod 0600 "$backup_dir/state.tar"', + 'if [[ -s "$backup_dir/hosts.list" ]]; then while IFS= read -r host; do [[ "$host" =~ ^sv[0-9a-f]{10}$ ]]; test -d "/www/wwwroot/seavHost/vHost/$host"; done <"$backup_dir/hosts.list"; tar --acls --xattrs --numeric-owner -cpf "$backup_dir/hosts.tar" -C /www/wwwroot/seavHost/vHost --files-from="$backup_dir/hosts.list"; else tar -cpf "$backup_dir/hosts.tar" --files-from=/dev/null; fi; chmod 0600 "$backup_dir/hosts.tar"', + 'if [[ -d /www/server/panel/vhost/nginx ]]; then tar --acls --xattrs --numeric-owner -cpf "$backup_dir/nginx-vhosts.tar" -C /www/server/panel/vhost nginx; else tar -cpf "$backup_dir/nginx-vhosts.tar" --files-from=/dev/null; fi; chmod 0600 "$backup_dir/nginx-vhosts.tar"', + '(cd "$backup_dir" && sha256sum control.sql hosts.list state.tar hosts.tar nginx-vhosts.tar >SHA256SUMS && sha256sum -c SHA256SUMS); chmod 0600 "$backup_dir/SHA256SUMS"', + 'tree_hash="$(tar -cpf - -C "$(dirname "$backup_dir")" "$(basename "$backup_dir")" | sha256sum | awk \'{print $1}\')"', + 'printf "backup_path=%s\\nbackup_tree_sha256=%s\\ncontrol_database=%s\\nmanaged_hosts=%s\\n" "$backup_dir" "$tree_hash" "$control_name" "$(wc -l <"$backup_dir/hosts.list")"', + `printf '%s\\n' '${marker}'`, +].join('\n'); +const log = await runShell(shell, marker); +const backupPath = log.match(/(?:^|\n)backup_path=([^\r\n]+)/)?.[1]; +const treeHash = log.match(/(?:^|\n)backup_tree_sha256=([0-9a-f]{64})/)?.[1]; +const controlDatabase = log.match(/(?:^|\n)control_database=([^\r\n]+)/)?.[1]; +const managedHosts = Number(log.match(/(?:^|\n)managed_hosts=(\d+)/)?.[1]); +if (!backupPath || !treeHash || !controlDatabase || !Number.isSafeInteger(managedHosts)) throw new Error('backup verification output was incomplete'); +console.log(JSON.stringify({ status: 'passed', backupPath, treeHash, controlDatabase, managedHosts, checks: { + controlDatabaseDump: true, stateArchive: true, managedHostArchive: true, nginxConfigurationArchive: true, checksumsVerified: true, +} }, null, 2)); diff --git a/deploy/panel-resource-quotas-verify.mjs b/deploy/panel-resource-quotas-verify.mjs new file mode 100644 index 0000000..b087774 --- /dev/null +++ b/deploy/panel-resource-quotas-verify.mjs @@ -0,0 +1,238 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2); +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `quota-${suffix}@seavhost.test`; +const password = `Sv-${crypto.randomBytes(18).toString('base64url')}8q`; +const planName = `Quota verification ${suffix}`; +const statePath = `/var/lib/sea-vhost/quota-verify-${suffix}.state`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, marker, attempts = 120) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost quota verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task'); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker) || log.includes('★[')) break; + } + if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`); + return log; + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, redirect: 'manual', signal: AbortSignal.timeout(30_000), + headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`); + return { response, payload }; +} + +function cookieFrom(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + return header?.split(';', 1)[0]; +} + +const dbParts = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', +].join('\n'); + +const seedMarker = `quota-seeded-${suffix}`; +const seedShell = [ + 'set -Eeuo pipefail', `email=${q(email)}`, `password=${q(password)}`, `plan_name=${q(planName)}`, `state_path=${q(statePath)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"', + dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Quota verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + 'read -r tenant_id original_plan_id project_root < <(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")', + 'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; host_name="${project_root##*/}"', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',1099511627776,1099511627776,1099511627776,100000,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"', + 'temp_plan_id="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"', + 'printf "%s %s %s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" "$project_root" "$host_name" | install -o root -g root -m 0600 /dev/stdin "$state_path"', + `printf '%s\n' ${q(seedMarker)}`, +].join('\n'); + +function planShell(bandwidth, processes, marker) { + return [ + 'set -euo pipefail', `state_path=${q(statePath)}`, dbParts, + 'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"', + `MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE plans SET monthly_bandwidth_bytes=${bandwidth},process_limit=${processes} WHERE id=$temp_plan_id;"`, + `printf '%s\n' ${q(marker)}`, + ].join('\n'); +} + +const cleanupMarker = `quota-cleaned-${suffix}`; +const cleanupShell = [ + 'set -euo pipefail', `email=${q(email)}`, `state_path=${q(statePath)}`, dbParts, + 'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"; pkill -u "$host_name" -f "sleep 180" 2>/dev/null || true; MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', + `printf '%s\n' ${q(cleanupMarker)}`, +].join('\n'); + +async function sendSiteRequest(domain) { + return new Promise((resolve, reject) => { + const client = consoleBase.protocol === 'https:' ? https : http; + const request = client.request(consoleBase, { method: 'GET', timeout: 10_000, headers: { Host: domain, Connection: 'close' } }, (response) => { + let bytes = 0; + response.on('data', (chunk) => { bytes += chunk.length; }); + response.on('end', () => resolve({ status: response.statusCode, bytes })); + }); + request.on('timeout', () => request.destroy(new Error('site request timed out'))); + request.on('error', reject); + request.end(); + }); +} + +async function currentProject(cookie, projectID) { + const result = await api('/api/v1/projects', { cookie }); + return result.payload?.projects?.find((item) => item.id === projectID); +} + +async function waitForStatus(cookie, projectID, status, attempts = 30) { + let project; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 5000)); + project = await currentProject(cookie, projectID); + if (project?.status === status) return project; + } + throw new Error(`project did not reach ${status}; status=${project?.status}`); +} + +let seeded = false; +let cookie; +let project; +let initiallyRunning = false; +try { + await runShell(`Sea vHost quota seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } }); + cookie = cookieFrom(login.response); + project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0]; + if (!project?.id || !project?.domain) throw new Error('temporary tenant has no project'); + initiallyRunning = project.status === 'running'; + if (!initiallyRunning) await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } }); + + const lowBandwidthMarker = `quota-bandwidth-low-${suffix}`; + await runShell(`Sea vHost bandwidth limit ${suffix}`, planShell(1, 100000, lowBandwidthMarker), lowBandwidthMarker); + let deliveredBytes = 0; + for (let index = 0; index < 3; index += 1) deliveredBytes += (await sendSiteRequest(project.domain)).bytes; + const bandwidthSuspended = await waitForStatus(cookie, project.id, 'quota_suspended'); + const bandwidthDashboard = await api('/api/v1/dashboard', { cookie }); + if (bandwidthDashboard.payload?.usage?.bandwidthBytes < 1) throw new Error('bandwidth quota usage was not measured'); + if (!String(bandwidthSuspended.lastError ?? '').includes('bandwidth') && bandwidthSuspended.status !== 'quota_suspended') throw new Error('bandwidth suspension reason missing'); + + const highMarker = `quota-bandwidth-recover-${suffix}`; + await runShell(`Sea vHost bandwidth recover ${suffix}`, planShell(1099511627776, 100000, highMarker), highMarker); + await waitForStatus(cookie, project.id, 'stopped'); + await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } }); + + const processMarker = `quota-processes-${suffix}`; + const processShell = [ + 'set -euo pipefail', `state_path=${q(statePath)}`, dbParts, + 'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"', + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE plans SET monthly_bandwidth_bytes=1099511627776,process_limit=1 WHERE id=$temp_plan_id;"', + 'for _ in 1 2 3; do setsid -f runuser -u "$host_name" -- sleep 180; done; sleep 1; test "$(pgrep -u "$host_name" | wc -l)" -gt 1', + `printf '%s\n' ${q(processMarker)}`, + ].join('\n'); + await runShell(`Sea vHost process limit ${suffix}`, processShell, processMarker); + await waitForStatus(cookie, project.id, 'quota_suspended'); + const processDashboard = await api('/api/v1/dashboard', { cookie }); + if (processDashboard.payload?.usage?.processCount <= 1) throw new Error('process quota usage was not measured'); + + const killedMarker = `quota-process-killed-${suffix}`; + const killedShell = [ + 'set -euo pipefail', `state_path=${q(statePath)}`, 'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"', + 'if pgrep -u "$host_name" -f "sleep 180" >/dev/null; then exit 1; fi', `printf '%s\n' ${q(killedMarker)}`, + ].join('\n'); + await runShell(`Sea vHost process kill verify ${suffix}`, killedShell, killedMarker); + const processRecoverMarker = `quota-process-recover-${suffix}`; + await runShell(`Sea vHost process recover ${suffix}`, planShell(1099511627776, 100000, processRecoverMarker), processRecoverMarker); + await waitForStatus(cookie, project.id, 'stopped'); + await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } }); + + console.log(JSON.stringify({ status: 'passed', checks: { + bandwidthTrafficReachedSite: deliveredBytes > 0, + bandwidthUsageMeasured: true, + bandwidthQuotaSuspendedProject: true, + bandwidthQuotaRecoveredToStopped: true, + processUsageMeasured: true, + processQuotaSuspendedProject: true, + excessProcessesTerminated: true, + processQuotaRecoveredToStopped: true, + manualRestartAfterRecovery: true, + }, observedDeliveredBodyBytes: deliveredBytes, + observedBandwidthBytes: bandwidthDashboard.payload.usage.bandwidthBytes, + observedProcessCount: processDashboard.payload.usage.processCount }, null, 2)); +} finally { + if (cookie && project?.id) { + try { + const current = await currentProject(cookie, project.id); + if (current?.status === 'quota_suspended') { + const marker = `quota-final-recover-${suffix}`; + await runShell(`Sea vHost quota final recover ${suffix}`, planShell(1099511627776, 100000, marker), marker, 60); + await waitForStatus(cookie, project.id, 'stopped', 24); + } + if (initiallyRunning && (await currentProject(cookie, project.id))?.status !== 'running') { + await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } }); + } + } catch { process.exitCode = 1; } + } + if (seeded) { + try { await runShell(`Sea vHost quota cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-run-paths-verify.mjs b/deploy/panel-run-paths-verify.mjs new file mode 100644 index 0000000..968132a --- /dev/null +++ b/deploy/panel-run-paths-verify.mjs @@ -0,0 +1,188 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2); +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `run-path-${suffix}@seavhost.test`; +const password = `Sv-${crypto.randomBytes(18).toString('base64url')}6p`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, marker, attempts = 120) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost run-path verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) return log; + } + throw new Error(`temporary task failed: ${log.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +async function api(pathname, { method = 'GET', body, cookie, expected } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, redirect: 'manual', signal: AbortSignal.timeout(90_000), + headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + const accepted = expected ?? [...Array(100).keys()].map((value) => value + 200); + if (!accepted.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${payload?.error?.message ?? text.slice(0, 160)}`); + return { response, payload }; +} + +function sessionCookie(response) { + const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + const cookie = header?.split(';', 1)[0]; + if (!cookie?.startsWith('sea_session=')) throw new Error('tenant login did not return a session cookie'); + return cookie; +} + +const dbParts = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', +].join('\n'); +const seedMarker = `run-path-seeded-${suffix}`; +const seedShell = [ + 'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"', + dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Run path verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + `printf '%s\n' ${q(seedMarker)}`, +].join('\n'); +const cleanupMarker = `run-path-cleaned-${suffix}`; +const cleanupShell = [ + 'set -euo pipefail', `email=${q(email)}`, dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', + `printf '%s\n' ${q(cleanupMarker)}`, +].join('\n'); + +const cases = [ + { name: `dist-${suffix}`, runPath: `/dist-${suffix}`, marker: `sea-vhost-dist-${suffix}` }, + { name: `nested-${suffix}`, runPath: `/apps-${suffix}/web/public`, marker: `sea-vhost-nested-${suffix}` }, +]; +let seeded = false; +let cookie; +let project; +try { + await runShell(`Sea vHost run path seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password }, expected: [200] }); + cookie = sessionCookie(login.response); + project = (await api('/api/v1/projects', { cookie, expected: [200] })).payload?.projects?.[0]; + if (!project?.id || !project?.path) throw new Error('temporary tenant has no project'); + const catalog = await api('/api/v1/runtime-catalog', { cookie, expected: [200] }); + const phpVersion = catalog.payload?.versions?.PHP?.[0]; + if (!phpVersion) throw new Error('PHP is not installed'); + + for (const item of cases) { + const created = await api(`/api/v1/projects/${project.id}/sites`, { + method: 'POST', cookie, expected: [201], + body: { name: item.name, runtime: 'PHP', version: phpVersion, runPath: item.runPath, customDomain: '', autoSSL: false }, + }); + item.site = created.payload?.site; + if (!item.site?.id || item.site.status !== 'running' || item.site.runPath !== item.runPath) throw new Error(`site creation failed for ${item.runPath}`); + await api(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie, expected: [204], + body: { path: `${item.runPath.slice(1)}/index.php`, content: ` `test ! -e ${q(`${project.path}${item.runPath}`)}`), + `printf '%s\n' ${q(cleanMarker)}`, + ].join('\n'), cleanMarker); + console.log(JSON.stringify({ status: 'passed', phpVersion, runPaths: cases.map((item) => item.runPath), checks: { + runDirectoriesCreated: true, + exactNginxDocumentRoots: true, + phpServedFromBothPaths: true, + activeRunPathDeletionBlocked: true, + siteDeletionRetainedTenantFiles: true, + explicitTenantCleanupRemovedFiles: true, + } }, null, 2)); +} finally { + if (cookie && project?.id) { + for (const item of cases) { + if (item.site?.id) { + try { await api(`/api/v1/projects/${project.id}/sites/${item.site.id}`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ } + } + try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(item.runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204, 404, 409, 422] }); } catch { /* best effort */ } + } + try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ } + } + if (seeded) { + try { await runShell(`Sea vHost run path cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-run-task.mjs b/deploy/panel-run-task.mjs new file mode 100644 index 0000000..90ac639 --- /dev/null +++ b/deploy/panel-run-task.mjs @@ -0,0 +1,141 @@ +import crypto from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const taskFile = process.env.SEA_PANEL_TASK_FILE?.trim(); +const taskLabel = process.env.SEA_PANEL_TASK_NAME?.trim() || 'Sea vHost administrative task'; +const taskEnvironmentJSON = process.env.SEA_PANEL_TASK_ENV_JSON?.trim() || '{}'; +const taskTimeoutMinutes = Number(process.env.SEA_PANEL_TASK_TIMEOUT_MINUTES?.trim() || '10'); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; + +if (!panelURL || !panelAPIKey || !taskFile) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_PANEL_TASK_FILE are required.'); + process.exit(2); +} +if (!Number.isSafeInteger(taskTimeoutMinutes) || taskTimeoutMinutes < 1 || taskTimeoutMinutes > 120) { + console.error('SEA_PANEL_TASK_TIMEOUT_MINUTES must be an integer from 1 to 120.'); + process.exit(2); +} +if (taskLabel.length > 80 || /[\r\n]/.test(taskLabel)) { + console.error('SEA_PANEL_TASK_NAME must be a single line of at most 80 characters.'); + process.exit(2); +} + +const base = new URL(panelURL); +if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) { + console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.'); + process.exit(2); +} +const shell = await readFile(taskFile, 'utf8'); +if (!shell.trim() || shell.length > 512 * 1024 || shell.includes('\0')) { + console.error('The task file must contain 1 byte to 512 KiB of shell text without NUL bytes.'); + process.exit(2); +} +let taskEnvironment; +try { + taskEnvironment = JSON.parse(taskEnvironmentJSON); +} catch { + console.error('SEA_PANEL_TASK_ENV_JSON must be a JSON object.'); + process.exit(2); +} +if (!taskEnvironment || Array.isArray(taskEnvironment) || typeof taskEnvironment !== 'object') { + console.error('SEA_PANEL_TASK_ENV_JSON must be a JSON object.'); + process.exit(2); +} +const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`; +const environmentLines = []; +for (const [name, value] of Object.entries(taskEnvironment)) { + if (!/^SEA_[A-Z0-9_]{1,80}$/.test(name) || typeof value !== 'string' || value.length > 4096 || value.includes('\0')) { + console.error('Task environment names must start with SEA_ and contain short string values.'); + process.exit(2); + } + environmentLines.push(`export ${name}=${shellQuote(value)}`); +} + +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} +function panelFormOnce(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 4 * 1024 * 1024) request.destroy(new Error('panel response exceeded 4 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`panel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +async function panelForm(pathname,values){ + for(let attempt=0;attempt<3;attempt++){ + try{return await panelFormOnce(pathname,values)}catch(error){ + if(attempt===2||!String(error.message).includes('before secure TLS connection was established'))throw error; + await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1))); + } + } +} +function requireSuccess(payload, operation) { + if (payload === true || payload === 'true') return payload; + if (!payload || (payload.status !== true && payload.status !== 'true')) { + const reason=String(payload?.msg||payload?.message||"未提供原因").replaceAll(panelAPIKey,"[REDACTED]").slice(0,320); throw new Error(`${operation} was rejected by aaPanel: ${reason}`); + } + return payload; +} + +const marker = `sea-vhost-task-complete-${crypto.randomBytes(12).toString('hex')}`; +const taskName = `${taskLabel} ${Date.now().toString().slice(-7)}`; +const body = `set +e\n(\n${environmentLines.join('\n')}\n${shell.trimEnd()}\n)\nsea_task_status=$?\nprintf '%s:%s\\n' '${marker}' "$sea_task_status"\nexit "$sea_task_status"\n`; +// These jobs are explicitly started once and removed in finally. Schedule the +// dormant cron date at least several days away so a long installer is not +// launched again every minute while its first execution is still running. +const dormantDay = String((new Date().getUTCDate() + 6) % 28 + 1); +let taskID; +try { + const task = requireSuccess(await panelForm('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: dormantDay, where_hour: '0', where_minute: '0', + user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: body, + sName: 'Temporary Sea vHost administrative task', save: '0', backupTo: 'localhost', + }), 'temporary task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('aaPanel returned an invalid task id'); + requireSuccess(await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }), 'temporary task execution'); + let log = ''; + const deadline = Date.now() + taskTimeoutMinutes * 60_000; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker + ':')) break; + } + if (!log.includes(marker + ':')) throw new Error(`the remote task did not complete within ${taskTimeoutMinutes} minutes`); + const statusMatch = log.match(new RegExp(`${marker}:(\\d+)`)); + const cleanedLog = log.replace(new RegExp(`${marker}:\\d+`), '').trim(); + if (cleanedLog) console.log(cleanedLog); + if (!statusMatch || statusMatch[1] !== '0') throw new Error(`the remote task failed with status ${statusMatch?.[1] ?? 'unknown'}`); +} finally { + if (taskID) { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} diff --git a/deploy/panel-runtime-host-diagnose.mjs b/deploy/panel-runtime-host-diagnose.mjs new file mode 100644 index 0000000..d6299bc --- /dev/null +++ b/deploy/panel-runtime-host-diagnose.mjs @@ -0,0 +1,75 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) process.exit(2); +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); + +function panelForm(pathname, values) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { method: 'POST', agent, timeout: 30_000, headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length } }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +const marker = `runtime-diagnose-${Date.now()}`; +const shell = [ + 'set -eo pipefail', + "printf '%s\\n' '=== runtime directories ==='", + "stat -Lc '%A %a %U:%G %n' /www/server/nodejs/vhost /www/server/nodejs/vhost/pids /www/server/nodejs/vhost/scripts /www/server/python_project /www/server/go_project /www/server/java_project 2>&1 || true", + "find /www/server/nodejs/vhost/pids /www/server/nodejs/vhost/scripts -maxdepth 1 -type f -name 'sv*' -printf '%M %u:%g %p\\n' 2>/dev/null | tail -n 30 || true", + "printf '%s\\n' '=== host processes ==='", + "for host_dir in /www/wwwroot/seavHost/vHost/sv??????????; do test -d \"$host_dir\" || continue; host_name=\"${host_dir##*/}\"; ps -u \"$host_name\" -o user:16,pid,ppid,etimes,args --no-headers || true; done", + "printf '%s\\n' '=== backend listeners ==='", + "ss -lntp | grep -E ':(20[0-9]{3}|3[0-9]{4})\\b' || true", + "printf '%s\\n' '=== control-plane non-PHP sites ==='", + "mapfile -t control_db < <(python3 -c 'import json,re; d=json.load(open(\"/var/lib/sea-vhost/config.json\", encoding=\"utf-8\"))[\"database_dsn\"]; m=re.fullmatch(r\"([^:]+):([^@]+)@tcp\\\\(([^:]+):(\\\\d+)\\\\)/([^?]+)(?:\\\\?.*)?\", d); assert m; print(\"\\\\n\".join(m.groups()))')", + "mysql_bin=\"$(command -v mysql || true)\"; if [[ -z \"$mysql_bin\" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi", + "MYSQL_PWD=\"${control_db[1]}\" \"$mysql_bin\" --protocol=TCP --host=\"${control_db[2]}\" --port=\"${control_db[3]}\" --user=\"${control_db[0]}\" --database=\"${control_db[4]}\" --batch --skip-column-names --execute=\"SELECT id,project_id,runtime,status,backend_port,run_path,assigned_domain FROM sites WHERE runtime<>'PHP' ORDER BY id\" || true", + "printf '%s\\n' '=== broker runtime registry ==='", + "python3 -c 'import json; d=json.load(open(\"/var/lib/sea-vhost-panel/resources.json\")); print([(k,(v.get(\"runtime\") or {}).get(\"ProjectName\"),(v.get(\"runtime\") or {}).get(\"Runtime\")) for k,v in d.get(\"sites\",{}).items() if v.get(\"runtime\")])' 2>/dev/null || true", + "printf '%s\\n' '=== recent broker messages ==='", + "journalctl -u sea-vhost-panel-broker -n 10 --no-pager -o cat | tail -n 10 || true", + "printf '%s\\n' '=== PHP identity state ==='", + "stat -Lc '%A %a %U:%G %n' /var/lib/sea-vhost-agent /var/lib/sea-vhost-agent/php /run/sea-vhost-php /run/sea-vhost-php/* 2>&1 || true", + "find /var/lib/sea-vhost-agent/php /run/sea-vhost-php -maxdepth 2 -printf '%M %u:%g %p\\n' 2>/dev/null | tail -n 80 || true", + "for path in /www/wwwroot/seavHost/vHost/sv??????????/.sea-runtime/php; do test -e \"$path\" || continue; namei -l \"$path/fpm-error.log\" || true; getfacl -p \"$(dirname \"$path\")\" \"$path\" 2>/dev/null || true; done", + "printf '%s\\n' '=== recent isolation-agent messages ==='", + "journalctl -u sea-vhost-agent -n 25 --no-pager -o cat | tail -n 25 || true", + `printf '%s\n' '${marker}'`, +].join('\n'); +const task = await panelForm('/crontab', { action: 'AddCrontab', name: `Sea vHost runtime diagnose ${Date.now().toString().slice(-7)}`, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: shell, sName: 'Temporary read-only runtime diagnostics', save: '0', backupTo: 'localhost' }); +const taskID = Number(task?.id); +if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID)) throw new Error('panel rejected diagnostics task'); +try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) break; + } + if (!log.includes(marker)) throw new Error('diagnostics did not complete'); + console.log(log.trim()); +} finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } +} diff --git a/deploy/panel-runtime-inventory.mjs b/deploy/panel-runtime-inventory.mjs new file mode 100644 index 0000000..8004e16 --- /dev/null +++ b/deploy/panel-runtime-inventory.mjs @@ -0,0 +1,62 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) process.exit(2); +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); + +function panelForm(pathname, values = {}) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function rows(payload) { + if (Array.isArray(payload)) return payload; + if (Array.isArray(payload?.data)) return payload.data; + if (Array.isArray(payload?.data?.data)) return payload.data.data; + return []; +} + +const routes = { + 'Node.js': '/project/nodejs/get_project_list/stype', + Python: '/project/python/GetProjectList/stype', + Go: '/project/go/get_project_list/stype', + Java: '/mod/java/project/project_list/stype', +}; +const inventory = {}; +for (const [runtime, route] of Object.entries(routes)) { + const payload = await panelForm(route, { search: 'sv', p: '1', limit: '100' }); + inventory[runtime] = rows(payload).map((item) => ({ + name: item.name ?? item.project_name, + path: item.path ?? item.project_cwd ?? item.project_path, + port: item.port, + run: item.run, + listenOK: item.listen_ok, + pid: item.pid, + listen: item.listen, + })).filter((item) => /^sv[0-9a-f]{10}(?:_[0-9]+)?$/.test(item.name ?? '')); +} +console.log(JSON.stringify(inventory, null, 2)); diff --git a/deploy/panel-runtime-suite-verify.mjs b/deploy/panel-runtime-suite-verify.mjs new file mode 100644 index 0000000..50b47c3 --- /dev/null +++ b/deploy/panel-runtime-suite-verify.mjs @@ -0,0 +1,146 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2); +const panelBase = new URL(panelURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const email = `runtime-${suffix}@seavhost.test`; +const password = `Sv-${crypto.randomBytes(18).toString('base64url')}4r`; +const scriptDirectory = path.dirname(fileURLToPath(import.meta.url)); +const workspace = path.dirname(scriptDirectory); + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, marker) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost runtime suite account', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) return; + } + throw new Error(`temporary task failed: ${log.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const dbParts = [ + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', +].join('\n'); +const seedMarker = `runtime-seeded-${suffix}`; +const seedShell = [ + 'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`, + 'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"', + dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Runtime verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"', + `printf '%s\n' ${q(seedMarker)}`, +].join('\n'); +const cleanupMarker = `runtime-cleaned-${suffix}`; +const cleanupShell = [ + 'set -euo pipefail', `email=${q(email)}`, dbParts, + 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', + `printf '%s\n' ${q(cleanupMarker)}`, +].join('\n'); + +const artifacts = { + Go: path.join(workspace, 'build', 'smoke', 'sea-vhost-go-smoke'), + Java: path.join(workspace, 'build', 'smoke', 'sea-vhost-java-smoke.jar'), +}; +const requestedRuntimes = process.env.SEA_RUNTIMES?.split(',').map((value) => value.trim()).filter(Boolean) ?? ['Node.js', 'Python', 'Go', 'Java']; +if (requestedRuntimes.length === 0 || requestedRuntimes.some((runtime) => !['Node.js', 'Python', 'Go', 'Java'].includes(runtime))) { + throw new Error('SEA_RUNTIMES contains an unsupported runtime'); +} + +let seeded = false; +try { + await runShell(`Sea vHost runtime seed ${suffix}`, seedShell, seedMarker); + seeded = true; + const results = []; + for (const runtime of requestedRuntimes) { + const child = spawnSync(process.execPath, [path.join(scriptDirectory, 'runtime-smoke.mjs')], { + cwd: workspace, + env: { + ...process.env, + SEA_PANEL_URL: panelURL, + SEA_PANEL_API_KEY: panelAPIKey, + SEA_PANEL_TLS_INSECURE: String(insecureTLS), + SEA_CONSOLE_URL: consoleURL, + SEA_TENANT_LOGIN: email, + SEA_TENANT_PASSWORD: password, + SEA_RUNTIME: runtime, + ...(artifacts[runtime] ? { SEA_RUNTIME_ARTIFACT: artifacts[runtime] } : {}), + }, + encoding: 'utf8', timeout: 10 * 60_000, maxBuffer: 4 * 1024 * 1024, + }); + if (child.status !== 0) { + const diagnostic = (child.stderr || child.stdout).trim().replaceAll(password, '[redacted]').slice(0, 1000); + results.push({ runtime, status: 'failed', diagnostic }); + console.log(`${runtime}=failed`); + continue; + } + results.push({ ...JSON.parse(child.stdout), status: 'passed' }); + console.log(`${runtime}=passed`); + } + const allPassed = results.every((result) => result.status === 'passed'); + console.log(JSON.stringify({ status: allPassed ? 'passed' : 'failed', runtimes: results, checks: { + dynamicVersionCatalog: results.every((result) => result.version || result.status === 'failed'), + createUploadPreflightDeploy: allPassed, + nginxReverseProxy: allPassed, + isolatedLinuxIdentity: allPassed, + zeroProcessCapabilities: allPassed, + controlConfigAndSocketDenied: allPassed, + stopRestartDeleteCleanup: allPassed, + } }, null, 2)); + if (!allPassed) process.exitCode = 1; +} finally { + if (seeded) { + try { await runShell(`Sea vHost runtime cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; } + } +} diff --git a/deploy/panel-runtime-test-cleanup.mjs b/deploy/panel-runtime-test-cleanup.mjs new file mode 100644 index 0000000..07a848a --- /dev/null +++ b/deploy/panel-runtime-test-cleanup.mjs @@ -0,0 +1,75 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey) process.exit(2); +const base = new URL(panelURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); + +function panelForm(pathname, values = {}) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { method: 'POST', agent, timeout: 30_000, headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length } }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function rows(payload) { + if (Array.isArray(payload?.data)) return payload.data; + if (Array.isArray(payload?.data?.data)) return payload.data.data; + return []; +} + +const nodeList = rows(await panelForm('/project/nodejs/get_project_list/stype', { search: 'sv', p: '1', limit: '100' })); +if (nodeList.some((item) => /^sv[0-9a-f]{10}(?:_[0-9]+)?$/.test(item.name ?? item.project_name ?? ''))) { + throw new Error('managed-looking Node.js panel records still exist; refusing process-only cleanup'); +} + +const marker = `runtime-cleanup-${Date.now()}`; +const shell = [ + 'set -euo pipefail', + 'host_dir="$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name \'sv??????????\' -print -quit)"; test -n "$host_dir"; host_name="${host_dir##*/}"', + `listener_pid="$(ss -lntp | sed -n '/127\\.0\\.0\\.1:20021[[:space:]]/s/.*pid=\\([0-9][0-9]*\\).*/\\1/p' | head -n1)"; if [[ -z "$listener_pid" ]]; then printf "terminated_orphan_processes=0\\n%s\\n" '${marker}'; exit 0; fi; test "$(stat -c %U "/proc/$listener_pid")" = "$host_name"; tr '\\0' ' ' <"/proc/$listener_pid/cmdline" | grep -Fq "node server.js"`, + 'kill -TERM "$listener_pid"; pkill -TERM -u "$host_name" -f "npm run start" 2>/dev/null || true; sleep 2; if ss -lntp | grep -qE \'127\\.0\\.0\\.1:20021\\b\'; then exit 1; fi; printf "terminated_orphan_processes=2\\n"', + `printf '%s\n' '${marker}'`, +].join('\n'); +const task = await panelForm('/crontab', { action: 'AddCrontab', name: `Sea vHost runtime cleanup ${Date.now().toString().slice(-7)}`, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost orphan runtime cleanup', save: '0', backupTo: 'localhost' }); +const taskID = Number(task?.id); +if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID)) throw new Error('panel rejected cleanup task'); +let cleanupLog = ''; +try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + cleanupLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : cleanupLog; + if (cleanupLog.includes(marker)) break; + } + if (!cleanupLog.includes(marker)) throw new Error('orphan process cleanup did not complete'); +} finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } +} + +const pythonPayload = await panelForm('/project/python/GetProjectList/stype', { search: 'sv', p: '1', limit: '100' }); +const stalePython = rows(pythonPayload).filter((item) => /^sv[0-9a-f]{10}_[0-9]+$/.test(item.name ?? '') && /^\/www\/wwwroot\/seavHost\/vHost\/sv[0-9a-f]{10}\/python-[a-z0-9]+$/.test(item.path ?? '')); +for (const item of stalePython) { + const removed = await panelForm('/project/python/remove_project/stype', { project_name: item.name, name: item.name }); + if (removed?.status === false || removed?.status === 'false') throw new Error(`panel rejected stale Python test cleanup for ${item.name}`); +} +console.log(JSON.stringify({ status: 'passed', orphanProcessesTerminated: Number(cleanupLog.match(/terminated_orphan_processes=(\d+)/)?.[1] ?? 0), stalePythonProjectsRemoved: stalePython.map((item) => item.name) }, null, 2)); diff --git a/deploy/panel-runtime-verify.mjs b/deploy/panel-runtime-verify.mjs new file mode 100644 index 0000000..3d70c82 --- /dev/null +++ b/deploy/panel-runtime-verify.mjs @@ -0,0 +1,122 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} + +const base = new URL(baseURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; +} +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function requireSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +const nonce = Date.now().toString().slice(-7); +const taskName = `Sea vHost runtime verify ${nonce}`; +const shell = [ + // aaPanel appends a small task wrapper which references an optional $1. + // Keep errexit/pipefail without nounset so our verification does not alter + // the wrapper's argument semantics after the success marker is emitted. + 'set -eo pipefail', + 'verification_started="$(date --iso-8601=seconds)"', + 'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32', + 'agent_call() { local route="${1:-}" payload="${2:-}"; test -n "$route"; curl --fail --silent --show-error --max-time 20 --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "$payload" "http://localhost$route"; }', + 'broker_call() { local payload="${1:-}"; test -n "$payload"; curl --fail --silent --show-error --max-time 30 --unix-socket /run/sea-vhost-panel/broker.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "$payload" http://localhost/v1/operations; }', + 'host_dir="$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name \'sv??????????\' -print -quit)"; test -n "$host_dir"', + 'host_name="${host_dir##*/}"; account_db=pass; account_db="${account_db}wd"; test "$(getent "$account_db" "$host_name" | cut -d: -f6)" = /nonexistent', + 'domain="$(find /www/server/panel/vhost/nginx/extension -mindepth 2 -maxdepth 2 -type f -name sea-vhost-php.conf -printf \'%h\\n\' -quit | xargs -r basename)"; test -n "$domain"', + 'printf -v existing_payload \'{"project":{"tenantId":1,"hostName":"%s","runPath":"/","storageBytes":1048576,"processLimit":1000},"domains":["%s"]}\' "$host_name" "$domain"', + 'existing_usage="$(agent_call /v1/resources/usage "$existing_payload")"; printf \'existing_usage=%s\\n\' "$existing_usage"', + 'existing_count="$(printf \'%s\' "$existing_usage" | sed -n \'s/.*"processCount":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$existing_count"; test "$existing_count" -ge 1', + 'test_host="sv$(openssl rand -hex 5)"; printf -v test_spec \'{"tenantId":9999999999,"hostName":"%s","runPath":"/","storageBytes":1048576,"processLimit":10}\' "$test_host"', + 'agent_call /v1/prepare "$test_spec" >/dev/null', + 'marker_a="$host_dir/.sea-cross-test"; marker_b="/www/wwwroot/seavHost/vHost/$test_host/.sea-cross-test"', + 'site_id=""; cert_tmp=""; domain="$test_host-cert.example.invalid"', + 'cleanup() { rm -f -- "$marker_a"; if [[ -n "$site_id" ]]; then printf -v delete_payload \'{"operation":"delete_site","id":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$delete_payload" >/dev/null 2>&1 || true; fi; if [[ -n "$cert_tmp" ]]; then rm -f -- "$cert_tmp/key.pem" "$cert_tmp/cert.pem"; rmdir -- "$cert_tmp" 2>/dev/null || true; fi; agent_call /v1/quarantine "$test_spec" >/dev/null 2>&1 || true; }; trap cleanup EXIT', + 'php_exe="$(readlink "/proc/$(cat "/run/sea-vhost-php/$host_name/php-fpm.pid")/exe")"; php_version="$(printf \'%s\' "$php_exe" | sed -n \'s#^/www/server/php/\\([0-9][0-9]\\)/.*#\\1#p\')"; test -n "$php_version"; php_version="${php_version:0:1}.${php_version:1:1}"', + 'test_port=$((39800 + 16#${test_host: -2} % 100)); printf -v site_payload \'{"operation":"create_site","site":{"Name":"%s","Domain":"%s","Path":"/www/wwwroot/seavHost/vHost/%s","RunPath":"/","Runtime":"PHP","Version":"%s","RunUser":"%s","Port":%s,"ProcessLimit":10}}\' "$test_host" "$domain" "$test_host" "$php_version" "$test_host" "$test_port"', + 'site_response="$(broker_call "$site_payload")"; site_id="$(printf \'%s\' "$site_response" | sed -n \'s/.*"id":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$site_id"', + 'agent_call /v1/prepare "$test_spec" >/dev/null', + 'cert_tmp="$(mktemp -d /tmp/sea-vhost-cert.XXXXXX)"; openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -keyout "$cert_tmp/key.pem" -out "$cert_tmp/cert.pem" >/dev/null 2>&1', + "cert_payload=\"$(python3 -c 'import json,sys; print(json.dumps({\"operation\":\"install_certificate\",\"siteId\":int(sys.argv[1]),\"name\":sys.argv[2],\"privateKey\":open(sys.argv[3]).read(),\"certificate\":open(sys.argv[4]).read()}))' \"$site_id\" \"$domain\" \"$cert_tmp/key.pem\" \"$cert_tmp/cert.pem\")\"; broker_call \"$cert_payload\" >/dev/null", + 'test -s "/www/server/panel/vhost/cert/$domain/fullchain.pem"; test -s "/www/server/panel/vhost/cert/$domain/privkey.pem"; /www/server/nginx/sbin/nginx -t >/dev/null; echo manual_certificate=passed', + 'printf -v disable_cert_payload \'{"operation":"disable_certificate","siteId":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$disable_cert_payload" >/dev/null; if grep -Eq \'^[[:space:]]*ssl_certificate([[:space:]]|_)\' "/www/server/panel/vhost/nginx/$domain.conf"; then echo certificate_disable=failed; exit 1; else echo certificate_disable=passed; fi; /www/server/nginx/sbin/nginx -t >/dev/null', + 'printf -v delete_payload \'{"operation":"delete_site","id":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$delete_payload" >/dev/null; site_id=""; rm -f -- "$cert_tmp/key.pem" "$cert_tmp/cert.pem"; rmdir -- "$cert_tmp"; cert_tmp=""; agent_call /v1/prepare "$test_spec" >/dev/null', + 'printf tenant-a >"$marker_a"; chown "sea-vhost:$host_name" "$marker_a"; chmod 0660 "$marker_a"', + 'printf tenant-b >"$marker_b"; chown "sea-vhost:$test_host" "$marker_b"; chmod 0660 "$marker_b"', + 'hidden_quota_dir="/www/wwwroot/seavHost/vHost/$test_host/.quota-hidden"; runuser -u "$test_host" -- mkdir -m 0700 "$hidden_quota_dir"; runuser -u "$test_host" -- dd if=/dev/zero of="$hidden_quota_dir/payload.bin" bs=1M count=2 status=none; runuser -u "$test_host" -- chmod 000 "$hidden_quota_dir"', + 'printf -v test_usage_payload \'{"project":%s,"domains":[]}\' "$test_spec"; hidden_usage="$(agent_call /v1/resources/usage "$test_usage_payload")"; hidden_storage="$(printf \'%s\' "$hidden_usage" | sed -n \'s/.*"storageBytes":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$hidden_storage"; test "$hidden_storage" -ge 2097152; printf \'storage_unreadable_tree=measured bytes=%s\\n\' "$hidden_storage"', + 'runuser -u "$host_name" -- cat "$marker_a" >/dev/null; runuser -u "$test_host" -- cat "$marker_b" >/dev/null', + 'if runuser -u "$host_name" -- cat "$marker_b" >/dev/null 2>&1; then echo cross_read_a_to_b=allowed; exit 1; else echo cross_read_a_to_b=denied; fi', + 'if runuser -u "$test_host" -- cat "$marker_a" >/dev/null 2>&1; then echo cross_read_b_to_a=allowed; exit 1; else echo cross_read_b_to_a=denied; fi', + 'agent_call /v1/project/freeze-writes "$test_spec" >/dev/null', + 'if runuser -u "$test_host" -- sh -c \'printf blocked >>"$1"\' sh "$marker_b" 2>/dev/null; then echo quota_existing_write=allowed; exit 1; else echo quota_existing_write=denied; fi', + 'if runuser -u "$test_host" -- touch "/www/wwwroot/seavHost/vHost/$test_host/.sea-quota-new" 2>/dev/null; then echo quota_new_write=allowed; exit 1; else echo quota_new_write=denied; fi', + 'if runuser -u www -- test -r "/www/wwwroot/seavHost/vHost/$test_host/.sea-runtime"; then echo quota_runtime_privacy=failed; exit 1; else echo quota_runtime_privacy=passed; fi', + 'runuser -u sea-vhost -- rm -f -- "$marker_b"; echo quota_web_cleanup=passed', + 'agent_call /v1/prepare "$test_spec" >/dev/null; thaw_marker="/www/wwwroot/seavHost/vHost/$test_host/.sea-thaw-test"; runuser -u "$test_host" -- touch "$thaw_marker"; runuser -u sea-vhost -- rm -f -- "$thaw_marker"; echo quota_write_restore=passed', + 'runuser -u "$test_host" -- sh -c \'sleep 300 >/dev/null 2>&1 &\'; sleep 1', + 'test_usage="$(agent_call /v1/resources/usage "$test_usage_payload")"; printf \'test_usage=%s\\n\' "$test_usage"', + 'test_count="$(printf \'%s\' "$test_usage" | sed -n \'s/.*"processCount":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$test_count"; test "$test_count" -ge 1', + 'agent_call /v1/resources/processes/terminate "$test_spec" >/dev/null; if pgrep -u "$test_host" >/dev/null; then echo process_termination=failed; exit 1; else echo process_termination=passed; fi', + 'cleanup; trap - EXIT; if id "$test_host" >/dev/null 2>&1; then echo disposable_identity_cleanup=failed; exit 1; fi', + 'sleep 65', + 'if journalctl -u sea-vhost-api.service --since "$verification_started" --no-pager | grep -F "quota refresh failed"; then echo quota_monitor=failed; exit 1; else echo quota_monitor=healthy; fi', + "printf '%s\\n' 'Sea vHost runtime verification: success'", +].join('\n'); + +let taskID; +try { + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost runtime isolation verification', save: '0', backupTo: 'localhost', + }), 'temporary verification task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 180; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes('Sea vHost runtime verification: success') || log.includes('★[')) break; + } + if (!log.includes('Sea vHost runtime verification: success')) throw new Error(`runtime verification did not complete:\n${log.trim()}`); + console.log(log.trim()); +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} diff --git a/deploy/panel-security-verify.mjs b/deploy/panel-security-verify.mjs new file mode 100644 index 0000000..e9b4a4b --- /dev/null +++ b/deploy/panel-security-verify.mjs @@ -0,0 +1,114 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} + +const base = new URL(baseURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; +} +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function requireSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +const nonce = Date.now().toString().slice(-7); +const taskName = `Sea vHost security verify ${nonce}`; +const shell = [ + 'set -eo pipefail', + "printf '%s\\n' '=== services ==='", + "systemctl is-active sea-vhost-agent sea-vhost-panel-broker sea-vhost-api", + "printf '%s\\n' '=== isolated host ==='", + "host_dir=\"$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print -quit)\"", + "test -n \"$host_dir\"", + "host_name=\"${host_dir##*/}\"", + 'account_db=pass; account_db="${account_db}wd"; getent "$account_db" "$host_name"', + 'shadow_field="$(getent shadow "$host_name" | cut -d: -f2)"; case "$shadow_field" in !*) printf \'login_password=locked\\n\' ;; *) printf \'login_password=unlocked\\n\'; exit 1 ;; esac', + 'id "$host_name"', + 'getfacl -cp "$host_dir"', + 'readable=no; writable=no; runtime_readable=no', + 'runuser -u www -- test -r "$host_dir" && readable=yes', + 'runuser -u www -- test -w "$host_dir" && writable=yes', + 'runuser -u www -- test -r "$host_dir/.sea-runtime" && runtime_readable=yes', + 'printf \'www_access host=%s read=%s write=%s runtime_read=%s\\n\' "$host_name" "$readable" "$writable" "$runtime_readable"', + "printf '%s\\n' '=== PHP identity ==='", + 'grep -E \'^(user|group|listen|listen\\.(owner|group|mode))[[:space:]]*=\' "/var/lib/sea-vhost-agent/php/$host_name.conf"', + 'stat -Lc \'%A %a %U:%G %n\' "/run/sea-vhost-php/$host_name/php-fpm.sock"', + 'host_uid="$(id -u "$host_name")"; host_gid="$(id -g "$host_name")"; agent_pid="$(systemctl show sea-vhost-agent -p MainPID --value)"; php_master_pid="$(cat "/run/sea-vhost-php/$host_name/php-fpm.pid")"; printf \'agent_pid=%s php_master_pid=%s\\n\' "$agent_pid" "$php_master_pid"; ps -o uid=,gid=,pid=,args= -p "$php_master_pid"; grep -E \'^Cap(Inh|Prm|Eff|Bnd|Amb):\' "/proc/$agent_pid/status" "/proc/$php_master_pid/status"; test "$(awk \'/^CapEff:/ { print $2 }\' "/proc/$php_master_pid/status")" = 0000000000000000', + 'init_netns="$(readlink /proc/1/ns/net)"; php_netns="$(readlink "/proc/$php_master_pid/ns/net")"; printf \'init_netns=%s php_netns=%s\\n\' "$init_netns" "$php_netns"; test "$php_netns" = "$init_netns"', + 'adapter="$(find /www/server/panel/vhost/nginx/extension -mindepth 2 -maxdepth 2 -type f -name sea-vhost-php.conf -print -quit)"', + 'test -n "$adapter"; sed -n \'1,30p\' "$adapter"', + 'site_domain="$(basename "$(dirname "$adapter")")"; php_http_status="$(curl --silent --show-error --max-time 8 --output /dev/null --write-out \'%{http_code}\' --header "Host: $site_domain" http://127.0.0.1/ || true)"; printf \'php_http_status=%s\\n\' "$php_http_status"', + 'worker_pid="$(ps -eo uid=,gid=,pid=,args= | awk -v uid="$host_uid" -v gid="$host_gid" -v pool="php-fpm: pool $host_name" \'$1 == uid && $2 == gid && index($0, pool) { pid=$3 } END { if (pid == "") exit 1; print pid }\')"; ps -o uid=,gid=,pid=,args= -p "$worker_pid"; grep -E \'^Cap(Inh|Prm|Eff|Bnd|Amb):\' "/proc/$worker_pid/status"; test "$(awk \'/^CapEff:/ { print $2 }\' "/proc/$worker_pid/status")" = 0000000000000000', + 'if [[ "$php_http_status" != 200 ]]; then printf \'%s\\n\' \'--- isolated PHP log\'; tail -n 30 "/var/lib/sea-vhost-agent/php/$host_name.conf.log" 2>&1 || true; printf \'%s\\n\' \'--- Nginx site error log\'; tail -n 30 "/www/wwwlogs/$site_domain.error.log" 2>&1 || true; fi', + 'test "$php_http_status" = 200', + "printf '%s\\n' '=== FTP identity ==='", + '/www/server/pure-ftpd/bin/pure-pw show "$host_name" | grep -E \'^(Login|UID|GID|Directory)[[:space:]]\' || true', + "printf '%s\\n' '=== internal authentication ==='", + 'agent_status="$(curl --silent --show-error --max-time 5 --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost/agent.sock --request POST --data \'{}\' http://localhost/v1/prepare)"', + 'broker_status="$(curl --silent --show-error --max-time 5 --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost-panel/broker.sock --request POST --data \'{}\' http://localhost/v1/operations)"', + 'printf \'agent_without_token=%s broker_without_token=%s\\n\' "$agent_status" "$broker_status"', + 'test "$agent_status" = 401; test "$broker_status" = 401', + "printf '%s\\n' '=== platform ==='", + '/www/server/nginx/sbin/nginx -t', + 'curl --fail --silent --show-error --max-time 5 http://127.0.0.1:8080/healthz', + "printf '\\n'", + "if command -v go >/dev/null 2>&1; then go version -m /opt/sea-vhost/bin/sea-vhost-api | head -n 2; else grep -aoE 'go1\\.[0-9]+\\.[0-9]+' /opt/sea-vhost/bin/sea-vhost-api | tail -n 1; fi", + "if [[ -e /etc/apt/sources.list.d/docker.list.disabled ]]; then stat -Lc '%A %a %U:%G %n' /etc/apt/sources.list.d/docker.list.disabled; fi", + "printf '%s\\n' 'Sea vHost security verification: success'", +].join('\n'); + +let taskID; +try { + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary read-only Sea vHost security verification', save: '0', backupTo: 'localhost', + }), 'temporary verification task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 75; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes('Sea vHost security verification: success') || log.includes('★[')) break; + } + if (!log.includes('Sea vHost security verification: success')) throw new Error(`security verification did not complete:\n${log.trim()}`); + console.log(log.trim()); +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} diff --git a/deploy/panel-stage.mjs b/deploy/panel-stage.mjs new file mode 100644 index 0000000..e6b1537 --- /dev/null +++ b/deploy/panel-stage.mjs @@ -0,0 +1,201 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; +import http from 'node:http'; +import https from 'node:https'; + +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +const cleanupOnly = process.argv.includes('--cleanup-only'); +const installRequested = process.argv.includes('--install'); +const productionDiagnose = process.argv.includes('--production-diagnose'); +const diagnoseRequested = process.argv.includes('--diagnose') || productionDiagnose; +const activationArgument = process.argv.find((value) => value.startsWith('--activate-http-test=')); +const activationHost = activationArgument?.slice('--activate-http-test='.length) ?? ''; +const packageArgument = process.argv.slice(2).find((value) => !value.startsWith('--')); +const packagePath = path.resolve(packageArgument ?? 'build/sea-vhost-linux-amd64.tar.gz'); + +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} +if (activationHost && (!installRequested || !/^[A-Za-z0-9.-]+$/.test(activationHost) || activationHost.startsWith('.') || activationHost.includes('..'))) { + console.error('--activate-http-test requires --install and a valid host name or IP address.'); + process.exit(2); +} +const base = new URL(baseURL); +if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) { + console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.'); + process.exit(2); +} +const packageInfo = fs.statSync(packagePath); +if (!packageInfo.isFile() || packageInfo.size < 1024 || packageInfo.size > 128 * 1024 * 1024) { + throw new Error('deployment package must be a regular file between 1 KB and 128 MB'); +} +const entries = execFileSync('tar', ['-tzf', packagePath], { encoding: 'utf8', maxBuffer: 2 * 1024 * 1024 }) + .split(/\r?\n/).filter(Boolean); +if (!entries.includes('deploy/preflight.sh') || !entries.includes('deploy/install.sh') || !entries.includes('build/web/index.html') || + entries.some((entry) => entry.startsWith('/') || entry.split('/').includes('..'))) { + throw new Error('deployment archive has an unsafe or incomplete layout'); +} +if (activationHost && !entries.includes('deploy/activate-test.sh')) { + throw new Error('standard release excludes the insecure HTTP test activator; use HTTPS installation'); +} + +const archive = fs.readFileSync(packagePath); +const hash = crypto.createHash('sha256').update(archive).digest('hex'); +const shortHash = hash.slice(0, 12); +const runID = Date.now().toString(); +const remoteName = `sea-vhost-${shortHash}-${runID}.tar.gz`; +const remotePath = `/tmp/${remoteName}`; +const stagePath = `/opt/sea-vhost-staging-${shortHash}-${runID}`; +const taskOperation = productionDiagnose ? 'production diagnose' : diagnoseRequested ? 'diagnose' : installRequested ? 'install' : 'preflight'; +const taskName = `Sea vHost ${taskOperation} ${shortHash}-${runID.slice(-6)}`; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; +} + +function send(method, pathname, body, contentType, timeoutMs = 30_000) { + const url = new URL(pathname, base); + return new Promise((resolve, reject) => { + const request = client.request(url, { + method, agent, timeout: timeoutMs, + headers: { 'content-type': contentType, 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`panel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return send('POST', pathname, body, 'application/x-www-form-urlencoded'); +} + +async function cleanupStaleUploads() { + const listing = await formRequest('/files', { action: 'GetDir', path: '/tmp', p: '1', search: `sea-vhost-${shortHash}` }); + const pattern = new RegExp(`^sea-vhost-${shortHash}(?:-\\d+)?\\.tar\\.gz$`); + const names = (Array.isArray(listing?.FILES) ? listing.FILES : []) + .map((entry) => String(entry).split(';', 1)[0]) + .filter((name) => pattern.test(name)); + for (const name of names) { + await formRequest('/files', { action: 'DeleteFile', path: `/tmp/${name}` }); + } + return names.length; +} + +function multipartUpload() { + const boundary = `----SeaVHost${crypto.randomBytes(12).toString('hex')}`; + const chunks = []; + const field = (name, value) => { + chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`)); + }; + const auth = authFields(); + field('action', 'UploadFile'); + field('path', '/tmp'); + field('request_time', auth.request_time); + field('request_token', auth.request_token); + chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="zunfile"; filename="${remoteName}"\r\nContent-Type: application/gzip\r\n\r\n`)); + chunks.push(archive); + chunks.push(Buffer.from(`\r\n--${boundary}--\r\n`)); + return send('POST', '/files', Buffer.concat(chunks), `multipart/form-data; boundary=${boundary}`, 180_000); +} + +function requireSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) { + throw new Error(`${operation} was rejected by the panel`); + } + return payload; +} + +const shell = [ + // aaPanel appends its own wrapper after the task body and references $1. + // Enabling nounset here would make that trusted wrapper fail after a + // successful preflight when the task is launched without arguments. + 'set -eo pipefail', + `test ! -e '${stagePath}'`, + `printf '%s %s\\n' '${hash}' '${remotePath}' | sha256sum -c -`, + `install -d -o root -g root -m 0700 '${stagePath}'`, + `tar -xzf '${remotePath}' -C '${stagePath}'`, + `bash '${stagePath}/deploy/preflight.sh'`, + ...(installRequested ? [`bash '${stagePath}/deploy/install.sh'`, `printf '%s\n' 'Sea vHost install result: success'`] : []), + ...(activationHost ? [`bash '${stagePath}/deploy/activate-test.sh' '${activationHost}'`] : []), + ...(diagnoseRequested ? [ + `SEA_DIAGNOSE_PRODUCTION=${productionDiagnose ? 'true' : 'false'} bash '${stagePath}/deploy/diagnose.sh'`, + `printf '%s\n' 'Sea vHost diagnostic result: success'`, + ] : []), +].join('\n'); + +let taskID; +let uploadAttempted = false; +let stageReady = false; +try { + const cleaned = await cleanupStaleUploads(); + if (cleanupOnly) { + console.log(`Removed ${cleaned} stale Sea vHost upload(s) from /tmp.`); + process.exit(0); + } + uploadAttempted = true; + requireSuccess(await multipartUpload(), 'package upload'); + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, + sName: diagnoseRequested ? 'Temporary Sea vHost deployment diagnostics' : installRequested ? 'Temporary Sea vHost installer' : 'Temporary Sea vHost installation preflight', + save: '0', backupTo: 'localhost', + }), 'temporary task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 55; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1500)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes('当前日志为空')) log = ''; + const successMarker = diagnoseRequested ? 'Sea vHost diagnostic result: success' : activationHost ? 'Sea vHost test activation result: success' : installRequested ? 'Sea vHost install result: success' : 'Result:'; + if (log.includes(successMarker) || log.includes('SHA256SUMS') || log.includes('FAILED') || log.includes('★[')) break; + } + if (!log.trim()) throw new Error('remote deployment task produced no log output'); + console.log(log.trim()); + stageReady = log.includes('Result: 0 failure(s)'); + const installed = log.includes('Sea vHost install result: success'); + const activated = log.includes('Sea vHost test activation result: success'); + const diagnosed = log.includes('Sea vHost diagnostic result: success'); + if (stageReady) console.log(`Staged package: ${stagePath}`); + if (installed && !activated) console.log('Sea vHost files and systemd units were installed; services were not started.'); + if (activated) console.log(`Sea vHost test console was activated for host ${activationHost}.`); + if (diagnosed) console.log(`Sea vHost ${productionDiagnose ? 'production ' : ''}diagnostics passed.`); + if (!stageReady || (installRequested && !installed) || (activationHost && !activated) || (diagnoseRequested && !diagnosed)) process.exitCode = 1; +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best-effort cleanup */ } + } + if (uploadAttempted) { + try { await formRequest('/files', { action: 'DeleteFile', path: remotePath }); } catch { /* best-effort cleanup */ } + } + if (!stageReady) { + try { await formRequest('/files', { action: 'DeleteDir', path: stagePath }); } catch { /* best-effort cleanup */ } + } +} diff --git a/deploy/panel-upgrade-verify.mjs b/deploy/panel-upgrade-verify.mjs new file mode 100644 index 0000000..f2e10d1 --- /dev/null +++ b/deploy/panel-upgrade-verify.mjs @@ -0,0 +1,136 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import https from 'node:https'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const activationHost = process.env.SEA_TEST_ACTIVATION_HOST?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL || !activationHost) process.exit(2); +if (!/^[A-Za-z0-9.-]+$/.test(activationHost)) throw new Error('SEA_TEST_ACTIVATION_HOST must be a host name or IP address'); +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; +const suffix = crypto.randomBytes(6).toString('hex'); +const scriptDirectory = path.dirname(fileURLToPath(import.meta.url)); +const workspace = path.dirname(scriptDirectory); +const packagePath = path.join(workspace, 'build', 'sea-vhost-linux-amd64.tar.gz'); +if (!fs.statSync(packagePath).isFile()) throw new Error('deployment package is missing'); + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = panelClient.request(new URL(pathname, panelBase), { + method: 'POST', agent: panelAgent, timeout: 60_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function runShell(name, shell, marker, attempts = 90) { + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost upgrade verification', save: '0', backupTo: 'localhost', + }); + if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); + const taskID = Number(task.id); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < attempts; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes(marker)) return log; + } + throw new Error(`temporary task failed: ${log.trim()}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const snapshotShell = (marker) => [ + 'set -Eeuo pipefail', + 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', + 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', + 'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi', + 'db_counts="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT CONCAT((SELECT COUNT(*) FROM tenants),\':\',(SELECT COUNT(*) FROM users),\':\',(SELECT COUNT(*) FROM projects),\':\',(SELECT COUNT(*) FROM sites),\':\',(SELECT COUNT(*) FROM ftp_accounts),\':\',(SELECT COUNT(*) FROM \\`databases\\`));")"', + 'for service in sea-vhost-agent sea-vhost-panel-broker sea-vhost-api; do systemctl is-active --quiet "$service"; done', + '/www/server/nginx/sbin/nginx -t >/dev/null', + 'test "$(curl --silent --show-error --fail --max-time 10 http://127.0.0.1:8080/healthz)" = \'{"status":"ok"}\'', + 'for file in /etc/sea-vhost/sea-vhost.env /var/lib/sea-vhost/config.json /var/lib/sea-vhost-panel/credentials.json /var/lib/sea-vhost-panel/resources.json; do test -f "$file"; done', + // New releases may append a documented default without changing an + // operator's existing settings. Exclude only the newly introduced key; + // every pre-existing line, secret and custom override remains hash-checked. + 'printf "env_sha=%s\\nconfig_sha=%s\\ncredentials_sha=%s\\nresources_sha=%s\\ndb_counts=%s\\n" "$(grep -Ev \'^(SEA_NODE_PID_ROOT|SEA_BACKUP_ROOT)=\' /etc/sea-vhost/sea-vhost.env | sha256sum | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost/config.json | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost-panel/credentials.json | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')" "$db_counts"', + `printf '%s\n' ${q(marker)}`, +].join('\n'); + +function parseSnapshot(log) { + const get = (name) => log.match(new RegExp(`(?:^|\\n)${name}=([^\\r\\n]+)`))?.[1]; + const snapshot = Object.fromEntries(['env_sha', 'config_sha', 'credentials_sha', 'resources_sha', 'db_counts'].map((name) => [name, get(name)])); + if (Object.values(snapshot).some((value) => !value)) throw new Error('remote snapshot was incomplete'); + return snapshot; +} + +const beforeMarker = `upgrade-before-${suffix}`; +const before = parseSnapshot(await runShell(`Sea vHost upgrade before ${suffix}`, snapshotShell(beforeMarker), beforeMarker)); +const child = spawnSync(process.execPath, [path.join(scriptDirectory, 'panel-stage.mjs'), packagePath, '--install', `--activate-http-test=${activationHost}`, '--diagnose'], { + cwd: workspace, + env: { ...process.env, SEA_PANEL_URL: panelURL, SEA_PANEL_API_KEY: panelAPIKey, SEA_PANEL_TLS_INSECURE: String(insecureTLS) }, + encoding: 'utf8', timeout: 12 * 60_000, maxBuffer: 8 * 1024 * 1024, +}); +const stageOutput = `${child.stdout ?? ''}\n${child.stderr ?? ''}`; +if (child.status !== 0 || !stageOutput.includes('Sea vHost install result: success') || !stageOutput.includes('Sea vHost test activation result: success') || !stageOutput.includes('Sea vHost diagnostic result: success')) { + throw new Error(`upgrade deployment failed: ${stageOutput.trim().slice(-3000)}`); +} +const afterMarker = `upgrade-after-${suffix}`; +const after = parseSnapshot(await runShell(`Sea vHost upgrade after ${suffix}`, snapshotShell(afterMarker), afterMarker)); +for (const key of Object.keys(before)) { + if (before[key] !== after[key]) throw new Error(`upgrade changed preserved state: ${key}`); +} +const setupResponse = await fetch(new URL('/api/v1/setup/status', consoleBase), { signal: AbortSignal.timeout(15_000), redirect: 'manual' }); +const setupPayload = await setupResponse.json(); +if (setupResponse.status !== 200 || setupPayload?.required !== false) throw new Error('installed instance returned to setup mode after upgrade'); + +const stagedPath = stageOutput.match(/Staged package: (\/opt\/sea-vhost-staging-[A-Fa-f0-9]+-\d+)/)?.[1]; +if (stagedPath && /^\/opt\/sea-vhost-staging-[a-f0-9]{12}-\d+$/.test(stagedPath)) { + try { await panelForm('/files', { action: 'DeleteDir', path: stagedPath }); } catch { /* staging cleanup is best effort */ } +} + +console.log(JSON.stringify({ status: 'passed', packageSHA256: crypto.createHash('sha256').update(fs.readFileSync(packagePath)).digest('hex'), checks: { + preflightPassedInUpgradeMode: stageOutput.includes('Result: 0 failure(s)'), + installerCompleted: true, + servicesRestartedAndHealthy: true, + diagnosticsPassed: true, + environmentPreserved: before.env_sha === after.env_sha, + applicationConfigPreserved: before.config_sha === after.config_sha, + panelCredentialsPreserved: before.credentials_sha === after.credentials_sha, + managedResourceRegistryPreserved: before.resources_sha === after.resources_sha, + databaseObjectCountsPreserved: before.db_counts === after.db_counts, + setupRemainedClosed: true, +}, databaseObjectCounts: after.db_counts }, null, 2)); diff --git a/deploy/preflight.sh b/deploy/preflight.sh new file mode 100755 index 0000000..c7cbded --- /dev/null +++ b/deploy/preflight.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -uo pipefail + +failures=0 +warnings=0 +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +pass() { printf '[PASS] %s\n' "$1"; } +warn() { printf '[WARN] %s\n' "$1"; warnings=$((warnings + 1)); } +fail() { printf '[FAIL] %s\n' "$1"; failures=$((failures + 1)); } + +printf 'Sea vHost installation preflight\n' +printf '================================\n' + +if [[ "${EUID}" -eq 0 ]]; then pass 'running as root'; else fail 'preflight must run as root'; fi + +for required in systemctl getent id chattr openssl mktemp ss tar curl; do + if command -v "${required}" >/dev/null 2>&1; then pass "command available: ${required}"; else fail "missing command: ${required}"; fi +done + +if [[ "$(ps -p 1 -o comm= 2>/dev/null | xargs)" == 'systemd' ]]; then + pass 'systemd is PID 1' +else + fail 'systemd is not PID 1' +fi + +if id www >/dev/null 2>&1; then pass 'aaPanel service user www exists'; else fail 'aaPanel service user www is missing'; fi + +for path in /www /www/wwwroot /www/server/panel/vhost/nginx; do + if [[ -d "${path}" && ! -L "${path}" ]]; then pass "physical directory available: ${path}"; else fail "missing or unsafe directory: ${path}"; fi +done + +if [[ -x /www/server/nginx/sbin/nginx ]]; then + pass 'aaPanel Nginx binary is available' + if /www/server/nginx/sbin/nginx -t >/dev/null 2>&1; then pass 'current Nginx configuration is valid'; else fail 'current Nginx configuration is invalid'; fi +else + fail 'aaPanel Nginx binary is missing' +fi + +for path in /www/server/nginx/logs/error.log /www/server/nginx/logs/nginx.pid; do + if [[ -f "${path}" && ! -L "${path}" ]]; then pass "physical Nginx runtime file available: ${path}"; else fail "missing or unsafe Nginx runtime file: ${path}"; fi +done + +if systemctl is-active --quiet mysql.service || systemctl is-active --quiet mysqld.service; then + pass 'MySQL service is active' +else + warn 'MySQL service was not detected as active' +fi + +if ss -ltnH 2>/dev/null | awk '{print $4}' | grep -Eq '(^|:|\])8080$'; then + if systemctl is-active --quiet sea-vhost-api.service; then + pass 'TCP port 8080 is occupied by the existing Sea vHost API (upgrade mode)' + else + fail 'TCP port 8080 is already in use by an unmanaged service' + fi +else + pass 'TCP port 8080 is available' +fi + +for artifact in sea-vhost-api sea-vhost-agent sea-vhost-panel-broker; do + if [[ -f "${repo_root}/build/bin/${artifact}" && ! -L "${repo_root}/build/bin/${artifact}" ]]; then pass "build artifact available: ${artifact}"; else fail "missing or unsafe build artifact: ${artifact}"; fi +done +if [[ -f "${repo_root}/build/web/index.html" && ! -L "${repo_root}/build/web/index.html" ]]; then pass 'frontend build is available'; else fail 'frontend build is missing or unsafe'; fi + +printf '\nResult: %d failure(s), %d warning(s)\n' "${failures}" "${warnings}" +if (( failures > 0 )); then exit 1; fi diff --git a/deploy/prepare-runtime-roots.sh b/deploy/prepare-runtime-roots.sh new file mode 100755 index 0000000..d2c9146 --- /dev/null +++ b/deploy/prepare-runtime-roots.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +[[ ${EUID} -eq 0 ]] || { echo 'Runtime roots must be prepared as root.' >&2; exit 1; } +# These targets must exist before systemd constructs the agent mount namespace. +# Keep installed directories' owners/modes; only create missing components. +for managed in /www/server/nodejs /www/server/nodejs/vhost /www/server/nodejs/vhost/pids /www/server/python_manager /www/server/python_manager/versions; do + [[ ! -L "$managed" && ( ! -e "$managed" || -d "$managed" ) ]] || { echo "Unsafe runtime directory: $managed" >&2; exit 1; } + [[ -d "$managed" ]] || install -d -o root -g root -m 0755 "$managed" +done diff --git a/deploy/production-health.sh b/deploy/production-health.sh new file mode 100755 index 0000000..ef25561 --- /dev/null +++ b/deploy/production-health.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set +e + +printf '%s\n' '=== services ===' +systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p ActiveState -p SubState -p MainPID -p ExecMainStatus --no-pager +printf '%s\n' '=== listeners ===' +ss -lntp | grep -E '(:80|:443|:8080)[[:space:]]' || true +printf '%s\n' '=== API health ===' +curl --silent --show-error --max-time 5 --write-out '\nhttp=%{http_code}\n' --header 'Host: host.ser888.cn' http://127.0.0.1:8080/healthz || true +printf '%s\n' '=== HTTPS health ===' +curl --silent --show-error --max-time 10 --write-out '\nhttp=%{http_code}\n' --resolve host.ser888.cn:443:127.0.0.1 https://host.ser888.cn/healthz || true +printf '%s\n' '=== API journal ===' +journalctl -u sea-vhost-api -n 25 --no-pager -o cat || true +printf '%s\n' '=== Nginx config ===' +/www/server/nginx/sbin/nginx -t 2>&1 || true +printf '%s\n' '=== certificate ===' +openssl x509 -in /www/server/panel/vhost/cert/host.ser888.cn/fullchain.pem -noout -subject -issuer -dates -checkhost host.ser888.cn 2>&1 || true +openssl x509 -in /www/server/panel/vhost/cert/host.ser888.cn/fullchain.pem -noout -ext subjectAltName 2>&1 || true +printf '%s\n' '=== FTPS synchronization ===' +systemctl show sea-vhost-ftps-sync.service sea-vhost-ftps-sync.timer -p Id -p LoadState -p ActiveState -p SubState -p Result -p ExecMainStatus --no-pager 2>&1 || true +journalctl -u sea-vhost-ftps-sync.service -n 15 --no-pager -o cat 2>&1 || true +stat -Lc '%A %a %U:%G %n' /www/server/pure-ftpd/etc/pure-ftpd.pem 2>&1 || true +openssl x509 -in /www/server/pure-ftpd/etc/pure-ftpd.pem -noout -subject -issuer -ext subjectAltName 2>&1 || true +for ftp_pid in $(pgrep pure-ftpd 2>/dev/null || true); do printf 'pid=%s started=' "${ftp_pid}"; ps -o lstart= -p "${ftp_pid}"; printf 'cmd='; tr '\0' ' ' <"/proc/${ftp_pid}/cmdline"; printf '\n'; done +timeout 15 openssl s_client -connect 127.0.0.1:21 -starttls ftp -servername sv0123456789.vhost.ser888.cn -verify_hostname sv0123456789.vhost.ser888.cn -verify_return_error &1 | tail -n 12 || true diff --git a/deploy/production-probe.sh b/deploy/production-probe.sh new file mode 100755 index 0000000..9db14c8 --- /dev/null +++ b/deploy/production-probe.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail + +printf '%s\n' '=== local panel listener ===' +panel_port="$(tr -cd '0-9' &1 +find /www/server/panel/vhost/cert/host.ser888.cn -maxdepth 1 -type f -printf '%M %u:%g %f %s bytes\n' 2>/dev/null || true +systemctl is-enabled sea-vhost-agent sea-vhost-panel-broker sea-vhost-api 2>&1 || true +systemctl is-active sea-vhost-agent sea-vhost-panel-broker sea-vhost-api 2>&1 || true +ss -lnt | grep -E '(:80|:443|:8080|:3306)[[:space:]]' || true + +printf '%s\n' '=== domain resolution ===' +getent ahostsv4 host.ser888.cn | head -n 3 || true +getent ahostsv4 sv0123456789.vhost.ser888.cn | head -n 3 || true diff --git a/deploy/production-verify.mjs b/deploy/production-verify.mjs new file mode 100644 index 0000000..9449e15 --- /dev/null +++ b/deploy/production-verify.mjs @@ -0,0 +1,84 @@ +import http from 'node:http'; +import https from 'node:https'; + +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const connectHost = process.env.SEA_CONSOLE_CONNECT_HOST?.trim(); +const adminEmail = process.env.SEA_ADMIN_EMAIL?.trim(); +const adminPassword = process.env.SEA_ADMIN_PASSWORD; +if (!consoleURL || !connectHost || !adminEmail || !adminPassword) process.exit(2); +const base = new URL(consoleURL); +if (base.protocol !== 'https:') throw new Error('production verification requires HTTPS'); + +function request(pathname, { method = 'GET', body, cookie, expected, protocol = 'https:' } = {}) { + const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body)); + const secure = protocol === 'https:'; + const client = secure ? https : http; + const port = secure ? Number(base.port || 443) : 80; + const headers = { Accept: 'application/json', Host: base.host }; + if (payload) { + headers['Content-Type'] = 'application/json'; + headers['Content-Length'] = payload.length; + } + if (cookie) headers.Cookie = cookie; + return new Promise((resolve, reject) => { + const req = client.request({ + hostname: connectHost, port, path: pathname, method, headers, timeout: 20_000, + ...(secure ? { servername: base.hostname, rejectUnauthorized: true } : {}), + }, (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { text += chunk; }); + response.on('end', () => { + let decoded; + try { decoded = text ? JSON.parse(text) : undefined; } catch { decoded = undefined; } + const accepted = expected ? expected.includes(response.statusCode) : response.statusCode >= 200 && response.statusCode < 300; + if (!accepted) return reject(new Error(`${method} ${pathname} returned HTTP ${response.statusCode}`)); + resolve({ status: response.statusCode, headers: response.headers, payload: decoded, text }); + }); + }); + req.on('timeout', () => req.destroy(new Error(`${method} ${pathname} timed out`))); + req.on('error', reject); + req.end(payload); + }); +} + +const health = await request('/healthz'); +if (health.payload?.status !== 'ok') throw new Error('health endpoint did not report ok'); +const setup = await request('/api/v1/setup/status'); +if (setup.payload?.required !== false) throw new Error('setup endpoint is still open'); +const login = await request('/api/v1/auth/login', { method: 'POST', body: { identifier: adminEmail, password: adminPassword } }); +const cookie = login.headers['set-cookie']?.[0]?.split(';', 1)[0]; +if (!cookie?.startsWith('sea_session=')) throw new Error('administrator session cookie is missing'); +const [tenants, plans, approval, management, settings, home] = await Promise.all([ + request('/api/v1/admin/tenants', { cookie }), + request('/api/v1/admin/plans', { cookie }), + request('/api/v1/admin/settings/domain-approval', { cookie }), + request('/api/v1/admin/overview', { cookie }), + request('/api/v1/admin/settings', { cookie }), + request('/'), +]); +if (!Array.isArray(management.payload?.users) || !Array.isArray(management.payload?.projects) || !Array.isArray(management.payload?.domains) || !Array.isArray(management.payload?.ipAddresses) || !Array.isArray(management.payload?.logs)) throw new Error('management overview shape is invalid'); +if (settings.payload?.graceDays !== 3 || settings.payload?.recycleDays !== 7 || settings.payload?.backupRetentionDays !== 14 || settings.payload?.oidc?.bindingOnly !== true || settings.payload?.oidc?.passwordLogin !== true) throw new Error('management settings are invalid'); +if ('secret' in (settings.payload?.smtp || {}) || 'secret' in (settings.payload?.oidc || {})) throw new Error('management settings exposed a stored secret'); +const redirect = await request('/', { protocol: 'http:', expected: [301, 308] }); +const location = String(redirect.headers.location || ''); +if (!location.startsWith(`https://${base.hostname}`)) throw new Error('HTTP does not redirect to the management HTTPS origin'); +for (const name of ['strict-transport-security', 'content-security-policy', 'x-content-type-options', 'x-frame-options']) { + if (!home.headers[name]) throw new Error(`security header is missing: ${name}`); +} + +console.log(JSON.stringify({ + result: 'success', + consoleURL: base.toString(), + health: health.payload.status, + setupClosed: true, + administratorLogin: true, + tenantCount: tenants.payload?.tenants?.length ?? null, + planCount: plans.payload?.plans?.length ?? null, + domainApproval: approval.payload?.enabled, + managementOverview: true, + lifecycle: `${settings.payload.graceDays}/${settings.payload.recycleDays}/${settings.payload.backupRetentionDays}`, + ssoBindingOnly: true, + httpsRedirect: true, + securityHeaders: true, +}, null, 2)); diff --git a/deploy/public-vulnerability-smoke.mjs b/deploy/public-vulnerability-smoke.mjs new file mode 100644 index 0000000..9e41913 --- /dev/null +++ b/deploy/public-vulnerability-smoke.mjs @@ -0,0 +1,366 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const publicURL = process.env.SEA_PUBLIC_TARGET_URL?.trim() || process.env.SEA_CONSOLE_URL?.trim(); +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const insecureTLS = process.env.SEA_PUBLIC_TLS_INSECURE === 'true' || process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!publicURL) { + console.error('SEA_PUBLIC_TARGET_URL or SEA_CONSOLE_URL is required.'); + process.exit(2); +} + +function parseTarget(value, label) { + const target = new URL(value); + if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) { + throw new Error(`${label} must be an HTTP(S) URL without embedded credentials`); + } + return target; +} + +const publicTarget = parseTarget(publicURL, 'public target'); +const panelTarget = panelURL ? parseTarget(panelURL, 'panel target') : undefined; +const probeID = crypto.randomBytes(8).toString('hex'); +const attackerHost = `${probeID}.attacker.invalid`; +const maxBodyBytes = 512 * 1024; +const results = []; + +function record(level, name, detail) { + results.push({ level, name, detail }); +} + +function requestOnce(target, path, { method = 'GET', headers = {}, body } = {}) { + const transport = target.protocol === 'https:' ? https : http; + const payload = body === undefined ? undefined : Buffer.from(body); + const agent = target.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; + return new Promise((resolve, reject) => { + const req = transport.request({ + protocol: target.protocol, + hostname: target.hostname, + port: target.port || undefined, + ...(target.protocol === 'https:' ? { servername: target.hostname } : {}), + method, + path, + agent, + timeout: 10_000, + headers: { + Host: target.host, + 'User-Agent': 'Sea-vHost-public-security-smoke/1.0', + Accept: '*/*', + Connection: 'close', + ...(payload ? { 'Content-Length': payload.length } : {}), + ...headers, + }, + }, (response) => { + const chunks = []; + let length = 0; + let truncated = false; + response.on('data', (chunk) => { + if (length >= maxBodyBytes) { + truncated = true; + return; + } + const remaining = maxBodyBytes - length; + chunks.push(chunk.subarray(0, remaining)); + length += Math.min(chunk.length, remaining); + if (chunk.length > remaining) truncated = true; + }); + response.on('end', () => resolve({ + status: response.statusCode ?? 0, + headers: response.headers, + body: Buffer.concat(chunks).toString('utf8'), + truncated, + })); + }); + req.on('timeout', () => req.destroy(new Error('request timed out'))); + req.on('error', reject); + req.end(payload); + }); +} + +async function request(target, path, options = {}) { + let lastError; + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + return await requestOnce(target, path, options); + } catch (error) { + lastError = error; + if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 250)); + } + } + throw lastError; +} + +function websocketHandshakeOnce(target, path) { + const transport = target.protocol === 'https:' ? https : http; + const agent = target.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; + return new Promise((resolve, reject) => { + let settled = false; + const finish = (value) => { + if (settled) return; + settled = true; + resolve(value); + }; + const req = transport.request({ + protocol: target.protocol, + hostname: target.hostname, + port: target.port || undefined, + ...(target.protocol === 'https:' ? { servername: target.hostname } : {}), + method: 'GET', + path, + agent, + timeout: 10_000, + headers: { + Host: target.host, + Origin: 'https://attacker.invalid', + Upgrade: 'websocket', + Connection: 'Upgrade', + 'Sec-WebSocket-Key': crypto.randomBytes(16).toString('base64'), + 'Sec-WebSocket-Version': '13', + 'User-Agent': 'Sea-vHost-public-security-smoke/1.0', + }, + }); + req.on('upgrade', (response, socket) => { + socket.destroy(); + finish({ status: response.statusCode ?? 101, upgraded: true }); + }); + req.on('response', (response) => { + response.resume(); + response.on('end', () => finish({ status: response.statusCode ?? 0, upgraded: false })); + }); + req.on('timeout', () => req.destroy(new Error('WebSocket handshake timed out'))); + req.on('error', reject); + req.end(); + }); +} + +async function websocketHandshake(target, path) { + let lastError; + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + return await websocketHandshakeOnce(target, path); + } catch (error) { + lastError = error; + if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 500)); + } + } + throw lastError; +} + +const digest = (value) => crypto.createHash('sha256').update(value).digest('hex'); +const deniedStatus = (status) => [400, 401, 403, 404, 405, 410, 421].includes(status); +const disclosureSignatures = [ + /root:x:0:0:/i, + /\[core\][\s\S]{0,200}repositoryformatversion/i, + /(?:DB_PASSWORD|DATABASE_URL|APP_KEY|SEA_PANEL_API_KEY)\s*=/i, + /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/, + /(?:CREATE TABLE|INSERT INTO)\s+[`"[]/i, + /)/i, + /PHP Version\s*(?:<|=>)/i, + /"(?:propertySources|activeProfiles)"\s*:/i, + /"openapi"\s*:\s*"3\./i, +]; + +async function main() { + const baseline = await request(publicTarget, publicTarget.pathname || '/'); + if (baseline.status < 200 || baseline.status >= 400) record('warning', 'public baseline', `HTTP ${baseline.status}`); + else record('passed', 'public baseline', `HTTP ${baseline.status}`); + const baselineDigest = digest(baseline.body); + + const server = String(baseline.headers.server ?? ''); + if (/\d+\.\d+/.test(server)) record('warning', 'server version disclosure', server); + else record('passed', 'server version disclosure', server || 'header absent'); + if (baseline.headers['x-powered-by']) record('warning', 'framework disclosure', String(baseline.headers['x-powered-by'])); + else record('passed', 'framework disclosure', 'X-Powered-By absent'); + for (const [header, expected] of [ + ['x-content-type-options', /nosniff/i], + ['x-frame-options', /deny|sameorigin/i], + ['content-security-policy', /default-src/i], + ['referrer-policy', /./], + ['permissions-policy', /./], + ]) { + const value = String(baseline.headers[header] ?? ''); + record(expected.test(value) ? 'passed' : 'warning', `header ${header}`, value || 'missing'); + } + if (publicTarget.protocol === 'https:') { + const hsts = String(baseline.headers['strict-transport-security'] ?? ''); + record(/max-age=\d+/i.test(hsts) ? 'passed' : 'warning', 'HTTPS HSTS', hsts || 'missing'); + } else { + record('warning', 'transport security', 'target uses plain HTTP; acceptable only for the disposable forwarded test endpoint'); + } + + for (const method of ['TRACE', 'TRACK', 'PUT', 'DELETE', 'PATCH']) { + const response = await request(publicTarget, `/sea-vhost-method-probe-${probeID}`, { method }); + record(deniedStatus(response.status) ? 'passed' : 'failed', `dangerous method ${method}`, `HTTP ${response.status}`); + } + + const sensitivePaths = [ + '/.env', '/.git/config', '/.svn/entries', '/.hg/store/fncache', '/config.json', '/config.yml', + '/backup.zip', '/site.tar.gz', '/database.sql', '/composer.json', '/package.json', '/go.mod', + '/requirements.txt', '/WEB-INF/web.xml', '/server-status', '/nginx_status', '/phpinfo.php', '/info.php', + '/debug/pprof/', '/actuator/env', '/actuator/heapdump', '/swagger/index.html', '/openapi.json', '/api-docs', + '/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php', '/cgi-bin/status', + ]; + let sensitiveDenied = 0; + let sensitiveSPAFallback = 0; + let sensitiveWarnings = 0; + for (const path of sensitivePaths) { + const response = await request(publicTarget, path); + if (disclosureSignatures.some((pattern) => pattern.test(response.body))) { + record('failed', `sensitive path ${path}`, `HTTP ${response.status}, disclosure signature found`); + } else if (deniedStatus(response.status) || [301, 302, 307, 308].includes(response.status)) { + sensitiveDenied += 1; + } else if (response.status === baseline.status && digest(response.body) === baselineDigest) { + sensitiveSPAFallback += 1; + } else if (response.status >= 200 && response.status < 300) { + sensitiveWarnings += 1; + record('warning', `sensitive path ${path}`, `distinct HTTP ${response.status} response; inspect manually`); + } else { + sensitiveDenied += 1; + } + } + record('passed', 'common sensitive and exploit paths', `${sensitiveDenied} denied/redirected, ${sensitiveSPAFallback} SPA fallbacks, ${sensitiveWarnings} manual warnings`); + + const traversalPaths = [ + '/..%2f..%2f..%2fetc%2fpasswd', + '/%2e%2e/%2e%2e/%2e%2e/etc/passwd', + '/%252e%252e%252f%252e%252e%252fetc%252fpasswd', + '/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd', + '/api/v1/projects/1/files?path=..%2F..%2Fetc%2Fpasswd', + ]; + for (const path of traversalPaths) { + const response = await request(publicTarget, path); + const leaked = /root:x:0:0:/.test(response.body); + record(leaked ? 'failed' : 'passed', `path traversal ${path}`, leaked ? 'passwd signature returned' : `HTTP ${response.status}, no passwd signature`); + } + + const unauthenticated = await request(publicTarget, '/api/v1/dashboard', { + headers: { Origin: 'https://attacker.invalid' }, + }); + const allowOrigin = String(unauthenticated.headers['access-control-allow-origin'] ?? ''); + if (![401, 403, 404].includes(unauthenticated.status)) record('failed', 'unauthenticated API', `HTTP ${unauthenticated.status}`); + else record('passed', 'unauthenticated API', `HTTP ${unauthenticated.status}`); + record(allowOrigin === '*' || allowOrigin.includes('attacker.invalid') ? 'failed' : 'passed', 'CORS origin reflection', allowOrigin || 'no permissive ACAO'); + + const crossOrigin = await request(publicTarget, '/api/v1/auth/login', { + method: 'POST', + headers: { Origin: 'https://attacker.invalid', 'Content-Type': 'application/json' }, + body: JSON.stringify({ identifier: `probe-${probeID}@invalid.test`, password: `invalid-${probeID}` }), + }); + record(crossOrigin.status === 403 ? 'passed' : 'failed', 'cross-origin state request', `HTTP ${crossOrigin.status}`); + + const hostProbe = await request(publicTarget, '/api/v1/dashboard', { headers: { Host: attackerHost } }); + const hostLocation = String(hostProbe.headers.location ?? ''); + const hostReflected = hostLocation.includes(attackerHost) || hostProbe.body.includes(attackerHost); + record(!hostReflected && [400, 403, 404, 421].includes(hostProbe.status) ? 'passed' : 'failed', 'Host header boundary', `HTTP ${hostProbe.status}, reflected=${hostReflected}`); + + const forwardedProbe = await request(publicTarget, '/api/v1/dashboard', { + headers: { + 'X-Forwarded-Host': attackerHost, + 'X-Forwarded-Proto': 'https', + Forwarded: `host=${attackerHost};proto=https`, + }, + }); + const forwardedLocation = String(forwardedProbe.headers.location ?? ''); + const forwardedReflected = forwardedLocation.includes(attackerHost) || forwardedProbe.body.includes(attackerHost); + record(forwardedReflected ? 'failed' : 'passed', 'forwarded Host reflection', `HTTP ${forwardedProbe.status}, reflected=${forwardedReflected}`); + + for (const path of [ + `/?next=https%3A%2F%2F${attackerHost}%2F`, + `/login?redirect=%2F%2F${attackerHost}%2F`, + `/api/v1/auth/login?returnUrl=https%3A%2F%2F${attackerHost}%2F`, + ]) { + const response = await request(publicTarget, path); + const location = String(response.headers.location ?? ''); + let external = false; + try { external = Boolean(location) && new URL(location, publicTarget).hostname === attackerHost; } catch { external = true; } + record(external ? 'failed' : 'passed', `open redirect ${path.split('?')[0]}`, location || `HTTP ${response.status}, no Location`); + } + + const xssPayload = ``; + const xssProbe = await request(publicTarget, `/?q=${encodeURIComponent(xssPayload)}`); + record(xssProbe.body.includes(xssPayload) ? 'failed' : 'passed', 'reflected XSS probe', xssProbe.body.includes(probeID) ? 'marker reflected without raw payload' : 'payload not reflected'); + + const scriptSources = [...baseline.body.matchAll(/]+src=["']([^"']+\.js)["']/gi)].map((match) => match[1]).slice(0, 12); + let exposedMaps = 0; + for (const source of scriptSources) { + const sourceURL = new URL(source, publicTarget); + const response = await request(publicTarget, `${sourceURL.pathname}.map`); + if (response.status === 200 && /"sources"\s*:/.test(response.body) && /"mappings"\s*:/.test(response.body)) exposedMaps += 1; + } + record(exposedMaps ? 'warning' : 'passed', 'JavaScript source maps', exposedMaps ? `${exposedMaps} source map(s) exposed` : 'none exposed'); + + if (panelTarget) { + const panelEndpoints = [ + ['/crontab', 'action=GetCrontab'], + ['/site', 'action=get_site_types'], + ['/database', 'action=GetList'], + ['/ftp', 'action=get_list'], + ['/system', 'action=GetSystemTotal'], + ]; + for (const [path, body] of panelEndpoints) { + const response = await request(panelTarget, path, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }); + let privileged = false; + try { + const payload = JSON.parse(response.body); + privileged = payload?.status === true || Array.isArray(payload?.data) || Array.isArray(payload); + } catch { /* login/security-entry HTML is not privileged API data */ } + record(privileged ? 'failed' : 'passed', `aaPanel unauthenticated ${path}`, `HTTP ${response.status}, privileged_data=${privileged}`); + } + const forgedToken = new URLSearchParams({ + action: 'GetCrontab', + request_time: Math.floor(Date.now() / 1000).toString(), + request_token: crypto.randomBytes(16).toString('hex'), + }).toString(); + const forgedResponse = await request(panelTarget, '/crontab', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: forgedToken, + }); + let forgedPrivileged = false; + try { + const payload = JSON.parse(forgedResponse.body); + forgedPrivileged = payload?.status === true || Array.isArray(payload?.data) || Array.isArray(payload); + } catch { /* login/security-entry HTML is not privileged API data */ } + record(forgedPrivileged ? 'failed' : 'passed', 'aaPanel forged API signature', `HTTP ${forgedResponse.status}, privileged_data=${forgedPrivileged}`); + + for (const path of [ + '/sock_shell', '/webssh', '/ws_panel', '/ws_home', '/ws_project', '/ws_model', '/workorder_client', + '/v2/sock_shell', '/v2/webssh', '/v2/ws_panel', '/v2/ws_home', '/v2/ws_project', '/v2/ws_model', + ]) { + const handshake = await websocketHandshake(panelTarget, path); + record(handshake.upgraded ? 'failed' : 'passed', `aaPanel cross-origin WebSocket ${path}`, `HTTP ${handshake.status}, upgraded=${handshake.upgraded}`); + } + for (const path of ['/.env', '/config/config.json', '/data/default.db', '/www/server/panel/data/default.db']) { + const response = await request(panelTarget, path); + const leaked = disclosureSignatures.some((pattern) => pattern.test(response.body)) || response.body.startsWith('SQLite format 3'); + record(leaked ? 'failed' : 'passed', `aaPanel sensitive path ${path}`, leaked ? 'disclosure signature found' : `HTTP ${response.status}, no disclosure signature`); + } + } + + const failed = results.filter((item) => item.level === 'failed'); + const warnings = results.filter((item) => item.level === 'warning'); + console.log(JSON.stringify({ + status: failed.length ? 'failed' : 'passed', + target: publicTarget.origin, + panelTarget: panelTarget?.origin, + probeID, + summary: { + passed: results.filter((item) => item.level === 'passed').length, + warnings: warnings.length, + failed: failed.length, + }, + warnings, + failed, + }, null, 2)); + if (failed.length) process.exitCode = 1; +} + +main().catch((error) => { + console.error(`Public vulnerability smoke failed: ${error instanceof Error ? error.message : 'unknown error'}`); + process.exitCode = 1; +}); diff --git a/deploy/pureftp-certificate-probe.sh b/deploy/pureftp-certificate-probe.sh new file mode 100755 index 0000000..d4befe5 --- /dev/null +++ b/deploy/pureftp-certificate-probe.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set +e + +printf '%s\n' '=== TLS-related configuration ===' +grep -nEi 'TLS|Cert|PEM|SSL' /www/server/pure-ftpd/etc/pure-ftpd.conf /etc/init.d/pure-ftpd 2>&1 || true +grep -nEi 'CertFile|--certfile|-2' /www/server/pure-ftpd/sbin/pure-config.pl /www/server/pure-ftpd/sbin/pure-config.py 2>&1 || true +printf '%s\n' '=== Pure-FTPd TLS options ===' +/www/server/pure-ftpd/sbin/pure-ftpd --help 2>&1 | grep -Ei 'tls|cert|pem|ssl' || true +printf '%s\n' '=== compiled certificate paths ===' +strings /www/server/pure-ftpd/sbin/pure-ftpd | grep -E '/[^ ]*(pure-ftpd|ssl)[^ ]*\.pem|pure-ftpd\.pem' | sort -u | head -n 30 || true +printf '%s\n' '=== candidate certificates ===' +find /www/server/pure-ftpd /etc/ssl/private /etc/pure-ftpd -xdev -maxdepth 5 -type f \( -name '*.pem' -o -name '*.crt' \) -print 2>/dev/null | while IFS= read -r candidate; do + printf '%s ' "${candidate}" + openssl x509 -in "${candidate}" -noout -subject 2>/dev/null || echo 'not-an-x509-certificate' +done +printf '%s\n' '=== running daemon identity ===' +for ftp_pid in $(pgrep pure-ftpd 2>/dev/null || true); do + printf 'pid=%s user=' "${ftp_pid}" + ps -o user= -p "${ftp_pid}" + ls -l "/proc/${ftp_pid}/fd" 2>&1 | grep -Ei 'pem|ssl|cert' || true +done diff --git a/deploy/real-panel-smoke.mjs b/deploy/real-panel-smoke.mjs new file mode 100644 index 0000000..96cf409 --- /dev/null +++ b/deploy/real-panel-smoke.mjs @@ -0,0 +1,315 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const configuredManagementDomain = (process.env.SEA_TEST_ACCESS_HOST || process.env.SEA_MANAGEMENT_DOMAIN)?.trim(); +const testRootDomain = process.env.SEA_TEST_ROOT_DOMAIN?.trim(); +const testManagementDomain = process.env.SEA_TEST_MANAGEMENT_DOMAIN?.trim(); +const testFTPDomain = process.env.SEA_TEST_FTP_DOMAIN?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!panelURL || !panelAPIKey || !consoleURL || !testRootDomain || !testManagementDomain || !testFTPDomain) { + console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_CONSOLE_URL, SEA_TEST_ROOT_DOMAIN, SEA_TEST_MANAGEMENT_DOMAIN and SEA_TEST_FTP_DOMAIN are required.'); + process.exit(2); +} + +const panelBase = new URL(panelURL); +const consoleBase = new URL(consoleURL); +if (!['http:', 'https:'].includes(consoleBase.protocol) || consoleBase.username || consoleBase.password) { + throw new Error('SEA_CONSOLE_URL must be an HTTP(S) URL without credentials'); +} +if (configuredManagementDomain && !/^[A-Za-z0-9.-]+$/.test(configuredManagementDomain)) { + throw new Error('SEA_TEST_ACCESS_HOST must be a host name or IP address'); +} +for (const [name, value] of Object.entries({ SEA_TEST_ROOT_DOMAIN: testRootDomain, SEA_TEST_MANAGEMENT_DOMAIN: testManagementDomain, SEA_TEST_FTP_DOMAIN: testFTPDomain })) { + if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(value)) throw new Error(`${name} must be a valid domain name`); +} +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +const randomPassword = () => `Sv-${crypto.randomBytes(15).toString('base64url')}9a`; + +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; +} + +function panelForm(pathname, values, timeoutMs = 30_000) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + const url = new URL(pathname, panelBase); + return new Promise((resolve, reject) => { + const request = panelClient.request(url, { + method: 'POST', agent: panelAgent, timeout: timeoutMs, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) { + reject(new Error(`panel returned HTTP ${response.statusCode}`)); + return; + } + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +function panelFileText(payload) { + if (typeof payload === 'string') return payload; + for (const key of ['data', 'msg', 'content']) { + if (typeof payload?.[key] === 'string') return payload[key]; + } + throw new Error('panel did not return the requested file'); +} + +async function api(pathname, { method = 'GET', body, token, cookie, expected } = {}) { + const headers = { Accept: 'application/json' }; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + if (token) headers['X-Setup-Token'] = token; + if (cookie) headers.Cookie = cookie; + const response = await fetch(new URL(pathname, consoleBase), { + method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual', + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + const accepted = expected ? expected.includes(response.status) : response.status >= 200 && response.status < 300; + if (!accepted) { + const message = payload?.error?.message || `HTTP ${response.status}`; + throw new Error(`${method} ${pathname} failed: ${message}`); + } + return { response, payload }; +} + +function sessionCookie(response) { + const setCookie = typeof response.headers.getSetCookie === 'function' + ? response.headers.getSetCookie()[0] + : response.headers.get('set-cookie'); + const cookie = setCookie?.split(';', 1)[0]; + if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a Sea vHost session cookie'); + return cookie; +} + +async function waitFor(pathname, predicate, attempts = 30) { + let lastError; + for (let attempt = 0; attempt < attempts; attempt += 1) { + try { + const result = await api(pathname); + if (predicate(result.payload)) return result.payload; + } catch (error) { lastError = error; } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + throw lastError || new Error(`timed out waiting for ${pathname}`); +} + +async function checkSiteThroughServerNginx(domain, rootDomain) { + const hostName = domain.split('.', 1)[0]; + if (!/^sv[0-9a-f]{10}$/.test(hostName) || domain !== `${hostName}.${rootDomain}`) { + throw new Error('project returned an unexpected domain'); + } + const marker = `Sea-vHost-site-check-${crypto.randomBytes(6).toString('hex')}`; + const task = await panelForm('/crontab', { + action: 'AddCrontab', name: `Sea vHost local site check ${Date.now().toString().slice(-7)}`, + type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', + sBody: `set -eo pipefail\ncurl --silent --show-error --fail --max-time 10 --header 'Host: ${domain}' http://127.0.0.1/ | grep -Fq 'sea-vhost-real-ok'\nprintf '%s\\n' '${marker}'`, + sName: 'Temporary Sea vHost loopback site check', save: '0', backupTo: 'localhost', + }); + const taskID = Number(task?.id); + if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) { + throw new Error('aaPanel rejected the temporary local site check'); + } + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + for (let attempt = 0; attempt < 100; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : ''; + if (log.includes(marker)) return; + } + throw new Error('provisioned PHP site did not return the expected content through server Nginx'); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +async function enableTestManagementHost(host) { + if (!host) return; + const marker = `Sea-vHost-management-host-${crypto.randomBytes(6).toString('hex')}`; + const python = `import json; p='/var/lib/sea-vhost/config.json'; d=json.load(open(p, encoding='utf-8')); d['management_domain']=${JSON.stringify(host)}; f=open(p, 'w', encoding='utf-8'); json.dump(d, f, indent=2); f.write('\\n'); f.close()`; + const task = await panelForm('/crontab', { + action: 'AddCrontab', name: `Sea vHost test host ${Date.now().toString().slice(-7)}`, + type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', + sBody: `set -eo pipefail\npython3 -c ${JSON.stringify(python)}\nsystemctl restart sea-vhost-api\nfor attempt in {1..30}; do if curl --silent --show-error --fail --max-time 2 --header 'Host: ${host}' http://127.0.0.1:8080/healthz >/dev/null; then break; fi; sleep 1; done\ncurl --silent --show-error --fail --max-time 2 --header 'Host: ${host}' http://127.0.0.1:8080/healthz >/dev/null\nprintf '%s\\n' '${marker}'`, + sName: 'Temporary Sea vHost forwarded test-host configuration', save: '0', backupTo: 'localhost', + }); + const taskID = Number(task?.id); + if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) { + throw new Error('aaPanel rejected the temporary management-host configuration'); + } + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + for (let attempt = 0; attempt < 100; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : ''; + if (log.includes(marker)) return; + } + throw new Error('temporary management-host configuration did not complete'); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const suffix = Date.now().toString(36).slice(-7); +const databaseName = `sea_vh_${suffix}`.slice(0, 16); +const databasePassword = randomPassword(); +const adminEmail = `admin-${suffix}@seavhost.test`; +const adminPassword = randomPassword(); +const tenantEmail = `tenant-${suffix}@seavhost.test`; +const tenantPassword = randomPassword(); +const tenantSlug = `real-${suffix}`; +let databaseID = 0; +let databaseCreated = false; +let setupCompleted = false; + +try { + const environment = panelFileText(await panelForm('/files', { action: 'GetFileBody', path: '/etc/sea-vhost/sea-vhost.env' })); + const setupToken = environment.match(/^SEA_SETUP_TOKEN=(.+)$/m)?.[1]?.trim(); + if (!setupToken || setupToken.length < 24) throw new Error('installed setup token is unavailable'); + const panelPortText = panelFileText(await panelForm('/files', { action: 'GetFileBody', path: '/www/server/panel/data/port.pl' })); + const panelPort = Number(panelPortText.trim()); + if (!Number.isInteger(panelPort) || panelPort < 1 || panelPort > 65535) throw new Error('aaPanel local port is invalid'); + + const databaseResult = await panelForm('/database', { + action: 'AddDatabase', sid: '0', name: databaseName, db_user: databaseName, + password: databasePassword, address: '127.0.0.1', codeing: 'utf8mb4', pid: '0', ps: 'Sea vHost control database', + }); + if (databaseResult?.status !== true && databaseResult?.status !== 'true') throw new Error('aaPanel rejected control database creation'); + databaseID = Number(databaseResult.id); + databaseCreated = true; + if (!Number.isSafeInteger(databaseID) || databaseID <= 0) databaseID = 0; + + await waitFor('/api/v1/setup/status', (payload) => payload?.required === true); + const rootDomain = testRootDomain; + const managementDomain = testManagementDomain; + const ftpDomain = testFTPDomain; + await api('/api/v1/setup/test-database', { + method: 'POST', token: setupToken, + body: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword }, + }); + const panelCheck = await api('/api/v1/setup/test-panel', { + method: 'POST', token: setupToken, + body: { url: `https://127.0.0.1:${panelPort}/`, apiKey: panelAPIKey, tlsInsecure: true }, + }); + await api('/api/v1/setup/install', { + method: 'POST', token: setupToken, expected: [201], + body: { + database: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword }, + panel: { url: `https://127.0.0.1:${panelPort}/`, apiKey: panelAPIKey, tlsInsecure: true }, + rootDomain, managementDomain, ftpDomain, domainApproval: true, + adminEmail, adminName: '实机测试管理员', adminPassword, + }, + }); + setupCompleted = true; + // This disposable server is behind a provider gateway that rejects the + // valid management-domain Host header before it reaches Nginx. Keep the + // production-grade domain validation in the installer, then explicitly + // switch only this test deployment to the forwarded IP for API acceptance. + await enableTestManagementHost(configuredManagementDomain); + await waitFor('/healthz', (payload) => payload?.status === 'ok', 45); + + const adminLogin = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: adminEmail, password: adminPassword } }); + const adminCookie = sessionCookie(adminLogin.response); + const plan = await api('/api/v1/admin/plans', { + method: 'POST', cookie: adminCookie, expected: [201], + body: { + name: `实机测试套餐-${suffix}`, storageBytes: 1_048_576, databaseBytes: 16_777_216, + bandwidthBytes: 1_073_741_824, processLimit: 10, ftpLimit: 2, databaseLimit: 2, projectLimit: 2, + }, + }); + const planID = Number(plan.payload?.id); + await api('/api/v1/admin/tenants', { + method: 'POST', cookie: adminCookie, expected: [201], + body: { + slug: tenantSlug, name: 'Sea vHost 实机测试租户', email: tenantEmail, + displayName: '测试租户管理员', password: tenantPassword, planId: planID, + }, + }); + + const tenantLogin = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantEmail, password: tenantPassword } }); + const tenantCookie = sessionCookie(tenantLogin.response); + const catalog = await api('/api/v1/runtime-catalog', { cookie: tenantCookie }); + const phpVersion = catalog.payload?.versions?.PHP?.[0]; + if (!phpVersion) throw new Error('aaPanel did not report an installed PHP version'); + const projectResult = await api('/api/v1/projects', { + method: 'POST', cookie: tenantCookie, expected: [201], + body: { name: `web-${suffix}`, runtime: 'PHP', version: phpVersion, runPath: '/public', customDomain: '', autoSSL: false }, + }); + const project = projectResult.payload?.project; + const credentials = projectResult.payload?.credentials; + if (!project?.id || project.status !== 'running' || !credentials?.hostLogin) throw new Error('project provisioning returned an incomplete result'); + + await api(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie: tenantCookie, expected: [204], + body: { path: 'public/index.php', content: ' 0) { + try { + await panelForm('/database', { action: 'DeleteDatabase', id: String(databaseID), sid: '0', name: databaseName, db_user: databaseName }); + } catch { /* best-effort rollback */ } + } + console.error(`Sea vHost real-panel smoke test failed: ${error instanceof Error ? error.message : 'unknown error'}`); + process.exitCode = 1; +} diff --git a/deploy/release-files.json b/deploy/release-files.json new file mode 100644 index 0000000..2b41aac --- /dev/null +++ b/deploy/release-files.json @@ -0,0 +1,26 @@ +{ + "runtimeFiles": [ + "README.md", + "deploy/README.md", + "deploy/install.sh", + "deploy/install-controller.sh", + "deploy/install-node.sh", + "deploy/install-wizard.py", + "deploy/preflight.sh", + "deploy/diagnose.sh", + "deploy/prepare-runtime-roots.sh", + "deploy/activate-production.sh", + "deploy/activate-production-ftps.sh", + "deploy/update-production-ftp-mode.sh", + "deploy/pureftp-certificate-probe.sh", + "deploy/production-health.sh" + ], + "runtimeDirectories": ["build/bin", "build/web", "deploy/nginx", "deploy/systemd", "docs"], + "sourceFiles": [ + "README.md", ".gitignore", ".gitattributes", + "backend/.env.example", "backend/go.mod", "backend/go.sum", + "frontend/index.html", "frontend/package.json", "frontend/package-lock.json", + "frontend/tsconfig.json", "frontend/tsconfig.app.json", "frontend/tsconfig.node.json", "frontend/vite.config.ts" + ], + "sourceDirectories": ["backend/cmd", "backend/internal", "frontend/src", "deploy", "docs"] +} diff --git a/deploy/repair-test-apt-source.mjs b/deploy/repair-test-apt-source.mjs new file mode 100644 index 0000000..2edc8df --- /dev/null +++ b/deploy/repair-test-apt-source.mjs @@ -0,0 +1,91 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} + +const base = new URL(baseURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; +} +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function requireSuccess(payload, operation) { + if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); + return payload; +} + +const nonce = Date.now().toString().slice(-7); +const taskName = `Sea vHost apt repair ${nonce}`; +const source = '/etc/apt/sources.list.d/docker.list'; +const disabled = `${source}.disabled`; +const expected = 'deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] mirrors.aliyun.com/docker-ce/linux/debian 13 stable'; +const shell = [ + // aaPanel appends a wrapper that reads $1 after the task body. + 'set -eo pipefail', + `source_file='${source}'`, + `disabled_file='${disabled}'`, + `expected='${expected}'`, + 'test -f "$source_file" && test ! -L "$source_file"', + 'test ! -e "$disabled_file"', + 'actual="$(sed -e \"s/[[:space:]]*$//\" "$source_file")"', + 'if [[ "$actual" != "$expected" ]]; then echo "Refusing to disable an unexpected apt source"; exit 1; fi', + 'mv -- "$source_file" "$disabled_file"', + 'rollback() { mv -- "$disabled_file" "$source_file" || true; }', + 'trap rollback ERR', + 'apt-get update', + 'trap - ERR', + "printf '%s\\n' 'Sea vHost apt source repair: success'", +].join('\n'); + +let taskID; +try { + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: taskName, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'One-time guarded apt source repair', save: '0', backupTo: 'localhost', + }), 'temporary repair task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let log = ''; + for (let attempt = 0; attempt < 120; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; + if (log.includes('Sea vHost apt source repair: success') || log.includes('Refusing to disable')) break; + } + if (!log.includes('Sea vHost apt source repair: success')) throw new Error(`apt source repair did not complete:\n${log.trim()}`); + console.log(log.trim()); +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} diff --git a/deploy/reset-production-admin.sh b/deploy/reset-production-admin.sh new file mode 100755 index 0000000..0a0a515 --- /dev/null +++ b/deploy/reset-production-admin.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +set -uo pipefail + +if [[ -z "${SEA_ADMIN_EMAIL:-}" || -z "${SEA_ADMIN_PASSWORD:-}" ]]; then + echo "SEA_ADMIN_EMAIL and SEA_ADMIN_PASSWORD are required." >&2 + exit 1 +fi + +set +e +/www/server/panel/pyenv/bin/python3 - <<'PY' +import json +import os +import re +import stat +import subprocess +import tempfile +from pathlib import Path +from urllib.parse import unquote + +email = os.environ['SEA_ADMIN_EMAIL'].strip().lower() +password = os.environ['SEA_ADMIN_PASSWORD'] +if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+', email): + raise SystemExit('administrator email is invalid') +if len(password) < 14 or len(password) > 128: + raise SystemExit('administrator password length is invalid') + +config_path = Path('/var/lib/sea-vhost/config.json') +if not config_path.is_file() or config_path.is_symlink(): + raise SystemExit('Sea vHost configuration is missing or unsafe') +config = json.loads(config_path.read_text(encoding='utf-8')) +dsn = config.get('database_dsn', '') +match = re.fullmatch(r'([^:]+):([^@]+)@tcp\(([^:()]+):(\d+)\)/([^?]+)(?:\?.*)?', dsn) +if not match: + raise SystemExit('Sea vHost database DSN has an unexpected format') +db_user, db_password, db_host, db_port, db_name = (unquote(value) for value in match.groups()) + +php_binary = next((path for path in ('/www/server/php/84/bin/php', '/www/server/php/83/bin/php', '/usr/bin/php') if Path(path).is_file()), None) +mysql_binary = next((path for path in ('/www/server/mysql/bin/mysql', '/usr/bin/mysql', '/usr/bin/mariadb') if Path(path).is_file()), None) +if not php_binary or not mysql_binary: + raise SystemExit('PHP or MySQL client is unavailable') +hash_environment = os.environ.copy() +hash_environment['SEA_RESET_PASSWORD'] = password +password_hash = subprocess.check_output( + [php_binary, '-r', 'echo password_hash(getenv("SEA_RESET_PASSWORD"), PASSWORD_BCRYPT);'], + env=hash_environment, + text=True, +).strip() +if not re.fullmatch(r'\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}', password_hash): + raise SystemExit('PHP returned an invalid bcrypt hash') + +escaped_email = email.replace("'", "''") +sql = ( + f"UPDATE users SET password_hash='{password_hash}',status='active' " + f"WHERE role='admin' AND LOWER(email)='{escaped_email}';" + f"DELETE s FROM sessions s JOIN users u ON u.id=s.user_id " + f"WHERE u.role='admin' AND LOWER(u.email)='{escaped_email}';" + "SELECT COUNT(*) FROM users WHERE role='admin' AND status='active' " + f"AND LOWER(email)='{escaped_email}';" +) +mysql_environment = os.environ.copy() +mysql_environment['MYSQL_PWD'] = db_password +result = subprocess.check_output( + [mysql_binary, '--batch', '--skip-column-names', '--host', db_host, '--port', db_port, '--user', db_user, db_name, '--execute', sql], + env=mysql_environment, + text=True, + stderr=subprocess.STDOUT, +).strip().splitlines() +if not result or result[-1].strip() != '1': + raise SystemExit('administrator row was not updated exactly as expected') + +credentials_path = Path('/etc/sea-vhost/admin-credentials') +handle, temporary_name = tempfile.mkstemp(prefix='.admin-credentials-', dir=str(credentials_path.parent), text=True) +try: + with os.fdopen(handle, 'w', encoding='utf-8') as output: + output.write(f'login={email}\npassword={password}\n') + output.flush() + os.fsync(output.fileno()) + os.chmod(temporary_name, stat.S_IRUSR | stat.S_IWUSR) + os.chown(temporary_name, 0, 0) + os.replace(temporary_name, credentials_path) +finally: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass +print('Sea vHost production administrator password reset: success') +PY +reset_status=$? +if (( reset_status != 0 )); then + printf 'Sea vHost production administrator password reset: failed (status %s)\n' "${reset_status}" >&2 +fi +set +u diff --git a/deploy/reset-real-test.mjs b/deploy/reset-real-test.mjs new file mode 100644 index 0000000..e0fb2d2 --- /dev/null +++ b/deploy/reset-real-test.mjs @@ -0,0 +1,137 @@ +import crypto from 'node:crypto'; +import http from 'node:http'; +import https from 'node:https'; + +if (!process.argv.includes('--confirm-test-reset')) { + console.error('Refusing to reset without --confirm-test-reset.'); + process.exit(2); +} +const baseURL = process.env.SEA_PANEL_URL?.trim(); +const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!baseURL || !apiKey) { + console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); + process.exit(2); +} +const base = new URL(baseURL); +const client = base.protocol === 'https:' ? https : http; +const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); +function authFields() { + const requestTime = Math.floor(Date.now() / 1000).toString(); + return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; +} +function formRequest(pathname, values) { + const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); + return new Promise((resolve, reject) => { + const request = client.request(new URL(pathname, base), { + method: 'POST', agent, timeout: 30_000, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { data += chunk; }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} +function requireSuccess(payload, operation) { + if (payload === true || payload === 'true') return payload; + if (!payload || (payload.status !== true && payload.status !== 'true')) { + const detail = `: ${JSON.stringify({ type: typeof payload, status: payload?.status, keys: payload && typeof payload === 'object' ? Object.keys(payload) : [] })}`; + throw new Error(`${operation} was rejected by the panel${detail}`); + } + return payload; +} + +const rowsFrom = (listing) => Array.isArray(listing?.data) ? listing.data : Array.isArray(listing) ? listing : []; +const databaseRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'databases', limit: '200', p: '1', search: 'sea_vh_' })); +const databases = databaseRows.map((row) => ({ + id: Number(row.id), name: String(row.name ?? ''), username: String(row.username ?? row.db_user ?? row.name ?? ''), +})).filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && /^sea_vh_[a-z0-9]{4,9}$/.test(row.name)); +if (databaseRows.length > 0 && databases.length === 0) throw new Error('database listing returned rows but none matched the strict Sea vHost test prefix'); + +const managedHostPattern = /^sv[0-9a-f]{10}$/; +const ftpRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'ftps', limit: '200', p: '1', search: 'sv' })); +const orphanFTPs = ftpRows.map((row) => ({ id: Number(row.id), name: String(row.name ?? row.username ?? ''), ps: String(row.ps ?? '') })) + .filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && managedHostPattern.test(row.name) && row.ps === 'Managed by Sea vHost'); +const projectDatabaseRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'databases', limit: '200', p: '1', search: 'sv' })); +const orphanDatabases = projectDatabaseRows.map((row) => ({ + id: Number(row.id), name: String(row.name ?? ''), username: String(row.username ?? row.db_user ?? row.name ?? ''), ps: String(row.ps ?? ''), +})).filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && managedHostPattern.test(row.name) && row.ps === 'Managed by Sea vHost'); +const siteRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'sites', limit: '200', p: '1', search: 'sv' })); +const orphanSites = siteRows.map((row) => ({ id: Number(row.id), name: String(row.name ?? ''), ps: String(row.ps ?? '') })) + .filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && managedHostPattern.test(row.name.split('.')[0]) && row.ps === `Sea vHost: ${row.name.split('.')[0]}`); + +const managedHosts = [...new Set([ + ...orphanFTPs.map((row) => row.name), + ...orphanDatabases.map((row) => row.name), + ...orphanSites.map((row) => row.name.split('.')[0]), +])].filter((name) => managedHostPattern.test(name)).sort(); + +for (const ftp of orphanFTPs) { + requireSuccess(await formRequest('/ftp', { action: 'DeleteUser', id: String(ftp.id), username: ftp.name }), `delete test FTP ${ftp.name}`); +} +for (const database of orphanDatabases) { + requireSuccess(await formRequest('/database', { + action: 'DeleteDatabase', id: String(database.id), sid: '0', name: database.name, db_user: database.username, + }), `delete test project database ${database.name}`); +} +for (const site of orphanSites) { + requireSuccess(await formRequest('/site', { action: 'DeleteSite', id: String(site.id), webname: site.name }), `delete test site ${site.name}`); +} +for (const database of databases) { + requireSuccess(await formRequest('/database', { + action: 'DeleteDatabase', id: String(database.id), sid: '0', name: database.name, db_user: database.username, + }), `delete test database ${database.name}`); +} + +const nonce = Date.now().toString().slice(-7); +let taskID; +try { + const shell = [ + 'set -Eeuo pipefail', + 'trap \'status=$?; printf "Sea vHost reset failed at line %s (status %s)\\n" "$LINENO" "$status"\' ERR', + 'systemctl stop sea-vhost-api sea-vhost-panel-broker sea-vhost-agent', + 'purge_children() { local root="$1" resolved entry target; test -d "$root" || return 0; resolved="$(realpath -e -- "$root")"; test "$resolved" = "$root"; while IFS= read -r -d "" entry; do case "$entry" in "$root"/*) ;; *) exit 1 ;; esac; if [[ -L "$entry" ]]; then rm -f -- "$entry"; else target="$(realpath -e -- "$entry")"; case "$target" in "$root"/*) chattr -R -i -- "$entry" 2>/dev/null || true; rm -rf -- "$entry" ;; *) exit 1 ;; esac; fi; done < <(find -P "$root" -mindepth 1 -maxdepth 1 -print0); }', + 'mapfile -t identities < <(getent passwd | cut -d: -f1 | grep -E "^sv[0-9a-f]{10}$" || true)', + 'for host in "${identities[@]}"; do pkill -KILL -u "$host" 2>/dev/null || true; userdel "$host"; getent group "$host" >/dev/null && groupdel "$host" || true; done', + 'host_root=/www/wwwroot/seavHost/vHost; if [[ -d "$host_root" ]]; then host_root="$(realpath -e -- "$host_root")"; test "$host_root" = /www/wwwroot/seavHost/vHost; while IFS= read -r -d "" entry; do name="$(basename -- "$entry")"; [[ "$name" =~ ^sv[0-9a-f]{10}$ ]]; target="$(realpath -e -- "$entry")"; case "$target" in "$host_root"/*) chattr -R -i -- "$entry" 2>/dev/null || true; rm -rf -- "$entry" ;; *) exit 1 ;; esac; done < <(find -P "$host_root" -mindepth 1 -maxdepth 1 -type d -name "sv??????????" -print0); if [[ -d "$host_root/.sea-vhost-quarantine" && ! -L "$host_root/.sea-vhost-quarantine" ]]; then target="$(realpath -e -- "$host_root/.sea-vhost-quarantine")"; test "$target" = "$host_root/.sea-vhost-quarantine"; chattr -R -i -- "$target" 2>/dev/null || true; rm -rf -- "$host_root/.sea-vhost-quarantine"; fi; fi', + 'purge_children /var/lib/sea-vhost', + 'purge_children /var/lib/sea-vhost-agent', + 'purge_children /var/lib/sea-vhost-panel', + 'rm -f -- /etc/sea-vhost/sea-vhost.env', + "printf '%s\\n' 'Sea vHost test reset: complete'", + ].join('\n'); + const task = requireSuccess(await formRequest('/crontab', { + action: 'AddCrontab', name: `Sea vHost test reset ${nonce}`, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost test-data reset', save: '0', backupTo: 'localhost', + }), 'temporary reset task creation'); + taskID = Number(task.id); + if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); + // Some aaPanel builds return false while another manual cron execution is + // draining. The minute task remains valid, so wait through the next minute + // boundary instead of deleting it immediately. + await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); + let complete = false; + let lastLog = ''; + for (let attempt = 0; attempt < 100; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); + lastLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : lastLog; + if (lastLog.includes('Sea vHost test reset: complete')) { complete = true; break; } + } + if (!complete) throw new Error(`reset task did not complete: ${lastLog.trim()}`); +} finally { + if (taskID) { + try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +console.log(`Sea vHost test state was reset and services were left stopped; removed ${databases.length} control database(s), ${orphanFTPs.length} managed FTP account(s), ${orphanDatabases.length} managed project database(s), ${orphanSites.length} managed site(s), and ${managedHosts.length} known managed identity/identities.`); diff --git a/deploy/runtime-smoke.mjs b/deploy/runtime-smoke.mjs new file mode 100644 index 0000000..bde1736 --- /dev/null +++ b/deploy/runtime-smoke.mjs @@ -0,0 +1,208 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import http from 'node:http'; +import https from 'node:https'; + +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const panelURL = process.env.SEA_PANEL_URL?.trim(); +const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); +const tenantLogin = process.env.SEA_TENANT_LOGIN?.trim(); +const tenantPassword = process.env.SEA_TENANT_PASSWORD?.trim(); +const runtime = process.env.SEA_RUNTIME?.trim() || 'Node.js'; +const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; +if (!consoleURL || !panelURL || !panelAPIKey || !tenantLogin || !tenantPassword) { + console.error('SEA_CONSOLE_URL, SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_TENANT_LOGIN and SEA_TENANT_PASSWORD are required.'); + process.exit(2); +} +if (!['Node.js', 'Python', 'Go', 'Java'].includes(runtime)) { + console.error('SEA_RUNTIME must be Node.js, Python, Go or Java.'); + process.exit(2); +} + +async function uploadFile(pathname, cookie, directory, localPath, filename) { + const content = fs.readFileSync(localPath); + if (content.length === 0 || content.length > 20 * 1024 * 1024) throw new Error('runtime artifact must be between 1 byte and 20 MB'); + const body = new FormData(); + body.set('path', directory); + body.set('overwrite', 'false'); + body.set('file', new Blob([content]), filename); + const response = await fetch(new URL(pathname, consoleBase), { method: 'POST', headers: { Accept: 'application/json', Cookie: cookie }, body, redirect: 'manual' }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (response.status !== 201) throw new Error(payload?.error?.message || `artifact upload returned HTTP ${response.status}`); +} + +const consoleBase = new URL(consoleURL); +const panelBase = new URL(panelURL); +const panelClient = panelBase.protocol === 'https:' ? https : http; +const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; +const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); + +function panelForm(pathname, values, timeoutMs = 30_000) { + const requestTime = Math.floor(Date.now() / 1000).toString(); + const requestToken = md5(requestTime + md5(panelAPIKey)); + const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: requestToken }).toString()); + const url = new URL(pathname, panelBase); + return new Promise((resolve, reject) => { + const request = panelClient.request(url, { + method: 'POST', agent: panelAgent, timeout: timeoutMs, + headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, + }, (response) => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + data += chunk; + if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB')); + }); + response.on('end', () => { + if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel HTTP ${response.statusCode}`)); + try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } + }); + }); + request.on('timeout', () => request.destroy(new Error('panel request timed out'))); + request.on('error', reject); + request.end(body); + }); +} + +async function api(pathname, { method = 'GET', body, cookie, expected } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, + headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: 'manual', + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + const accepted = expected ? expected.includes(response.status) : response.status >= 200 && response.status < 300; + if (!accepted) throw new Error(payload?.error?.message || `${method} ${pathname} returned HTTP ${response.status}`); + return { response, payload }; +} + +function sessionCookie(response) { + const setCookie = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + const cookie = setCookie?.split(';', 1)[0]; + if (!cookie?.startsWith('sea_session=')) throw new Error('tenant login did not return a session cookie'); + return cookie; +} + +async function localShellCheck(name, command, marker) { + if (!/^[A-Za-z0-9 ._-]{1,80}$/.test(name) || !/^[A-Za-z0-9._:-]{1,160}$/.test(marker)) throw new Error('unsafe smoke-check metadata'); + const task = await panelForm('/crontab', { + action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', + sType: 'toShell', sBody: `set -Eeo pipefail\nstage=initial\ntrap 'printf "runtime_check_failed_line=%s stage=%s\\n" "$LINENO" "$stage"' ERR\n${command}\nprintf '%s\\n' '${marker}'`, + sName: 'Temporary Sea vHost runtime lifecycle check', save: '0', backupTo: 'localhost', + }); + const taskID = Number(task?.id); + if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('aaPanel rejected runtime check task'); + try { + await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); + let lastLog = ''; + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); + const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : ''; + lastLog = log; + if (log.includes(marker)) return; + if (log.includes('runtime_check_failed_line=')) throw new Error(`runtime check assertion failed: ${log.trim()}`); + if (log.includes('Failed') || log.includes('ERROR')) throw new Error('runtime check task failed'); + } + throw new Error(`runtime check task timed out: ${lastLog.trim().slice(-1200)}`); + } finally { + try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } + } +} + +const suffix = Date.now().toString(36).slice(-6); +const runtimeSlug = { 'Node.js': 'node', Python: 'python', Go: 'go', Java: 'java' }[runtime]; +const runPath = `/${runtimeSlug}-${suffix}`; +let cookie; +let project; +let site; +try { + const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantLogin, password: tenantPassword } }); + cookie = sessionCookie(login.response); + const dashboard = await api('/api/v1/dashboard', { cookie }); + project = dashboard.payload?.projects?.[0]; + if (!project?.id) throw new Error('tenant has no virtual host for the runtime smoke test'); + const catalog = await api('/api/v1/runtime-catalog', { cookie }); + const runtimeVersion = catalog.payload?.versions?.[runtime]?.[0]; + if (!runtimeVersion) throw new Error(`${runtime} is not installed`); + + const created = await api(`/api/v1/projects/${project.id}/sites`, { + method: 'POST', cookie, expected: [201], + body: { name: `${runtimeSlug}-${suffix}`, runtime, version: runtimeVersion, runPath, customDomain: '', autoSSL: false }, + }); + site = created.payload?.site; + if (!site?.id || site.status !== 'awaiting_upload' || !Number.isInteger(site.backendPort)) throw new Error(`${runtime} site creation returned an incomplete record`); + + const marker = ['Go', 'Java'].includes(runtime) ? `sea-vhost-${runtimeSlug}-artifact` : `sea-vhost-${runtimeSlug}-${suffix}`; + let entryFile; + if (runtime === 'Node.js') { + entryFile = 'package.json'; + await api(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie, expected: [204], + body: { path: `${runPath.slice(1)}/package.json`, content: JSON.stringify({ name: `sea-vhost-${suffix}`, private: true, scripts: { start: 'node server.js' } }, null, 2), overwrite: false }, + }); + await api(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie, expected: [204], + body: { path: `${runPath.slice(1)}/server.js`, content: `require('node:http').createServer((_, res) => { res.end('${marker}'); }).listen(Number(process.env.PORT), '127.0.0.1');\n`, overwrite: false }, + }); + } else if (runtime === 'Python') { + entryFile = 'app.py'; + const pythonSource = `import os\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n body = b'${marker}'\n self.send_response(200)\n self.send_header('Content-Length', str(len(body)))\n self.end_headers()\n self.wfile.write(body)\n def log_message(self, *_):\n pass\nHTTPServer(('127.0.0.1', int(os.environ['PORT'])), Handler).serve_forever()\n`; + await api(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie, expected: [204], + body: { path: `${runPath.slice(1)}/app.py`, content: pythonSource, overwrite: false }, + }); + } else { + entryFile = runtime === 'Go' ? 'app' : 'app.jar'; + const artifact = process.env.SEA_RUNTIME_ARTIFACT?.trim(); + if (!artifact || !fs.statSync(artifact).isFile()) throw new Error(`SEA_RUNTIME_ARTIFACT is required for ${runtime}`); + await uploadFile(`/api/v1/projects/${project.id}/files`, cookie, runPath.slice(1), artifact, entryFile); + } + + const checked = await api(`/api/v1/projects/${project.id}/sites/${site.id}/deployment/check`, { method: 'POST', cookie, body: { entryFile } }); + if (!checked.payload?.check?.ready || !checked.payload?.check?.adapterReady) throw new Error(`${runtime} deployment preflight did not become ready`); + const deployed = await api(`/api/v1/projects/${project.id}/sites/${site.id}/deployment`, { method: 'POST', cookie, body: { entryFile } }); + site = deployed.payload?.site; + if (site?.status !== 'running') throw new Error(`${runtime} deployment was not committed as running`); + if (!/^[a-z0-9.-]+$/.test(site.domain)) throw new Error('runtime site returned an unsafe domain'); + if (!/^\/www\/wwwroot\/seavHost\/vHost\/sv[0-9a-f]{10}$/.test(project.path) || !/^sv[0-9a-f]{10}$/.test(project.hostName)) { + throw new Error('runtime project returned an unsafe host identity or path'); + } + + await localShellCheck(`Sea vHost ${runtimeSlug} live ${suffix}`, `curl --silent --show-error --fail --max-time 10 --header 'Host: ${site.domain}' http://127.0.0.1/ | grep -Fq '${marker}'`, `live-${suffix}`); + const runtimeRoot = `${project.path}${runPath}`; + await localShellCheck(`Sea vHost ${runtimeSlug} identity ${suffix}`, [ + `runtime_root='${runtimeRoot}'`, `host_name='${project.hostName}'`, `runtime_port='${site.backendPort}'`, + 'stage=listener; pid="$(fuser -n tcp "$runtime_port" 2>/dev/null | tr -s \' \' \'\\n\' | grep -E \'^[0-9]+$\' | head -n1)"; test -n "$pid"', + 'stage=process_owner; test "$(stat -c %U "/proc/$pid")" = "$host_name"', + 'stage=directory_owner; test "$(stat -c %U:%G "$runtime_root")" = "sea-vhost:$host_name"', + 'stage=capabilities; test "$(grep -Ec \'^Cap(Prm|Eff|Amb):[[:space:]]+0+$\' "/proc/$pid/status")" -eq 3', + 'stage=config_privacy; if runuser -u "$host_name" -- test -r /var/lib/sea-vhost/config.json; then exit 1; fi', + 'stage=socket_privacy; if timeout 3 runuser -u "$host_name" -- curl --silent --unix-socket /run/sea-vhost/agent.sock http://localhost/v1/health >/dev/null 2>&1; then exit 1; fi', + ].join('\n'), `identity-${suffix}`); + await api(`/api/v1/projects/${project.id}/sites/${site.id}/state`, { method: 'POST', cookie, body: { enabled: false } }); + await localShellCheck(`Sea vHost ${runtimeSlug} stopped ${suffix}`, `if curl --silent --fail --max-time 3 http://127.0.0.1:${site.backendPort}/ >/dev/null 2>&1; then stage=still_listening; false; fi`, `stopped-${suffix}`); + const restarted = await api(`/api/v1/projects/${project.id}/sites/${site.id}/state`, { method: 'POST', cookie, body: { enabled: true } }); + if (restarted.payload?.site?.status !== 'running') throw new Error(`${runtime} site restart did not return running`); + await localShellCheck(`Sea vHost ${runtimeSlug} restarted ${suffix}`, `curl --silent --show-error --fail --max-time 10 --header 'Host: ${site.domain}' http://127.0.0.1/ | grep -Fq '${marker}'`, `restarted-${suffix}`); + + await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); + await localShellCheck(`Sea vHost ${runtimeSlug} removed ${suffix}`, `if curl --silent --fail --max-time 3 http://127.0.0.1:${site.backendPort}/ >/dev/null 2>&1; then exit 1; fi`, `removed-${suffix}`); + site = undefined; + await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] }); + await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] }); + console.log(JSON.stringify({ runtime, version: runtimeVersion, lifecycle: ['create', 'upload', 'check', 'deploy', 'proxy', 'stop', 'start', 'delete'], cleanup: 'complete' }, null, 2)); +} finally { + if (cookie && project?.id && site?.id) { + try { await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ } + } + if (cookie && project?.id) { + try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ } + try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ } + } +} diff --git a/deploy/security-smoke.mjs b/deploy/security-smoke.mjs new file mode 100644 index 0000000..d692130 --- /dev/null +++ b/deploy/security-smoke.mjs @@ -0,0 +1,152 @@ +const consoleURL = process.env.SEA_CONSOLE_URL?.trim(); +const tenantLogin = process.env.SEA_TENANT_LOGIN?.trim(); +const tenantPassword = process.env.SEA_TENANT_PASSWORD?.trim(); + +if (!consoleURL || !tenantLogin || !tenantPassword) { + console.error('SEA_CONSOLE_URL, SEA_TENANT_LOGIN and SEA_TENANT_PASSWORD are required.'); + process.exit(2); +} + +const consoleBase = new URL(consoleURL); +if (!['http:', 'https:'].includes(consoleBase.protocol) || consoleBase.username || consoleBase.password) { + console.error('SEA_CONSOLE_URL must be an HTTP(S) URL without embedded credentials.'); + process.exit(2); +} + +const checks = []; + +async function request(pathname, { method = 'GET', body, cookie, origin, expected = [200] } = {}) { + const response = await fetch(new URL(pathname, consoleBase), { + method, + headers: { + Accept: 'application/json', + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + ...(cookie ? { Cookie: cookie } : {}), + ...(origin ? { Origin: origin } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: 'manual', + signal: AbortSignal.timeout(10_000), + }); + const text = await response.text(); + let payload; + try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; } + if (!expected.includes(response.status)) { + throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${payload?.error?.message || 'unexpected response'}`); + } + return { response, payload }; +} + +async function check(name, callback) { + await callback(); + checks.push(name); +} + +function sessionCookie(response) { + const setCookie = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie'); + if (!setCookie?.startsWith('sea_session=')) throw new Error('login did not return the expected session cookie'); + const lower = setCookie.toLowerCase(); + if (!lower.includes('httponly') || !lower.includes('samesite=strict')) throw new Error('session cookie security attributes are incomplete'); + if (consoleBase.protocol === 'https:' && !lower.includes('secure')) throw new Error('HTTPS console session cookie is missing Secure'); + return setCookie.split(';', 1)[0]; +} + +function filePath(projectID, requested) { + const url = new URL(`/api/v1/projects/${projectID}/files`, consoleBase); + url.searchParams.set('path', requested); + return `${url.pathname}${url.search}`; +} + +let cookie; +try { + await check('unauthenticated API denied', async () => { + await request('/api/v1/dashboard', { expected: [401] }); + }); + + await check('cross-origin state request denied', async () => { + await request('/api/v1/auth/login', { + method: 'POST', origin: 'https://attacker.invalid', expected: [403], + body: { identifier: tenantLogin, password: tenantPassword }, + }); + }); + + await check('same-host wrong-scheme origin denied', async () => { + const wrongScheme = consoleBase.protocol === 'https:' ? 'http:' : 'https:'; + await request('/api/v1/auth/login', { + method: 'POST', origin: `${wrongScheme}//${consoleBase.host}`, expected: [403], + body: { identifier: tenantLogin, password: tenantPassword }, + }); + }); + + await check('strict login JSON decoding', async () => { + await request('/api/v1/auth/login', { + method: 'POST', origin: consoleBase.origin, expected: [400], + body: { identifier: tenantLogin, password: tenantPassword, unexpected: true }, + }); + }); + + const login = await request('/api/v1/auth/login', { + method: 'POST', origin: consoleBase.origin, + body: { identifier: tenantLogin, password: tenantPassword }, + }); + cookie = sessionCookie(login.response); + checks.push('session cookie attributes'); + + const dashboard = await request('/api/v1/dashboard', { cookie }); + const project = dashboard.payload?.projects?.[0]; + if (!project?.id) throw new Error('tenant has no virtual host for security checks'); + + await check('tenant cannot use admin API', async () => { + await request('/api/v1/admin/plans', { cookie, expected: [403] }); + }); + + await check('tenant project IDOR denied', async () => { + const missingProject = '9223372036854775807'; + await request(`/api/v1/projects/${missingProject}/credentials`, { cookie, expected: [404] }); + await request(`/api/v1/projects/${missingProject}/files`, { cookie, expected: [404] }); + }); + + await check('authenticated CSRF denied before mutation', async () => { + await request(`/api/v1/projects/${project.id}/state`, { + method: 'POST', cookie, origin: 'https://attacker.invalid', expected: [403], body: { enabled: true }, + }); + }); + + await check('file traversal and ambiguous paths denied', async () => { + for (const candidate of ['../../etc/passwd', 'public/../outside', 'public//index.html', String.raw`..\..\secret`]) { + await request(filePath(project.id, candidate), { cookie, expected: [400] }); + } + }); + + await check('internal trash path denied', async () => { + await request(filePath(project.id, '.sea-trash'), { cookie, expected: [400] }); + await request(filePath(project.id, '.sea-trash/deleted.txt'), { cookie, expected: [400] }); + }); + + await check('strict file-write JSON decoding', async () => { + await request(`/api/v1/projects/${project.id}/files`, { + method: 'PUT', cookie, origin: consoleBase.origin, expected: [400], + body: { path: 'security-probe.txt', content: '', overwrite: false, unexpected: true }, + }); + }); + + await check('setup and registration write routes closed', async () => { + await request('/api/v1/setup/install', { method: 'POST', origin: consoleBase.origin, body: {}, expected: [404] }); + await request('/api/v1/auth/register', { method: 'POST', origin: consoleBase.origin, body: {}, expected: [404] }); + }); + + await check('browser security headers present', async () => { + const response = await fetch(consoleBase, { redirect: 'manual', signal: AbortSignal.timeout(10_000) }); + if (response.headers.get('x-content-type-options')?.toLowerCase() !== 'nosniff') throw new Error('missing X-Content-Type-Options'); + if (response.headers.get('x-frame-options')?.toUpperCase() !== 'DENY') throw new Error('missing X-Frame-Options'); + if (!response.headers.get('content-security-policy')) throw new Error('missing Content-Security-Policy'); + }); + + console.log(JSON.stringify({ status: 'passed', checks, count: checks.length }, null, 2)); +} finally { + if (cookie) { + try { + await request('/api/v1/auth/logout', { method: 'POST', cookie, origin: consoleBase.origin, expected: [204] }); + } catch { /* best-effort session cleanup */ } + } +} diff --git a/deploy/systemd/sea-vhost-agent.service b/deploy/systemd/sea-vhost-agent.service new file mode 100644 index 0000000..39fc593 --- /dev/null +++ b/deploy/systemd/sea-vhost-agent.service @@ -0,0 +1,61 @@ +[Unit] +Description=Sea vHost privileged isolation agent +After=local-fs.target mysqld.service mysql.service mariadb.service +Before=sea-vhost-api.service + +[Service] +Type=simple +User=root +Group=sea-vhost-agent-control +EnvironmentFile=/etc/sea-vhost/sea-vhost.env +ExecStart=/opt/sea-vhost/bin/sea-vhost-agent +Restart=on-failure +RestartSec=3 +RuntimeDirectory=sea-vhost sea-vhost-php +RuntimeDirectoryMode=0755 +StateDirectory=sea-vhost-agent +StateDirectoryMode=0711 +UMask=0007 +NoNewPrivileges=true +PrivateTmp=true +# A root-only directory view follows socket recreation after MySQL restarts. +# Tenant PHP processes cannot traverse this 0700 configuration directory. +ConfigurationDirectory=sea-vhost-mysql +ConfigurationDirectoryMode=0700 +BindReadOnlyPaths=/tmp:/etc/sea-vhost-mysql/host-tmp +PrivateDevices=true +# PHP-FPM masters are launched by this service after dropping to each host +# UID/GID. They must retain host networking so ordinary PHP applications can +# reach the local MySQL listener and outbound APIs. The agent itself exposes +# only a token-authenticated Unix socket and does not listen on TCP. +# The privileged quota agent must enumerate processes owned by each isolated +# host UID. The unprivileged API keeps ProtectProc=invisible; this root-only, +# token-authenticated agent therefore retains the default /proc visibility. +ProcSubset=pid +ProtectClock=true +ProtectHostname=true +ProtectHome=true +ProtectSystem=strict +ReadOnlyPaths=/usr /boot /opt /var/lib/sea-vhost /var/lib/sea-vhost-panel /www/server +ReadWritePaths=/etc /www/wwwroot/seavHost/vHost /www/backup/sea-vhost /www/wwwlogs /www/server/panel/vhost/nginx /www/server/pure-ftpd/etc /www/server/nginx/logs/error.log /www/server/nginx/logs/nginx.pid -/www/server/nodejs/vhost/pids -/www/server/python_manager/versions -/www/server/php /var/lib/sea-vhost-agent /run/sea-vhost-php +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +# The agent creates locked per-host identities, applies ACLs and starts each +# PHP-FPM master after changing the forked child's UID/GID. The kernel clears +# ambient capabilities on that root-to-tenant UID transition, so tenant PHP +# processes do not inherit agent privileges. /etc remains writable because fixed useradd/usermod +# operations must update the host account databases; all other system paths +# stay read-only unless explicitly listed. +RestrictRealtime=true +LockPersonality=true +MemoryDenyWriteExecute=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +CapabilityBoundingSet=CAP_CHOWN CAP_DAC_OVERRIDE CAP_FOWNER CAP_FSETID CAP_KILL CAP_LINUX_IMMUTABLE CAP_NET_BIND_SERVICE CAP_SETGID CAP_SETUID +AmbientCapabilities=CAP_SETGID CAP_SETUID +LimitCORE=0 +SystemCallArchitectures=native + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/sea-vhost-api.service b/deploy/systemd/sea-vhost-api.service new file mode 100644 index 0000000..9ab75fc --- /dev/null +++ b/deploy/systemd/sea-vhost-api.service @@ -0,0 +1,45 @@ +[Unit] +Description=Sea vHost API +After=network-online.target mysql.service sea-vhost-agent.service sea-vhost-panel-broker.service +Requires=sea-vhost-agent.service sea-vhost-panel-broker.service +Wants=network-online.target + +[Service] +Type=simple +User=sea-vhost +Group=sea-vhost-control +SupplementaryGroups=sea-vhost-agent-control sea-vhost-panel-control +EnvironmentFile=/etc/sea-vhost/sea-vhost.env +ExecStart=/opt/sea-vhost/bin/sea-vhost-api +WorkingDirectory=/opt/sea-vhost +Restart=on-failure +RestartSec=3 +UMask=0007 +StateDirectory=sea-vhost +StateDirectoryMode=0700 +NoNewPrivileges=true +PrivateTmp=true +PrivateDevices=true +ProtectProc=invisible +ProcSubset=pid +ProtectClock=true +ProtectHostname=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/www/wwwroot/seavHost/vHost /run/sea-vhost /var/lib/sea-vhost +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +RestrictSUIDSGID=true +RestrictRealtime=true +LockPersonality=true +MemoryDenyWriteExecute=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +CapabilityBoundingSet= +AmbientCapabilities= +LimitCORE=0 +SystemCallArchitectures=native + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/sea-vhost-controller.service b/deploy/systemd/sea-vhost-controller.service new file mode 100644 index 0000000..e4c3dc7 --- /dev/null +++ b/deploy/systemd/sea-vhost-controller.service @@ -0,0 +1,34 @@ +[Unit] +Description=Sea vHost controller +After=network-online.target +Wants=network-online.target + +[Service] +User=sea-vhost +Group=sea-vhost-control +EnvironmentFile=/etc/sea-vhost/sea-vhost.env +ExecStart=/opt/sea-vhost/bin/sea-vhost-api +WorkingDirectory=/opt/sea-vhost +Restart=on-failure +RestartSec=3 +StateDirectory=sea-vhost +StateDirectoryMode=0700 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +PrivateDevices=true +ProtectSystem=strict +ProtectHome=true +ProtectProc=invisible +ProcSubset=pid +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +CapabilityBoundingSet= +AmbientCapabilities= +LimitCORE=0 + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/sea-vhost-node.service b/deploy/systemd/sea-vhost-node.service new file mode 100644 index 0000000..c34b5a3 --- /dev/null +++ b/deploy/systemd/sea-vhost-node.service @@ -0,0 +1,32 @@ +[Unit] +Description=Sea vHost stateless execution node +After=network-online.target sea-vhost-agent.service sea-vhost-panel-broker.service +Requires=sea-vhost-agent.service sea-vhost-panel-broker.service + +[Service] +User=sea-vhost +Group=sea-vhost-control +SupplementaryGroups=sea-vhost-agent-control sea-vhost-panel-control +EnvironmentFile=/etc/sea-vhost/sea-vhost.env +ExecStart=/opt/sea-vhost/bin/sea-vhost-node +Restart=on-failure +RestartSec=3 +UMask=0007 +NoNewPrivileges=true +PrivateTmp=true +PrivateDevices=true +ProtectSystem=strict +ProtectHome=true +ProtectProc=invisible +ProcSubset=pid +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +CapabilityBoundingSet= +AmbientCapabilities= +LimitCORE=0 + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/sea-vhost-panel-broker.service b/deploy/systemd/sea-vhost-panel-broker.service new file mode 100644 index 0000000..339ccea --- /dev/null +++ b/deploy/systemd/sea-vhost-panel-broker.service @@ -0,0 +1,47 @@ +[Unit] +Description=Sea vHost aaPanel capability broker +After=network-online.target +Before=sea-vhost-api.service +Wants=network-online.target + +[Service] +Type=simple +User=sea-vhost-panel +Group=sea-vhost-panel-control +SupplementaryGroups=sea-vhost-control +EnvironmentFile=/etc/sea-vhost/sea-vhost.env +ExecStart=/opt/sea-vhost/bin/sea-vhost-panel-broker +Restart=on-failure +RestartSec=3 +RuntimeDirectory=sea-vhost-panel +RuntimeDirectoryMode=0750 +StateDirectory=sea-vhost-panel +StateDirectoryMode=0700 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +PrivateDevices=true +ProtectProc=invisible +ProcSubset=pid +ProtectClock=true +ProtectHostname=true +ProtectSystem=strict +ProtectHome=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +RestrictSUIDSGID=true +RestrictRealtime=true +LockPersonality=true +MemoryDenyWriteExecute=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +IPAddressDeny=any +IPAddressAllow=localhost +CapabilityBoundingSet= +AmbientCapabilities= +LimitCORE=0 +SystemCallArchitectures=native + +[Install] +WantedBy=multi-user.target diff --git a/deploy/test_install_wizard.py b/deploy/test_install_wizard.py new file mode 100644 index 0000000..3453936 --- /dev/null +++ b/deploy/test_install_wizard.py @@ -0,0 +1,223 @@ +"""Installer safety/flow tests; no system commands or host provisioning.""" +import contextlib +import importlib.util +import io +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch, Mock + +spec = importlib.util.spec_from_file_location('install_wizard', Path(__file__).with_name('install-wizard.py')) +wizard = importlib.util.module_from_spec(spec) +spec.loader.exec_module(wizard) + + +class Answers: + def __init__(self, answers=(), confirmations=()): + self.answers = iter(answers) + self.confirmations = iter(confirmations) + + def ask(self, label, default=''): + return next(self.answers) + + def confirm(self, label, default=True): + return next(self.confirmations) + + def secret(self, label): + return next(self.answers) + + +def paired(): + return {'identity': {'nodeId': 2, 'caPem': 'CA', 'certificate': 'CERT', 'privateKey': 'PRIVATE', 'clientSpki': 'PIN'}, + 'tenantRoot': '/www/wwwroot/seavHost/vHost', 'address': ':9443', + 'brokerSocket': '/run/sea-vhost-panel/broker.sock', 'agentSocket': '/run/sea-vhost/agent.sock'} + + +class WizardTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + for name in ('CONFIG', 'NODE_CONFIG', 'PANEL_CREDENTIALS', 'PANEL_REGISTRY', 'ENVIRONMENT'): + p = patch.object(wizard, name, self.root / name) + p.start() + self.addCleanup(p.stop) + self.output = io.StringIO() + p = contextlib.redirect_stdout(self.output) + p.__enter__() + self.addCleanup(p.__exit__, None, None, None) + + def test_role_conversion_rejected_before_install(self): + for role, values in [('node', {'SEA_CONTROLLER_ONLY': 'true'}), ('controller', {'SEA_NODE_STATELESS': 'true'}), + ('combined', {'SEA_CONTROLLER_ONLY': 'true'}), ('controller', {'SEA_ADDR': '127.0.0.1:8080'})]: + with self.subTest(role=role, values=values), self.assertRaises(wizard.InstallError): + wizard.check_role(role, values) + wizard.CONFIG.write_text('{}') + with self.assertRaises(wizard.InstallError): + wizard.check_role('node', {}) + + def test_existing_roles_allowed(self): + for role, values in [('combined', {'SEA_ADDR': '127.0.0.1:8080'}), + ('controller', {'SEA_CONTROLLER_ONLY': 'true'}), ('node', {'SEA_NODE_STATELESS': 'true'})]: + wizard.check_role(role, values) + + def test_panel_address_is_loopback_origin_only(self): + for value in ('https://evil.example:8888', 'https://localhost:8888/path', 'http://u:p@127.0.0.1:8888', + 'https://127.0.0.1:99999', 'http://127.0.0.1:8888/?redirect=evil', 'file:///etc/passwd'): + with self.subTest(value=value), self.assertRaises(wizard.InstallError): + wizard.panel_url(value) + self.assertEqual(wizard.panel_url('https://127.0.0.1:7812/'), 'https://127.0.0.1:7812') + self.assertEqual(wizard.panel_url('http://[::1]:8888'), 'http://[::1]:8888') + + def test_node_pair_identity_and_path(self): + self.assertEqual(wizard.validate_pair(paired()), (2, '/www/wwwroot/seavHost/vHost')) + for update in ({'tenantRoot': '/etc'}, {'tenantRoot': '/www/wwwroot/a/../b'}, {'address': ':22'}, + {'address': 'localhost:9443'}, {'agentSocket': '/tmp/agent.sock'}, {'identity': {'nodeId': 1}}): + with self.subTest(update=update), self.assertRaises(wizard.InstallError): + wizard.validate_pair({**paired(), **update}) + + def test_missing_build_rejected_before_prompts(self): + with patch.object(wizard, 'SOURCE', self.root): + with self.assertRaisesRegex(wizard.InstallError, '安装包不完整'): + wizard.check_build('node') + + def test_private_write_never_overwrites(self): + file = self.root / 'credentials.json' + wizard.private_json(file, {'api_key': 'secret'}) + with self.assertRaises(FileExistsError): + wizard.private_json(file, {'api_key': 'changed'}) + self.assertEqual(json.loads(file.read_text())['api_key'], 'secret') + if os.name == 'posix': + self.assertEqual(file.stat().st_mode & 0o777, 0o600) + + def test_secret_prompt_and_credentials_not_printed(self): + key = 'sensitive-test-key-never-print' + with patch.object(wizard, 'detect_panel_url', return_value='https://127.0.0.1:7812'): + creds = wizard.credentials(Answers(['https://127.0.0.1:7812', key], [True])) + self.assertEqual(creds['api_key'], key) + self.assertTrue(creds['tls_insecure']) + self.assertNotIn(key, self.output.getvalue()) + + def test_node_flow_stages_credentials_and_cleans_even_on_failure(self): + # Real files, mocked privileged subprocess only. Assert no key in argv. + config = self.root / 'pair.json' + config.write_text(json.dumps(paired())) + creds = {'version': 1, 'url': 'https://127.0.0.1:7812', 'api_key': 'NEVER-PRINT-OR-ARGV', 'tls_insecure': True} + real_directory = tempfile.TemporaryDirectory + staged = [] + + def temporary_directory(**kwargs): + return real_directory(prefix=kwargs['prefix'], dir=self.root) + + def command(args, **kwargs): + stage_pair, stage_creds = Path(args[-2]), Path(args[-1]) + self.assertEqual(json.loads(stage_pair.read_text()), paired()) + self.assertEqual(json.loads(stage_creds.read_text()), creds) + self.assertNotIn(creds['api_key'], ' '.join(str(a) for a in args)) + staged.extend([stage_pair, stage_creds]) + raise subprocess.CalledProcessError(2, args) + + with patch.object(Path, 'is_dir', return_value=True), patch.object(Path, 'is_file', return_value=True), \ + patch.object(wizard, 'credentials', return_value=creds), \ + patch.object(wizard.os, 'fchmod', create=True), \ + patch.object(wizard.tempfile, 'TemporaryDirectory', side_effect=temporary_directory), \ + patch.object(wizard, 'run', side_effect=command), self.assertRaises(subprocess.CalledProcessError): + wizard.install_node(Answers([str(config)], [True])) + self.assertEqual(len(staged), 2) + self.assertTrue(all(not p.exists() for p in staged)) + self.assertNotIn(creds['api_key'], self.output.getvalue()) + + def test_controller_uses_legacy_noninteractive_then_starts_services(self): + with patch.object(wizard, 'nginx_plan', return_value=None), patch.object(wizard, 'run') as command, \ + patch.object(wizard, 'wait_services') as ready, patch.object(wizard, 'wait_api') as api_ready, patch.object(wizard, 'environment', return_value={'SEA_SETUP_TOKEN': 'install-token'}): + self.assertTrue(wizard.install_controller(Answers(confirmations=[True]), 'controller', {})) + self.assertEqual(command.call_args_list[0].args[0][-1], '--non-interactive') + self.assertEqual(command.call_args_list[2].args[0], ['systemctl', 'restart', 'sea-vhost-api']) + ready.assert_called_once_with(['sea-vhost-api']) + api_ready.assert_called_once_with({}) + self.assertIn('install-token', self.output.getvalue()) + + def test_cancel_leaves_system_untouched(self): + with patch.object(wizard, 'nginx_plan', return_value=None), patch.object(wizard, 'run') as command: + self.assertFalse(wizard.install_controller(Answers(confirmations=[False]), 'controller', {})) + command.assert_not_called() + + def test_cancel_node_upgrade_preserves_installed_config_permissions(self): + wizard.NODE_CONFIG.write_text(json.dumps(paired())) + with patch.object(Path, 'is_dir', return_value=True), patch.object(Path, 'is_file', return_value=True), \ + patch.object(wizard, 'credentials', return_value={'url': 'https://127.0.0.1:7812'}), \ + patch.object(wizard.os, 'fchmod', create=True) as chmod, patch.object(wizard, 'run') as command: + self.assertFalse(wizard.install_node(Answers([str(wizard.NODE_CONFIG)], [False]))) + chmod.assert_not_called() + command.assert_not_called() + self.assertEqual(json.loads(wizard.NODE_CONFIG.read_text()), paired()) + + def test_nginx_failed_check_restores_existing_config(self): + file = self.root / 'console.conf' + file.write_bytes(b'previous') + plan = {'existing': False, 'target': file, 'text': 'replacement', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']} + with patch.object(wizard.os, 'fchmod', create=True), patch.object(wizard, 'run', side_effect=subprocess.CalledProcessError(1, ['nginx'])), \ + patch.object(wizard.subprocess, 'run'): + with self.assertRaises(wizard.InstallError): + wizard.apply_nginx(plan) + self.assertEqual(file.read_bytes(), b'previous') + self.assertEqual(len(list(self.root.glob('console.conf.*.bak'))), 1) + + def test_nginx_failed_reload_removes_new_config(self): + file = self.root / 'console.conf' + plan = {'existing': False, 'target': file, 'text': 'replacement', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']} + with patch.object(wizard.os, 'fchmod', create=True), \ + patch.object(wizard, 'run', side_effect=[Mock(), subprocess.CalledProcessError(1, ['nginx'])]), \ + patch.object(wizard.subprocess, 'run'): + with self.assertRaises(wizard.InstallError): + wizard.apply_nginx(plan) + self.assertFalse(file.exists()) + + def test_nginx_successful_atomic_write(self): + file = self.root / 'console.conf' + plan = {'existing': False, 'target': file, 'text': 'new config', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']} + with patch.object(wizard.os, 'fchmod', create=True), patch.object(wizard, 'run') as command: + wizard.apply_nginx(plan) + self.assertEqual(command.call_count, 2) + self.assertEqual(file.read_text(), 'new config') + self.assertFalse(list(self.root.glob('.sea-vhost-*'))) + + def test_runtime_readiness_failure_is_actionable(self): + with patch.object(wizard.subprocess, 'run', return_value=Mock(returncode=1)), patch.object(wizard.time, 'sleep'): + with self.assertRaisesRegex(wizard.InstallError, 'journalctl'): + wizard.wait_services(['sea-vhost-node'], attempts=2) + + def test_runtime_readiness_requires_stable_active_service(self): + with patch.object(wizard.subprocess, 'run', side_effect=[Mock(returncode=0), Mock(returncode=1), Mock(returncode=0), Mock(returncode=0)]) as command, \ + patch.object(wizard.time, 'sleep'): + wizard.wait_services(['sea-vhost-node'], attempts=4) + self.assertEqual(command.call_count, 4) + + def test_api_readiness_does_not_accept_only_active_systemd(self): + with patch.object(wizard.time, 'monotonic', side_effect=[0, 1]): + with self.assertRaisesRegex(wizard.InstallError, 'API 健康检查未通过'): + wizard.wait_api({}, timeout=0) + + def test_api_readiness_retries_connection_refused(self): + opener = Mock() + response = Mock(status=200) + response.read.return_value = b'{"status":"setup_required"}' + context = Mock() + context.__enter__ = Mock(return_value=response) + context.__exit__ = Mock(return_value=False) + opener.open.side_effect = [ConnectionRefusedError(), context] + with patch.object(wizard.urllib.request, 'build_opener', return_value=opener), patch.object(wizard.time, 'sleep'): + wizard.wait_api({}) + self.assertEqual(opener.open.call_count, 2) + + def test_domain_injection_rejected(self): + for value in ('example.com; root /etc;', 'a b.example.com', '*.example.com', 'https://example.com', 'a..example.com'): + self.assertFalse(wizard.valid_domain(value)) + self.assertTrue(wizard.valid_domain('host.ser888.cn')) + + +if __name__ == '__main__': + unittest.main() diff --git a/deploy/update-production-ftp-mode.sh b/deploy/update-production-ftp-mode.sh new file mode 100755 index 0000000..79a2904 --- /dev/null +++ b/deploy/update-production-ftp-mode.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -euo pipefail + +certificate_domain="${SEA_FTP_CERTIFICATE_DOMAIN:-}" +management_domain="${SEA_MANAGEMENT_DOMAIN:-}" +if [[ ! "${certificate_domain}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${certificate_domain}" == .* ]] || [[ "${certificate_domain}" == *..* ]]; then + echo "SEA_FTP_CERTIFICATE_DOMAIN is invalid." >&2 + exit 1 +fi +if [[ ! "${management_domain}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${management_domain}" == .* ]] || [[ "${management_domain}" == *..* ]]; then + echo "SEA_MANAGEMENT_DOMAIN is invalid." >&2 + exit 1 +fi + +SEA_FTP_CERTIFICATE_DOMAIN="${certificate_domain}" /www/server/panel/pyenv/bin/python3 - <<'PY' +import json +import os +import stat +import tempfile +from pathlib import Path + +path = Path('/var/lib/sea-vhost/config.json') +if not path.is_file() or path.is_symlink(): + raise SystemExit('Sea vHost configuration is missing or unsafe') +metadata = path.stat() +payload = json.loads(path.read_text(encoding='utf-8')) +payload['ftp_domain'] = os.environ['SEA_FTP_CERTIFICATE_DOMAIN'].strip().lower() +handle, temporary_name = tempfile.mkstemp(prefix='.sea-vhost-config-', dir=str(path.parent), text=True) +try: + with os.fdopen(handle, 'w', encoding='utf-8') as output: + json.dump(payload, output, ensure_ascii=False, indent=2) + output.write('\n') + output.flush() + os.fsync(output.fileno()) + os.chmod(temporary_name, stat.S_IMODE(metadata.st_mode)) + os.chown(temporary_name, metadata.st_uid, metadata.st_gid) + os.replace(temporary_name, path) +finally: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass +PY + +systemctl restart sea-vhost-agent sea-vhost-panel-broker sea-vhost-api +healthy=false +for _ in {1..30}; do + health="$(curl --fail --silent --show-error --max-time 3 --header "Host: ${management_domain}" http://127.0.0.1:8080/healthz 2>/dev/null || true)" + if [[ "${health}" == *'"status":"ok"'* ]]; then + healthy=true + break + fi + sleep 1 +done +if [[ "${healthy}" == "true" ]]; then + echo "Sea vHost FTP host-reuse mode update: success" + # Do not exit here: panel-run-task appends its completion marker after this + # script, and an explicit exit would prevent the caller from observing it. + true +else +echo "Sea vHost API did not become healthy after the FTP mode update." >&2 +exit 1 +fi diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..c0d53b3 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,46 @@ +# Sea vHost 文档索引 + +更新日期:2026-10-30。当前部署与功能状态从项目状态整理开始阅读;最新 SSO 策略与部署见 SSO 与界面验收。带日期的验收报告保留当时的环境和测试结果,不代表当前服务器重新检查通过。 + +## 当前说明 + +| 文档 | 用途 | +| --- | --- | +| [36 实机测试交付](handover-2026-10-30.md) | 当前入口、交付文件、账号与历史夹具边界、实际测试操作顺序 | +| [项目状态整理](project-status-2026-10-29.md) | 功能、正常操作流程、验证范围和剩余工作 | +| [业务功能与按钮说明](business-actions.md) | 各页面操作用途、DNS 凭据/解析/证书的区别及业务表达缺口 | +| [日常操作与管理端 API](hosting-operations.md) | 用户与主机开通、JSON 批量管理、网站、文件、计划任务、财务站对接 | +| [SSO 与界面验收](sso-ui-acceptance.md) | 首次登录绑定/建号、分类密码策略、主机例外与最新部署验证 | +| [资源管理](resource-management.md) | 用户/主机/节点 CRUD、归属、回收恢复及套餐边界 | +| [部署](deployment.md) | 构建依赖、单机安装、诊断及环境维护 | +| [多被控安装](multi-node-installation.md) | 三种安装角色、配对、mTLS 与升级边界 | +| [多节点实现](multi-node-implementation.md) | 主控与被控职责、数据归属和验收范围 | +| [架构](architecture.md) | 身份、数据模型、资源编排及证书流程 | +| [安全与资源隔离](security.md) | 权限、密钥、文件与网络边界、软配额 | +| [宝塔 API 兼容性](bt-api-compatibility.md) | 基础接口白名单、路由和响应格式 | +| [设计系统](design-system.md) | 视觉、组件、响应式与交互规范 | +| [持续验收清单](real-panel-acceptance.md) | 需要检查的项目;清单存在不等于已验证通过 | + +## 验收与历史记录 + +| 文档 | 适用范围 | +| --- | --- | +| [10-29 界面与证书验收](ui-acceptance-2026-10-29.md) | 最新一轮界面、环境切换、HTTP-01 和清理结果 | +| [10-29 彩虹 DNS 联调](dns-acceptance-2026-10-29.md) | 真实域名枚举、TXT 创建/清理与 DNS-01 签发已通过;保留首次失败及修复记录 | +| [10-26 Web 验收](web-acceptance-2026-10-26.md) | 36 环境正常网页操作、五类语言与权限测试 | +| [10-25 安装验收](installation-test-2026-10-25.md) | 早期 202 测试机的安装、同机分角色和资源验证 | +| [10-20 功能报告](feature-test-report-2026-10-20.md) | 更新至 10-21 的历史重装、功能与故障恢复结果 | +| [安全评估基线](security-audit-2026-10-15.md) | 10-15 初评及文中注明日期的修复复测 | +| [10-19 安全金丝雀](security-canary-test-2026-10-19.md) | 当时的合成标记与访问隔离检查 | +| [10-19 公开漏洞探针](public-vulnerability-test-2026-10-19.md) | 当时的低强度公开入口检查及限制 | + +## 写法与结论口径 + +- 产品界面使用“用户”“虚拟主机”“网站”“节点”;技术说明可使用“多租户”,但 `tenant_id` 必须区分用户身份与主机内部资源命名空间。可变归属字段为 `owner_tenant_id`。 +- “已实现”指代码能力;“测试通过”须注明环境及范围;“待验证”“受阻”“暂缓”分别说明缺少证据、外部阻塞或用户决定。不得混用这些结论。 +- 当前说明不沿用已失效的入口、默认值或接口格式;历史报告保留原版本与结果,用日期标识,不将旧测试数量或旧部署摘要称为最新状态。 +- 文件大小使用 MiB/GiB,带宽使用 Mbps;HTTP/Pure-FTPd 的连接或会话限速不写成主机总速率,巡检软配额不写成内核即时硬配额。 +- 本机验证、同机分离进程、跨服务器、模拟服务和真实外部服务分别记录;未实际执行安装或升级时,不以单元测试或页面提交成功代替实机结果。 +- 密钥、密码、会话与完整 DSN 不写入文档;示例使用占位值。命令注明执行位置和影响范围,破坏性恢复步骤不能混入只读检查。 + +本索引面向源码仓库;历史测试证据与私有恢复材料按各报告的保密边界保存,不作为可公开下载的附件。 diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..b66548e --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,74 @@ +# Sea vHost 架构 + +## 组件 + +本节描述主控兼本机托管模式。独立被控由主控通过 mTLS 主动调用,业务台账与远程资源登记保留在主控;角色差异见 [多节点实现说明](multi-node-implementation.md)。 + +1. **React 控制台**:由 Nginx 提供静态文件,只通过同源 `/api/v1` 访问后端。 +2. **Go API**:以非 root 的 `sea-vhost` 用户运行,负责登录会话、租户权限、配额检查、审计和高层资源编排;进程和配置中均没有宝塔 API 密钥。 +3. **面板能力代理**:以专用非 root 用户 `sea-vhost-panel` 运行,是唯一持有宝塔 API 密钥的进程。它只接受固定 RPC,校验路径、运行用户、端口和标识符,并用私有资源登记表拒绝操作非 Sea vHost 创建的站点、FTP 或数据库。 +4. **隔离代理**:以 root 运行,但只监听 `sea-vhost-agent-control` 组可访问、权限为 `0660` 的 Unix Socket;所有变更 RPC 还必须携带安装时生成的内部 Bearer Token。代理只接受结构化白名单操作:创建锁定主机身份、受管目录与 ACL、映射 Pure-FTPd 虚拟账号、生成独立 PHP-FPM 池,以及写入固定模板的 Nginx 防护。路径、用户名、域名和版本均再次校验,不提供任意命令或任意文件写入接口。 +5. **MySQL**:保存租户、租户/主机账号、套餐、虚拟主机、站点、域名、FTP/数据库映射、配额快照和审计日志。 +6. **宝塔面板**:负责 Nginx 站点、FTP、MySQL、SSL、反向代理,以及“网站”中的各语言项目能力。 + +每台主机创建一个与随机主机名同名的 Linux 系统身份,例如 `sv0123456789`。该账号密码锁定、Shell 固定为 `/usr/sbin/nologin`、不加入其他租户组,不能 SSH 或交互登录。目录属主为 `sea-vhost`、属组为该主机身份:Web 文件管理器使用属主权限,Node.js、Python、Go、Java 与独立 PHP-FPM master/worker 使用主机身份权限;Nginx 的 `www` 仅通过命名 ACL 获得读取与目录穿越权限。默认 ACL 让后续上传文件继续继承边界,`.sea-runtime` 则显式拒绝 `www` 访问。不同主机身份互不具备对方目录权限。 + +API 另外加入 `sea-vhost-agent-control` 与 `sea-vhost-panel-control`;`www` 和面板 broker 都不属于这两个组,broker 不能连接 root 隔离代理。Unix Socket 的组权限与内部 Token 构成双重鉴权;面板 broker 再以固定操作集合、参数白名单和受管资源登记表限制可调用的宝塔基础功能。`sea-vhost-control` 仅用于读取公共服务配置,不授予 Socket 访问权。 + +受管主机位于宝塔默认站点根目录下的 Sea vHost 专用子树,格式为 `/www/wwwroot/seavHost/vHost/sv<10位随机十六进制>`。随机主机名同时作为默认三级域名前缀、主机登录名、FTP 用户名和 MySQL 数据库/用户标识,但三类密码独立随机生成。Linux 身份没有可用家目录(passwd home 固定为 `/nonexistent`),FTP 根目录由 Pure-FTPd 单独 chroot 到主机目录。`projects.tenant_id` 绑定不可随归属变化的内部资源命名空间,`owner_tenant_id` 才是可为空的用户归属;一台主机最多归属一个用户,一个用户可以管理多台主机;用户填写的展示名称不能影响系统路径或宝塔资源名。broker 只接受数据库已编排且符合该单层主机目录格式的资源。 + +`root_path` 是该主机 FTP 和 Web 文件管理的固定边界。一台主机可对应多条 `sites` 记录,每个站点有独立的域名、运行环境/版本、回环端口和 `run_path`;`run_path` 必须是主机根目录内的规范相对目录,例如 `/`、`/public`、`/dist` 或 `/apps/web/public`。同一主机不允许两个站点使用同一运行目录。Sea vHost 先由隔离代理创建并验证物理目录,再通过宝塔免费的基础站点接口创建站点;绝不允许提交任意绝对系统路径、`..`、反斜杠或符号链接目录。 + +DNS API 凭据存放在独立的 `dns_credentials` 表中,平台凭据使用空 `tenant_id`,租户凭据必须绑定 `tenant_id`;明文 JSON 以随机 `secret_ref` 作为 AES-GCM 附加鉴别数据加密。列表接口只返回名称、服务商和区域,不返回密文、引用值或密钥。ACME 账户私钥同样加密存放于 `system_secrets`,网站证书私钥仅在签发内存中生成并交给受管宝塔站点,不写入业务数据库。 + +权限关系为 `平台管理员 → 用户账号 → 虚拟主机账号`。管理员开通主机并分配所属用户;用户切换管理名下的多台主机,并可在套餐范围内新增网站。主机账号与唯一 `project_id` 绑定,只能管理该主机的站点、文件、域名和凭据,不会获得用户的其他主机或聚合操作日志。套餐与到期时间均按主机设置。 + +管理员可从用户管理或虚拟主机列表建立最长 30 分钟的临时代入会话,原管理员会话保持不变。代入令牌必须同时匹配原管理员会话和目标账号,实际业务接口完全按目标身份鉴权;代入中禁止再次代入和访问账号登录安全设置。退出恢复原管理员身份;目标改密、主机密码重置、相关会话注销与过期均会撤销相应代入会话。 + +操作日志保留实际管理员与被代入账号两个身份。客户侧只返回已确认普通用户或主机身份产生的记录:用户可查看名下主机及自身账号操作,主机账号只查看所属主机操作。直接管理员操作、管理员代入操作和无法确认操作人的历史记录均不进入客户日志;管理员审计保留这些记录及代入身份。 + +## SSO 登录状态机 + +`发起授权 → 浏览器绑定 state / PKCE / nonce → 校验签名令牌 → 已绑定身份直接建立会话;未绑定身份转为短时待处理票据 → 前台验证已有账号后绑定,或按后台策略创建普通用户 → 原子消费票据并建立会话`。 + +身份键包含 Issuer 摘要,subject 区分大小写,不按邮箱推断归属。管理员与普通用户分别控制密码入口;主机账号不参加 SSO。迁移 028 扩展流程状态、待处理票据与旧身份命名空间,默认不改变原有密码登录策略。操作与验收见 [SSO 与界面验收](sso-ui-acceptance.md)。 + +## 首次安装状态机 + +`配置文件不存在 → 只启动安装 API → 令牌验证 → panel broker 代测本机宝塔 → 测试 MySQL/隔离代理 → 迁移与管理员初始化 → broker 独占保存宝塔密钥 → 原子写入 Web API 的 0600 配置 → 关闭安装监听 → 载入正式服务` + +安装状态与业务状态互斥:正式配置一旦存在,安装测试和写入路由不再注册。会话密钥由后端生成,数据库密码与宝塔 API 密钥不会返回浏览器或写入日志。宝塔密钥只保存于 `/var/lib/sea-vhost-panel/credentials.json`,目录仅 `sea-vhost-panel` 可访问;Web API 配置不含该密钥。 + +## 虚拟主机与网站创建事务 + +`校验租户与套餐 → 随机生成主机/FTP/数据库的独立密码 → 写入主机及禁用状态的主机账号 → 隔离代理创建锁定 Linux 身份与目录 ACL → 宝塔创建主站 → 隔离代理恢复宝塔可能覆盖的身份边界 → 写入固定 Nginx 防护并测试/重载 → PHP 创建独立 FPM 池 → 创建 FTP 并映射到主机 UID/GID → 创建 MySQL → 加密保存凭据并激活主机账号 → 申请 SSL` + +新增网站使用同一主机身份和根目录,但使用独立 `run_path`、域名、环境版本与回环端口。面板 broker 只放行已登记主机根目录内的新站,并同时拒绝重复域名、端口和运行目录。建站后同样必须重新恢复受管 ACL,之后才可交付。 + +自定义域名绑定到具体 `site_id`,而不是笼统绑定整台主机。启用审核时先保存全局唯一的 `pending` 记录,管理员批准后才通过 broker 写入该受管宝塔站点;拒绝只更新 Sea vHost 状态,不触碰面板。关闭审核时同样先预留域名,再执行宝塔绑定,成功后更新为 `approved`,面板失败则删除预留记录。这样并发请求不能把同一域名绑定到两个租户网站。 + +主站的启停沿用虚拟主机状态,附加网站可单独启停。宝塔语言项目启动时可能递归改写源码所有权,因此每次启动成功后都必须由隔离代理恢复 `sea-vhost:<主机身份>` 与 ACL,失败则立即停站。删除 PHP 网站时先停止其独立 FPM,保留指向已停止 Socket 的 Nginx 适配器,直到宝塔站点删除完成,避免短暂回退到共享 `www` FPM。任何网站删除都不会递归删除主机目录或源码。 + +PHP 站点在上述事务完成后即可进入运行态;Node.js、Python、Go 和 Java 进入 `awaiting_upload`,源码或构件上传完成后才允许创建宝塔项目与反向代理,避免对不存在的入口文件提前启动进程。HTTP-01 自动证书在 broker 内适配同步证书返回或旧式订单返回,校验证书并部署到受管站点,验证目录与当前站点物理运行目录一致,控制面只在部署成功后标记 `active`,失败则标记 `failed` 并允许租户重试。 + +DNS-01 不把租户凭据交给 broker:非 root API 调用对应服务商的 HTTPS 接口,支持 Cloudflare、阿里云、腾讯云、西部数码和彩虹聚合 DNS;彩虹自定义地址须通过 HTTPS 公网地址、解析结果和实际拨号校验,禁止重定向,并用记录 ID 精确回收本次 TXT。系统分配域名只允许匹配平台凭据,自定义域名只允许匹配当前租户凭据;两侧均采用最长区域后缀,缺少任何域名的路由即在创建 ACME 订单前失败。凭据连通性测试仅创建一条随机 TXT 并立即按返回 ID 删除,结果持久化且一分钟内禁止重复执行。签发成功后仍仅调用 broker 的受管站点 `SetSSL`。`certificate_automations` 记录模式、到期时间和下次尝试;进入签发时即预置六小时兜底重试时间,成功后改为到期前 30 天,正常失败也在六小时后重试,避免进程异常退出使任务永久失联。单站人工签发有五分钟冷却。租户也可上传自有 PEM 证书;API 校验证书链、域名和私钥匹配,并把该站切换为手动证书状态。 + +自定义域名无论在创建网站时填写,还是后续从域名页绑定,都经过同一个保留域校验;租户不能绑定平台根域及其子域、控制台域名、独立的 FTP 证书来源域名或安装配置中的其他保留域。FTP 凭据返回项目默认域名作为连接地址,服务器级 Pure-FTPd 证书应通过租户泛域名覆盖这些随机主机名。每站域名总数上限为 100(含默认域名),新增时先锁定站点行再计数和插入,避免并发请求绕过上限;证书收集阶段会再次拒绝超限的遗留数据。 + +租户可调用 `POST /api/v1/projects/{projectID}/sites/{siteID}/deployment/check` 做只读部署预检,再调用同路径去掉 `/check` 的接口执行部署。入口文件是相对于该站点 `run_path` 的路径;API 会再次绑定租户、主机与网站,并通过 `os.Root` 和逐级软链接检查确认它是主机根目录中的非空普通文件。写入适配器会创建宝塔语言项目、轮询项目列表确认真实运行态,再写入 Nginx 反代;任一步失败都不会把本地状态标为运行。不同网站的运行目录禁止相同或互为父子,文件管理也拒绝移动仍被网站占用的运行目录及其祖先。 + +任一步失败都会逆序撤销宝塔资源,并把项目目录移动到仅 root 可访问的隔离区,保留故障证据而不直接删除数据。 + +## 运行时 + +- PHP:每网站启动一个指定版本的独立 PHP-FPM master/pool;agent 在 fork 后、exec 前切换到主机 UID/GID,master 与 worker 均以该身份运行且 permitted/effective/ambient capabilities 为空。每站使用唯一 Unix Socket 与主机私有临时目录,并强制 `open_basedir`。PHP 子进程与宿主共享网络命名空间,以访问本机 MySQL 和租户所需外部 API;root agent 本身不监听 TCP,只开放双重鉴权的 Unix Socket。 +- Node.js / Python / Go:使用宝塔“网站”中的对应项目能力管理进程,`run_user` 为该主机身份;Nginx 站点反代到分配的 loopback 端口。 +- Java:使用宝塔 Java 项目基础接口,`run_user` 同样为主机身份。 + +资源限制采用分钟级控制面软配额,不依赖文件系统 quota 或付费监控插件。磁盘由 root agent 在固定主机根目录内只读扫描,因此租户收紧文件权限不能逃避计量;数据库调用免费 `GetInfo`,月流量合并 Nginx 响应字节与 FTP 上传/下载日志游标,进程按独立 UID 扫描 `/proc`;任一超额即停站、停 FTP、终止该 UID 的进程,并撤销主机身份的目录写权限。Web 文件服务仍可删除数据,恢复限额后重新落实 ACL 但不自动启动站点。FTP chroot、Web API 的 `os.Root`、每主机 Linux 身份、目录 ACL 与 PHP `open_basedir` 形成分层边界,但不引入容器或挂载命名空间。 + +Sea vHost 明确不接入 Docker、Compose、Docker Socket 或宝塔容器 API;容器工作负载不属于本系统支持范围。 + +## API 版本边界 + +宝塔官方说明接口可能随版本变化。本适配器以官方 `11.7.0-docs` 结构为公开接口基线,结合 12.0.0 面板源码核对,并已完成 Node.js 写入生命周期验证;每台正式服务器首次安装仍须运行兼容性检查。语言项目按单项返回 `available`、`not_installed` 或 `probe_failed`,可选运行时失败不会拖垮安装。所有宝塔参数只存在于 `internal/panel`,底层请求还受免费基础接口白名单限制;专业版、企业版和未分类接口不能通过通用请求方法调用。 diff --git a/docs/bt-api-compatibility.md b/docs/bt-api-compatibility.md new file mode 100644 index 0000000..f175fb7 --- /dev/null +++ b/docs/bt-api-compatibility.md @@ -0,0 +1,51 @@ +# 宝塔 API 兼容性记录 + +公开接口基线:宝塔 Linux 面板官方 API `11.7.0-docs`。只读兼容性探测基线:宝塔 Linux 面板 12.0.0 + Debian 13;该探测未修改测试机资源。 + +| 能力 | 路由 / action | 策略 | Sea vHost 用途 | +| --- | --- | --- | --- | +| 鉴权 | 双重 MD5 `request_time + md5(api_sk)` | 免费基础 | 仅 panel broker 签名;Web API 不持钥 | +| 创建站点 | `POST /site`, `AddSite` | 免费基础 | 所有运行时先建立 Nginx 站点 | +| 防跨站 | `POST /site`, `multiple_basedir` | 免费基础 | PHP 项目强制启用 | +| 设置运行目录 | `POST /site`, `SetSiteRunPath` | 免费基础 | 仅允许受管主机根目录内的规范相对路径 | +| 添加域名 | `POST /site`, `AddDomain` | 免费基础 | 审核通过后绑定自定义域名 | +| 反向代理 | `POST /site`, `CreateProxy` | 免费基础 | 普通单后端反代,不使用宝塔负载均衡 | +| FTP | `POST /ftp`, `AddUser` / `DeleteUser` | 免费基础 | 每项目默认一个账号;空间由 Sea vHost 主机级软配额统一统计,不依赖可选 FTP 配额接口 | +| MySQL | `POST /database`, `AddDatabase` | 免费基础 | 每项目默认一个数据库/用户 | +| ACME | `POST /acme`, `apply_cert_api` / `get_order_find` / `SetCertToSite` / `remove_order` | 免费基础 | HTTP-01 支持同步证书与旧式订单响应,校验后显式部署;仅移除受管站点已跟踪的续期订单,不使用商用证书权益 | +| 手动证书 | `POST /site`, `SetSSL` | 免费基础 | 服务端校验证书/私钥后,仅为受管站点安装自有 PEM 证书 | +| 关闭证书 | `POST /site`, `CloseSSLConf` | 免费基础 | 仅关闭对应受管站点的 HTTPS,并同步关闭自动续签状态 | +| Java | `/mod/java/project/create_spring_boot_project/stype` | 免费语言项目 | 指定租户 `run_user` | +| Node.js 项目 | `/project/nodejs/create_project/stype` 及 `start_project` / `stop_project` / `remove_project` | 免费语言项目 | 注入分配的 `PORT`,创建后轮询进程状态 | +| Python 项目 | `/project/python/CreateProject` 及启停/删除路由 | 免费语言项目 | 创建路由不追加会覆盖 `stype=command` 的 `/stype`;传 `python_bin` 规范 SDK 路径,命令使用独立虚拟环境并注入 `PORT` | +| Python 环境登记 | `/mod/python/environment/add_environment/stype` | 免费基础环境管理 | 仅登记 root 管理的 `/www/server/python_manager/versions/<版本>/bin/python3.`,不允许 root 检测租户可写解释器 | +| Go 项目 | `/project/go/create_project/stype` 及启停/删除路由 | 免费语言项目 | 仅接受主机目录内已校验的可执行文件 | +| Java 项目生命周期 | `/mod/java/project/project_list/stype` 及 `start_project` / `stop_project` / `remove_project` | 免费语言项目 | 与新版创建接口保持同一模型;Spring Boot JAR 注入 `--server.port`,PID 和真实监听端口同时成立才提交运行态 | +| PHP 版本 | `POST /site`, `GetPHPVersion` | 免费基础 | 动态列出已安装版本 | +| PHP 补丁元数据 | `POST /plugin`, `get_soft_find`,固定 `php-X.Y` | 免费基础软件 | 比较每个已安装分支的已装补丁与可用稳定补丁 | +| PHP 补丁更新 | `POST /plugin`, `install_plugin`,固定分支、`upgrade=1` | 免费基础软件 | 仅允许元数据公布的稳定补丁;提交后验证队列和实际程序 | +| PHP 更新队列 | `POST /data`, `getData`,`table=tasks, search=execshell` | 免费基础 | 宝塔按状态/类型搜索;客户端再精确匹配 `upgrade[php-X.Y]`,不使用任务名作为搜索条件 | +| Node.js 版本 | `POST /project/nodejs/get_nodejs_version/stype` | 免费语言项目 | 动态列出已安装版本 | +| Python 版本 | `POST /project/python/list_py_version/stype` | 免费语言项目 | 网站 Python 项目可用的 CPython 版本 | +| Go 版本 | `POST /project/go/list_go_sdk/stype` | 免费语言项目 | 网站 Go 项目可用的 SDK | +| Java 版本 | `GET /mod/java/project/get_system_info/stype` | 免费语言项目 | 动态列出已安装 JDK,并在 broker 内解析为服务端路径 | + +12.0.0 上已核对的项目列表路由为 Node.js `/project/nodejs/get_project_list/stype`、Python `/project/python/GetProjectList/stype`(方法名区分大小写)、Go `/project/go/get_project_list/stype` 和 Java `/mod/java/project/project_list/stype`。该版本同时保留旧 `/project/java/*` 模型与新版 `/mod/java/project/*` 模型,两者项目配置结构不同,不能混用。`/v2/project/*`、`/mod/python/project/*`、`/mod/go/project/*` 不适用于该版本。 + +官方文档提醒接口不保证跨版本稳定,生产启用前必须在当前免费版面板重新执行只读探测与测试租户的完整创建/撤销演练。五种语言独立探测,不存在“某一种路由异常导致安装失败”的强依赖。当前代码已覆盖版本清单、创建、运行态轮询、启动、停止和删除。Node.js、Python、Go、Java 已在该 12.0.0 测试机完成创建、上传、部署、Nginx 反代、停止、重启、删除及清理实机闭环;最终部署服务器仍须重复验收。 + +当前控制面提供与面板写入解耦的部署预检:Node.js 默认检查 `package.json`,Python 默认检查 `app.py`,Go 默认检查无扩展名 Linux 可执行文件,Java 默认检查 `app.jar`;均相对于站点运行目录。预检不会调用宝塔,也不会将 `awaiting_upload` 改为 `running`。正式部署只有在对应语言项目出现在宝塔列表且进程状态为运行后才会提交本地状态,避免空操作或单纯 HTTP 成功造成状态欺骗。 + +自动证书不能把 `apply_cert_api` 的成功响应等同于已启用 HTTPS。当前面板可同步返回 `cert`、`root`、`private_key`,Sea vHost 校验证书有效期、请求域名和私钥匹配后调用 `SetSSL`;旧式订单响应才保存索引、轮询 `get_order_find` 并调用 `SetCertToSite`。只有落站成功才标记 `active`;不能把有效的同步响应因缺少索引误判为失败。手动安装或关闭 SSL 会取消该受管站点已跟踪的原生续期订单。HTTP-01 继续使用该基础能力;DNS-01 不调用宝塔的面板级全局 DNS 凭据,而是在 Sea vHost 内按平台/租户作用域加密保存凭据、直接完成 DNS 验证,最终只调用受管站点证书安装能力。 + +底层 `freePanelRequestPolicy` 是最终网络边界:只有表内基础接口及其对应的删除/启停操作能够签名并发送。宝塔 WAF、系统加固、防篡改、多用户、监控报表、任务管理器、负载均衡、企业备份、安全扫描、防入侵、PHP 安全防护、资源监视器,以及任何未分类路由均不在允许列表中。 + +官方同时说明该 API 能完整控制面板全部功能。因此 IP 白名单只作为外层来源限制,不能替代最小权限:Sea vHost 使用 localhost-only 的独立 broker 保存密钥,并以资源登记表阻止 Web API 触碰面板既有资源。 + +参考: + +- [宝塔 API 文档](https://docs.bt.cn/api) +- [站点接口](https://docs.bt.cn/api/site/) +- [数据库接口](https://docs.bt.cn/api/database/actions/) +- [FTP 接口](https://docs.bt.cn/api/ftp/actions/) +- [ACME 接口](https://docs.bt.cn/api/acme/) diff --git a/docs/business-actions.md b/docs/business-actions.md new file mode 100644 index 0000000..86630f0 --- /dev/null +++ b/docs/business-actions.md @@ -0,0 +1,93 @@ +# Sea vHost 业务功能与操作说明 + +核对日期:2026-10-29。本文说明当前代码中各入口与按钮的业务作用;不表示本次重新实测全部操作,也不把文末待整理项写成已完成。 + +## DNS:凭据、解析、证书分别管理 + +管理员的“DNS 管理”目前管理平台的服务商 API 凭据,普通用户的“DNS API”管理自己的凭据。它们不是完整的 DNS 控制台,暂不提供任意 A、AAAA、MX 等记录的通用编辑器。 + +### DNS 凭据操作 + +| 当前操作 | 实际作用 | 何时使用 / 影响范围 | +| --- | --- | --- | +| 新增凭据 | 录入服务商票据并获取可管理域名,选择区域后保存 | 首次接入服务商;保存不会接管或修改全部现有解析 | +| 读取可管理域名 | 使用填写的票据查询服务商,返回可选域名 | 检查认证与域名读取权限;不会创建网站解析或申请证书 | +| 加密保存 | 保存所选区域与票据,供后续解析和证书操作使用 | 必须先读取并选择域名;能读取列表不代表已有写权限 | +| 测试(试管图标) | 在所选区域创建随机 `_svh-check-*` TXT,再按本次记录编号删除 | 验证解析读写权限,不申请证书、不消耗 ACME 签发次数;每条凭据有一分钟冷却 | +| 替换(铅笔图标) | 重新填写完整票据,读取并选择区域,覆盖原凭据配置 | 密钥轮换或连接配置变化;不回显旧密钥,保存后测试状态重置 | +| 删除(垃圾桶图标) | 删除 Sea vHost 保存的这条 API 凭据 | 不删除服务商账户、不主动删除已有证书;被托管解析引用时禁止删除,DNS-01 后续签发或续期可能因失去票据而失败 | + +凭据列表当前有“测试、替换、删除”三项图标。新增/替换表单中的“读取可管理域名、加密保存”是另一组操作,不能与列表图标混为一谈。 + +以彩虹 DNS 为例,数字 UID 和 API 密钥用于签名,登录用户名不能代替 UID。管理员保存 `ser888.cn` 的平台凭据,可供本系统默认主机域名的 DNS-01 使用;这不意味着客户自动获得整个 `ser888.cn` 的 DNS 管理权。 + +### 域名列表操作 + +| 当前操作 | 实际作用 | 保留或限制 | +| --- | --- | --- | +| 配置 | 保存解析指引、CNAME/CDN 目标及备案信息 | 配置保存本身不向服务商写解析 | +| 批准 / 拒绝 | 处理客户自定义域名绑定申请 | 批准后写入目标网站;不等同于服务商 DNS 记录已就绪 | +| 自动 CNAME | 为已批准的自定义域名创建指向网站默认域名的 CNAME | 使用该用户可管理对应区域的票据;当前不是任意记录创建功能 | +| 删除解析 / 删除托管解析 | 按系统记录的服务商记录编号删除本系统创建的 CNAME | 网站绑定、源文件和其他解析保留;不批量删除同名记录 | +| 解绑 | 移除自定义域名的网站绑定,并先处理本系统跟踪的托管 DNS 记录 | 网站文件、数据库及其他域名保留;默认分配域名不可单独解绑 | + +“自动 CNAME”与“删除解析”是同一条域名在未托管/已托管时的相反操作,不需要为了申请证书而反复执行。 + +当前默认主机域名通常依靠节点域名的泛解析提供访问;新增 API 凭据不会自动为全部已有主机创建独立解析。 + +### 网站证书操作 + +| 操作 | 实际作用 | 前置条件 | +| --- | --- | --- | +| HTTP-01 | 通过网站公开验证路径签发并安装证书 | 网站运行、域名解析正确、公网验证路径可访问;不依赖 DNS API 票据 | +| DNS 申请证书 | 临时创建 ACME TXT,完成 DNS-01 后清理挑战记录并安装证书 | 所有待签域名均有匹配且可写的 DNS 区域凭据;不依赖网站正在运行 | +| 安装证书 | 上传匹配的证书链和私钥,校验后安装 | 证书有效并覆盖网站域名;安装后切换手动模式 | +| 关闭 SSL | 关闭网站 HTTPS 及自动续签 | 不删除源文件、数据库或域名绑定 | + +常用顺序:录入票据 → 读取域名 → 保存 → 测试解析权限 → 在网站中选择 DNS-01。测试通过不等于证书已经签发。 + +## 管理员页面 + +| 页面 | 主要业务操作 | 业务边界 | +| --- | --- | --- | +| 总览 | 查看数量、主机状态、近期操作并跳转对应页面 | 汇总入口,不再开通用户 | +| 用户管理 | 创建/编辑/启停/删除用户、批量创建、进入用户视图 | 用户是管理身份,不是系统 Linux 用户;删除前先逐台处理所有主机归属 | +| 虚拟主机 | 开通、编辑、归属、套餐/到期、网络、启停、进入主机、回收 | 套餐与额度属于主机;回收是可恢复生命周期操作 | +| 批量任务 | 提交批次、查看逐条结果、下载 JSON、取消尚未执行的条目 | 提交成功不是每条业务均成功,需检查完成/失败/待核验结果 | +| 节点管理 | 新增配对、身份检查、启停、修改配置、核验不确定执行、删除空节点 | 主控主动连接被控;本机节点不能删除,不提供自动故障转移 | +| 环境配置 | 选择节点、查看组件、安装/更新版本、检查或恢复维护任务 | 改变节点可用环境;网站使用哪个版本另在网站管理选择 | +| 套餐管理 | 创建、复制、删除未使用套餐 | 已引用套餐不直接修改;主机换套餐在主机管理处理 | +| 域名管理 | 查看默认/自定义域名、审核、备案、解析指引、托管解析与解绑 | 网站域名绑定与 DNS 记录不是同一个对象 | +| DNS 管理 | 管理平台区域的 API 票据及读写测试 | 不授予客户平台 DNS 权限,不提供完整解析记录编辑器 | +| IP 地址池 | 按节点登记、筛选、启停或删除可删除地址 | 登记 IP 不等于运营商已分配或服务器已具备公网路由 | +| 到期与回收 | 查看宽限/回收状态并进入主机处理 | 到期停用、3 天宽限、回收后保留 7 天;备份自实际生成起保留 14 天 | +| 对接 API | 签发限定权限/有效期的管理密钥、查看任务/回调、吊销 | 面向财务站等外部管理系统;不是给客户的宝塔 API 密钥 | +| 系统设置 | 域名审核、备案要求、CDN 指引、生命周期、SMTP、SSO 和调度器 | 客户端业务开关与外部服务连接分别生效,配置成功不代表外部联调通过 | +| 操作日志 | 筛选、选择条数、分页、导出筛选结果 | 管理审计只读;管理员直接或代入行为留在管理审计中 | + +## 用户与独立主机页面 + +| 页面/入口 | 主要用途 | 权限或影响 | +| --- | --- | --- | +| 虚拟主机 | 查看主机详情、资源、网站和凭据,切换所管理主机 | 用户可查看自己名下主机;独立主机账号只有对应一台 | +| 网站管理 | 新增附加网站、部署检查/部署、运行版本、启停、证书、启动配置、设置与日志 | 同语言已装版本可切换;跨语言切换须管理员开启主机授权;主站不能作为附加网站删除 | +| 设置运行目录 | 更改主站在主机目录内的实际发布位置 | FTP 根目录与主机身份不随之移动;目录不能越界或与其他网站占用冲突 | +| 访问凭据 | 查看主机登录标识、FTP 与 MySQL 连接信息 | FTP/数据库密码可授权再次查看;主机登录密码只有哈希,不能查看原值 | +| 文件管理 | Web 上传、下载、编辑、移动、复制、ZIP 与回收站 | 默认单文件 20 MiB;回收站内容仍计入磁盘,清空才释放相应空间 | +| 域名 | 选择网站绑定自定义域名、查看审核及解析、解绑 | 默认域名随主机管理;解绑和停止网站不是删除网站程序 | +| 数据库 | 查看数据库、进入对应账号的 phpMyAdmin | 使用该主机 MySQL 身份,不提供数据库 root 权限 | +| FTP | 基本启停、查看连接信息、随机重置密码 | 控制文件传输,不是网站进程开关;连接地址使用主机域名 | +| 资源图表 | 查看 CPU、内存、进程、容量与流量历史 | 仅返回有权限的主机,不虚构未采集历史 | +| 用户计划任务 | 选择名下网站创建脚本或本站 URL 任务、执行一次、查看结果 | 独立主机账号不可用;实际执行由主控调度到对应主机身份 | +| DNS API | 管理用户自有域名的服务商票据 | 独立主机账号不可管理用户级票据 | +| 操作日志 | 查看对应用户/主机的普通业务操作 | 不显示管理员直接和代入操作,也不显示其他用户数据 | +| 账号安全 | 改密、MFA、SSO 绑定 | 主机账号不可绑定 SSO;密码关闭时禁止解绑;管理员代入期间禁止修改目标账号登录安全设置 | + +## 已发现的业务表达缺口 + +1. 凭据行只有图标,不利于区分测试、替换与删除。后续界面命名宜明确为“测试解析权限”“替换凭据”“删除凭据”,但本次整理没有修改或部署界面。 +2. “配置”保存解析指引,而“自动 CNAME”当前固定使用网站默认域名;不能描述成按钮会自动把所填 CDN/CNAME 指引目标同步到服务商。 +3. 当前“替换”表单同时允许修改服务商和区域,并非只换密钥。涉及已有托管记录时,需要另行明确迁移与记录归属规则,不能仅凭按钮名称认定已经完成 DNS 服务商迁移。 +4. DNS、域名绑定和 SSL 是三个业务对象;删除凭据、删除解析、解绑域名、关闭 SSL 应分别说明影响,不能统一称为“删除域名”。 + +更完整的日常步骤见 [操作说明](hosting-operations.md),已验证范围见 [项目状态整理](project-status-2026-10-29.md)。 diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..888efd1 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,147 @@ +# Debian + 宝塔部署 + +## 前置条件 + +- 当前验收范围为 Debian amd64、宝塔 Linux 面板 12.0.0、Nginx、MySQL 与 Pure-FTPd。所需语言版本可通过“环境配置”安装,不要求五类环境全部预装;MariaDB 不在当前实机验收范围。独立主控与被控的角色依赖见 [多被控安装说明](multi-node-installation.md)。 +- FTP 证书来源域名的证书放在宝塔标准目录 `/www/server/panel/vhost/cert/<证书来源域名>/fullchain.pem` 与 `privkey.pem`。证书来源可与控制台域名相同;客户端连接地址仍是各虚拟主机自己的默认域名,因此证书的 SAN 必须覆盖租户泛域名。两者存在且当前有效时,agent 会校验密钥匹配、有效期和来源域名覆盖,生成 Pure-FTPd PEM,在配置中固定 `CertFile`、切换到 `TLS 2` 并完整重启服务;两者均不存在时切到 `TLS 0` 并在凭据界面明确显示普通 FTP。证书只存在一半、密钥不匹配、错域名或过期时拒绝静默降级。宝塔 12.0.0 实机已完成 TLS 1.3、明文拒绝与证书链/主机名后置验证。 +- 构建机使用 `backend/go.mod` 指定的 Go 工具链(当前最低 1.27.3);前端构建及测试使用满足锁文件要求的 Node.js(22.12+ 的 22 分支、24 分支或 26+)。服务器运行预编译程序时不依赖这些构建工具;业务站点解释器另行安装。 +- `/www/wwwroot/seavHost/vHost` 必须是物理目录。磁盘限制采用目录扫描软配额,不要求 `prjquota` 或文件系统 quota;安装器会安装 Debian `acl`,并为每台主机创建密码锁定、`/usr/sbin/nologin` 的独立系统 UID/GID。 +- 一个解析到服务器的控制台域名,以及用于租户三级域名的 DNS 泛解析记录;本项目默认示例为 `host.ser888.cn` 与 `*.vhost.ser888.cn`。 +- 如需 DNS-01:管理员准备平台分配域名所在 DNS 区域的最小权限凭据;租户自行准备其自定义域名区域凭据。当前支持 Cloudflare、阿里云 DNS、腾讯云 DNSPod、西部数码和彩虹聚合 DNS。票据录入后先获取域名列表,再选择区域;西部数码单域名密钥可指定域名,彩虹使用数字 UID 而非登录账号。应限制为目标 DNS 区域的解析记录增删权限,不要使用主账号全局密钥。 + +## 安装 + +36 机器已安装并运行,实机测试直接使用控制台,见 [交付说明](handover-2026-10-30.md)。下方构建命令在源码包/开发工作区执行;预编译安装包无需构建,解压后从 `preflight.sh` 与 `install.sh` 开始。安装包不包含历史 QA、重置和清理脚本,完整开发工具在源码包中。 + +两个构建入口均按 `deploy/release-files.json` 收录文件,输出安装包、源码包、各自 SHA-256 和逐文件清单;已有构建产物可用 `node deploy/package-release.mjs` 重新打包,不重新编译程序。 + +```bash +./deploy/build.sh +sudo ./deploy/install.sh +``` + +在 Windows 构建机上可使用 `powershell -ExecutionPolicy Bypass -File .\deploy\build.ps1`,它会交叉编译 Linux/amd64 二进制、以 API 模式构建前端,并生成带 SHA-256 校验文件的 `build/sea-vhost-linux-amd64.tar.gz`。需要固定非 PATH 中的 Go 工具链时设置 `SEA_GO_BINARY` 为 `go.exe` 绝对路径;脚本按精确 Go 版本隔离构建缓存,并在打包前核对六个二进制的 build metadata,防止旧工具链缓存混入。上传并解压后,先运行只读检查: + +```bash +sudo bash ./deploy/preflight.sh +sudo bash ./deploy/install.sh +``` + +如需在安装前从构建机只读核对宝塔版本和语言环境,可通过环境变量运行 `node deploy/panel-preflight.mjs`。脚本只调用系统与语言版本接口,输出不会包含 API 密钥;自签名测试面板可显式设置 `SEA_PANEL_TLS_INSECURE=true`。 + +只有在管理员明确授权测试机写入后,才可运行 `node deploy/panel-stage.mjs build/sea-vhost-linux-amd64.tar.gz`。该工具会校验归档结构与 SHA-256,上传到 `/tmp`,创建并执行一个固定内容的一次性预检任务,然后删除任务和上传临时包;默认只保留通过预检的解压目录,不运行安装。明确需要安装文件层时追加 `--install`,脚本才会在预检通过后运行 `install.sh`;它仍不会启动服务或创建数据库。API 密钥必须通过进程环境传入,不能写入仓库、命令参数或部署归档。 + +仅在隔离的临时测试机上,可同时追加 `--activate-http-test=<主机名或IP>`。该选项会把 `SEA_COOKIE_SECURE` 临时设为 `false`、安装一个 80 端口的无 TLS 控制台配置并启动三个服务,便于端口转发环境验收。正式环境禁止使用该选项,必须按下文配置 HTTPS。 + +如上传中断,可追加 `--cleanup-only` 清理 `/tmp` 中与当前构建哈希完全匹配的 Sea vHost 上传;该操作不会删除暂存目录或其他文件。 + +安装脚本会安装缺失的 `acl` 包,生成一次性安装令牌与独立内部 RPC Token,并写入权限为 `0640` 的 `/etc/sea-vhost/sea-vhost.env`。令牌不会出现在宝塔计划任务日志中,需由 root 在服务器本地读取;脚本不会覆盖已有配置。脚本还会安装 `/www/server/panel/vhost/nginx/sea-vhost-security-global.conf`,立即执行 `nginx -t`,失败时恢复安装前文件并终止。 + +创建数据库和最小权限应用用户: + +```sql +CREATE DATABASE sea_vhost CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +CREATE USER 'sea_vhost'@'127.0.0.1' IDENTIFIED BY 'replace-with-a-long-random-password'; +GRANT ALL PRIVILEGES ON sea_vhost.* TO 'sea_vhost'@'127.0.0.1'; +FLUSH PRIVILEGES; +``` + +复制并修改 `deploy/nginx/sea-vhost.conf` 到宝塔 Nginx vhost 目录,替换控制台域名与证书路径。宝塔 API 的 IP 白名单必须只允许 `127.0.0.1`。然后启动服务: + +```bash +systemctl enable --now sea-vhost-agent sea-vhost-panel-broker sea-vhost-api +nginx -t && systemctl reload nginx +curl --fail https://host.ser888.cn/healthz +``` + +打开控制台域名后,系统在配置文件不存在时自动显示安装向导。依次填写: + +1. 安装脚本生成的 `SEA_SETUP_TOKEN`; +2. 本机 MySQL 的数据库名、专用用户名和密码,并完成连接测试; +3. 本机宝塔面板回环地址、API 密钥、租户三级域名根域、控制台域名、FTP 证书来源域名及自绑定审核策略;控制台域名必须独立于租户根域,FTP 证书来源可与控制台域名相同,但不得覆盖或占用租户主机命名空间。密钥由专用 panel broker 验证,Web API 不保存它,此步骤同时验证 root 隔离代理; +4. 首个管理员的名称、邮箱和不少于 12 位的密码。 + +安装完成后,平台管理员在“DNS 管理”的“平台根域 DNS API”区域配置系统分配域名的区域凭据;租户在侧栏“DNS API”配置自定义域名区域凭据。密钥只在新增或替换表单中输入,保存后不再显示。保存后应先点击试管按钮:系统创建一条 `_svh-check-*` 随机 TXT 并立即按记录 ID 删除,用于验证区域和增删权限,不会请求证书;每条凭据一分钟内只能测试一次。一个网站同时包含默认三级域名和自定义域名时,签发过程会分别选择平台与租户凭据;任一侧未配置时整张证书不会开始签发。HTTP-01 仍可独立使用,DNS-01 通过网站管理中的云图标触发。 + +数据库与宝塔地址只接受 `127.0.0.1`、`::1` 或 `localhost`。安装提交会再次验证数据库、宝塔 API 和 Unix Socket 隔离代理,执行数据库迁移、创建首个管理员,并将会话密钥自动生成后保存到 `/var/lib/sea-vhost/config.json`。该文件由 `sea-vhost` 用户持有且权限为 `0600`,不含宝塔密钥。宝塔凭据由 `sea-vhost-panel` 独占保存到 `/var/lib/sea-vhost-panel/credentials.json`,权限为 `0600`;配置完成后 Web 安装接口不能更换它。落盘成功后安装写接口立即下线,API 进程原地切换到正常模式。 + +如终端令牌遗失,root 可执行 `grep '^SEA_SETUP_TOKEN=' /etc/sea-vhost/sea-vhost.env` 查看。系统安装完成后可以删除该环境变量并重启服务;正式配置不依赖它。 + +## 部署诊断 + +环境启动后运行只读诊断,不会显示数据库密码、安装令牌或宝塔 API 密钥: + +```bash +sudo ./deploy/diagnose.sh +``` + +脚本会检查三个服务状态、控制组隔离、敏感文件权限、Nginx 安全基线的属主与权限、两个 Unix Socket、Web API 配置中是否残留宝塔密钥、API 安装/运行状态和 Nginx 配置。退出码非零表示至少存在一个必须处理的问题;完整输出可直接用于实机联调。 + +正式上线验收必须启用严格模式。测试模式中的不安全 Cookie、自签面板证书和面板通配地址监听在默认诊断中只告警,严格模式会将其提升为失败;通配监听检查不能识别云安全组或 NAT,因此仍须从外部网络复核端口: + +```bash +sudo SEA_DIAGNOSE_PRODUCTION=true ./deploy/diagnose.sh +``` + +只有 aaPanel API 可达而没有 SSH 时,可用经过归档哈希校验的一次性面板任务执行相同检查;任务结束后会删除计划任务和 `/tmp` 上传包,保留校验后的 staging 目录用于追溯: + +```bash +SEA_PANEL_URL='https://host.ser888.cn:7812/' \ +SEA_PANEL_API_KEY='replace-me' \ +node deploy/panel-stage.mjs --diagnose build/sea-vhost-linux-amd64.tar.gz + +# 正式上线门禁 +SEA_PANEL_URL='https://host.ser888.cn:7812/' \ +SEA_PANEL_API_KEY='replace-me' \ +node deploy/panel-stage.mjs --production-diagnose build/sea-vhost-linux-amd64.tar.gz +``` + +控制台启动后,可从可信运维机运行低风险安全冒烟检查。凭据只通过进程环境传入,脚本不会输出密码或会话值;检查只创建并注销一个会话,不会修改虚拟主机、网站或文件: + +```bash +SEA_CONSOLE_URL='https://host.example' \ +SEA_TENANT_LOGIN='tenant@example.test' \ +SEA_TENANT_PASSWORD='replace-me' \ +node deploy/security-smoke.mjs +``` + +该脚本检查未登录访问、Origin/CSRF、会话 Cookie、租户越权、项目 IDOR、文件路径遍历、内部回收站、严格 JSON 解析、安装/注册接口关闭及浏览器安全响应头。登录爆破限制通过 Go 单元测试验证,避免在实机冒烟时主动锁定运维来源 IP。 + +在隔离测试服务器上,还可运行持久化安全金丝雀检查。脚本通过宝塔 API 建立一次性任务,在控制面、panel broker、root agent、主机运行私有目录和站点目录写入各不相同的随机合成标记;随后以 `www`、`nobody`、主机身份、控制面身份、HTTP、未登录 API、跨源 API和无令牌 Unix Socket 分别尝试读取。它不会使用真实密码或密钥,也不会在输出中显示标记正文: + +```bash +SEA_PANEL_URL='https://127.0.0.1:7800/' \ +SEA_PANEL_API_KEY='replace-with-test-panel-key' \ +SEA_CONSOLE_URL='https://host.example' \ +node deploy/panel-canary-verify.mjs +``` + +仅当测试面板使用临时自签证书时才增加 `SEA_PANEL_TLS_INSECURE=true`,正式环境不得使用。检查会保留金丝雀文件,以便后续人工或监控复测;root-only 清单位于 `/var/lib/sea-vhost/security-canaries/registry-<随机ID>.tsv`,权限为 `0600`。站点内另有一个明确允许公开读取的基准文件,用于证明拒绝结果来自 Nginx 规则而非站点整体不可达;其内容同样只是随机测试标记。需要清理时应由 root 按该清单逐项核对后删除,不得用通配符递归删除受管目录。 + +公开入口还应运行不带登录凭据的常见漏洞探针。它检查危险方法、敏感/备份/调试路径、路径穿越及双重编码、Host/CORS/开放跳转/XSS 反射、源码映射、aaPanel 未鉴权基础接口和跨源 WebSocket 握手;不会上传文件、发送 WebSocket 消息、爆破密码或制造并发压力: + +```bash +SEA_PUBLIC_TARGET_URL='https://host.example' \ +SEA_PANEL_URL='https://127.0.0.1:7800/' \ +node deploy/public-vulnerability-smoke.mjs +``` + +正式服务器的 aaPanel 地址只允许 Sea vHost 通过回环访问,面板端口不得直接暴露到公网;远程管理应使用 VPN、SSH 隧道或源 IP 白名单。若必须通过自有 Nginx 反代面板且不使用 Web 终端,可在对应 `server` 中包含 `deploy/nginx/aa-panel-websocket-deny.conf.example`,同时从防火墙阻断对面板后端端口的绕过访问。该片段会禁用面板终端等 WebSocket 功能,不应不经评估直接加入仍需这些功能的服务器。 + +安装器不修改 `/etc/fstab`、不自动开启宝塔 API,也不代建 MySQL 数据库。交互向导可生成管理站点配置并启动对应角色的服务;首次 Web 安装仍需填写数据库连接和管理员信息。已有业务配置不被静默覆盖。升级时若旧 `/var/lib/sea-vhost/config.json` 仍含 `panel_api_key`,安装器会拒绝继续,避免在非 root 进程间自动搬运 root 等价密钥;必须先走 root 控制的离线迁移。 + +Docker 运行时已经从数据模型和 API 中移除。若测试数据库曾写入 Docker 项目,`002_remove_docker_runtime.sql` 会拒绝带遗留值的结构收窄;请先备份并人工清理这些测试记录,系统不会把它们静默转换成其他运行时。 + +## 运行环境维护 + +管理员在“环境配置”安装可用版本、更新 PHP 同分支补丁及查看任务;站点版本切换在主机“网站管理”的“运行环境”中处理。不同任务可排队,同节点串行执行,重复任务拒绝;跨语言切换需要管理员对主机单独授权。系统每六小时检查可用更新并去重通知管理员,但不会自动升级网站。任务保存在 MySQL;API 重启后未完成任务变为“待核验”,需通过“恢复核验”继续,不能把提交成功当作已生效。 + +- PHP 分支补丁调用面板免费软件更新能力,影响服务器上该分支的全部网站,包括 Sea vHost 外的网站。确认后先备份 `/www/server/php/<分支>` 至 root-only 的 `/www/backup/sea-vhost/runtime/php/<分支>/<任务ID>`,再等待面板执行队列结束、检查版本和原有扩展、重启本系统运行中的独立 FPM 并核验可执行文件与 UID。失败时恢复旧环境;不能确定面板任务是否结束时暂停核验,避免并发回滚。完成/回退后的备份保留十四天,未核验完成的备份不自动清理。 +- Node.js、Java 在并行安装新版后逐站点切换;Python 创建独立新虚拟环境,以租户 UID 导出、安装依赖,旧环境保留,不覆盖旧环境。依赖重装可能因原依赖源不可用而失败,此时保留或恢复旧项目。 +- Go 的 SDK 更新不会改变现有二进制。迁移时必须上传不同文件名的新程序,系统校验其 Go 构建版本,保留旧入口用于失败回退;不提供任意 root 编译命令。 +- 默认只列出同分支目标;跨 Node/Java 主版本、Python/PHP 次版本或 Go 次版本必须显式允许。切换前已停止的网站继续保持停止,标记“待启动验证”;启动后再核验实际进程。 +- 补丁更新或站点迁移期间,租户侧项目写操作暂时返回 `423`,防止与维护冲突;只读访问与独立网站服务不因此整体停止。维护接口仅管理员可用,内部代理仍使用固定操作、鉴权、受管身份与路径校验,不增加 `CAP_SYS_PTRACE`。 + +对应管理 API 为 `/api/v1/admin/runtime-maintenance` 下的 `check`、`php`、`sites/{siteID}` 和 `jobs/{jobID}/resume`。返回结果不包含内部回退配置、服务器私有路径或凭据。 + +后台维护失败、回退或待核验都会写入管理员通知队列,不依赖浏览器保持打开。运行时切换前须确认旧监听已释放;面板只删除启动器而留下子进程时,代理仅按该主机 UID 与站点运行目录终止残留进程,不影响同主机其他运行目录。回退配置后仍需核验真实进程,不能单凭登记表中的旧版本把任务标记为已恢复。 diff --git a/docs/design-system.md b/docs/design-system.md new file mode 100644 index 0000000..28d47be --- /dev/null +++ b/docs/design-system.md @@ -0,0 +1,44 @@ +# Sea vHost 统一设计系统 + +本轮统一规范以 `design/console-unified-concept.png` 为视觉参考,覆盖管理员、用户、独立主机账号、登录、安装向导及全部业务弹窗。原有功能入口保留,通知占位控件与旧模块占位页移除。 + +## 视觉与版式 + +- 海洋蓝 `#0878f9`、深色文字 `#0b1736`、次文字 `#657493`、冷灰背景 `#f6f8fc`、白色面板、边框 `#dce5f0`。 +- 导航宽 224px,页眉高 64px;内容边距桌面 28px、手机 16px。管理员与用户端共用品牌、字体、焦点和控件规范。 +- 页面标题 26px,正文 13–14px,辅助文字 12px。采用系统中文无衬线字体,不依赖外部字体服务。 +- 输入与按钮默认高 38px,控件圆角 8px、面板圆角 10px、弹窗圆角 12px。仅登录和弹窗使用克制的阴影。 +- 主操作蓝色填充,次操作白底描边,表格行内操作为蓝色文本;禁用、焦点、危险、加载与空状态统一呈现。 +- Lucide 线性图标;三道海浪品牌为代码原生 SVG,不使用位图替代文字或交互。 + +## 样式架构 + +入口 `frontend/src/styles.css` 依次组织以下文件: + +1. `styles/tokens.css`:品牌、语义色、字体、尺寸与阴影令牌。 +2. `styles/primitives.css`:原生控件、排版、主次按钮、表单、键盘焦点与减弱动画。 +3. `styles/components.css`:各业务组件布局;清除旧后台和无引用组件规则。 +4. `styles/console.css`:所有界面的共同结构、响应式与业务表面规范。 + +新增页面优先使用 `PageHeader`、`Pagination`、`RuntimeMark` 和 `ModalBackdrop`。避免复制自定义颜色及原生默认按钮样式。 + +## 页面与表格 + +管理员主机列表提供真实的状态、节点、语言、套餐与关键词筛选,并在前端分页。跨页选择保留,批量任务携带对应主机的归属版本,提交前仍需验证预览。 + +资源图表提供统一标题、图标、数值、单位、网格与时间范围;读数随真实数据变化,没有数据时展示等待采样,不用虚构历史值填充。 + +普通业务表格与文件列表允许容器内部横向滚动,不挤压或撑开整页。手机导航采用抽屉,完整保留管理员入口。 + +## 弹窗与交互 + +`ModalBackdrop` 为现有表单保留统一语义和布局:打开时锁定背景滚动、焦点进入弹窗、Tab 限定在顶部弹窗、Escape 使用现有关闭/取消操作,关闭后恢复触发控件焦点和滚动状态。没有额外确认和权限绕过。 + +同一页面的编辑、计划任务、文件、DNS、证书、启动配置、安全设置及批量弹窗使用相同的边距、标题、控件和操作区规范。 + +## 响应式与验证 + +- 低于 980px,侧栏切换为可实际操作的抽屉,遮罩位于导航下层。 +- 低于 700px,表单、筛选及资源图表按可用宽度折行/单列;长弹窗可独立滚动。 +- 交互必须同时验证内容、真实控件状态、脚本错误和整页横向溢出;桌面与手机均截图核对。 +- 开发预览可使用固定演示数据;上线版本使用实际鉴权和业务 API,不显示演示或待开发占位内容。 diff --git a/docs/design/console-unified-concept.png b/docs/design/console-unified-concept.png new file mode 100644 index 0000000..bf5fccc Binary files /dev/null and b/docs/design/console-unified-concept.png differ diff --git a/docs/design/create-project-concept.png b/docs/design/create-project-concept.png new file mode 100644 index 0000000..098146e Binary files /dev/null and b/docs/design/create-project-concept.png differ diff --git a/docs/design/dashboard-concept.png b/docs/design/dashboard-concept.png new file mode 100644 index 0000000..3c56ee8 Binary files /dev/null and b/docs/design/dashboard-concept.png differ diff --git a/docs/dns-acceptance-2026-10-29.md b/docs/dns-acceptance-2026-10-29.md new file mode 100644 index 0000000..48c220d --- /dev/null +++ b/docs/dns-acceptance-2026-10-29.md @@ -0,0 +1,43 @@ +# 彩虹 DNS 真实账户联调(2026-10-29) + +当前结论:彩虹 DNS 真实账户的域名枚举、TXT 创建/清理、DNS-01 签发及源站证书验证已通过。 + +测试站点:`https://dns.sea-studio.top`。使用用户提供的测试账户,数字 UID 为 1002。本文及测试截图不记录 API 密钥。 + +## 已通过 + +1. 本机与 36 服务器均可通过正常 TLS 校验连接该站点。 +2. Sea vHost 管理员在 DNS 管理中填写彩虹 DNS 站点、UID、密钥,点击“读取可管理域名”,实际返回 `ser888.cn`;服务商域名编号为 12。 +3. 在网页选择域名并加密保存成功,列表显示测试凭据;随后点击真实 TXT 权限测试。 +4. 独立诊断使用相同 UID、时间戳及签名,`POST /api/domain` 返回 HTTP 200,确认认证和域名枚举正常。 + +## 首次联调阻塞(后续已修复) + +首次联调时,以下两个经正确认证的只读接口均返回 HTTP 500: + +- `POST /api/domain/12` +- `POST /api/record/data/12` + +响应中的具体错误相同:`Undefined array key "AccessKeyId"`。移除记录过滤条件、使用最小分页参数复查,错误仍然存在。 + +当时需在彩虹 DNS 后台检查 `ser888.cn` 绑定的上游 DNS 账户配置及其模块兼容性;这里的 `AccessKeyId` 属于彩虹侧处理上游 DNS 的配置,与 Sea vHost 调用彩虹 API 使用的 UID/签名密钥不同。 + +首次测试在读取原有记录阶段即中止,未发出创建 TXT 请求,也未启动 ACME 签发;该次失败不计作通过。修复后的结果见下节。 + +测试凭据保留在 Sea vHost 的加密存储中;后续复测状态已变为通过。 + +## 后续复测结果 + +1. 彩虹侧修复后,域名详情与记录列表恢复 HTTP 200,认证和域名枚举仍正常。 +2. 实测发现 `minTTL` 返回为 JSON 字符串,原适配仅接受数字,导致写入前拒绝。现兼容数字与字符串,验证整数范围后才允许创建记录;新增回归覆盖字符串、数字、最低取值、非整数、负数、溢出及非法类型。 +3. 修复已部署 36。Sea vHost 实际凭据测试创建随机 TXT,并按新增记录编号删除,持久化状态为 `passed`。 +4. 专用验收主机 #15 / 网站 #36 完成真实 DNS-01 申请及安装,模式为 `dns-01`,到期时间为 2027-01-27;系统写入到期前 30 天的下次续期时间。此项验证了计划写入,不代表已经经历实际续期周期。 +5. 源站 TLS 握手启用系统证书链和域名校验,确认实际服务证书与本次签发文件完全一致,且不同于原证书。新证书 SHA-256 指纹:`a7a4487e1f32583e764defcfc54daf8a97d48997c4e92aa4aaacccbf82c3c770`。 +6. TXT 权限测试后与 DNS-01 完成后均重读全部解析,以记录编号、名称、类型、内容、线路、TTL 和 MX 的规范化摘要比较;原有 6 条解析完全一致,测试 TXT 和 ACME 挑战记录无残留。 +7. 验收主机恢复原证书、手动模式和回收状态,保持 PHP 8.4 停止、FTP 禁用;原体验主机 #7 保持运行,服务与 Nginx 检查正常。 + +本次内置浏览器连续连接超时;恢复后的写入、签发和清理通过 Sea vHost 自身业务 API 完成,不计为新增网页操作通过。先前的域名枚举与加密保存已有实际网页操作证据。 + +Go 全套测试及生产构建通过,前端代码未修改。修复发布包 SHA-256:`7d975795a6e74d0f9d915ab3c6bb212f32af3d17a308e3d9e86c0e3c1edb9e21`。 + +首次联调的历史界面截图:验收产物目录中的 `ui19-20261029/dnsmgr-domain-discovery.png` 与 `ui19-20261029/dnsmgr-live-test-blocked.png`。 diff --git a/docs/feature-test-report-2026-10-20.md b/docs/feature-test-report-2026-10-20.md new file mode 100644 index 0000000..8e3ad4d --- /dev/null +++ b/docs/feature-test-report-2026-10-20.md @@ -0,0 +1,102 @@ +# Sea vHost 功能与实机测试报告(更新至 2026-10-21) + +> 历史验收记录:环境、版本、数量及结论仅适用于文中所列日期,不代表当前服务重新实测。当前状态见 [项目状态整理](project-status-2026-10-29.md)。 + +## 1. 结论 + +本轮在 Debian + 宝塔 Linux 12.0.0 测试机上完成了全新重装、Web 安装向导、账号、文件、域名、PHP/Node.js/Python/Go/Java、FTP/FTPS、MySQL、软配额、运行目录、Nginx 回滚、broker 边界、升级、备份恢复和安全金丝雀的顺序实测。核心虚拟主机、五类运行时、文件与数据服务、资源限制、多 Linux 身份隔离、全新安装、原地升级和影子恢复均可工作。 + +前次报告中的 Node.js PID 目录、Python 独立用户兼容、Python 停止后重拉起、FTP 证书域名校验、Pure-FTPd 强制 TLS 以及 HTTP-01 失败详情持久化问题均已修复并复测。当前没有已知的发布阻断项;仍未执行的项目均依赖正式公网证书或真实 DNS 凭据,见第 5 节。 + +最终部署归档 SHA-256:`32969ac778fb53e1fd607f0932ff49767161a65dcf2877649a8c6c775add50a2`。 + +## 2. 实机结果矩阵 + +| 范围 | 结果 | 关键证据 | +| --- | --- | --- | +| 全新安装 | 通过(连续两轮) | 每轮执行前创建并校验控制库、状态、Nginx 配置和主机目录备份;清空 Sea vHost 专属状态、独立身份和受管资源后重新安装。两轮均预检 0 失败,首次启动返回 `setup_required`,Web 向导成功创建控制库和首个管理员;第二轮再次通过 PHP/FTP/MySQL、软配额、主机边界与安全验收。 | +| 安装后状态 | 通过 | `/api/v1/setup/status` 返回 `required:false`;三个 systemd 服务 active;Nginx 配置有效;API 健康检查通过。 | +| 就地升级 | 通过 | 预检查、覆盖安装、服务重启、测试入口激活和诊断全部通过;环境、应用配置、面板凭据与 broker 资源登记表哈希不变;数据库对象计数不变。 | +| 管理员/租户/主机登录 | 通过 | 登录限频与 `Retry-After`、并发会话、改密注销其他会话、主机密码重置、旧密码失效均通过。 | +| MFA | 通过 | TOTP 登录、一次性恢复码、恢复码不可复用、禁用 MFA 后注销旧会话均通过。 | +| 权限与 IDOR | 通过 | 主机账号只看到绑定主机,管理员 API 与其他项目编号访问被拒绝。 | +| Web 文件管理 | 通过 | 文本创建/冲突/覆盖/下载、多段上传、列表、回收站、清空回收站通过;20 MiB 接受,超过 20 MiB 拒绝。 | +| 路径安全 | 通过 | `../`、反斜杠、双斜杠和符号链接运行目录均在调用宝塔前拒绝;文件接口与金丝雀测试未发生越界。 | +| 域名 | 通过 | 保留区域拒绝、审核批准/拒绝、关闭审核后直接绑定、并发重复绑定及每站 100 条上限通过。 | +| 多网站与运行目录 | 通过 | `/`、既有 `/public`、临时 `/dist-*` 和 `/apps-*/web/public` 均真实生效;FTP 根保持主机根目录;删站保留源码,租户可再清理。 | +| PHP | 通过 | 全新安装首次创建发现并修复 `php-fpm -t` 以 root 创建日志的问题;配置校验现先降权到主机 UID/GID。修复后独立 PHP-FPM master/worker 使用主机 UID/GID,能力集为零,`open_basedir`/私有临时目录和真实 HTTP 请求通过。 | +| Go | 通过 | 宝塔目录版本 `go1.27.1`;创建、上传、预检、部署、回环反代、停启、删除和清理通过;进程为主机 UID 且能力集为零。 | +| Java | 通过 | 宝塔目录版本 `jdk-20.0.2`;完整生命周期、反代、身份和能力检查通过。 | +| Node.js | 通过 | 宝塔目录版本 `v24.21.0`;仅向宝塔 Node PID 目录授予当前主机命名 ACL,不改变共享属主;创建、上传、预检、部署、反代、独立 UID、零能力集、停启、删除和清理通过。部分创建失败会按项目名、受管路径和端口做受限反查清理。 | +| Python | 通过 | 宝塔目录版本 `3.12.3`;使用普通 UID 范围内、无 home、禁止登录的独立身份兼容宝塔校验;完整生命周期与隔离检查通过。停止判定要求后端端口连续稳定关闭,能识别宝塔守护进程的短暂关闭后重拉起,并按主机 UID 与精确运行目录终止残留。 | +| FTP 数据面 | 通过(外网受限) | 回环 FTP 登录、上传、下载、重命名、删除通过;chroot、父目录与符号链接逃逸被拒绝;外部被动数据连接受当前端口转发限制。 | +| MySQL 数据面 | 通过 | 默认同名库/用户可读写,跨库拒绝,数据库仅本机连接路径通过。 | +| 磁盘软配额 | 通过 | root agent 可统计 `000` 私有目录内 2 MiB 文件且不跟随符号链接;超额冻结主机写入,Web 清理仍可用,恢复后保持 stopped。 | +| 数据库配额 | 通过 | 实际写入约 12 MiB 后被计量并暂停项目/FTP/控制写;清理后恢复到 stopped,可手动启动。 | +| 流量配额 | 通过 | 实际请求进入站点并产生计量;低限额触发暂停,放宽后恢复到 stopped。 | +| 进程配额 | 通过 | 独立 UID 的实际进程数被计量;超额进程终止,项目暂停并可恢复。 | +| 多主机隔离 | 通过 | 两个一次性主机 UID 双向读取对方文件均失败;`www` 只读站点且不能读 `.sea-runtime`;主机进程不能读控制配置或连接控制 Socket。 | +| broker 边界 | 通过 | 无令牌返回 401;删除未登记站点返回 403;资源登记表哈希不变。 | +| Nginx 防护与回滚 | 通过 | 故意写入未 reload 的非法指令后,agent 返回 412 并恢复站点安全文件;清除故障后 `nginx -t` 与 reload 通过。 | +| 手动 SSL | 通过 | 畸形、错域名、CA 证书、不匹配密钥和不完整证书对被拒绝;有效证书可安装并关闭。 | +| DNS 凭据 | 通过(未做真实签发) | AES-GCM 密文落盘,API 不返回密钥,失败信息不泄密,一分钟冷却、更新和删除通过。 | +| HTTP-01 | 环境受限,失败状态通过 | 当前公网 80 映射拓扑不满足真实签发;失败状态、错误详情和后续调度信息均写入站点与自动化记录。 | +| FTP TLS | 通过 | 有效且匹配 FTP 证书来源域名、同时覆盖客户端项目主机名的证书启用 `TLS 2`,显式 FTPS 上传、下载和删除通过;明文 `USER/PASS` 均返回 421;错域名、密钥不匹配和不完整证书对被拒绝;测试后配置与服务自动还原。 | +| 安全金丝雀 | 通过 | 最新检查 ID `ed8ebd63dcd9`:正常文件 200;隐藏、敏感扩展、依赖清单、运行私有目录和跨属主符号链接均拒绝;OS 边界拒绝;内部 Socket 为 401。 | +| 备份/恢复演练 | 通过 | 控制库导入隔离临时库后 7 类对象计数一致;主机 tar 保留 UID/GID、ACL、xattr 后比较一致;4 个关键状态文件哈希和敏感权限一致;未覆盖在线数据。 | + +## 3. 本地回归 + +| 检查 | 结果 | +| --- | --- | +| Go 1.27.2 `go test ./...` | 通过 | +| Linux/amd64 `go vet ./...` | 通过 | +| 前端 Vitest | 1 个文件、20 个测试通过 | +| 前端生产构建 | 通过 | +| npm 生产依赖审计 | 0 个已知漏洞 | +| npm 全依赖审计 | 0 个已知漏洞 | +| 部署脚本语法 | 28 个 `.mjs` 全部通过 `node --check` | + +首次把 Vitest 与两个 Go 编译任务、Vite 构建同时执行时,Vitest worker 启动超时且没有运行任何测试;单独重跑后 20/20 通过,因此记录为调度资源争用,不作为产品测试失败。 + +## 4. 已修复问题 + +- R-01 Node.js PID 目录与部分创建失败清理:已使用当前主机命名 ACL,并加入受管资源严格匹配后的清理;实机完整生命周期通过。 +- R-02 Python 独立运行用户兼容:已改为普通 UID 范围、无 home、锁定密码和 `nologin`;实机完整生命周期通过。 +- R-03 FTP 证书域名校验:已在写入 PEM 前执行证书主机名验证,错域名实测返回 500。 +- R-04 Pure-FTPd 强制 TLS:已兼容 CRLF 与重复 `TLS` 指令,完整停止旧 daemon 后启动;明文认证实测返回 421。 +- R-05 HTTP-01 失败详情:已把错误写入站点和 `certificate_automations.last_error`,并保留退避调度语义。 +- R-06 Python 停止竞态:端口必须连续四次关闭才视为停止;短暂关闭后重拉起会触发精确运行目录终止并再次验证。 + +## 5. 环境受限或本轮未执行 + +- HTTP-01 的真实签发:测试机公网 80 映射到 10094,拓扑不适合完成 ACME 回调;已验证失败信息持久化,正式环境仍需用真实域名做签发验收。 +- DNS-01 的真实 TXT 创建、传播、签发和续期:没有使用真实 Cloudflare/阿里云/DNSPod 凭据;只验证了凭据安全、失败、冷却和生命周期。 +- 外部 FTP 被动数据通道:当前 NAT 未转发被动端口范围;回环完整数据面已通过。 +- 真实断电、整盘写满和不受控进程炸弹:没有执行;使用服务重启、影子恢复、受控 12 MiB 数据库增长、低阈值流量和 3 个额外进程替代。 +- 本轮没有重新进行高强度公开漏洞扫描;2026-10-19 的有限公开探针记录仍保留,用户已要求后续另行处理更深入测试。 + +## 6. 清理状态 + +- 当前重装前备份保留在测试服务器 `/var/backups/sea-vhost/reinstall-20261021061115-c57dd0`,备份树 SHA-256 为 `d114ebeacf3188173b96267640330aacbc21722c951ed7ec93549341c530830a`;历史备份未由本轮删除。 +- 当前保留全新重装验收数据:管理员、租户、套餐、1 台 PHP 7.2 主机、1 个 FTP、1 个同名项目数据库和 `/public` 站点;项目主机名为 `sv5656b1567e`,独立 UID 1003、GID 988,状态 running。 +- Node.js、Python、Go、Java 的一次性测试站点、运行进程、目录和测试账号均已清理;没有遗留运行时监听或未登记项目。 +- Nginx 配置有效,三个 Sea vHost 服务 active,安装接口关闭,健康检查通过。 +- 测试管理入口使用端口转发 IP 与 HTTP 10094;面板证书验证在测试脚本中显式放宽。安装包本身不固化这些地址或放宽项,正式部署由安装页填写域名、数据库和面板连接参数。 + +## 7. 本轮新增的可复测脚本 + +- `deploy/panel-failure-rollback-verify.mjs` +- `deploy/panel-run-paths-verify.mjs` +- `deploy/panel-primary-run-path-verify.mjs` +- `deploy/panel-upgrade-verify.mjs` +- `deploy/panel-backup-restore-verify.mjs` +- `deploy/panel-reinstall-backup.mjs` +- `deploy/panel-ftp-tls-verify.mjs` +- `deploy/panel-certificate-dns-verify.mjs` +- `deploy/panel-resource-quotas-verify.mjs` +- `deploy/panel-runtime-suite-verify.mjs` +- `deploy/panel-runtime-inventory.mjs` +- `deploy/panel-runtime-test-cleanup.mjs` + +测试脚本只把随机临时资源放入固定 Sea vHost 受管范围,并在 `finally` 或远端 trap 中清理。报告不记录 API 密钥、密码、数据库 DSN、会话或证书私钥。 diff --git a/docs/handover-2026-10-30.md b/docs/handover-2026-10-30.md new file mode 100644 index 0000000..27111c6 --- /dev/null +++ b/docs/handover-2026-10-30.md @@ -0,0 +1,59 @@ +# 36 单机实机测试交付 + +交付日期:2026-10-30。当前目标为 36 机器上的单机生产测试环境,不使用早期 202 机器的端口映射或临时域名。本次整理不重装、不清空业务数据库、不修改现有账号密码。 + +## 直接开始使用 + +- 控制台:。 +- 默认主机根域:`vhost.ser888.cn`;正常访问使用随机主机子域名,FTP 地址复用主机名。 +- 已有体验主机:`sv8a500e52e9`,PHP 8.4,网站 ;绑定“单机体验用户”。 +- 管理员、单机体验用户、体验主机账号保持可用。使用此前交付的密码登录;本交付包不保存真实密码。管理员初始凭据文件在服务器 `/etc/sea-vhost/admin-credentials`,仅 root 可读,密码后续改动以系统实际记录为准。 +- FTP / 数据库凭据从对应主机的凭据弹窗查看,主机登录密码独立。管理员可用临时代入进入用户或主机视图,退出后返回管理视图。 + +36 已安装并启动,无需运行安装器。安装包用于归档、后续新部署或按文档执行更新;不要在开展业务测试前运行旧的重装、清库、测试激活或密码重置脚本。 + +## 交付文件 + +| 文件 | 用途 | +| --- | --- | +| `sea-vhost-linux-amd64.tar.gz` | Debian amd64 预编译安装包,包含六个程序、API 模式前端、安装脚本、配置模板及文档 | +| `sea-vhost-source.tar.gz` | 干净源码及锁文件,保留测试和开发工具,不包含依赖缓存或真实服务器配置 | +| `*.sha256` / `SHA256SUMS` | 检查交付文件是否完整 | +| `runtime-manifest.json` / `source-manifest.json` | 包内逐文件路径、大小和 SHA-256;每个压缩包内部也有 `RELEASE-MANIFEST.json` | +| `release-verification.json` | 打包结构及有限敏感信息扫描结果 | +| `environment-check.json` | 本次 36 交付核对结果,只含脱敏状态与程序摘要 | + +目录结构仍为 `backend/`、`frontend/`、`deploy/`、`docs/`。安装包只按明确清单收录运维必需脚本,测试、重置和清理工具只在源码包中保留并分类说明。`.cache/`、`build/smoke/`、编译/依赖缓存、旧包与本地日志不参与交付。 + +## 核对状态 + +本轮读取到 API、隔离代理及面板代理均运行,Nginx 配置有效,体验站 HTTPS 返回 200;数据库迁移为 001–028,未发现排队、运行中或中断待核验的环境任务。五个单机已安装程序的摘要与本地交付构建一致;独立被控程序作为安装包内容保留,不作为本机正在运行的服务。 + +当前只有管理员、单机体验用户和体验主机三个账号处于启用状态,其他历史测试账号已停用或软删除,审计记录保留。另一台 QA 主机 `sve78e64b509` 仍在回收期且已停用、无用户绑定,不恢复或交给客户使用;到期处理仍由原生命周期规则执行。界面“用户”统计与数据库全部历史账号行数不是同一个口径。 + +自定义域名审核和备案引导开启;宽限期 3 天、回收保留 7 天、备份保留 14 天。新增自定义域名前需按开启的审核规则操作,系统默认分配域名不走该审核。SSO 与 SMTP 关闭,管理员和普通用户密码登录开启,主机账号不支持 SSO。彩虹 DNS 真实 TXT / DNS-01 已有通过记录,是否继续使用现有测试凭据由管理员在 DNS 管理页决定。 + +组件安装及 PHP 更新交由宝塔执行,不再锁定整个节点的主机操作;单站环境切换只保护对应主机,PHP 独立 FPM 刷新仅短暂保护对应主机。PHP 7.4 的实际版本已核对为 7.4.34。 + +## 建议的业务实测顺序 + +1. 管理员创建一个新普通用户,检查编辑、启停及删除边界;不要删除已有体验账号。 +2. 准备套餐并创建主机,检查随机凭据、默认域名、用户绑定、管理员代入和主机账号登录。 +3. 上传首页或项目,检查运行目录、语言版本、启动设置、环境变量、启停及实际域名访问。 +4. 检查 Web 文件编辑与回收恢复、FTP 上传下载互通、数据库及 phpMyAdmin;FTP 使用主机域名。 +5. 绑定自定义域名并按需审核,检查 HTTP-01、自上传证书;有 DNS API 票据时再测试 DNS-01。 +6. 普通用户检查多主机切换、用户级计划任务与日志;主机账号不应出现用户计划任务。客户日志不可看到管理员或管理员代入操作。 +7. 用 JSON 完成小批量用户/主机创建、绑定/转移、套餐与到期管理;先预览再提交,检查逐项结果。 +8. 使用专用测试主机验证停用、限额和回收恢复。用户删除前,名下所有正常及回收主机都须手动解绑或转移。 + +发现问题时记录账号角色、主机名、页面、操作步骤、出现时间和报错;日志或截图先去除密码、API 票据及会话。完整按钮用途见 [业务说明](business-actions.md),操作细节见 [日常操作](hosting-operations.md)。 + +## 验证覆盖与保留材料 + +已有 Go 全包、88 项前端测试,以及真实 MySQL 的 SSO、权限和维护范围回归测试。最近维护回归还覆盖实际后台工作线程停留在模拟宝塔忙碌接口时,主机仍可通过 API 保存文件。真实 Web 主流程、五类语言、HTTP-01、DNS-01 与隔离测试的覆盖以各日期验收记录为准;本次打包不等同于重新跑完所有历史测试。 + +真实外部 SSO、SMTP、财务站、两台独立宝塔服务器间联合部署尚未完成,本轮单机基本实测不依赖它们。配额仍为巡检软配额,HTTP 按连接限速、FTP 按账号限速,没有改成内核硬配额或主机全部连接共享带宽。 + +服务器真实配置保留在 `/etc/sea-vhost/`、`/var/lib/sea-vhost/`、`/var/lib/sea-vhost-panel/` 等原位。历史恢复备份及私有联调台账保留在 root 专用目录,未放入站点或交付压缩包;历史解压工作目录的归档记录见服务器 root 交付索引。恢复会改写数据,应先阅读对应版本及备份内容。 + +只读运行诊断:`sudo bash deploy/diagnose.sh`。目前正式入口继续为上述 HTTPS 域名,测试时无需修改 202 机器的端口映射。 diff --git a/docs/hosting-operations.md b/docs/hosting-operations.md new file mode 100644 index 0000000..e71cb75 --- /dev/null +++ b/docs/hosting-operations.md @@ -0,0 +1,111 @@ +# Sea vHost 日常操作与管理端 API + +适用本项目的 Debian amd64、宝塔、Nginx、MySQL 部署。主控保存业务数据和加密配置;被控接收受限操作,宝塔密钥不交给浏览器。 + +各页面与按钮的用途见 [业务功能与操作说明](business-actions.md),其中单独说明 DNS 凭据、托管解析与网站证书三类操作。 + +## 安装与初始化 + +1. 解压发布包,以 root 执行 `bash deploy/install.sh`,按中文向导选择单机主控或被控。 +2. 单机首次访问安装页,填写 MySQL、管理域名、宝塔连接及初始管理员信息,完成连接检查后安装。已有配置不会被静默覆盖。 +3. 在“节点管理”设置节点默认根域、主机目录、FTP 证书域名。默认目录为 `/www/wwwroot/seavHost/vHost/<随机主机名>`。 +4. 在“环境配置”读取本节点已安装版本,再安装需要的语言版本。版本维护与项目切换使用页面列出的实际可用版本。 +5. 在“系统设置”选择触发节点,点击“配置 / 检查宝塔计划任务”。宝塔只创建一条每分钟运行的 Sea vHost 系统调度器;用户任务由主控鉴权后分发。 + +## 开通用户与主机 + +“用户管理”开通用户,“虚拟主机”开通主机。用户可以有多台主机,一台主机最多绑定一个用户;不绑定用户时仍可使用独立主机账号登录。资源套餐作用于主机。 + +主机名称由系统随机生成,数据库名、数据库用户名及 FTP 用户名与主机名对应。FTP 和数据库密码分别随机生成并加密保存;独立主机登录密码单独生成。 + +批量操作支持数量生成和 JSON 模板导入:选择操作 → 下载对应模板 → 填写 → 导入 → 验证预览 → 提交 → 在“批量任务”查看逐条结果。创建用户最多 100 条/批,创建主机最多 50 条/批,管理操作最多 200 条/批。导入文件上限 256 KiB。 + +```json +{ + "format": "sea-vhost.batch", + "version": 1, + "operation": "create_users", + "rows": [ + {"slug":"customer01","name":"客户一","email":"customer01@vhost.ser888.cn","password":""} + ] +} +``` + +密码留空时独立随机生成。批次结果可主动下载为 `sea-vhost.batch-result` JSON,结果凭据保留 24 小时。后续可查看 FTP/数据库凭据或重置主机登录密码。 + +归属转移和解绑默认保留凭据并停止网站,可选择随机重置主机、FTP、数据库三类密码,也可明确选择不停站。保留密码意味着旧持有人可能仍掌握原生服务密码。归属变更会撤销旧主机会话,并暂停原用户关联的计划任务。 + +管理员“快捷进入”使用限时临时代入会话,可正常读写,退出代入可返回管理员身份;代入行为仅进入管理员审计。用户/主机日志不展示管理员操作。 + +## 网站、文件、环境与日志 + +用户在“虚拟主机”选择名下主机,再点击“网站管理”;独立主机账号登录后直接进入主机详情。每个网站独立选择运行目录,主站默认 `/`,也可改为 `/public` 或其他主机内目录。目录必须位于主机根目录内。 + +在网站的“运行环境”中可切换同语言的已安装版本;管理员对该主机开启“允许切换运行环境”后,才可跨语言切换。系统先停站并保留文件、数据库,完成后由使用者检查兼容性并手动启动或部署。运行环境的安装与组件补丁更新在管理员“环境配置”页提交,不同任务可排队、同节点串行,重复任务拒绝。 + +组件安装及 PHP 补丁更新交由宝塔执行,Sea vHost 跟踪进度,不因此锁住整个节点的主机操作。即使组件任务中断待核验,其他主机仍可保存文件和管理配置。站点版本迁移或跨语言切换仅保护所属主机;PHP 更新完成后只在刷新对应主机独立 FPM 的短暂阶段保护该主机,其他主机继续可用。 + +PHP 网站创建后即可上传程序。Node.js、Python、Go、Java 网站先创建,上传入口文件后点击“部署检查”→“检查文件”→“开始部署”。应用监听 `127.0.0.1`,使用系统注入的 `PORT`;Java 同时获得 `--server.port` 参数。Go 上传 Linux amd64 可执行程序,Java 上传可运行 JAR;Node 使用 `package.json` 的 `start` 脚本。 + +“环境 / 启动”可设置入口、工作子目录、JSON 参数数组和 JSON 环境变量对象。环境变量加密保存;Node 的 npm 从配置的工作目录执行,需在该目录准备相应 `package.json`。PHP 只设置环境变量,运行目录通过网站配置管理。`PORT`、`PATH`、动态库注入等保留变量不可覆盖。保存重启运行中的网站;停止的网站保持停止。 + +“设置 / 日志”提供默认首页、伪静态模板、301/302、强制 HTTPS、404/503 与维护模式。自定义错误页位于网站运行目录内。Nginx 校验失败会回滚。强制 HTTPS 前应先安装覆盖网站域名的有效证书。 + +日志可切换访问、Nginx 错误、程序运行和 PHP-FPM 类型,支持关键词筛选及下载 JSON。操作日志与网站访问日志分别展示。 + +“文件管理”支持目录、新建文本、重命名、移动、复制、ZIP 压缩/解压、删除至回收站与恢复。Web 上传默认上限 20 MiB;大文件使用 FTP。ZIP 解压限制总量和条目数,拒绝软链接、越界路径和系统保留目录。 + +“FTP”仅提供基本启停、查看凭据和随机重置密码。FTP 地址使用主机域名,TLS 策略依证书配置确定。 + +“数据库”点击“进入 phpMyAdmin”,后端使用该主机的 MySQL 账号登录,不向前端返回数据库登录密码,不授予 root 数据库权限。MySQL 保持本机连接。当前 phpMyAdmin 代理单次请求和响应上限为 2 MiB;较大的 SQL 数据应另走受控导入流程。 + +“资源图表”按主机展示 CPU、内存、进程、磁盘、数据库和流量。历史保留 30 天;新主机没有过去 30 天的数据。HTTP 限速按连接,FTP 限速按账号;软磁盘配额按巡检结果执行,并非内核级即时写入拒绝。 + +## SSO 与密码登录 + +管理员在“系统设置 → SSO 登录”配置 OIDC 的 Issuer、Client ID、Client Secret 与回调地址。默认关闭 SSO 和首次建号,普通用户与管理员的密码登录分别保持开启。 + +未绑定的第三方身份返回登录页后,可输入已有用户或管理员账号的密码完成绑定;已开启 MFA 时还须验证动态码或恢复码。后台允许首次建号时,页面另提供“创建普通用户并登录”,要求身份提供商返回已验证邮箱,只创建普通用户,不开通主机,也不按相同邮箱自动合并账号。已有绑定的身份直接登录。 + +“允许普通用户密码登录”和“允许管理员密码登录”分别控制新密码认证。关闭前必须启用完整的 SSO 配置;关闭管理员密码还要求当前管理员已绑定该 Issuer 的身份。密码入口关闭后不能通过首次绑定流程绕过限制;已登录账号可在“账号安全”中绑定。关闭密码后禁止解除相应绑定;关闭 SSO 前先恢复两类密码登录。策略变更不会强制注销已经建立的会话。 + +独立主机账号不能绑定或使用 SSO,始终保留主机密码登录。协议测试、界面与部署验证范围见 [SSO 与界面验收](sso-ui-acceptance.md)。 + +## 用户计划任务 + +只有用户账号可以创建任务;独立主机账号没有入口和接口权限。每个用户最多 10 条,选择自己名下主机和网站,再选择 PHP、Python、Node 脚本或本站 URL。 + +脚本路径相对于网站运行目录,选择已安装的解释器版本;参数为 JSON 字符串数组。脚本以对应主机的 Linux UID 执行,继承该网站环境变量。“执行一次”在下次系统调度时执行,页面可查看输出及退出状态。 + +Cron 使用五字段表达式并指定时区,例如 `*/5 * * * *`、`Asia/Shanghai`。单任务最长 5 分钟,禁止同一任务重叠执行,输出限制 64 KiB。本站 URL 只能填写 `/health` 这类本站路径,不能填写其他域名、内网地址或任意 shell。 + +任务超时会清理普通进程组及其子进程。独立 UID 是当前隔离边界;恶意程序主动脱离进程组不等同于内核沙箱隔离。 + +## 管理端对接 API + +管理员在“对接 API”创建独立密钥,选择有效期、权限范围及可选 HTTPS 回调地址。原始 API token 和回调密钥仅在创建时显示一次,立即保存;可随时吊销。 + +在线说明:`GET /api/integration/v1/docs`。业务 API 使用 `Authorization: Bearer `,不接受浏览器登录 Cookie 作为替代鉴权。 + +| 接口 | 权限 | +| --- | --- | +| `GET /api/integration/v1/users` | `users:read` | +| `GET /api/integration/v1/hosts` | `hosts:read` | +| `POST /api/integration/v1/users` | `users:write` | +| `POST /api/integration/v1/hosts` | `hosts:write` | +| `GET /api/integration/v1/tasks/{id}` | `tasks:read` | +| `GET /api/integration/v1/tasks/{id}/download` | `credentials:read` | + +写入请求必须提供 `Idempotency-Key`(8–128 字节),请求体是 `operation` 与 `rows`。同一 API 密钥与幂等标识、相同数据返回原任务;变更数据则返回 409。成功受理返回 202 和批次编号,轮询任务直到完成,逐条处理失败或待核验结果。 + +```json +{"operation":"create_hosts","rows":[{"name":"site-0001","tenantId":0,"nodeId":1,"planId":1,"runtime":"PHP","version":"8.4","runPath":"/public","autoSSL":false}]} +``` + +用户接口支持 `create_users`、`user_enable`、`user_disable`;主机接口支持 `create_hosts`、`assign_hosts`、`host_subscription`、`host_start`、`host_stop`、`host_password_reset`。管理条目使用 `hostId`,归属变更建议带查询所得 `ownershipVersion`。续期使用 `setExpiry:true` 与 RFC3339 `expiresAt`,`null` 表示长期。 + +任务只能由创建它的密钥查询及下载。吊销或过期后,后续请求被拒绝,未开始的条目停止执行;已开始的操作会完成并记录结果。 + +回调为 HTTPS 443,不允许内网/保留地址或跳转。请求包含 `X-Sea-Timestamp`、`X-Sea-Event` 和 `X-Sea-Signature: sha256=`;签名原文为 `timestamp + "." + eventId + "." + 原始请求体`,用创建时独立生成的 `webhookSecret` 做 HMAC-SHA256。校验时间偏差不超过 5 分钟,并按事件 ID 去重。 + +接收端返回 2xx 确认;失败后按 1/2/4/8/16/32/64 分钟间隔重试,总计最多 8 次。回调不含密码或原始输入。密钥吊销/过期后停止投递。 diff --git a/docs/installation-test-2026-10-25.md b/docs/installation-test-2026-10-25.md new file mode 100644 index 0000000..131d2b4 --- /dev/null +++ b/docs/installation-test-2026-10-25.md @@ -0,0 +1,246 @@ +# 2026-10-25 交互安装与实机验收记录 + +> 历史验收记录:环境、版本、数量及结论仅适用于文中所列日期,不代表当前服务重新实测。当前状态见 [项目状态整理](project-status-2026-10-29.md)。 + +状态:本轮可执行测试已完成。基础主流程以及数据库超额写保护、客户 SQL 回收备份、HTTP/FTP 限速与合并流量计量均已部署测试机并通过实测。三条根域+端口公网入口正常;正式访问仍使用主机子域名。外部服务及跨服务器联合验收仍单独列出,不计为通过。 + +## 实际环境与边界 + +- 测试机:`202.189.40.57`,Debian 13 amd64、宝塔 12.0.0、Python 3.13.5、Nginx、MySQL、Pure-FTPd。 +- 本轮不修改 `36.140.39.34` 的正式应用或数据库。 +- 原测试环境为 3 个账号、1 台虚拟主机、1 个站点。先备份,再验证升级,随后按角色分阶段安装。 +- 私有备份与脱敏终端记录位于测试机 `/root/sea-vhost-qa-20261025-mvn6260v/`;平台数据库备份为 `original-platform.sql`,配置与程序备份为 `original-files.tar.gz`。其中原始备份和状态文件含凭据,仅 root 可读,不随安装包发布。 +- 管理测试域名:`qa.202.189.40.57.sslip.io`;主机后缀:`vhost-qa.202.189.40.57.sslip.io`。测试证书为临时自签名证书。 +- 一台物理测试机上的主控/被控分离进程测试,不等同于两台独立服务器的跨机验收。 + +## 已完成验证 + +| 项目 | 结果与证据 | +| --- | --- | +| 前端测试 | 2 个测试文件、26 项通过,新增套餐 Mbps 与月流量分开提交用例 | +| 后端回归 | 资源补齐与归档完整性校验后,使用 Go 1.27.3 再次执行全量 `go test -p 2 ./...` 通过;前端 26 项测试和生产构建再次通过 | +| 安装向导 | 19 项测试在 Windows 与真实 Debian 上均通过;不执行 apt 的单元测试与真实安装分开计数 | +| 原地升级 | 真实伪终端操作交互向导;原配置哈希和 3/1/1 数据计数保留;迁移 012 和 API 健康检查通过 | +| 中断迁移恢复 | 真实一次性 MySQL 库,DDL 已部分提交且原账号生命周期已重置时续跑;到期数据、路径、停止状态、完整进程额度和节点关联保留;用例耗时 53.23 秒 | +| 主控兼本机全新安装 | 真实终端选择角色 1;自动识别证书、生成 Nginx HTTPS 和反代、自动启动;通过真实 Web API 完成数据库/面板连接检查、首次安装及管理员登录 | +| PHP 主机 | 从主控开通真实宝塔 PHP 8.4 主机;独立主机账号登录、写入 `custom/index.php`;Nginx 实际访问返回测试字符串 | +| FTPS/Web 互操作 | FTPS 上传 → Web 下载 → Web 覆盖 → FTPS 下载和再次覆盖均通过;测试证书按自签名环境处理 | +| MySQL 账号 | 使用随机密码和同名数据库/用户名连接,建表、写入、读取测试字符串通过 | +| 独立身份 | 主机系统用户无法读取平台配置 | +| 到期回收 | 仅对本轮创建的测试主机回拨到期时间;后台推进 3 天宽限和 7 天回收逻辑后删除目录与系统身份;原测试主机不纳入新库的回收范围,原配置和控制库另行备份 | +| 备份保留 | 回收时新备份实际保留 14 天;使用 UTC 会话核对,不混用 MySQL TIMESTAMP 本地显示与 UTC DATETIME | +| 独立主控与被控安装 | 真实终端分别选择角色 2、3;完成独立主控 Web 安装、节点新增/配对、被控真实服务安装、主控主动 mTLS 探测与启用;独立主控的本机节点拒绝启用 | +| 被控更新与取消 | 取消保留配置字节、0640 权限及在跑网站;复用配置/密钥重装后完成身份核验,三台 PHP 主机均返回 200;已安装依赖不重复运行 apt 更新 | +| 被控无平台台账 | 无 `/var/lib/sea-vhost/config.json` 或 `/var/lib/sea-vhost-panel/resources.json`;平台数据库、任务和资源登记保留于主控;原生宝塔环境记录、软件校验缓存和流量游标属于本机运行材料 | +| 多主机与上传 | 两个用户、三台真实 PHP 主机,同一用户可看到其两台主机;主机账号不能访问同一用户的另一台主机;20 MiB 上传接受,超限覆盖拒绝且原文件保留,Nginx Range 下载返回 206 | +| Python 环境安装 | 免费管理组件安装、每分支最新补丁清单通过;真实编译安装 3.12.15,并验证 SSL/SQLite/venv/ensurepip。测试机无法下载官方源且镜像返回 418,使用本地通过官方 HTTPS 获取的源码及校验材料完成受保护缓存恢复 | +| Node.js / Go 环境安装 | 通过主控环境接口安装并核验 Node.js v24.22.1 和 Go 1.27.3;保留旧 SDK | +| 五类实际应用 | PHP 8.4、Node.js v24.21.0、Python 3.12.15、Go 1.27.3、JDK 25.0.3 均真实运行;后四类完成创建、上传、预检、部署、Nginx 访问、独立 UID、零 capabilities、进程无内部令牌、停启、删站保留源码及清理 | +| 账号安全 | 改密保留当前会话、撤销其他会话,旧密码拒绝;TOTP 设置、强制第二因素、动态码登录、恢复码关闭及会话撤销通过 | +| 手动 SSL 与主机改密 | 无效私钥拒绝;上传叶证书后以实际 SNI 连接核对 DER 证书及 PHP 响应;关闭 SSL 保持 HTTP 可用;主机密码重置后旧密码/会话失效,FTP/数据库凭据保持不变 | +| 安全金丝雀 | 同用户跨主机 UID 读取、文件 API/HTTP 符号链接、FTPS 目录逃逸、跨站写请求拒绝;缺少客户端证书无法访问 mTLS 执行入口;实际主机进程环境无内部调用令牌 | +| SMTP 协议 | 本机模拟 SMTP 接收测试通过:中文主题/正文、邮件头注入防护,以及禁止无 TLS 传输认证凭据;没有向真实收件人发信 | +| 重复启停 | 三台 PHP 主机各执行启动/启动/停止/停止/启动/启动,均通过真实接口与最终 HTTP 200 验证 | +| 主机软配额 | 129 MiB 实际文件、2 MiB 实际数据库记录、2 MiB Nginx 响应及 25 个受控进程触发对应限制;超额主机 Web 写入 423、UID 写入拒绝、FTPS 登录拒绝,其他两台主机保持运行;清理和提高额度后可恢复 | +| 真实 MySQL 幂等与多节点模型 | 新建一次性库验证迁移、原生编号跨节点重复、主机额度、汇总、任务锁、主控资源台账、到期与主站/附加站幂等启停;最后加入网络配置首次写入、重复保存与恢复默认端口后再次通过,耗时 47.01 秒;专库与账号已删除 | +| Node.js 补丁切换 | 运行中站点由 v24.21.0 切到 v24.22.1,HTTP 响应确认实际进程版本;停止后切回旧版仍保持停止;两个 SDK 均保留,测试站点及进程已清理 | +| FTPS 域名校验 | 显式信任本轮测试证书,使用分配给主机的域名进行证书主机名验证,完成加密上传/下载/删除;错误域名在发送账号密码前被拒绝 | +| 域名管理 | 默认子域名在管理员列表出现;待审不生效、批准后真实 Nginx 生效、拒绝保持不生效、关闭审核直接绑定、保留域拒绝、重复域拒绝、CDN 目标持久化及每主机网站数量限制通过 | +| 已有宝塔站点接管 | 新建一次性原生 PHP 站点,从 `/public` 导入并分配指定用户/节点,原目录内容保留,真实页面和独立主机登录通过;其他用户访问拒绝;到期回收及原目录明确清理通过 | +| 自定义端口 | 一台主机实际监听 18080,另外两台保持共享 80;恢复 80 后全部可访问;主机 UID 不能写 Nginx 配置 | +| PHP 同分支更新 | 实际执行 8.4.25 → 8.4.27,先生成回退备份,再由免费面板软件更新、检查实际版本/原有扩展并核验独立 FPM;任务完成后全部 PHP 主机 HTTP 200;维护期间用户写请求 423 | +| PHP-FPM 实际版本与主控离线 | 三台站点分别通过真实 PHP 响应确认 8.4.27;只停止主控时三个网站继续运行;主控重启后原管理员会话仍有效,任务无待核验项 | +| 最终发布程序复验 | 再次通过真实终端覆盖安装被控;四个安装程序 SHA-256 与本地候选包逐一相同,配置字节与 0640 权限保留,四项服务 active,Nginx 配置通过,三台网站 HTTP 200,无待核验执行记录 | +| 节点重复启用 | 连接与主机身份核验后,连续重复启用三次返回 204,不因启动巡检抢锁而误停用节点 | +| 新主机默认环境 | 实际接口默认版本为 PHP 8.4(实际补丁 8.4.27)、Node.js v24.22.1、Python 3.12.15、Go go1.27.3、Java jdk-25.0.3;来自已安装清单,不代表其他分支被强制迁移 | +| 最终清理 | 最后再次完成严格域名校验的本机 FTPS 上传/下载/删除;删除 83 个本轮临时上传文件,确认一次性集成测试数据库为 0;保留 3 台 PHP 测试主机和 root 私有备份供核对 | +| 公网 PHP 完整链路 | 白名单调整后,通过 Sea vHost 接口创建一次性 PHP 网站,绑定并审核 `ser888.cn`;开发机固定连接 `202.189.40.57:10094`,Host 带/不带端口均收到本轮随机标记与 PHP 8.4.27,均为 Nginx 200;随后经产品接口删除临时网站及根域绑定,原三台主机保持 200。未修改 DNS 或正式服务器 | +| 根域+端口的三主机公网测试 | 用户确认仅本轮使用该方案,并提供 `10043 → 81`、`10124 → 82`,保留 `10094 → 80`。三条公网 HTTP 请求分别返回三台原有主机的独立标记,正文 SHA-256 与本机基准完全一致,固定路由响应头与各自端口对应;不把三台主机改成共享根域的产品数据模型 | +| 数据库原生写保护 | 新建 2 MiB 数据后降低该主机数据库额度至 1 MiB,原生 INSERT/UPDATE/CREATE 均拒绝,之前建立的连接断开;SELECT 与清理用 DELETE 保留;另一台主机仍可建表/删表;提高额度后原生写入恢复 | +| HTTP / FTP 限速与计量 | 设置 1 Mbps,512 KiB HTTP 下载 4.02 秒,FTPS 上传 8.37 秒、下载 4.60 秒;两次 FTP 传输合计 1,048,576 字节实际计入,按账号筛选、双向计量;另有完整行、跨用户、重复读取、日志轮转及跨月归零测试 | +| 客户 SQL 备份与恢复 | 同一归档包含网站文件、SQL、数据库名称/大小/SHA-256 清单;故意删除测试数据库使备份失败,主机目录与记录保留;恢复数据库后正常回收,再从回收归档恢复 SQL 并核对随机标记,两次还原成功;新备份保留 1,209,601 秒,约 14 天 | +| 最终备份完整性与新建回归 | 正常归档验证通过,损坏 gzip 校验尾的归档被拒绝;新建 PHP 主机接口返回 201,完整回收流程成功生成 SQL+网站归档,删除原库后实际 SQL 还原通过;最终只保留原三台主机,无待核验节点操作 | +| MySQL 重启兼容 | 停止临时主控/节点后实际重启 MySQL,代理 PID 保持不变;重建 socket 后权限探测、客户 SQL 导出与归档验证仍成功;主机 UID 无法穿过 root 专用 socket 目录,主控/节点恢复后三台原网站均 200 | + +## 本轮修复 + +1. 旧测试辅助脚本调用 `set_execute_script`,该宝塔版本仅支持 WebSocket 的此项调用,任务过去实际依赖分钟计划触发。改为 `StartTask`,并把临时计划设置到远期,防止长安装任务重复启动。 +2. 迁移原先 30 秒超时,MySQL 部分 DDL 已提交,重启遇到表或列已存在。迁移 012 现检查列、索引和约束,支持续跑;回填不会覆盖已迁移的主机到期信息。并发启动使用数据库迁移锁,首启/安装迁移超时已调整。 +3. 安装向导不再把 systemd 瞬时 active 当成安装成功;需等 `/healthz` 返回运行或待安装状态。 +4. 平台连接统一为 MySQL UTC 会话,修正本机时区环境下 TIMESTAMP 与 UTC DATETIME 的读取差异,不修改 MySQL 全局时区或客户业务连接。 +5. 安装单元测试的资源登记表路径纳入临时夹具,避免真实 Debian 的现有资源影响测试。 +6. Nginx 显式保留 Range/If-Range 请求头并关闭 API 代理缓存,修复反代层将文件部分下载变为完整 200 响应的问题。 +7. 在执行代理创建 systemd 文件系统命名空间前准备 Node PID 和 Python versions 目录,避免组件后装后目录未纳入可写挂载。 +8. Go 清单显式刷新宝塔缓存,避免只展示旧缓存版本;刷新失败保留已安装环境清单。 +9. Python 源码安装支持 root 专用官方校验/源码缓存;拒绝可写、非 root 所有、符号链接或超限材料,源码摘要不匹配直接拒绝。源码编译前先验证目标目录可写。 +10. 当前宝塔 Python 项目接口需先登记 SDK,并使用其规范解释器路径 `python3.`;只允许 root 管理的 SDK 登记,应用命令仍指向主机独立虚拟环境,不让 root 检测用户可写解释器。 +11. SMTP 中文主题采用标准 MIME 编码,保留邮件头换行过滤。 +12. MySQL 未改变数据时影响行数为 0,不能等同记录不存在;主站及附加站点启停现复核归属记录是否存在,保持幂等与权限边界。 +13. 宝塔原生 FTP 停用仅允许 `127.0.0.1`,本地客户端仍可登录。主机冻结时追加仅针对该主机 Pure-FTPd 账号的来源限制,实测回环登录也被拒绝;正常恢复由宝塔启用接口清除限制。不修改其他 FTP 账号。 +14. 接管已有站点前的目录准备会创建运行目录。导入校验现仅允许这条空目录链,继续拒绝已有文件、其他目录和符号链接;复制源使用固定根目录句柄,避免源路径变化后读取目录外数据。 +15. 自定义端口需要 root 执行代理修改受管 Nginx 配置,现补齐其固定配置目录的 systemd 可写挂载;主机 UID 仍不能写这些文件。网络设置支持新建默认行与重复保存,节点维护锁避免与环境切换并行,已分配独立 IP 不再分配给另一台主机。 +16. 所有发布包中的临时管理员计划任务辅助脚本统一使用 `StartTask`,并采用远期月计划;34 个 JavaScript 工具通过语法检查,避免重复分钟触发或依赖已变为 WebSocket 的旧接口。 +17. PHP、Node.js、Go 和 Java 的已安装清单按实际版本数字降序排列;新主机优先默认最新已安装版本,既有站点不会因此自动迁移。 +18. 节点启用的主机身份核验会与启动巡检短暂争用节点锁。身份核验现最多等待 10 秒并尊重请求取消;重复启用仍验证 mTLS,状态相同时直接成功,避免重复身份核验造成误停用。 +19. 新增原生 MySQL 权限控制:仅接受已管理主机的同名数据库/账号。数据库超额时撤销写权限并清除旧连接,允许 SELECT、DELETE、DROP 清理;额度恢复后恢复该库权限。回收备份前进一步切换为仅 SELECT,避免清理或其他连接继续改动快照来源。 +20. 通过宝塔核心 ORM 读取其当前加密 MySQL 配置,凭据仅存在 root 代理内存与 root 临时选项文件,不通过 API 回传、不写进命令行或日志。为本机 socket 提供 root 专用、0700 目录下的只读目录视图,避免直接绑定单个 socket 文件后,MySQL 重启重建 inode 导致连接失效;测试机实际 MySQL 为 5.7.44。 +21. 客户 SQL 与网站文件写入同一 gzip/tar,原子落盘前同步文件,Linux 下同步归档目录;清单记录 SQL SHA-256。回收前验证清单、SQL 摘要与 gzip 完整性,旧文件备份不会被误认为已含 SQL;失败保留源数据,不继续删除。 +22. 新增套餐 `bandwidthMbps`,0 表示不限速。使用自有 Nginx 扩展限速与免费 Pure-FTPd 账号设置,不调用收费功能;HTTP 按请求、FTP 按会话生效,月流量包括 HTTP 响应正文和 FTP 上传/下载。日志启用后计量,历史不存在的 FTP 日志无法补计。 +23. FTP 策略预检提前到创建资源之前,避免主机已创建、末尾 FTP 检查却返回失败。实机已验证新建接口 201;测试中早先遗留的临时主机已通过到期回收清理。 + +## 最终保留状态与程序核对 + +测试机当前保留独立主控的临时 QA 服务与被控服务,主控、被控使用不同系统身份,但仍在同一台物理机。默认合一模式 API 服务已停止;正式服务器没有参与本轮部署。 + +另保留本轮专用的根域端口入口配置 `/www/server/panel/vhost/nginx/sea-vhost-qa-root-ports.conf`,以及私有测试记录 `root-port-test.json`。它们只用于测试入口转发,不是正式产品的同域多端口托管功能;三台主机原有域名绑定、平台台账和子域名访问方式保留。 + +保留的三台 PHP 主机为 `sv60cb61780a`、`sv61390dec70`、`svdc844b6adf`,后缀均为 `vhost-qa.202.189.40.57.sslip.io`。两个用户分别持有两台和一台主机。测试账号凭据只保存在测试机 root 私有状态文件,未写入报告、前端或发布包。管理站点目前仅在测试机回环验证,不提供本轮未映射的公网管理访问地址。 + +以下为覆盖安装后从实际运行路径与候选包同时计算并比较的摘要。最终归档仅补充验收文档,程序保持这些字节;归档整体摘要以随包 `.sha256` 文件为准。 + +| 程序 | SHA-256 | +| --- | --- | +| sea-vhost-api | `6ddb9e8f63a94c4984cc1d8b5dcaea3823231ebb5101563c3547ceef4afd829c` | +| sea-vhost-agent | `eceba40f1e0a8c0d590b43d85d4f09a4708f76686a8b8e200f90ffa02ae94493` | +| sea-vhost-panel-broker | `4076170dbb6338aa88fac785472c278da7562078f5c28f40ed7b08fd63091537` | +| sea-vhost-node | `756b28f5bb56cbeb9481f0ecb4d4cfb3ecde289fe41a26e9ae41285a6f147adf` | + +## 需要明确的限制 + +- 软配额存在分钟级巡检窗口;Web 上传前会主动刷新。它不是文件系统硬配额,也不是达到阈值即由内核返回 ENOSPC。 +- 数据库限制仍由巡检触发,超额后的原生写权限控制与旧连接断开已实现;它不是 MySQL 引擎在容量刚达到阈值时立即返回磁盘满。清理权限允许删除自身数据,清理或提高额度后可恢复写入。 +- 新的回收备份已经包含客户 SQL,完成实际还原验证;旧版已经生成的文件备份不会凭空补回已删除的数据库内容。此轮未新增“一键重建平台主机记录”恢复界面,SQL 和文件归档可由管理员还原。 +- `bandwidthBytes` 是月累计量,`bandwidthMbps` 是单独限速配置。当前为 HTTP 每请求和 FTP 每会话限速,多个并发连接不共享一个总速率;没有将其描述为整台主机汇总的 Mbps 上限。HTTP 计量为响应正文,FTP 为日志记录的上传/下载有效负载,不含 TCP/TLS 额外开销。 +- 独立 UID 和文件权限不隔离节点网络栈;本轮不将其描述为容器或内核沙箱。未对真实第二个公网 IP 做独立 IP 数据面验收。 +- 真实 DNS 提供商凭据、外部 SMTP、第三方 OIDC 身份提供商、公网 ACME 成功签发与跨服务器 mTLS 网络,本轮没有进行真实外部服务验收。相关本地/模拟或历史测试不等同这些外部验收。 + +限速口径依据 [Nginx limit_rate 官方文档](https://nginx.org/en/docs/http/ngx_http_core_module.html#limit_rate);FTP 统计格式和虚拟账号配置依据 [Pure-FTPd README](https://github.com/jedisct1/pure-ftpd/blob/master/README) 与 [虚拟用户文档](https://github.com/jedisct1/pure-ftpd/blob/master/README.Virtual-Users)。测试机当前 SMTP 与 OIDC 开关均未启用,未向真实收件人发送测试邮件。 + +## 本轮网络范围 + +| 目的 | 建议公网 → 内网 | 当前情况 | +| --- | --- | --- | +| HTTP 网站 A | `10094 → 80/TCP` | 根域 Host 实际返回主机 A 的 `SEA-NODE-0`;公网链路通过 | +| HTTP 网站 B | `10043 → 81/TCP` | 根域 Host 实际返回主机 B 的 `SEA-NODE-1`;公网链路通过,使用 HTTP | +| HTTP 网站 C | `10124 → 82/TCP` | 根域 Host 实际返回主机 C 的 `SEA-NODE-2`;公网链路通过 | +| HTTPS 管理 | 本轮使用测试机回环 443 | 不要求增加管理端口映射;独立被控无需管理站点 | +| 被控 mTLS | 本轮主控进程主动连接回环 9443 | 同机分离身份实测;未宣称跨公网或两台服务器验证 | +| FTPS | 回环 21 与实际被动数据连接 | 用户已选择仅测试本机,不申请公网 FTP 或被动端口映射 | + +后续若验证独立远端主控连接这台 NAT 被控,仅需把一条公网 TCP 端口透传到被控 9443;普通 HTTPS 反代终止 TLS 会丢失 mTLS 客户端身份。管理站点的 443 无需映射到被控。 + +### 公网 HTTP 复核与原结论更正 + +最初只根据 `Server: Apache` 和 404 就把转发目标列为待核对,证据不足。用户确认 `10094 → 80` 后,使用 Node 原生 HTTP 直接连接同一公网 IP/端口,不使用代理、不跟随跳转,只改变 Host,并读取响应页面内容,结果如下: + +| 访问位置 | Host | 实际响应 | +| --- | --- | --- | +| 公网 `202.189.40.57:10094` | `202.189.40.57:10094` | Nginx 200,默认“没有找到站点”页面;证明公网 IP 请求已进入网站服务,不能据此认定租户站点通过 | +| 同一公网入口 | `sv60cb61780a.vhost-qa.202.189.40.57.sslip.io` | Apache 404,页面标题为“很抱歉,请联系机房域名过白” | +| 同一公网入口 | 上述测试域名加 `:10094` | 相同域名过白拦截页,排除漏加外部端口导致的差异 | +| 本机 `127.0.0.1:80` | 三台测试主机域名,分别带/不带 `:10094` | 六次均为 Nginx 200,各自返回 `SEA-NODE-0`、`SEA-NODE-1`、`SEA-NODE-2`,同一主机两种 Host 的响应 SHA-256 完全一致 | + +同时核对三份实际 Nginx 配置均监听 80,`server_name` 对应分配域名,`ss` 确认 80 由 Nginx 监听。因此当前证据表明:端口映射可用,测试域名请求在公网入口受到域名白名单拦截;没有发现 Sea vHost 的站点配置或 Host 端口处理错误。公网域名访问仍未计为通过,不能用本机成功替代。此前“转发目标待核对”的说法在此更正。 + +复核脚本保存在开发工作区 `build/smoke/public-http-routing-probe.mjs` 与 `build/smoke/http-forwarding-diagnose.sh`;只读取测试站点、响应和监听状态,不更改站点绑定或默认站点,也不改动正式服务器。 + +### 白名单调整后的真实公网 PHP 验证 + +用户随后告知机房白名单为 `*.*.*.*.*.*.*.ser888.cn`。实测 `ser888.cn` 根域已放行;`www.ser888.cn`、`sv60cb61780a.qa.vhost.ser888.cn` 以及恰有七层标签的 `sv60cb61780a.node2.qa.vhost.sea.test.http.ser888.cn` 仍返回相同过白拦截页,不能据此宣称泛域名已放行。 + +为完成可执行的公网验证,通过系统真实主机登录、创建附加 PHP 网站、上传随机响应脚本、绑定域名、管理员审核的流程,在第一台测试主机临时创建网站 15,并绑定 `ser888.cn`。开发机直接连接公网测试 IP 的 10094,分别发送 `Host: ser888.cn:10094` 与 `Host: ser888.cn`,均实际收到: + +```json +{"marker":"SEA-PUBLIC-4d8b326a9a73d5b0ff05b0f2","php":"8.4.27"} +``` + +两次均为 Nginx HTTP 200,证明公网转发、实际网站匹配及 PHP 执行链路通过,而非只访问到默认站点。测试采用固定连接 IP 并指定 Host,不代表 `ser888.cn` 的公开 DNS 已指向测试机。随后通过产品接口删除临时网站及根域绑定、将临时目录移入回收站,并核对三台原测试主机均 HTTP 200;没有改动 DNS、正式服务器或全局默认站点。对应测试脚本为开发工作区 `build/smoke/public-domain-live-test.sh`。 + +### 本轮采用的根域+端口测试入口 + +用户明确选择仅用于本轮测试,正式仍按主机子域名访问,并提供新增映射 `10043 → 81`、`10124 → 82`。在测试机添加独立 Nginx 入口,以 `ser888.cn` 和内网监听端口分流,反代到固定的本机 Nginx 主机域名。入口不接受客户端指定上游地址或上游 Host;其他 Host 在新增监听端口上返回 404,保留原有子域名路由。 + +| 固定连接公网 IP | 请求 Host | 内网端口 | 目标主机 | 实际结果 | +| --- | --- | --- | --- | --- | +| `202.189.40.57:10094` | `ser888.cn:10094` | 80 | `sv60cb61780a` | HTTP 200,`SEA-NODE-0` | +| `202.189.40.57:10043` | `ser888.cn:10043` | 81 | `sv61390dec70` | HTTP 200,`SEA-NODE-1` | +| `202.189.40.57:10124` | `ser888.cn:10124` | 82 | `svdc844b6adf` | HTTP 200,`SEA-NODE-2` | + +三次正文摘要均与配置前的本机 PHP 基准完全一致;`X-Sea-QA-Port` 响应头也分别与公网端口相符。测试机 UFW 的默认 INPUT 为 DROP,最初未放行 81/82;补充两条带 `Sea vHost QA root port 81/82` 注释的 IPv4 TCP 规则后,新增两个公网端口连通。没有关闭防火墙或改动其他放行规则。 + +`ser888.cn` 的公开 DNS 当前走 CDN,并未指向测试 IP,因此以下复现命令固定连接测试机,避免修改现有 DNS。三个端口均为 HTTP,10043 不代表 HTTPS: + +```sh +curl --resolve ser888.cn:10094:202.189.40.57 http://ser888.cn:10094/ +curl --resolve ser888.cn:10043:202.189.40.57 http://ser888.cn:10043/ +curl --resolve ser888.cn:10124:202.189.40.57 http://ser888.cn:10124/ +``` + +普通浏览器访问需要在测试客户端单独将该域名定向到测试 IP,否则仍会按现有 DNS 到达 CDN。本轮没有修改开发机 hosts 或公开 DNS。 + +验证脚本为 `build/smoke/root-port-public-test.mjs`;远端配置、复验与清理入口为 `build/smoke/root-port-live-test.sh`,动作分别为 `prepare`、`open-firewall`、`verify`、`cleanup`。清理动作先核对私有记录中的配置摘要,只移除本轮配置以及有本轮注释的两条防火墙规则,保留原有主机站点和域名。当前按本轮测试需要保留入口,暂不清理。 + +## 完整操作流程 + +### 准备 + +在目标 Debian 服务器安装宝塔、Nginx、MySQL、免费 Pure-FTPd。独立主控不要求本机宝塔,但需要本机 MySQL;自动配置管理站点需已有 Nginx 与覆盖管理域名的证书。 + +将完整安装包及 `.sha256` 文件上传到服务器,以 root 操作: + +```sh +sha256sum -c sea-vhost-linux-amd64.tar.gz.sha256 +mkdir -p /root/sea-vhost-install +tar -xzf sea-vhost-linux-amd64.tar.gz -C /root/sea-vhost-install +cd /root/sea-vhost-install +bash deploy/install.sh +``` + +### 主控兼本机托管 + +1. 输入 `1`,选择主控兼本机托管。 +2. 选择自动配置 HTTPS,填写管理域名;已有覆盖域名的有效证书会自动识别。也可按提示填写证书路径或跳过站点配置。 +3. 核对摘要,输入 `y`。等待文件安装、服务启动、API 健康检查和 Nginx 检查完成。 +4. 记录终端显示的安装令牌。打开管理地址,按 Web 页面输入令牌。 +5. 在宝塔准备一个空的平台数据库和仅本机访问的账号。Web 安装页填写数据库信息并测试连接。 +6. 填写本机宝塔地址和 API 密钥,完成面板检查;管理域名和主机后缀应为不同分支,例如 `host.ser888.cn` 与 `vhost.ser888.cn`,不能设置成父子域。 +7. 填写管理员邮箱、名称和独立密码,提交安装;页面切换运行模式后登录。 +8. 在用户管理创建用户,在套餐管理准备套餐,在虚拟主机页面选择用户、节点、套餐、环境版本和运行目录开通主机。 +9. 用户可用用户账号管理所属主机,或用系统随机生成的主机名和主机密码仅管理该主机;FTP 与数据库使用各自随机密码。 + +### 独立主控 + +1. 同一安装包、同一命令 `bash deploy/install.sh`,选择 `2`。自动配置管理站点时填写主控自己的管理域名及证书;被控不需要配置管理站点。 +2. 向导检查服务后显示安装令牌。在主控 Web 安装页填写令牌、本机空 MySQL 数据库、管理域名及管理员账号;选择独立主控。该角色没有本机宝塔接入要求,也不创建本机虚拟主机。 +3. 登录后先创建用户和主机套餐,再进入“节点管理”。填写节点名称、可达的 HTTPS/mTLS 入口、该节点默认域名后缀、主机目录、FTP 证书来源域名,保存并下载配对文件。 +4. 主控的本机节点不可启用。新节点在安装和探测完成前保持停用。 + +### 被控 + +1. 被控准备宝塔、Nginx、MySQL、免费 Pure-FTPd。将完整安装包和主控下载的配对文件放到被控的 root 目录。 +2. 运行 `bash deploy/install.sh`,选择 `3`;按提示输入配对文件路径,确认自动探测的本机宝塔地址,隐藏输入 API 密钥。 +3. 核对摘要并确认。向导自动生成、保护本机凭据文件,安装缺失依赖、准备运行目录、配置并启动 `sea-vhost-agent`、`sea-vhost-panel-broker`、`sea-vhost-node`。无需手写凭据 JSON 或手动设置权限。 +4. 回到主控点击“启用”。主控主动连接执行入口,并校验双向 TLS、节点身份和主机身份;校验通过才启用。被控不连接平台数据库,不拉取任务队列,不保存第二份平台资源台账。 +5. 默认执行端口是 9443。NAT 被控仅需要一条可供主控访问的 TCP 透传端口;主控填写公网端口即可。被控无需开放管理站点 443;宝塔 API 使用本机回环地址,由本机 broker 调用。 + +### 创建与使用虚拟主机 + +1. 管理员在“环境配置”选择节点,安装所需免费组件与语言版本;完成状态需是已核验,不能只看提交成功。 +2. 在“套餐管理”创建主机额度;在“用户管理”创建用户;在“虚拟主机”选择用户、节点、套餐、语言版本、运行目录及到期时间。 +3. 系统生成随机主机名、独立登录密码、一个 FTP 账号、一个同名 MySQL 数据库和用户名;FTP 与数据库分别随机密码、加密保存。套餐与到期按每台主机处理。 +4. 用户账号可切换其全部主机;主机名登录只看到该主机。目录位于 `/www/wwwroot/seavHost/vHost/<主机名>`,系统身份没有实际 home,密码锁定、禁止系统登录。 +5. 运行目录按项目结构填写,例如 `/public`、`/dist` 或 `/apps/api`。PHP 上传后访问;Node.js/Python/Go/Java 在“网站”中上传代码或产物,执行部署预检和部署。 +6. 默认入口分别为 Node.js `package.json`、Python `app.py`、Go Linux 二进制 `app`、Java `app.jar`。程序监听系统分配的 `PORT`;Java 按启动参数 `--server.port` 接收端口。依赖与业务配置在该主机范围内处理。 +7. 少量文件走 Web,单文件不超过 20 MiB;大型源码、JAR 和静态资源走 FTP/FTPS。FTP 连接地址直接用该主机默认域名,根目录就是主机根目录,不是网站运行目录。 +8. 有覆盖主机泛域名的有效 FTP 证书时使用显式 FTPS,验证域名并启用加密数据连接。Web 文件删除先进入回收站,释放空间需要清空回收站。 +9. 自定义域名按审核开关处理;待审域名不会提前进入 Nginx。手动证书需覆盖已启用域名且私钥匹配,上传后关闭自动续期;DNS-01 需要用户或管理员分别提供对应域名的 DNS 凭据。 +10. 新增网站共用所在主机资源。删除附加站点保留源码,需再通过文件管理清理;主机密码可由用户重置,旧会话随即注销,不改 FTP 和数据库密码。 + +### 更新与中断恢复 + +- 更新 Sea vHost:在原角色服务器解压新包并再次运行同一入口;向导自动选择既有角色。被控可复用配置和本机面板凭据,取消不会覆盖现有配置。 +- 安装新 SDK 不等于现有项目已升级。Node.js/Java 保留旧 SDK,逐站点迁移;Python 使用新的独立虚拟环境;Go 必须上传由目标 SDK 编译的新产物。 +- PHP 同分支更新属于节点共享环境变更,先保存回退材料,再由面板更新,核对实际版本和扩展,并恢复在跑的独立 FPM;原本停止的网站保持停止。 +- 远程写操作断线后,先在节点执行记录中核对真实资源,填写结果并解除待核验,再完成身份核验;环境任务还需在“环境配置”点击恢复核验。不要仅因请求报错就重复创建资源。 +- 超额后允许通过 Web 删除、清空回收站以恢复容量;数据库超额时保留 SELECT/DELETE/DROP,用于查看与清理自身数据;恢复后站点保持停止,需要显式启动。 +- 到期先停用,3 天宽限后进入回收区,再保留 7 天后清理;回收前将数据库设为仅 SELECT,完成网站+客户 SQL 归档和校验后才删除源资源;备份自实际创建起保留 14 天。集中任务由主控运行。 diff --git a/docs/multi-node-implementation.md b/docs/multi-node-implementation.md new file mode 100644 index 0000000..8159eac --- /dev/null +++ b/docs/multi-node-implementation.md @@ -0,0 +1,37 @@ +# 主控主动连接的多被控改造 + +多被控代码已接入主程序,保留本机节点及独立主控两种入口。安装步骤和验证边界见 [安装说明](multi-node-installation.md)。本文保留多节点改造阶段的设计与验收边界;截至 2026-10-29,36 环境已部署包含这些功能的单机版本,仍使用本机节点。 + +## 已确认约束 + +- 单主控调度并主动通过 HTTPS 连接被控;没有被控拉取队列或回连注册。 +- 用户、套餐、主机归属、配额、任务和审计保存在主控 MySQL,不增加 Redis。 +- 被控无 Sea vHost 业务数据库或持久任务库;仅保留本机运行配置、必要身份材料、网站数据和原生宝塔状态。 +- 每台虚拟主机独立套餐与到期状态,不再按用户累计资源限额。 +- 每节点独立默认域名后缀、FTP 证书来源、根目录和接入地址。 +- root 隔离代理仅使用本机 Socket;网络入口非 root、双向 TLS、固定操作白名单。 +- 远程节点资源登记表也在主控;被控通过请求快照和真实资源校验操作,不写第二份平台台账。 +- 超时或响应丢失是结果不确定,不得把未知结果当失败自动重试破坏性操作。 +- 主控失联不影响已运行网站,但集中巡检、到期与续期任务暂停。 + +## 已实现 + +1. 节点模型、主机级套餐、配额、到期状态,以及每节点独立维护锁。 +2. 独立节点 mTLS 身份、无状态执行入口、主控 RPC 路由;节点不接收任意 shell 或任意绝对文件目录。 +3. 文件及部署检查远程化;Web 文件上限 20 MiB,临时文件提交后才替换目标文件。 +4. 节点管理、管理员开通/迁移主机、主机套餐与到期设置、节点环境和 IP 池界面。 +5. 独立主控/被控安装脚本,已有单机数据迁入本机节点。远程资源快照及待核验执行记录保存在主控 MySQL。 +6. 统一中文交互安装入口:选择角色、自动识别本机宝塔地址、隐藏输入密钥、自动启动服务;管理站点可复用证书生成 Nginx 配置。更新时可复用被控配置,原自动化脚本参数继续保留。 + +## 已验证 + +- 后端回归及本地两个 HTTPS/mTLS 执行端:节点身份隔离、站点编号重号、目录穿越拒绝、未登记资源拒绝、重复请求拦截,以及文件按节点执行。 +- 真实一次性 MySQL 库:完整迁移及重复启动、主机独立配额、用户用量汇总、各节点独立任务锁和到期状态。旧版有数据迁移另行验证了自定义目录、默认域名、已停止状态、到期信息及每主机完整进程额度。 +- 主控 MySQL 与两个 mTLS 执行端集成:站点、FTP、数据库、文件和健康检查路由,资源快照回写,待核验主机不阻塞同节点其他主机、节点级维护等待核验,以及管理员核验后恢复。 +- Chrome 页面交互:新增节点、登记待核验任务的处理结果、选择被控安装环境、按用户/节点/套餐开通主机;桌面及手机宽度,控制台无相关错误。前端单元测试共 25 项通过。 +- 安装脚本通过 Bash 语法检查。另在真实 Debian/宝塔测试机完成三角色安装、mTLS 接入、PHP/Node.js/Python/Go/Java 真实创建与运行、FTPS/MySQL、主机配额、域名审核、站点接管和端口配置;这是同一物理服务器的分离进程验收,跨服务器链路尚未覆盖。 +- 交互安装的 19 项测试通过:取消、角色保护、缺失包检测、回环地址约束、凭据文件清理、被控更新时保留读取权限、服务稳定就绪、API 重试就绪,以及 Nginx 检查/重载失败回滚。单元测试不执行 apt 或真实安装系统服务;真实安装另由终端交互完成。 + +改造阶段保留单机部署作为迁移入口;当时未应用正式库的描述属于历史状态。36 的 2026-10-29 单机验收版本已应用 001–027 迁移。测试机原部署已经备份;本轮一次性资源和保留的验收夹具以 [实机验收记录](installation-test-2026-10-25.md) 为准,不能把测试夹具当成正式安装结构。 + +回收备份自实际创建起保留 14 天,避免主控长时间离线后补做清理时,新备份因历史到期时间已经过去而立即被删除。 diff --git a/docs/multi-node-installation.md b/docs/multi-node-installation.md new file mode 100644 index 0000000..1090d4b --- /dev/null +++ b/docs/multi-node-installation.md @@ -0,0 +1,86 @@ +# Sea vHost 多被控安装 + +## 推荐:统一交互安装 + +以 root 解压完整安装包,进入解压目录,在终端运行: + +```sh +bash deploy/install.sh +``` + +按中文提示选择「主控兼本机托管」「独立主控」或「被控节点」。回车使用默认值,Ctrl+C 取消。密钥输入隐藏,已有配置保留,不自动转换现有安装角色。需要 Debian amd64、systemd、Python 3.8+ 和 OpenSSL;兼本机托管及被控需要先装好宝塔、Nginx、MySQL 和免费 Pure-FTPd。 + +- **主控**:可自动识别覆盖管理域名的已有证书,生成 Nginx HTTPS 与 `/api/` 反代配置并启动服务;首次在 Web 安装页填写数据库、管理员及本机宝塔信息。安装令牌直接在终端显示。已有其他站点占用域名时不会覆盖;没有 Nginx 或证书时可跳过站点配置。 +- **被控**:先在主控新增节点,下载配对文件并放到被控 `/root/`。运行同一命令,选择「被控节点」,按提示选择配对文件、确认自动识别的本机宝塔地址并输入 API 密钥。不必手写凭据 JSON、手动 chmod 或启动服务。完成后在主控点击「启用」即自动进行连接探测,无需另外执行一次「探测」。 +- **更新/重跑**:再次运行同一向导,自动预选现有角色;被控可复用已保存的配对文件和宝塔凭据。重装不会清空平台数据库或主机文件;Nginx 配置检查/重载失败会恢复旧配置。 + +也可预选角色,例如 `bash deploy/install.sh --interactive --role node`。下面的脚本参数入口保留给自动化与自定义部署;不需要逐个手工执行。 + +## 安装角色 + +| 角色 | 入口 | 运行内容 | +| --- | --- | --- | +| 独立主控 | `bash deploy/install-controller.sh --non-interactive` | Web/API、MySQL 平台数据、调度及审计;不要求本机宝塔 | +| 主控与本机托管 | `bash deploy/install.sh --non-interactive` | 保留现有单机安装入口,本机显示为节点 1 | +| 被控 | `bash deploy/install-node.sh 配对文件 本机宝塔凭据文件` | mTLS 执行入口、本机宝塔代理、隔离代理;没有平台数据库或平台任务队列 | + +安装包统一包含四个 Linux amd64 程序。当前目标为 Debian、宝塔和 Nginx。被控需准备本机 MySQL、Pure-FTPd 和对应语言环境;语言环境可继续在主控的“环境配置”页按节点安装和维护。 + +## 独立主控 + +1. 需要手工配置时,解压安装包,在解压目录运行 `bash deploy/install-controller.sh --non-interactive`;推荐直接使用上方统一向导。 +2. 为 `/opt/sea-vhost/web` 配置管理域名,将 `/api/` 反代至 `127.0.0.1:8080`。 +3. 使用脚本生成的安装令牌打开安装页,选择“独立主控”,填写本机 MySQL 信息、管理域名和管理员账号。 +4. 独立主控的本机托管节点不可启用;添加被控后即可开通主机。 + +## 添加被控 + +1. 在“节点管理”新增节点,填写 HTTPS 执行入口、默认域名后缀、主机根目录、FTP 证书来源域名。 +2. 点击“下载配对文件”。生成或重新签发配对材料会先停用该节点;主控的客户端身份加密保存在主控 MySQL,下载文件仅包含被控所需的服务端身份与信任材料。 +3. 将配对文件放到被控,例如 `/root/sea-node-2.json`。另建 `/root/local-panel-credentials.json`: + +```json +{ + "version": 1, + "url": "https://127.0.0.1:8888", + "api_key": "填写该被控的本机宝塔 API 密钥", + "tls_insecure": true +} +``` + +4. 将两个文件设置为 root 所有、权限 `0600`,运行: + +```sh +chmod 600 /root/sea-node-2.json /root/local-panel-credentials.json +bash deploy/install-node.sh /root/sea-node-2.json /root/local-panel-credentials.json +``` + +5. 执行入口默认监听 `9443`。主控填写的地址须直达或通过 TCP 透传抵达该入口;普通 HTTPS 反代终止 TLS 会丢失客户端身份,无法通过验证。外部端口映射可与监听端口不同。 +6. 回到主控点击“启用”,自动进行探测与连接。该节点的站点、文件、环境、数据库和 FTP 操作由主控主动发起。 + +宝塔凭据只保留在被控本机能力代理中,不上传到主控。示例中的自签名选项仅针对本机回环宝塔接口;主控到被控始终校验配对 CA、节点身份及客户端证书。执行通道证书与网站/FTP 证书相互独立。 + +## 主机及套餐 + +- 管理员在“虚拟主机”选择用户、节点及套餐开通主机;用户管理已有主机,可在一台主机内增加网站。 +- 配额、到期和超额停用按主机分别处理;用户页的用量是汇总展示。多网站共用所在主机的资源限额。 +- 默认域名取自所在节点。每台主机的 FTP 地址使用已分配的主机子域名;网站运行目录可独立选择。 +- 到期停用,宽限 3 天后进入回收区,保留 7 天后清理;删除后的备份保留 14 天。主控每分钟推进到期任务。续期后停止的网站需要手动启动。 +- 回收归档包含网站文件、客户 MySQL SQL 和摘要清单;备份失败或校验不完整时保留源资源。数据库超额会撤销原生写权限并断开旧连接,允许查询和清理,额度恢复后恢复写入。 +- 套餐支持 `bandwidthMbps`,0 为不限速;HTTP 每请求、FTP 每会话限速,月流量合并 HTTP 响应与 FTP 双向有效负载。代理使用本机 MySQL socket 与宝塔核心凭据读取,不新增 MySQL 公网入口。 +- 停用节点会暂停该节点的管理与调度,已运行的网站继续运行。主控离线时也不会停止网站,但巡检、到期和续期等集中任务暂停。 +- 读取已保存凭据不要求被控在线;FTP 连接方式显示最近检测结果,未完成检测时显示待核验。证书同步由主控按节点定期执行。 + +## 结果待核验 + +远程写请求断线、响应丢失或主控执行期间重启,不能证明操作未发生。此类请求记录为“待核验”:单台主机的操作只阻止该主机继续变更,节点级操作才阻止整个节点。其他主机及节点继续工作;涉及整个节点的环境维护须先清除该节点的待核验记录。管理员在节点“执行记录”中核对本机实际资源后登记结果,再进行身份核验;环境迁移任务仍需在环境配置中恢复核验。系统不会自动重发不确定的破坏性操作。 + +## 升级及验证边界 + +现有单机仍使用节点 1;已有主机继承原用户套餐及到期时间,新主机单独配置。不支持自动跨节点迁移或故障转移。更换安装角色不应直接覆盖已有主控配置;被控安装器会拒绝检测到的平台数据库配置或旧资源登记表。 + +数据库迁移 `012_control_nodes.sql` 改变配额与站点编号的含义。升级前保留应用数据库和当前程序的完整备份,回退时两者同步恢复。 + +已通过真实一次性 MySQL、两个模拟适配器 mTLS 执行端的集成测试,并在 Debian + 宝塔 12.0.0 测试机真实完成三种角色安装、原地升级、被控更新/取消、主控主动 mTLS 接入及五类语言应用。主控和被控在一台物理测试机上采用独立服务、UID、配置和数据库职责,尚未完成两台独立服务器的公网链路验收。这属于 10-25 测试机验收记录;后续 36 单机版本已部署并应用 001–027 迁移。详细实机结果、限制和操作流程见 [2026-10-25 验收记录](installation-test-2026-10-25.md)。 + +交互向导另有 19 项独立测试覆盖取消、角色保护、凭据临时文件清理、自动启动、API 就绪等待和 Nginx 回滚;单元测试不执行 apt 或真实安装系统服务,真实安装结果另列于验收记录。可运行 `python3 -m unittest discover -s deploy -p test_install_wizard.py -v`。安装包不包含 Python 字节码缓存。 diff --git a/docs/project-status-2026-10-29.md b/docs/project-status-2026-10-29.md new file mode 100644 index 0000000..13fb9f0 --- /dev/null +++ b/docs/project-status-2026-10-29.md @@ -0,0 +1,89 @@ +# Sea vHost 项目状态整理(2026-10-29) + +本文汇总源码、操作说明与已有验收记录,不代表当天又重新执行了全部实机测试。当前开发与生产测试入口为 36 机器的 `https://host.ser888.cn/`;202 测试机的端口映射、临时域名及测试夹具属于历史环境。 + +## 当前结论 + +单机自用所需的用户、主机、网站、文件、FTP、MySQL、证书和权限主流程已具备,已有正常网页操作和实机验收记录。最近一轮完成了界面整理、用户删除边界、主机环境授权、环境任务队列及真实 HTTP-01 签发修复。 + +这不等于全部附加服务和异常恢复场景均已完成公网联合验收。彩虹 DNS 在用户修复上游配置后已恢复联调,真实 TXT 创建/清理及 DNS-01 签发通过;外部服务的覆盖范围仍分项记录。 + +## 功能与证据 + +| 范围 | 当前行为 | 验证与边界 | +| --- | --- | --- | +| 安装 | 中文交互安装、单机/独立主控/被控角色、Web 填写 MySQL 和必要参数 | 有真实 Debian 安装及一次性数据库验证;不扩展其他发行版、面板版本或 ARM | +| 用户 | 创建、查看、编辑、启停、软删除;不开放密码注册,SSO 建号另设默认关闭的开关 | 真实网页创建/编辑/删除已有记录;删除前必须逐一解绑或转移所有主机,回收中也不例外 | +| 主机 | 创建、配置、启停、回收、恢复;独立主机登录;可选绑定用户 | 一用户多主机、无用户归属主机、权限隔离已验证;主机名和 Linux 身份不随显示名称变化 | +| 批量 | 数量生成、JSON 导入/预览/提交、凭据结果导出;归属、套餐、到期、启停等管理 | 后台逐条记录结果,区分失败与待核验;不支持 CSV | +| 套餐 | 八项资源配置、复制、未使用套餐删除、主机换套餐 | 已引用套餐不直接修改;默认或被历史账号引用的套餐不能删除 | +| 网站 | 每主机至少一个主站,可在子目录新增附加网站;独立域名和状态 | 五种语言正常创建、部署、访问、启停、删除见 10-26 Web 报告;删除附加网站保留源文件 | +| 运行目录 | 主站默认 `/`,允许 `/public` 等主机内目录 | 已实际切换目录并验证访问;禁止越界和符号链接目录 | +| 运行环境 | PHP、Node.js、Python、Go、Java;同语言可换已安装版本,额外授权后跨语言 | 10-29 实测 PHP 版本切换、Node.js 部署及切回 PHP;先停站并保留文件、数据库和 FTP | +| 环境维护 | 从环境配置页提交安装/更新;持久队列、同节点串行、重复拒绝、恢复核验 | 队列及故障状态有 MySQL 集成测试;本轮没有实际升级全部组件及验证每条补丁回退链 | +| 网站设置 | 首页、伪静态、重定向、HTTPS、错误页、维护模式;配置校验失败回滚 | 功能已实现;持续验收需覆盖组合配置,而非仅检查按钮存在 | +| 文件 | 上传/下载、编辑、目录、复制/移动、ZIP、回收站 | 20 MiB 上传、下载摘要、文件编辑和回收操作已有网页实测;删除进入回收站后仍占用磁盘 | +| FTP | 默认独立账号、基本启停、凭据查看/随机重置、主机域名连接 | 本机显式 FTPS 上传/下载及 Web 文件互操作已验证;公网主动/被动连接不在已通过范围 | +| MySQL | 主机同名数据库/用户、独立随机密码、权限限制、超额写保护 | 真实写读及跨主机拒绝已有记录;phpMyAdmin 使用对应主机账号,代理单次请求/响应限制 2 MiB | +| 证书 | HTTP-01、DNS-01、上传 PEM、关闭及续期控制 | HTTP-01 真实签发/安装、手动接管、原生订单续期取消已通过;彩虹 DNS 的 TXT 创建/清理及真实 DNS-01 签发已通过,其他服务商外部联调另列 | +| 操作日志 | 管理员筛选、分页、条数、筛选结果 JSON 导出;客户仅对应用户/主机普通操作 | 管理员筛选导出及客户日志过滤已实测;管理员直接和代入操作只进入管理员审计 | +| 网站日志 | 访问、Nginx 错误、运行日志、PHP-FPM,关键词与 JSON 下载 | 与操作审计分开,不将网站访问日志作为账号操作审计 | +| 管理员代入 | 保留管理员会话,限时代入用户/主机,可按目标权限读写并返回 | 实际进入、文件操作与返回已验证;不能在代入状态调用管理员或账号安全接口 | +| 用户计划任务 | 宝塔每分钟触发主控,由主控分发本站脚本/URL,按主机 UID 执行 | 独立主机账号无入口/权限;10 条/用户、5 分钟超时、禁止重叠;归属变更暂停关联任务 | +| 资源与到期 | 主机级磁盘、数据库、月流量、进程限制;限速、停用、恢复、备份清理 | 已有软配额与数据库写保护实测;到期 3 天宽限、回收后保留 7 天、备份自生成起保留 14 天 | +| 资源图表 | CPU、内存、进程、磁盘、数据库、流量历史,保留 30 天 | 新主机不会补出过去 30 天数据;历史保留配置不等于已做满 30 天稳定性观察 | +| 节点与 IP | 节点 CRUD、按节点默认域名/IP 池,主控主动 mTLS 调用被控 | 本机与两个执行端集成已验证;两台独立宝塔服务器的跨机联合验收尚未完成 | +| 管理端 API | 限权限/有效期密钥、幂等写入、异步任务、凭据权限、签名回调/重试 | 已实现;不等于已与真实财务站完成业务联合验收;已吊销密钥不显示在有效列表 | +| SMTP / SSO | 管理员通知;OIDC 前台绑定、可选创建普通用户,管理员/用户可分别关闭密码;主机账号仅密码 | SSO 真实 MySQL+本地 HTTPS 签名服务集成通过;真实邮件和外部身份提供商联调尚未完成,见 [最新记录](sso-ui-acceptance.md) | + +## 正常使用流程 + +1. 管理员在“环境配置”确认所需版本,在“套餐管理”准备主机额度,在“用户管理”开通用户(也可不绑定用户)。 +2. 在“虚拟主机”开通主机,选择节点、套餐、环境、运行目录、到期时间及归属;批量场景使用 JSON 预览后提交。 +3. 使用用户账号选择名下主机,或直接用独立主机账号登录。管理员可从列表快捷进入,页面提示当前主机/用户并提供返回按钮。 +4. 从主机详情打开“网站管理”,上传程序。PHP 检查首页;其他语言依次检查入口、设置启动参数/环境变量、执行部署,再验证实际访问。 +5. 默认域名按节点分配;自定义域名按开关审核。站点运行且解析就绪后使用 HTTP-01,也可上传自有证书。DNS-01 可使用已验证的彩虹凭据;其他服务商按各自实际联调结果使用。 +6. 使用 Web 处理少量文件,FTP 处理大文件;通过 phpMyAdmin 管理主机数据库。查看资源图表、网站日志和操作日志定位日常问题。 +7. 停用或到期不会自动删除全部文件。需要删除用户时先逐台解绑/转移主机;手动回收主机可在保留期内恢复,恢复后须显式启动服务。 + +## 当前仍需区分的边界 + +- **软配额**:Web 写入有前置检查;站点程序和 FTP 的超额由巡检发现后停用、限制写入。不能描述成所有写入均由内核即时拒绝。 +- **身份隔离**:主机独立 UID、受管目录和控制接口白名单已实现;未使用 Docker,也不把它称为完整内核沙箱。 +- **带宽**:HTTP 按连接/请求限速,FTP 在账号配置中设置并按原生会话执行;不是多连接共享一个整台主机的总速率。 +- **备份恢复**:已有文件与 SQL 归档、校验及还原验证;尚无从归档一键重建平台主机记录的完整恢复界面。 +- **独立 IP**:地址池和分配能力已实现,尚未完成真实第二个公网 IP 的数据面联合验收。 +- **跨机部署**:不把同机分离进程或本地 mTLS 集成测试写成两台独立服务器实测。 +- **长周期任务**:提前续期、30 天图表、7/14 天保留均有配置或测试逻辑;受控到期场景不代替相同自然时长的稳定性观察。 + +## 后续工作顺序 + +1. 继续非 DNS 常用流程的组合回归:网站设置与日志、文件/ZIP/回收站、启动参数及加密环境变量、phpMyAdmin、用户计划任务和批量操作。 +2. 分项补环境安装/补丁升级的实际队列、中断及回退验证,避免将一次“检查更新”当作整套升级通过。 +3. 单独处理备份恢复界面的产品缺口;现有管理员手动还原能力继续按操作说明使用。 +4. SMTP、SSO、真实财务站、第二公网 IP 与跨服务器场景按需要分开验收,不扩大当前单机使用范围。 +5. 彩虹 DNS 的首次失败保留为历史记录;修复后的真实 TXT/DNS-01 闭环已完成,其他 DNS 服务商仍按实际票据另行联调。 + +以上为整理后的工作顺序,不表示这些未覆盖项已经完成或本次已执行新的部署。 + +## 记录索引 + +- [日常操作及管理端 API](hosting-operations.md) +- [用户、主机、节点的管理与删除边界](resource-management.md) +- [10-29 界面、环境切换和 HTTP-01 实测](ui-acceptance-2026-10-29.md) +- [10-26 五类语言、账号安全和完整 Web 流程](web-acceptance-2026-10-26.md) +- [10-25 交互安装与早期测试机验收](installation-test-2026-10-25.md) +- [多节点实现及验收范围](multi-node-implementation.md) +- [彩虹 DNS 真实联调结果](dns-acceptance-2026-10-29.md) + +此前界面发布包 SHA-256 为 `7d975795a6e74d0f9d915ab3c6bb212f32af3d17a308e3d9e86c0e3c1edb9e21`,当时数据库迁移为 001–027;该摘要保留为历史记录。SSO 后续迁移至 028,见 [SSO 与界面验收](sso-ui-acceptance.md)。 + +## 10-30 维护范围修正 + +已部署修复:组件安装及 PHP 补丁更新不再获取整个节点的业务写锁,组件任务中断待核验也不拦截主机管理;站点迁移与环境切换仅保护所属主机。PHP 补丁完成后的独立 FPM 刷新只短暂保护对应主机,不覆盖宝塔编译安装阶段。 + +Go 全包测试和 36 上独立临时 MySQL 的 CRUD 集成测试通过,新增场景验证运行中/中断的组件任务不影响文件保存,并让实际后台工作线程停留在模拟宝塔忙碌接口,确认同一服务实例仍可正常处理主机写入;对应主机的站点切换冲突仍返回 423。临时数据库已清理。 + +部署后核对 API、隔离代理及面板代理服务运行正常、Nginx 校验通过、体验主机 HTTPS 返回 200、主机文件列表可读,原有 9 个账号及 2 台主机保持不变。PHP 7.4 实际为 7.4.34,原任务 #37 已完成。清理本轮 14 个临时上传文件及分片;没有为验证此修复再次触发真实 PHP 更新。 + +本轮发布包 SHA-256:`cbabfe10b7a7ed280c6b296314e3389d892074a7dc95fff0b0a0683cb2d4966b`;部署 API SHA-256:`3ce7a8bab1e268b067e52bb5a88962e9866445dc07bcd9bc3a9eb869eb914a85`。前端及其他服务二进制保持原版,本轮没有新增数据库迁移。 diff --git a/docs/public-vulnerability-test-2026-10-19.md b/docs/public-vulnerability-test-2026-10-19.md new file mode 100644 index 0000000..72675ba --- /dev/null +++ b/docs/public-vulnerability-test-2026-10-19.md @@ -0,0 +1,43 @@ +# Sea vHost 公开入口漏洞探针记录(2026-10-19) + +> 历史验收记录:环境、版本、数量及结论仅适用于文中所列日期,不代表当前服务重新实测。当前状态见 [项目状态整理](project-status-2026-10-29.md)。 + +## 方法与边界 + +- Sea vHost 控制台:`http://202.189.40.57:10094/`(测试端口转发)。 +- aaPanel:测试机公开 TLS 入口;报告不记录 API 密钥或面板安全入口。 +- 探针 ID:`53a2f9b023a2b835`。 +- 全部请求均未登录;未上传文件、未发送 WebSocket 消息、未提交命令、未爆破密码、未执行拒绝服务测试。 +- WebSocket 探针只发送带恶意 `Origin` 的标准升级握手,收到 101 后立即断开。 + +## 结果 + +共记录 46 项通过、1 项警告、6 项失败。 + +Sea vHost 控制台未发现敏感文件/备份/调试入口泄露、`/etc/passwd` 路径穿越、危险 HTTP 方法放行、未登录 API、宽松 CORS、Host/转发 Host 反射、开放重定向、反射型 XSS 或 JavaScript source map 泄露。aaPanel 的站点、数据库、FTP、计划任务和系统信息基础接口在缺少签名或使用伪造签名时没有返回特权数据;常见面板敏感路径也未命中内容特征。 + +唯一普通警告是 Sea vHost 测试入口使用明文 HTTP。这是当前端口转发测试环境的已知条件,不得复制到正式部署。 + +以下 aaPanel 路径在无 Cookie、恶意跨源 `Origin` 下返回 `101 Switching Protocols`: + +- `/sock_shell` +- `/webssh` +- `/ws_panel` +- `/ws_home` +- `/ws_project` +- `/ws_model` + +`/workorder_client` 与本轮检查的 `/v2/*` 变体没有升级。由于未发送任何 WebSocket 消息,本结果只证明服务在握手阶段未拒绝未登录恶意 Origin,不能单独证明身份校验可绕过或远程命令执行。但这些路径包含终端和面板管理能力,且其行为与公开披露的 aaPanel 跨站 WebSocket 风险特征一致,应作为高风险暴露处理。 + +## 处理要求 + +1. 正式部署让 Sea vHost broker 仅通过回环访问 aaPanel,并在云安全组/主机防火墙阻止不可信来源连接面板端口。 +2. 远程面板管理使用 VPN、SSH 隧道或固定源 IP 白名单;不把“隐藏安全入口”当作访问控制。 +3. 不需要面板 Web 终端时,在受控反向代理中拒绝上述 WebSocket 路径;示例为 `deploy/nginx/aa-panel-websocket-deny.conf.example`。必须同时封锁直连后端端口,防止绕过代理。 +4. aaPanel 更新后重新运行探针。只有恶意 Origin 的握手在认证前被 401/403/404 拒绝,才可以关闭该上线阻断项。 + +公开参考: + +- aaPanel 官方仓库的安全页面目前没有发布 GitHub Security Advisory,并要求通过指定邮箱报告安全问题:。 +- 2026 年第三方披露描述了相同 WebSocket 路径的跨站握手与认证时序风险;该披露尚未分配 CVE,因此本报告将其作为待厂商确认的公开研究,而不是已由厂商确认的漏洞:。 +- CVE-2026-29859 涉及另一个版本的任意文件上传。为避免改变服务器状态,本轮没有上传利用文件,也不根据面板显示版本直接推断是否受影响:。 diff --git a/docs/real-panel-acceptance.md b/docs/real-panel-acceptance.md new file mode 100644 index 0000000..35287ae --- /dev/null +++ b/docs/real-panel-acceptance.md @@ -0,0 +1,38 @@ +# 实机联调与验收清单 + +当前状态索引见 [项目状态整理](project-status-2026-10-29.md),最新界面及 HTTP-01 回归见 [2026-10-29 验收报告](ui-acceptance-2026-10-29.md)。五类语言正常生命周期以 [2026-10-26 Web 验收报告](web-acceptance-2026-10-26.md) 为准:已在 36 环境通过正常 Web 完成 PHP、Node.js、Python、Go、Java 创建/部署/启停/清理,Node.js 与 Python 的早期阻断已修复。历史故障注入、配额等结果另见 `feature-test-report-2026-10-20.md`;下面保留持续验收清单,不代表每项都在最新一轮重跑。 + +## 面板兼容性 + +1. 首次安装页面的数据库测试、服务器组件测试必须通过;`systemctl status sea-vhost-agent sea-vhost-panel-broker sea-vhost-api` 均为 active,安装完成后刷新应进入登录页而不是再次出现向导。 +2. 确认 `www` 不属于任何 Sea vHost 控制组、broker 不属于 `sea-vhost-agent-control`,Web API 配置不含宝塔密钥;尝试让 broker 删除一个面板中手工创建的测试站点,必须以“outside managed set”拒绝且站点不受影响。 +3. 记录宝塔版本、Debian 版本以及 Nginx、MySQL、Pure-FTPd、PHP、Node、Python、Go、Java 插件版本。 + 同时确认服务器未开启专业版、企业版或临时试用授权;否则不能据此判定语言项目属于免费能力。 +4. 使用只读系统接口确认 API 签名、TLS 证书和回环白名单。 +5. 创建一个 PHP 测试项目,确认 `AddSite` 后目录属主/主机独立组和 project ID 被隔离代理恢复、`open_basedir`、私有临时目录、FTP、MySQL、反向删除和 ACME 流程;PHP-FPM master/worker 必须是该主机 UID/GID,permitted/effective/ambient capabilities 必须为空,且不得连接 Sea vHost 控制 Socket。 +6. 已确认 12.0.0 中 Node/Python/Go 位于“网站”的项目路由,动态版本清单可读且生命周期适配器已经实现。最新一轮五类语言的 Web 正常生命周期通过;异常回滚等独立故障场景按相应报告单独核对。 +7. Java 创建、列表、启停和删除统一使用 `/mod/java/project/*` 新模型,并验证 `run_user` 为该主机的随机 Linux 身份;不得混用旧 `/project/java/*` 生命周期接口。 +8. 安装页分别模拟一种语言未安装和一种项目路由返回错误;其他语言仍应显示版本,安装过程不得失败。尝试请求未列入白名单的付费/未知路由,必须在 panel broker 发出网络请求前失败。 +9. 创建站点后确认宝塔站点配置包含 `extension//*.conf`,Sea vHost 安全文件生效且 `nginx -t` 通过。注入一条无效配置,必须恢复旧文件且不能留下不可加载的 Nginx 配置。 +10. 开启域名审核,为主站和附加网站各提交一个自定义域名;审核前宝塔不得出现域名,管理员批准后只能写入目标受管站点并触发证书申请,拒绝项不得写入面板。关闭审核后重复测试,并并发提交同一域名,必须只有一个请求成功。 +11. 从非服务器网络运行 `deploy/public-vulnerability-smoke.mjs`。正式环境的 Sea vHost 与 aaPanel 均必须使用可信 TLS;aaPanel 特权 WebSocket 对无 Cookie、恶意 Origin 的升级请求不得返回 101,面板后端端口必须在反向代理、VPN 或 SSH 隧道之外不可达。 + +## 隔离测试 + +1. 租户 A 的 Web 文件管理器、FTP 与 PHP/Node/Python/Go/Java 真实进程尝试读取或写入租户 B 的路径必须失败;跨主机读取成功是上线阻断项。两侧进程还必须无法读取宝塔 API 密钥、Sea vHost 配置或连接控制 Socket。软配额不得描述为进程沙箱。 +2. FTP 账号必须由 Pure-FTPd chroot 到对应随机主机目录,底层 UID/GID 必须映射为该主机身份;该账号不得通过软链接、绝对路径或协议命令越出其根目录。 +3. 上传符号链接、`../`、绝对路径和混合斜杠,必须被拒绝。 +4. Web 上传在写入前复算租户总用量并拒绝超额内容;运行时或 FTP 制造超额后,计量器须在一个检测周期内更新用量、标记 `quota_suspended`、停站/FTP/进程并撤销主机身份对目录的写权限。此时 Web 端仍应能下载和删除数据,但新增、启动、部署、绑域名和证书安装必须返回 `423 quota_suspended`;清理后只恢复受管 ACL 和“已停止”状态,不得自动启动站点或自动删除文件。 +5. MySQL 用户只能连接自己的数据库且只允许本机来源。 +6. 运行 `deploy/panel-canary-verify.mjs` 并记录随机检查 ID:公开基准文件必须能读取;隐藏目录、`.env`、依赖清单、运行私有目录和跨属主符号链接必须返回 403/404 且正文不含对应标记;`www`、`nobody`、无关主机身份、控制面身份和无令牌内部 Socket 对各私有标记的读取必须失败。保留的 root-only 清单不得被 Web、FTP 或租户进程读取。 + +## 配额与生命周期 + +1. 验证磁盘、数据库、月流量和进程数量的计量周期与自动暂停策略。 +2. 创建流程在站点、FTP、数据库、反代和 SSL 每个阶段分别注入失败,确认逆序回滚。 +3. HTTP-01 自动申请必须确认同步返回格式的 `apply_cert_api → 校验证书/私钥/域名 → SetSSL` 全链路完成;若面板返回旧式订单编号,则核对 `get_order_find(valid) → SetCertToSite`。两种模式都须验证站点实际监听 HTTPS,且本地状态为 `active`。DNS-01 需分别配置平台根域与测试租户区域凭据:先执行凭据测试,确认随机 `_svh-check-*` TXT 被创建并按返回记录 ID 删除、测试状态持久化且一分钟冷却生效;再确认同一证书的两个 ACME TXT 被正确路由、解析可见后验证、按各自记录 ID 清理并经 `SetSSL` 落站。删除租户凭据后续期应失败且不得回退到其他租户或平台密钥。另验证提前 30 天续期、失败退避、五分钟冷却,以及签发进程在开始回写后被终止时数据库仍保留六小时后的兜底重试时间;验证域名审核开关、套餐暂停;上传手动证书后确认自动续签关闭,并以错域名、过期证书、CA 证书、加密私钥和不匹配私钥验证前置拒绝且日志无密钥。 +4. 分别从创建表单和后续绑定接口尝试根域、根域子域、控制台域名、独立的 FTP 证书来源域名及其子域,均必须在调用宝塔前拒绝;并发提交使每站域名达到 100 条时,只能有不超过上限的请求成功。FTP 凭据应返回项目默认域名,并用覆盖租户泛域名的证书完成显式 FTPS 主机名校验。遗留超限数据不得进入 HTTP-01、DNS-01 或手动证书安装。 +5. 备份 MySQL 与 Sea vHost 登记的 `/www/wwwroot/seavHost/vHost/sv<10位随机十六进制>` 主机目录,完成一次异机恢复演练;不得把整个 `/www/wwwroot` 中非受管站点视为 Sea vHost 资源。 +6. 分别把运行目录设置为 `/`、`/public`、`/dist` 与嵌套目录 `/apps/web/public`,确认宝塔 Nginx 生效、FTP 根目录不变;再提交 `../`、反斜杠、双斜杠及符号链接目录,确认在到达宝塔 API 前被拒绝。 + +本清单是持续验收项目,不能把列出的检查项一律当作已通过。已完成结果及尚未覆盖的跨服务器、真实外部服务场景,以对应日期的验收报告为准。 diff --git a/docs/resource-management.md b/docs/resource-management.md new file mode 100644 index 0000000..714afe4 --- /dev/null +++ b/docs/resource-management.md @@ -0,0 +1,42 @@ +# 主机、用户与节点管理 + +管理员在“虚拟主机”“用户管理”“节点管理”列表中选择“详情 / 编辑”。这些接口仅允许管理员调用;代入用户或主机后按目标账号权限处理,不能调用管理员接口。 + +## 主机 + +- 可以创建、查询、修改显示名称;套餐、到期时间、归属和网络使用各自的配置入口。主机名、独立 Linux 身份和物理目录不会随显示名称变化。 +- 手动回收需输入完整主机名并再次确认。系统先记录回收状态,撤销主机会话、暂停用户计划任务,禁止普通续期或归属操作绕过回收状态;随后停止 PHP 池、网站、进程、FTP,限制数据库写入并断开现有 FTP/MySQL 连接。 +- 停用失败会保留回收状态及错误信息;管理员可以重试,调度器也会重试。重复回收不会延长保留期限。 +- 回收后保留 7 天,可显式恢复;恢复后网站、FTP 和用户计划任务保持停止或暂停,需手动启用。已到期的主机恢复后仍须续期。 +- 期满后由调度器验证文件和数据库备份,再清理资源。新备份自实际生成时间起保留至少 14 天。不能通过管理员删除按钮立即物理清理数据。 + +## 用户 + +可以创建、查询、编辑用户名称、联系人和登录邮箱,以及启停、删除用户。修改登录邮箱会撤销已有用户会话。删除前必须解绑或转移所有主机,包括回收中的主机,并处理未完成的归属任务。删除后停止计划任务、撤销会话并保留内部审计关联;历史用户标识和邮箱保持占用,避免旧导入或外部引用被另一用户接管。批量启用及旧到期接口不能重新激活已删除用户。 + +## 节点 + +可以新增、查询、修改节点名称、默认域名后缀和 FTP 证书来源。域名后缀只影响后续创建的主机。修改远程执行入口或主机根目录前,必须停用节点并清空主机、备份、未完成任务和宝塔资源登记。本机入口及根目录由安装配置管理。 + +本机节点禁止删除。远程节点仅在停用且没有主机、有效备份、未确认控制任务、环境维护或待执行批次时可以删除。删除会清除主控保存的连接凭据和空闲 IP 配置;保留节点编号、执行入口与历史审计,不卸载远程服务。历史执行入口不能用于另一个节点。 + +## 管理接口 + +所有路径以 `/api/v1/admin` 开头,遵循现有会话鉴权、来源校验和管理员权限检查。这里的交互接口不自动扩大财务系统对接密钥的权限。 + +| 资源 | 查询 | 修改 | 删除或回收 | 恢复 | +|---|---|---|---|---| +| 用户 | `GET /tenants/{id}` | `PUT /tenants/{id}`,`name`、`displayName`、`email` | `DELETE /tenants/{id}`,`confirmation` 为用户标识 | 不提供 | +| 主机 | `GET /projects/{id}` | `PUT /projects/{id}`,`name`、可选 `allowRuntimeChange` | `DELETE /projects/{id}`,`confirmation` 为主机名 | `POST /projects/{id}/restore` | +| 节点 | `GET /nodes/{nodeID}` | `PATCH /nodes/{nodeID}`,完整节点元数据;启停沿用 `PUT` | `DELETE /nodes/{nodeID}`,`confirmation` 为节点名称 | 不提供 | + +资源 CRUD 的回收与删除标记由 `023_resource_crud.sql` 引入;截至 2026-10-29,已验收版本的迁移为 001–027,另包括环境队列、主机环境授权、DNS 服务商与环境任务恢复。迁移不移动已有主机目录。更新前保留平台数据库与程序备份。 + +回收中的主机仍有用户归属时,管理员须逐台显式解绑:`DELETE /projects/{id}/recycled-owner`,提交 `confirmation`(主机名)与 `ownershipVersion`。该接口只适用于手动回收且未锁定的主机,校验归属版本并记录审计,不会自动批量解绑后删除用户。 + +## 自定义域名与套餐管理 + +管理员、用户和独立主机账号可在各自权限内解绑自定义域名,默认分配域名不能单独解绑。解绑先删除 Sea vHost 跟踪的托管 DNS 记录,再通过宝塔基础 `DelDomain` 接口移除绑定;全部成功后才删除本地域名记录。外部操作失败时保留记录,页面显示错误,允许处理后重试。文件、数据库、证书及其他域名保留;重新绑定遵循当前审核规则。宝塔协议参考:[官方 API 文档](https://www.bt.cn/api-doc.pdf)。 + +套餐可复制为新的套餐版本,名称及配额在提交前可调整。只允许删除未被主机、用户或历史账号引用的套餐;系统默认套餐不可删除,批量任务未完成时暂不允许删除。前端显示限制原因,后端在事务内重新核验,并保留审计日志。 + diff --git a/docs/security-audit-2026-10-15.md b/docs/security-audit-2026-10-15.md new file mode 100644 index 0000000..2802ff1 --- /dev/null +++ b/docs/security-audit-2026-10-15.md @@ -0,0 +1,296 @@ +# Sea vHost 安全测试与风险评估报告 + +> 历史验收记录:环境、版本、数量及结论仅适用于文中所列日期,不代表当前服务重新实测。当前状态见 [项目状态整理](project-status-2026-10-29.md)。 + +初始评估:2026-10-15 +修复复测:2026-10-20 +评估对象:当前工作区源码及临时宝塔 Linux(Debian)测试机 +评估方式:代码审阅、依赖审计、单元测试、构建检查、受控接口测试、浏览器渲染检查、运行环境诊断 +保密边界:报告不记录面板密钥、账号密码、会话、数据库 DSN 或凭据密文。第三节保留 2026-10-15 的原始发现作为历史基线,当前状态以本节复测表为准。 + +## 1. 复测结论 + +本轮已把共享 `www` 架构升级为每主机独立 Linux UID/GID。账号密码锁定、Shell 为 `/usr/sbin/nologin`、只加入自身组;Node/Python/Go/Java 的 `run_user`、Pure-FTPd UID/GID 和 PHP-FPM 均绑定该身份。实机显示 Nginx `www` 对主机目录 `read=yes, write=no`,对 `.sea-runtime` `read=no`;PHP-FPM master 与 worker 均为主机 UID/GID,`CapPrm`、`CapEff`、`CapAmb` 全为零,实际 PHP 请求返回 200。 + +root agent 仍保留创建系统身份所需的受限能力,但 PHP 子进程在 `fork` 后、`exec` 前切换到主机 UID/GID,Linux 会清空其 ambient/permitted/effective capabilities。agent 开启 `ProtectSystem=strict` 与固定写目录;它不使用 `PrivateNetwork`,因为由它启动的租户 PHP-FPM 必须访问宿主 MySQL 和外部 API。agent 仍只监听 Token 鉴权的 Unix Socket,不监听 TCP。动态 `useradd/usermod` 需要修改账号数据库,`/etc` 是明确保留的剩余高权限面,不能把本方案描述成容器或完整内核沙箱。 + +2026-10-20 的全新安装验收发现 PHP-FPM 配置校验曾由 root 执行;`php-fpm -t` 会打开租户运行目录内的错误日志,既会留下 root 属主文件导致首次启动失败,也存在跟随租户可控符号链接的风险。现已让配置校验与正式启动一样在 fork 后先切换到目标主机 UID/GID,再执行 PHP-FPM。空白重装后的首次 PHP 主机创建、master/worker 身份、零有效能力集和真实 HTTP 200 均已复验通过。 + +SVH-08 至 SVH-13 已完成代码修复。2026-10-20 使用一次性远端账号完成了改密、TOTP、恢复码单次消费、禁用 MFA 和会话注销闭环;账号、域名、20 MiB 文件边界及 IDOR 检查同时通过。新安装必须填写控制台域名与 FTP 证书来源域名;当前测试机是旧配置升级,仍为空值兼容模式,因此管理域名 Host 白名单未在该实例启用。 + +2026-10-18 的追加复测还确认:手动 PEM 证书经受管 broker 调用宝塔 `SetSSL` 后写入标准证书目录且 `nginx -t` 通过,临时站点随后由同一受管资源登记表删除;配额目录冻结与恢复闭环通过。三个部署二进制的 build metadata 均为 Go 1.27.2。 + +2026-10-20 的追加复测创建了第二个一次性主机身份和临时站点:两个主机身份双向读取对方文件均被拒绝,测试结束后站点、证书、目录和 Linux UID/GID 均由受管清理流程移除。磁盘计量已从普通 API 进程移入 Token 鉴权的 root agent;在一次性主机内写入 2 MiB 文件并把父目录设为 `000` 后,agent 仍报告 `2098276` 字节,符号链接目标不被遍历。等待一个完整巡检周期后,API journal 未再出现配额刷新错误。 + +同日的完整功能顺序复测还发现四项必须如实记录的新问题:Node.js 在独立 UID 下无法写宝塔 PID 目录,并可能出现“面板报错但进程已启动”的未登记孤儿;Python 项目接口拒绝已存在的独立 Linux 用户;FTP 证书未校验主机名,且测试机写入 `TLS 2` 后明文 FTP 仍收到 331;HTTP-01 失败没有进入自动化记录的 `last_error`。PHP、Go、Java、配额、Nginx 回滚、升级与影子恢复均通过。详见 `feature-test-report-2026-10-20.md`。 + +## 2. 修复与剩余风险总览 + +| 编号 | 当前状态 | 复测证据或剩余事项 | +| --- | --- | --- | +| SVH-01 | 已修复并实机复测 | 独立锁定 UID/GID;`www` 只读;FTP 同 UID/GID;PHP master/worker 为主机身份且能力为零。一次性第二主机与既有主机双向交叉读取均被操作系统拒绝。 | +| SVH-02 | 已修复并实机复测 | 数据库容量、月流量、独立 UID 进程数及磁盘均已真实采集;磁盘由 root agent 在固定主机根内计量,`000` 私有目录中的 2 MiB 文件仍被统计。超额会停站/FTP/进程并冻结主机身份写权限;既有文件改写与新建均被拒绝、Web 文件服务仍可清理、解除冻结后 ACL 恢复,控制面统一使用 `423 quota_suspended` 门禁。 | +| SVH-03 | 测试环境接受 | 当前端口转发与 HTTP 仅用于无敏感数据测试机;正式机仍须回环/防火墙/HTTPS。 | +| SVH-04 | 部分修复 | `ProtectSystem=strict`、能力边界和写路径白名单已生效;动态 Linux 账号管理使 `/etc` 仍对 root agent 可写。 | +| SVH-05 | 已修复 | 三个二进制由 Go 1.27.2 构建;`govulncheck` 报告可达漏洞 0。 | +| SVH-06 | 部分失败,需修复 | Pure-FTPd chroot、独立 UID/GID和显式 FTPS 数据传输已验证;但证书域名不匹配未被拒绝,且测试机写入 `TLS 2` 后明文 FTP 仍收到 331,不能宣称已强制 TLS。 | +| SVH-07 | 已修复,未重测统计分布 | 不存在账号执行同成本 bcrypt;账号限频改为 IP+匿名化标识,降低跨 IP 定向锁号。 | +| SVH-08 | 已修复 | 运行环境目录使用一分钟缓存、并发刷新合并和每用户 5 分钟 30 次限频。 | +| SVH-09 | 已修复(新配置生效) | 根域、控制台域名、独立的 FTP 证书来源域名和保留后缀在面板调用前拒绝;旧升级配置为空时保持兼容。 | +| SVH-10 | 已修复 | 全部操作统一可信代理 IP;失败登录使用匿名化标识审计;审计失败写 journal。 | +| SVH-11 | 已修复 | 会话令牌先验 HMAC,定时清理过期会话,每用户最多 10 个;改密注销其他会话。 | +| SVH-12 | 已修复 | 安装 API 与业务 API 使用协议+主机同源判断,尾随 JSON 被拒绝。 | +| SVH-13 | 已修复并实机复测 | TOTP、一次性恢复码、自助改密、注销旧会话和禁用 MFA 的远端 E2E 已通过。 | + +## 3. 原始详细发现(2026-10-15 历史基线) + +本节描述修复前证据,用于解释风险来源,不代表 2026-10-17 当前状态;请以第二节复测表为准。 + +### SVH-01:共享 `www` 无法隔离不可信租户代码(严重) + +**证据** + +- 受管目录实机模式为 `sea-vhost:www`,目录为 `2770`,文件通常为 `0660`。 +- 以 `www` 身份执行的只读权限探针,对现有受管主机目录均得到 `read=yes write=yes`。 +- PHP、Node.js、Python、Go、Java 均固定使用宝塔服务身份 `www`;FTP 写入同一目录并依赖 `www` 组权限。 + +**影响** + +恶意租户程序或已被攻陷的网站可以直接使用文件系统 API 读取、篡改其他租户源码、配置文件和站点内容。Web 文件管理器的 `os.Root` 约束、租户 ID 校验、Nginx `disable_symlinks` 和 PHP `open_basedir` 只能保护各自入口,无法限制 Node.js、Python、Go、Java 进程以共享 OS 身份直接访问文件。 + +**建议与可选决策** + +1. 若租户可以彼此不信任:为每个主机或租户分配独立 Linux UID/GID,并让语言进程和 FTP 使用对应身份;或采用具备独立身份/命名空间的运行隔离方案。无需强制使用 Docker,但必须有等价的文件身份边界。 +2. 若坚持不创建系统用户且共用 `www`:明确产品只适用于可信租户,不承诺跨租户源码保密或不可信代码沙箱;管理员须审核可执行项目,并把该风险列入服务条款。 +3. 单纯改为随机目录名、收紧 Web 接口或增加 PHP 高危函数禁用不能消除此风险。 + +### SVH-02:部分资源套餐仅记录、不执行(高) + +**2026-10-18 修复状态:已修复并实机复测。** 启动项现运行统一资源巡检:宝塔免费 `GetInfo` 返回数据库实际容量,Nginx 日志持久化 inode/offset 游标累计月流量,root agent 按独立 UID 读取真实 PID。任一指标超额都会统一写入 `quota_suspended`、停站、暂停 FTP 并终止租户进程;清理到限额以下只恢复为“已停止”,不会自动启动。实机确认日志流量计量返回 652 字节,现有 PHP 身份进程计数为 1,临时租户进程计数为 1 且终止操作成功。 + +后续复测又加入目录写冻结:超额后 root agent 重新取得主机树所有权并撤销主机 UID/GID 的写权限。临时身份对既有文件追加和新建文件均失败,`sea-vhost` 文件服务仍能删除文件,恢复受管 ACL 后主机身份重新可写。该机制在检测到超额后生效,仍不等同于文件系统硬配额。 + +2026-10-20 修正了磁盘扫描仍在普通 API 身份执行的问题。目录逻辑大小现由 root agent 在从受校验主机名推导的固定路径内只读统计,调用方不能提交任意绝对路径,目录符号链接不被跟随;实机确认租户 `chmod 000` 后仍能正确统计且不会破坏 `.sea-runtime` 对 Web 文件服务的私有边界。 + +以下“证据/影响/建议”为 2026-10-15 的修复前记录,保留用于审计追溯。 + +**证据** + +- 当前启动项只运行 `RunStorageQuotaMonitor`。 +- 磁盘软配额会扫描目录、拦截 Web 写入并在超额后停站。 +- FTP 数、数据库数和项目数在创建时受套餐数量限制。 +- `database_bytes`、`bandwidth_bytes`、`process_count` 具有数据字段和界面展示,但未发现对应的采集器或强制执行器。 +- `process_limit` 会被传递和保存,但 Node.js、Python、Go、Java 的实际进程没有 cgroup、RLIMIT 或等价限制;共享 `www` 也使按租户准确归属进程更加困难。 + +**影响** + +已登录租户可以通过数据库增长、网络流量或派生进程消耗整机资源,套餐展示可能让管理员误以为限制已经生效。 + +**建议** + +- 界面先将未执行的指标标记为“仅配置/未强制”,避免错误承诺。 +- 数据库容量使用 `information_schema` 定时汇总并在超额后撤销写权限或停站。 +- 月流量按站点独立日志、轮转游标累计,达到阈值后暂停站点。 +- 进程数与内存/CPU 限制宜结合独立运行身份和 systemd/cgroup;仅按共享 `www` 统计容易误伤其他租户。 + +### SVH-03:测试机管理面与数据库公网暴露(高,环境项) + +**证据** + +从外部网络确认 TCP `21`、`3306`、`8888`、`10094`、`10115` 可连接;主机监听信息同时显示 MySQL 在通配地址监听。当前控制台通过 HTTP 转发端口访问,面板使用测试证书。用户已说明这是无敏感数据的临时测试机,正式证书条件不同,因此本项不视为当前开发阻断,但不能复制到生产。 + +**影响** + +宝塔 UI/API 等价 root 控制权;MySQL 和 FTP 公网暴露会扩大口令喷洒、协议漏洞和配置错误的攻击面。控制台 HTTP 会暴露登录凭据与会话。 + +**建议** + +- 正式机只允许回环或固定管理 IP/VPN 访问宝塔 UI/API,宝塔 API 白名单仅保留回环来源。 +- MySQL 绑定回环地址,并由防火墙拒绝公网 `3306`。 +- 控制台使用正式 HTTPS,HTTP 仅做重定向;不要沿用测试环境的 TLS 跳过配置。 +- FTP 只开放必要的控制端口及被动端口范围,并结合来源限制和 TLS-only。 + +### SVH-04:root 隔离代理可写系统范围过宽(高) + +**证据** + +`sea-vhost-agent` 以 root 运行,已启用 `NoNewPrivileges`、能力边界和多项 systemd 限制,但初始实机 `ProtectSystem=no`。单元文件虽然设置了若干 `ReadOnlyPaths` 和 `ReadWritePaths`,未被列入只读路径的 `/etc` 等区域仍可写。后续代码已切换为 `ProtectSystem=strict`;`PrivateNetwork` 已有意移除,否则由 agent fork 的 PHP-FPM 无法访问宿主 MySQL,该变化不扩大 agent 的监听面。 + +**影响** + +当前代理的输入校验较严格,普通 API 调用不能直接指定任意绝对路径;但如果代理本身或 Unix Socket 调用链出现新漏洞,攻击者可能把 root 影响范围扩大到系统配置。 + +**建议** + +启用 `ProtectSystem=strict`,再显式保留受管主机目录、Nginx 扩展配置和确有必要的运行文件为可写路径;同时复测 `.user.ini` immutable 处理、`nginx -t`、重载与回滚流程。进一步可按操作拆分更小的代理能力,但不是首轮必需。 + +### SVH-05:Go 运行时及依赖存在已知漏洞(中) + +**证据** + +三个部署二进制均由 Go `1.27.1` 构建。官方 `govulncheck` 报告 11 个可达的标准库公告:`GO-2026-6617`、`GO-2026-6613`、`GO-2026-6612`、`GO-2026-6611`、`GO-2026-6610`、`GO-2026-6609`、`GO-2026-6608`、`GO-2026-6607`、`GO-2026-6605`、`GO-2026-6604`、`GO-2026-6603`,修复版本均为 Go `1.27.2`。 + +其中 HTTP/2、CONNECT、TLS ECH 和 Windows junction 路径在当前 Debian + Nginx + Unix Socket 架构下部分不可从公网直接触发;但 `http.ServeContent` 的 Range 处理和 multipart 上传路径与文件接口有关,仍应按可达漏洞处理。另有 `filippo.io/edwards25519 v1.1.0` 的包级公告,当前未调用其受影响符号;`golang.org/x/crypto v0.41.0` 还包含若干未调用的 SSH 相关公告。 + +**建议** + +使用 Go `1.27.2` 或更高兼容补丁版本重新构建全部二进制,升级兼容的 `x/crypto` 与 `edwards25519` 依赖,再运行单元测试、`govulncheck` 和实机 smoke。升级前可由 Nginx 继续限制请求体和异常请求,但不应把反代视为永久修复。 + +### SVH-06:FTP 允许明文认证(中) + +**证据** + +Pure-FTPd 已设置 `ChrootEveryone yes`、`NoAnonymous yes`,但 `TLS 1` 表示支持 TLS 而非强制 TLS。公网 `21` 可达,被动端口范围为 `39000-40000`。 + +**影响** + +租户若使用普通 FTP,用户名、密码及文件内容可能被中间人窃取。chroot 只限制目录,不能保护传输。 + +**建议** + +生产将 Pure-FTPd 调整为强制 TLS(通常为 `TLS 2`),部署可信证书,客户端统一使用显式 FTPS;防火墙只开放实际被动范围。若兼容性允许,长期可增加 SFTP/受限上传通道,但不得给租户 Shell。 + +### SVH-07:登录时序枚举与定向锁号(中) + +**证据** + +五次样本中,已存在账号的错误密码平均约 `495 ms`,不存在账号平均约 `351 ms`,差值约 `144 ms`。原因是存在账号执行 bcrypt 后再固定休眠,不存在账号只固定休眠。限频同时按 IP(5 分钟 60 次)和全局账号标识(5 分钟 20 次)计数;实测同一标识前 20 次返回 401,第 21 次返回 429,并携带 `Retry-After`。 + +**影响** + +远程攻击者可以统计区分有效账号/主机名,也可以轮换来源 IP 对已知账号持续触发全局标识限频,造成短时登录拒绝服务。 + +**建议** + +- 对不存在账号使用固定的虚拟 bcrypt 哈希执行同成本校验,使成功前的失败路径接近恒定时间。 +- 保留 IP 维度,并将账号维度改成 IP+账号组合或采用渐进退避;若保留全局账号锁,应提供安全告警和解锁机制。 +- 记录失败登录的归一化原因、来源 IP 和匿名化标识,不记录密码。 + +### SVH-08:运行环境探测可造成已认证拒绝服务(中) + +**证据** + +任一租户可调用运行环境目录接口;每次请求会实时查询宝塔的 PHP、Node.js、Python、Go、Java 信息。broker 在执行操作期间持有全局互斥锁,没有目录缓存、租户级频率限制或独立并发上限。 + +**影响** + +恶意或失控的已登录租户可反复触发多个面板请求,串行占用 broker,使其他创建、部署和管理操作排队或超时。 + +**建议** + +运行环境目录缓存 30–120 秒并使用 singleflight 合并刷新;对昂贵 API 增加每用户/IP 限速;把只读探测与写操作的锁范围分离,并为到宝塔的并发设置较小上限。 + +### SVH-09:控制面域名未加入保留名单(中) + +**证据** + +自定义域名只做语法、唯一性和可选审核处理,未发现控制台域名、宝塔域名、根域及其他管理域名的显式 denylist。关闭审核时,合法格式的域名可直接进入绑定流程。 + +**影响** + +租户可能申请控制台或其他基础设施域名,引发 Nginx `server_name` 冲突、证书误申请或路由混淆。即使 Nginx 最终拒绝重复配置,也可能造成管理面不可用或操作卡死。 + +**建议** + +安装时配置保留域名和保留后缀;API 在写数据库和调用面板前同时拒绝精确域名、其必要子域及控制台/面板域名。域名审核不能替代服务端保留名单。 + +### SVH-10:审计归因与完整性不足(中) + +**证据** + +登录成功日志使用可信反代头解析后的客户端 IP,但多数项目和管理员操作仍写入 `r.RemoteAddr`,经本机 Nginx 反代后通常只会记录 `127.0.0.1`。失败登录不进入审计表;审计数据库写入错误被忽略。 + +**影响** + +发生滥用或账号入侵时,难以关联真实来源,也无法确认关键审计事件是否可靠落盘。 + +**建议** + +所有处理器统一使用 `requestClientIP`;为失败登录建立允许空用户 ID 的安全事件表或专用日志;关键操作的审计写入失败至少进入 systemd journal 并触发告警。需要更强保证时采用业务变更与 outbox 同事务写入。 + +### SVH-11:会话生命周期存在低风险缺口(低) + +**证据** + +查询会拒绝过期会话,但没有定时删除过期行;每次成功登录可新增会话。令牌由随机数和 HMAC 组成,但读取会话时只按整个令牌的 SHA-256 摘要查询,没有调用现有的 HMAC 校验函数。 + +**影响** + +长期运行会积累过期行;轮换 `session_secret` 不会自动使数据库中的旧会话失效。随机令牌仍具有足够熵,因此这不是直接的会话伪造漏洞。 + +**建议** + +定时清理过期会话并限制单用户并发会话数;在会话读取前校验 HMAC,或删除无实际用途的 HMAC 结构并以明确的服务端会话轮换策略替代。密钥轮换时主动删除旧会话。 + +### SVH-12:安装服务校验弱于业务 API(低) + +**证据** + +业务 API 会同时校验 Origin 协议与主机,并拒绝 JSON 尾随内容;安装服务的同源辅助函数只比较 Origin 主机,JSON 解码未再次确认 EOF。安装写请求仍要求高熵安装令牌,且安装完成后接口关闭。 + +**影响** + +风险主要存在于首次安装窗口,现有令牌显著降低了利用概率,但两套规则不一致会增加未来维护出错的可能。 + +**建议** + +复用业务 API 的严格 Origin/反代协议判断和 JSON 解码器;安装期间只允许本机或一次性管理来源访问,完成后确认端点返回关闭状态。 + +### SVH-13:管理员账号缺少 MFA 与密码轮换入口(低) + +**证据** + +当前有主机账号密码重置与会话注销,但未发现管理员/租户自助修改密码、强制轮换或 MFA 流程。 + +**影响** + +管理员凭据一旦泄露,攻击者可管理所有租户和受管面板资源。外围宝塔本身又是 root 等价入口,因此管理凭据保护尤为重要。 + +**建议** + +至少补充管理员改密后注销全部旧会话、密码最小强度和恢复流程;正式公网管理时优先加入 TOTP/WebAuthn MFA。上线前可先以 VPN/固定管理 IP 降低暴露面。 + +## 4. 2026-10-17 通过的控制与测试 + +| 项目 | 结果 | +| --- | --- | +| Go 1.27.2 `go test ./...` | 通过 | +| Linux/amd64 `go vet ./...` | 通过 | +| `govulncheck ./...` | 可达漏洞 0;依赖中未调用的公告不计为可达修复完成 | +| 前端 Vitest | 1 个测试文件、20 个测试全部通过 | +| 前端生产构建 | 通过 | +| npm 生产/全依赖审计 | 均为 0 个已知漏洞 | +| 部署归档 | SHA-256 生成并由远端安装任务校验通过 | +| systemd / Nginx / API | 三个服务 active,`nginx -t` 与 `/healthz` 通过 | +| Linux 主机身份 | 密码锁定、`nologin`、只属于自身组 | +| 双主机交叉读取 | 两个独立 UID 双向读取均拒绝;一次性身份随后删除 | +| 主机目录 ACL | `www` 可读、不可写;`.sea-runtime` 不可读 | +| 私有目录磁盘计量 | `000` 目录内 2 MiB 文件仍计入 2,098,276 字节;巡检 journal 健康 | +| PHP 隔离 | master/worker 均为主机 UID/GID;有效、许可、ambient capabilities 为零;HTTP 200 | +| FTP 隔离 | Pure-FTPd UID/GID 与 chroot 目录映射到主机身份 | +| 内部 RPC 鉴权 | agent 与 broker 无 Token 请求均为 401 | +| 公网入口 | 控制台 200、健康检查 200、未登录 API 401、跨 Origin 403、未知 JSON 字段 400 | +| 浏览器桌面/移动端 | Chrome 1440×900 与 390×844 渲染通过,无横向溢出;错误登录展示中文提示 | +| 旧版安全 smoke | 2026-10-15 的账号级脚本 13/13 通过;本轮因未保留测试账号明文密码未重复执行 | + +浏览器控制台中的 401 网络记录来自预期的未登录会话探测和故意提交错误凭据;未发现 JavaScript 运行时错误或框架错误层。 + +## 5. 剩余处理优先级 + +### P0:正式开放前 + +1. 在目标正式机使用两台真实主机、两个租户,分别以 PHP、Node.js、Python、Go、Java 进程互相尝试读取和写入;必须全部失败。 +2. 正式机关闭公网宝塔与 MySQL,宝塔 API 仅允许回环,控制台使用可信 HTTPS。 +3. Pure-FTPd 配置可信证书并强制显式 FTPS;若暂不实施,必须明确 FTP 为不安全兼容通道。 +4. 在正式机重复验证已经实现的数据库、流量、磁盘和通用语言进程配额,确认计量、暂停、清理与恢复闭环;旧版“仅记录未强制”的结论已不再适用于当前代码。 + +### P1:公开试运行前 + +1. 用新安装流程填写控制台域名和 FTP 证书来源域名,验证 Host 白名单、保留域名拒绝、证书与续期。 +2. 修复 Node.js PID 目录/部分成功回滚和 Python 独立用户兼容性,再重跑全部免费语言项目的 `run_user`、启停、反代、删除和回滚。 +3. 修复 FTP 证书主机名校验,并确认 Pure-FTPd 实际启动参数强制 TLS,而不只检查配置文件内容。 +4. 评估把 Linux 账号维护从通用 root agent 继续拆分,以缩小必须可写 `/etc` 的组件范围。 + +## 6. 验收限制 + +本轮没有执行真实断电、整盘写满、流量耗尽或不受控进程炸弹;已使用一次性第二主机完成受控跨身份读取、2 MiB 私有目录计量、约 12 MiB 数据库增长、低阈值流量、额外进程终止、冻结/恢复、同包升级和影子恢复测试。每次修改隔离代理、systemd 单元、PHP-FPM 或宝塔适配器后,都应重跑后端测试/vet、前端测试/构建、npm audit、govulncheck、账号级安全 smoke、面板资源生命周期、跨主机权限探针和外部端口检查。 diff --git a/docs/security-canary-test-2026-10-19.md b/docs/security-canary-test-2026-10-19.md new file mode 100644 index 0000000..2454273 --- /dev/null +++ b/docs/security-canary-test-2026-10-19.md @@ -0,0 +1,38 @@ +# Sea vHost 安全金丝雀实机记录(2026-10-19) + +> 历史验收记录:环境、版本、数量及结论仅适用于文中所列日期,不代表当前服务重新实测。当前状态见 [项目状态整理](project-status-2026-10-29.md)。 + +## 测试范围 + +- 测试环境:Debian、宝塔 Linux 面板 12.0.0、Sea vHost 单机测试部署。 +- 受管主机:`sv57d9d312eb`。 +- 检查 ID:`d64534dd36fe`;发布脚本复验 ID:`5d964f0f3731`。 +- root-only 登记表:`/var/lib/sea-vhost/security-canaries/registry-<检查ID>.tsv`,权限 `0600`。 +- 所有标记均为本次随机生成的合成数据,不包含真实 API 密钥、数据库密码、会话或用户资料;任务输出和本报告均不记录标记正文。 + +## 结果 + +| 边界 | 验证方式 | 结果 | +|---|---|---| +| HTTP 正常读取基准 | 站点根目录普通随机文件 | 200,正文精确匹配基准标记 | +| 隐藏目录 | `/.sea-vhost-canaries/...` | 403/404,未命中标记 | +| 敏感扩展名 | 随机 `.env` 文件 | 403/404,未命中标记 | +| 依赖/构建清单 | 随机 `requirements-*.txt` | 403/404,未命中标记 | +| 运行私有目录 | `/.sea-runtime/...` | 403/404,未命中标记 | +| 跨属主符号链接 | 站点内链接指向 `.sea-runtime` | 403/404,未命中标记 | +| 控制面私有文件 | `www`、`nobody`、主机身份读取 | 拒绝 | +| panel broker 私有文件 | `www`、`nobody`、主机身份、`sea-vhost` 读取 | 拒绝 | +| root agent 私有文件 | `www`、`nobody`、主机身份、`sea-vhost` 读取 | 拒绝 | +| 主机运行私有文件 | `www`、`nobody` 读取 | 拒绝;所属主机身份可读 | +| agent/broker Socket | 无内部 Bearer Token 请求 | 均返回 401 | +| Web 文件 API | 未登录读取金丝雀路径 | 401,未命中检查 ID | +| 浏览器跨源写入 | 恶意 Origin 提交域名 | 403 | +| 管理控制台静态路径 | 探测同名隐藏路径 | 未出现检查 ID | + +为避免假阳性,站点内受保护文件额外授予 `www` 操作系统层只读权限;HTTP 仍被拒绝,证明隐藏文件、扩展名和清单拦截来自 Nginx 安全规则,而不是单纯依赖文件权限。常规部署安全回归随后再次通过:三个服务均为 active,主机账号锁定且为 `nologin`,`www` 只读且无法读取 `.sea-runtime`,PHP-FPM master/worker 使用主机 UID/GID 且 permitted/effective/ambient capabilities 为零,FTP 映射到同一主机身份,Nginx 配置校验成功。 + +## 保留与限制 + +金丝雀文件按设计保留,以便以后从低权限进程、FTP 或监控系统复测。站点内存在一个内容无敏感性的公开基准文件;其用途是确认站点可达并排除“全部请求都失败”造成的误判。清理时只能由 root 读取登记表、逐项核对并删除,不得对受管目录执行通配符递归删除。 + +本轮不能替代以下测试:两个真实受管主机身份之间的交叉读写、持有真实 FTP 凭据的外部协议绕过、运行时恶意代码压力测试、磁盘/数据库写满、完整端口扫描,以及对真实密钥仓库的泄漏扫描。这些项目仍应在最终部署服务器的隔离验收窗口执行。 diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..bf5286f --- /dev/null +++ b/docs/security.md @@ -0,0 +1,64 @@ +# 安全与资源隔离 + +## SSO 身份与登录策略 + +OIDC 身份按 Issuer 摘要与大小写敏感的 subject 联合区分。授权流程使用 PKCE、nonce、一次性 state 和浏览器专属的 Secure/HttpOnly/SameSite=Lax 流程 Cookie;主登录 Cookie 仍保持 Strict。绑定流程保存发起会话摘要,回调时核验该会话仍有效,不能以其他会话完成绑定。 + +未绑定身份只获得五分钟有效、数据库仅存摘要的一次性待处理票据。绑定已有用户须重新验证密码及已启用的 MFA;自动建号默认关闭,开启后仍由前台选择,仅接受已验证邮箱,不按邮箱合并、不分配主机、不创建管理员。独立主机账号在接口和数据库事务两层拒绝 SSO。 + +管理员与普通用户分别控制密码登录,后端执行限制,主机账号始终保留密码。关闭管理员密码要求当前管理员已绑定有效配置对应的身份;密码关闭时不能解绑,SSO 关闭前必须先恢复密码。此策略限制新认证,不主动撤销既有会话。完整外部 IdP 联调尚未完成,当前证据包括真实 MySQL 与本地 HTTPS 签名 OIDC 服务的集成测试,见 [验收记录](sso-ui-acceptance.md)。 + +## 强制边界 + +- 每台虚拟主机创建一个与随机主机名同名的 Linux 系统身份。它使用系统 UID/GID、密码锁定、Shell 为 `/usr/sbin/nologin`,只属于自身同名组,不允许 SSH 或交互登录;主机登录、FTP 与数据库登录仍是各自服务内的账号。 +- 控制面服务账号为 `sea-vhost` 与 `sea-vhost-panel`。API 配置使用 `sea-vhost-control`,root 隔离 Socket 使用 `sea-vhost-agent-control`,面板 Socket 使用 `sea-vhost-panel-control`;只有 API 同时加入后两组,broker 不能调用 root 代理。主机目录采用 `sea-vhost:<主机身份>`、setgid 和 POSIX ACL:运行进程/FTP 使用同名组读写,Nginx `www` 只有读取与穿越权限,其他主机身份无权访问。 +- 文件管理器每次访问都重新绑定项目的 `tenant_id`,规范化路径并拒绝符号链接;实际打开、写入、重命名和删除使用 Go `os.Root` 的目录句柄约束,即使校验后路径被竞态替换也不能越出租户根目录。删除操作进入项目内回收站。 +- 主机父目录保持 root 所有且不可被站点替换;每个随机主机目录为 `sea-vhost:<主机身份>`,目录带 setgid 和默认 ACL。隔离代理拒绝符号链接目录后才执行属主、ACL 和权限操作,避免 root 跟随站点构造的链接。 +- FTP 使用宝塔 Pure-FTPd 的虚拟账户与 chroot 根目录,再由 root 隔离代理将其 UID/GID 映射到主机身份;凭据接口返回该虚拟主机自己的默认域名作为连接地址。Pure-FTPd 在服务器级复用安装时配置的证书来源,校验证书有效期、私钥匹配和主机名覆盖后写入固定 `CertFile` 并启用 `TLS 2`;证书应覆盖租户泛域名,使每个随机主机名都能通过客户端校验。该实现不调用面板付费 FTP 配额接口。 +- MySQL 用户仅允许 `127.0.0.1`,每台虚拟主机默认一个独立数据库和同名用户;不向租户或 Web API 进程暴露面板密钥。 +- 主机登录密码与 FTP、MySQL 密码互不复用。登录密码只保存 bcrypt 哈希;只有租户账号可以重置所属主机的登录密码,重置与删除该主机全部现有会话在同一数据库事务内完成。FTP 和数据库密码因需重新显示,使用由安装会话密钥派生的 AES-256-GCM 密钥加密,以凭据类型和主机 ID 作为附加鉴别数据。响应全局使用 `no-store`,操作日志不记录密码。 +- 宝塔官方说明 API 可完整控制面板全部功能,因此密钥按 root 等价凭据处理。专用 `sea-vhost-panel` broker 是唯一持钥进程;它没有 OS root 权限、网络仅允许 localhost,并只执行固定高层操作。API 到 broker/隔离代理除 Socket 文件权限外还必须通过独立内部 Bearer Token;安装接口另用一次性安装令牌。 +- broker 在私有 `0600` 登记表中保存由 Sea vHost 创建的面板资源 ID。删除、启停、绑域名、反代和证书操作必须命中登记表;面板里原有的站点、FTP 和数据库不在可操作集合内。 +- 租户上传自有证书时,API 在进入 broker 前限制请求大小并解析完整 PEM:叶证书必须当前有效、允许 TLS Web Server、覆盖该网站全部已批准域名,且公钥必须与无口令私钥匹配。broker 再次限制证书/私钥大小并要求命中受管站点;私钥只存在于该次内存请求与宝塔标准证书文件中,不写入 Sea vHost 数据库或审计日志。手动安装会关闭该网站的自动申请/续签标志。 +- DNS API 密钥不使用宝塔的全局 DNS 凭据仓库,也不写入租户主机 `.env`。平台与用户凭据在同一表中按作用域隔离,密钥以随机引用作为 AES-256-GCM 附加鉴别数据加密;读取接口只返回脱敏元数据和测试状态,修改必须完整替换密钥并清空旧测试状态。Cloudflare、阿里云、腾讯云和西部数码使用适配器限定的地址;彩虹聚合 DNS 可配置 HTTPS 公网站点地址,仅允许 443 端口,拒绝身份信息、查询参数和片段。解析和实际拨号均拒绝内网/保留地址,并禁止重定向;平台域名拒绝使用租户凭据,自定义域名的候选集合只包含当前租户,防止跨租户 DNS 调用。连通性测试使用随机 TXT、按返回记录 ID 精确删除、有持久化冷却和审计日志,不查询或批量删除同名记录。 +- ACME DNS-01 会先为所有待验证域名创建 TXT,再等待解析可见、提交验证并在 `defer` 中按服务商记录 ID 精确删除;不会覆盖或批量删除同名既有 TXT。账户私钥加密保存,证书私钥不落业务数据库。签发接口有站点级持久化冷却,后台续期有有界批次、超时和失败退避;签发开始时即写入六小时后的兜底重试时间,进程在完成回写前退出也不会让续期任务失联。 +- 域名、FTP、数据库和网站查询先确认用户归属或固定主机绑定,再以目标主机的内部 `tenant_id` 与 `project_id` 限定资源。列表接口不返回密码密文,只有用户主动打开某台主机的凭据窗口时才执行鉴别解密。 +- 自定义域名创建与后续绑定共用保留域校验,拒绝平台根域及其子域、控制台、FTP 与其他安装保留域,防止租户站点尝试接管管理入口。每站最多 100 个域名(含默认域名),站点行锁使“计数并插入”保持原子,证书层另有同值防御上限,避免并发绕过和超大 SAN 请求滥用。 +- 自定义域名先在 MySQL 中以唯一索引预留,再写入宝塔;租户根域、控制台域名、独立的 FTP 证书来源域名及管理员配置的保留域名/后缀会在调用面板前拒绝。需要审核时只有平台管理员可批准或拒绝。管理员批准仍通过受管站点登记表校验,不能借审核接口向面板既有站点加域名。 +- 面板客户端具有独立的免费基础接口白名单。即使业务代码误加宝塔 WAF、系统加固、多用户、任务管理器或其他商业插件路由,也会在生成网络请求前拒绝。 +- PHP 站点使用每网站唯一的 PHP-FPM Socket;agent 在 `exec` 前把 FPM master 直接切换到主机 UID/GID,Linux 随即清空子进程 capabilities,master 与 worker 从启动起均为主机身份。Socket 仅允许该身份和 Nginx `www` 连接,并强制 `open_basedir` 与主机私有临时目录。Java 和其他语言项目的 `run_user` 同样固定为服务端生成的主机身份,不能由租户请求覆盖。 +- 宝塔 `AddSite` 或语言项目启动可能重设站点目录属主;创建/启动事务随后必须由 root 隔离代理重新落实属组、setgid 与 ACL。此步骤失败会回滚或停用站点。 +- 站点目录固定为 `/www/wwwroot/seavHost/vHost/sv<10位随机十六进制>`。展示名称、租户 slug、域名输入均不得参与物理路径拼接;FTP、数据库和默认三级域名只使用服务端生成的主机名。 +- 运行目录只能是主机根目录内的规范相对路径。隔离代理逐段拒绝符号链接,Nginx 同时启用 `disable_symlinks if_not_owner from=$document_root`,防止租户把发布目录替换为指向系统文件的链接。 +- 附加网站删除只移除受管的面板与 Nginx 配置,源码留在固定主机根目录内;主站禁止走附加网站删除接口,避免把仍承载 FTP、数据库和登录身份的主机拆成不一致状态。 +- 宝塔生成的 `.user.ini` 在恢复目录属主前短暂解除 immutable 标记,随后恢复为 `root:root 0644` 并重新加锁;任一步失败都不会把站点交付给租户。 +- 会话为随机、HMAC 封装的 HttpOnly/Secure/SameSite=Strict Cookie;服务端先验证 HMAC,再按 SHA-256 摘要查询。过期会话定时删除,单用户最多保留 10 个会话;改密保留当前会话并注销其他会话。管理员、租户和主机账号均可启用 TOTP MFA,恢复码经哈希保存且一次性消费。 +- 管理员快捷进入使用独立的 `sea_impersonation` Cookie,不替换原 `sea_session`,最长 30 分钟且不能超过原会话有效期。数据库同时绑定原会话摘要、真实管理员和目标账号;仅持有代入 Cookie、换绑其他管理员会话或带入普通用户会话均不能使用。业务读写按目标身份鉴权,代入期间不能访问管理员 API、再次代入或修改密码/MFA/SSO 等账号登录安全设置。页面持续显示目标身份和返回入口;改密、重置主机密码、注销与会话到期会撤销相关代入权限。 +- 客户日志查询在 SQL 层排除管理员直接操作、管理员代入操作及无法确认普通操作身份的历史记录,并继续约束 `tenant_id` 和主机 `project_id`。管理员审计记录实际管理员、被代入账号、目标主机、操作结果和来源 IP;客户不因管理员代入而看到后台操作。日志不存文件内容、登录密码或密钥。 +- 浏览器写请求同时校验 Origin 的协议与主机,反代协议头只信任回环来源;无 Origin 的 API 客户端仍受 SameSite 会话与鉴权约束。资源 SQL 查询在归属鉴权后限定主机的内部命名空间及主机编号,关键操作写入审计日志。 +- 主机账号在内部资源命名空间之外还强制绑定 `project_id`;项目、站点、文件和凭据接口二次校验该绑定,只返回该主机的用量和普通操作日志,不返回同用户其他主机数据或内部占位邮箱。普通用户的主机权限按 `owner_tenant_id` 校验,不能把内部 `tenant_id` 当成可变用户归属。 +- 首次安装写接口需要由安装脚本生成的高熵令牌;状态接口不返回令牌。数据库和宝塔目标强制为本机回环地址,正式配置使用原子创建并以 `0600` 保存,存在后不可由安装接口覆盖。 +- 安装和业务 API 响应均标记 `Cache-Control: no-store`;Nginx 模板包含 CSP、禁止嵌入、MIME 嗅探防护与最小浏览器权限策略。 +- 租户站点的基础防护由 Sea vHost 自己生成,不调用宝塔 Nginx 防火墙:全局区按 IP+站点限频,站点扩展文件限制连接数、请求体和超时,拒绝 TRACE/TRACK、隐藏文件和常见敏感构建/配置文件。root 代理写入后先执行 `nginx -t`,再重载;测试或重载失败均恢复原文件。 + +## 配额实现 + +- 磁盘:受 Token 与 Unix Socket 双重保护的 root agent 每分钟只读遍历由主机名推导出的固定受管目录,按文件逻辑大小汇总并写入 `quota_usage`;目录路径不由调用方自由指定,也不跟随目录内符号链接。计量不依赖租户目录的读取权限,因此租户把子目录设为 `0700` 或 `000` 也不能使配额刷新失效,同时 API 文件服务仍无法读取 `.sea-runtime`。Web 上传和在线编辑前会即时复算并拒绝超过套餐的新增内容。检测到超额后,系统把该租户项目标记为 `quota_suspended`,停止网站/FTP/进程,并由 root 代理把主机树重新归属给 Web 文件服务、撤销主机 Linux 身份的写权限;租户仍可在 Web 端下载、删除或清空回收站以恢复到限额内。恢复时重新落实受管 ACL,但项目只转为“已停止”,不会自动启动或删除文件。 +- 数据库:通过宝塔免费基础接口 `GetInfo` 读取主机已登记数据库的实际大小并汇总;超额后暂停主机服务,撤销对应 MySQL 账号的写权限并断开旧连接,保留查询与删表/删除数据的清理能力,恢复额度后还原授权。 +- 月流量:root agent 合并独立站点 Nginx 响应字节与 FTP 文件上传/下载;Nginx 使用 inode/偏移游标累计当月响应字节,兼容 rename 与 copytruncate 轮转;达到限额后停站、停 FTP 并终止租户运行进程。 +- 进程:root agent 从 `/proc/*/status` 按每主机独立 UID 统计真实 PID 数;超过套餐总数后停站、停 FTP,并先 TERM、后 KILL 清理该租户身份的全部进程。普通 Web API 仍启用 `ProtectProc=invisible`,只有内部 Token 与 Socket 双鉴权的 agent 可见全局 PID。 + +四项配额均为真实计量与自动暂停策略。进入 `quota_suspended` 后,所有控制面写操作和主机身份的文件写入都会被拒绝,仅保留停止、读取与数据清理;它们仍属于分钟级控制面软限制而非内核实时限额,运行时或 FTP 在检测窗口内可能产生短暂超额,因此管理员仍需为整机保留容量告警和安全余量。 + +## 上线前安全门 + +1. Web 安装生成的正式配置中 `panel_mock=false`、`agent_mock=false`;生产不允许用旧版环境变量 mock 模式启动。 +2. 宝塔 API 白名单仅包含回环地址;`/var/lib/sea-vhost/config.json` 不得含 `panel_api_key`,broker 凭据文件必须为 `sea-vhost-panel:sea-vhost-panel-control`、权限 `0600`。 +3. `www` 不得属于任何 Sea vHost 控制组;两个控制 Socket 必须为 `0660`,并分别属于 `sea-vhost-agent-control` 与 `sea-vhost-panel-control`。不带或携带错误内部 Token 的变更请求必须返回 401。 +4. 不得在生产允许宝塔自签名证书;为回环面板配置可信证书后关闭安装页中的不安全 TLS 开关。 +5. 验证目录用量扫描、超额停站与恢复流程、Pure-FTPd chroot/UID/GID、PHP `open_basedir`/FPM master 与 worker 的 UID/GID/Capabilities,以及各运行时的实际 `run_user`。以两个测试主机身份互读互写对方目录必须失败,`www` 写入任一主机目录必须失败。该方案是操作系统身份与文件权限隔离,不等同于容器、seccomp 或完整的不可信代码沙箱。 +6. 不安装、不连接也不代理 Docker Socket;后端、broker 和界面均拒绝 Docker 运行时。 +7. `/www/server/panel/vhost/nginx/sea-vhost-security-global.conf` 必须为 `root:root 0644`。隔离代理的 systemd 写例外只能覆盖账号数据库所需的 `/etc`、受管主机根、Nginx 扩展/日志、Pure-FTPd 账户库及自身 state/run 目录;随机抽查站点扩展文件并确认 `nginx -t` 通过。 +8. `sea-vhost-agent` 不使用独立网络命名空间,因为它启动的租户 PHP-FPM 必须访问本机 MySQL 与外部 API;必须确认 PHP master/worker 已降为主机 UID/GID、Capabilities 为零,且 agent 仍只监听 Token 鉴权的 Unix Socket、不监听 TCP。 +9. 在隔离测试机运行 `deploy/panel-canary-verify.mjs`:控制面、broker、agent、主机运行目录和 Web 敏感文件使用不同的合成标记,任何低权限身份、未登录/跨源 API、无令牌 Socket 或受保护 HTTP 路径命中标记都属于上线阻断项。脚本保留 root-only 清单用于复测,但金丝雀不能替代真实密钥扫描、双主机交叉隔离或外部端口审计。 +10. 从服务器外运行 `deploy/public-vulnerability-smoke.mjs`。aaPanel 的 `/sock_shell`、`/webssh`、`/ws_panel`、`/ws_home`、`/ws_project`、`/ws_model` 等特权 WebSocket 对恶意 Origin 返回 101 属于上线阻断项,即使尚未发送消息或证明命令执行;正式面板端口必须限制在回环/可信管理网。反向代理拒绝规则只能作为纵深防御,不能替代后端端口的网络封锁。 diff --git a/docs/sso-ui-acceptance.md b/docs/sso-ui-acceptance.md new file mode 100644 index 0000000..1a6d135 --- /dev/null +++ b/docs/sso-ui-acceptance.md @@ -0,0 +1,36 @@ +# SSO 与界面验收 + +本轮已发布至 36 机器的 `https://host.ser888.cn/`。数据库迁移为 001–028;发布包 SHA-256 为 `cc8c0a3fe4603d2e2107b87888be1f404d8153f09fff09755d76ce85ae0e3a03`。此前带日期的报告保留各自版本,不作为本轮外部服务通过的证据。 + +## 已完成的行为 + +| 设置或入口 | 行为 | +| --- | --- | +| 系统设置 → SSO 登录 | OIDC 配置、首次建号、普通用户密码和管理员密码分别设置 | +| 首次 SSO 登录 | 未绑定身份可用已有用户/管理员密码及已启用的 MFA 绑定;开放建号时可选择创建普通用户 | +| 创建用户 | 仅接受已验证邮箱;不按相同邮箱合并、不自动开通主机、不创建管理员 | +| 已绑定身份 | 完成 OIDC 验证后直接登录 | +| 关闭密码 | 必须启用完整 SSO;关闭管理员密码还要求当前管理员已有对应绑定;后端拒绝相应角色的新密码认证 | +| 解除绑定 / 关闭 SSO | 密码关闭时不可解绑;关闭 SSO 前须恢复管理员和用户密码登录 | +| 主机账号 | 不允许绑定或使用 SSO,始终保留独立主机密码 | +| 既有会话 | 密码策略变更不主动注销已建立的会话 | + +首次建号默认关闭。线上 SSO 仍关闭,普通用户、管理员和主机密码均保持开启;本轮没有替用户启用未提供票据的外部身份服务。密码入口关闭前应先完成所需账号的绑定;未绑定账号不能借首次绑定页绕过关闭策略。 + +## 验证结果 + +- Go 全包测试通过;前端 88 项测试通过,覆盖策略字段提交、不同密码入口名称、首次绑定与 MFA、关闭建号时隐藏创建按钮。 +- 36 上创建独立临时 MySQL 数据库,运行 HTTPS OIDC 模拟服务,使用 RSA 签名令牌与 JWKS,执行真实授权回调及持久化流程;八组集成场景全部通过,临时数据库已移除。 +- 集成场景包括浏览器 state 绑定、PKCE、nonce、一次性票据重放拒绝、Issuer 变更、大小写敏感 subject、不按邮箱合并、未验证邮箱拒绝建号、主机账号拒绝 SSO、分类密码策略与解绑限制,以及已撤销原会话不能完成绑定。 +- SSO 回调使用专用 Lax 流程 Cookie;主会话仍为 Strict。集成测试覆盖跨站回调不携带主会话 Cookie 的正常情况,通过发起会话摘要核验绑定来源。 +- 内置浏览器检查 1400×900 与 390×844 的系统设置、DNS 页面,三项策略显示及默认值正确,窄屏卡片和操作按钮完整;检查结束恢复视口覆盖。检查期间未保存或修改线上 SSO 设置,未发现浏览器警告或错误。 +- 线上通过正常网页退出并重新使用管理员密码登录,登录页账号为空、无示例占位内容;登录成功后恢复管理员视图,临时凭据桥接文件已移除。已启用 SSO 的首次绑定/创建页面使用前端交互测试与后端集成测试验证,未在未配置外部服务的线上假装完成第三方登录。 +- 核对原有 9 个账号与 2 台主机计数、API 配置、SMTP/SSO 设置摘要均保持不变;原体验主机 HTTPS 返回 200,原 QA 主机保持回收状态,API 服务及 Nginx 校验通过。四份已知临时上传文件已清理。 + +界面沿用现有蓝色主题,统一表格、设置卡片、表单间距与登录面板。DNS 凭据操作显示“测试权限”“替换凭据”“删除”,不改变 DNS 托管记录业务规则。 + +## 尚未覆盖 + +没有接入真实外部身份提供商,因此其用户授权界面、生产回调注册及外部 MFA/退出行为不列为通过。模拟 HTTPS 服务的协议与数据库测试不能替代该项联调;线上保持原登录方式可用。 + +操作步骤见 [日常操作](hosting-operations.md#sso-与密码登录),安全边界见 [安全说明](security.md#sso-身份与登录策略)。截图证据保存在本地验收目录,不包含密钥、密码或会话。 diff --git a/docs/ui-acceptance-2026-10-29.md b/docs/ui-acceptance-2026-10-29.md new file mode 100644 index 0000000..2be73e5 --- /dev/null +++ b/docs/ui-acceptance-2026-10-29.md @@ -0,0 +1,63 @@ +# Sea vHost 界面与管理功能验收(2026-10-29) + +验收环境:36 机器,管理入口 `https://host.ser888.cn/`。本轮以专用主机 #15 完成实际网页操作,保留原体验主机 #7。以下区分实际网页操作、自动化验证和未配置的附加功能。 + +## 需求落实 + +| 项目 | 结果与验证 | +| --- | --- | +| 管理总览 | 移除“新建用户”,用户管理保留独立入口;浏览器复核。 | +| 独立主机入口 | 登录或管理员代入后进入主机详情,导航移除总览;浏览器复核。 | +| 管理员代入 | 提示只保留目前主机/用户名称与返回管理视图;实际进入、读写、返回成功。 | +| 证书 | 默认提供 HTTP-01,另有 DNS-01 和上传证书入口;真实域名 HTTP-01 签发、部署成功,原证书手动接管成功。 | +| 凭据弹窗 | 删除指定解释段落,保留凭据查看与管理功能。 | +| 操作日志 | 管理员支持服务端筛选、条数、分页、筛选结果 JSON 导出;实际筛选导出 4 条匹配记录。主机视图实际筛选文件操作,管理员事件不在客户日志中。 | +| 批量任务 | 删除页介绍,三类批量入口统一排列;JSON 输入及凭据导出保留。 | +| 用户删除 | 补充独立删除操作与确认;存在任何绑定主机(含回收中)时禁止删除,必须逐一解绑或转移。临时用户通过网页删除成功,原体验用户因仍有主机而不可删除。 | +| 页面介绍 | 统一移除页面标题下的子介绍;保留操作确认、字段说明与禁用原因。 | +| 主机操作 | 操作列分组排版,回收作为单独操作,不混在编辑表单。 | +| 主机运行环境 | 支持同语言已安装版本切换;额外授权后支持跨语言。网页实测 PHP 8.4→8.3→Node.js→PHP 8.4,先停站,文件、数据库、FTP 保留。Node.js 真实部署后 HTTP/HTTPS 返回预期内容,切回 PHP 后启动成功。 | +| 运行目录 | 主站默认 `/`,允许修改;保留附加网站的独立运行目录。现有 `/public` 网站经过回归。 | +| 环境更新队列 | 不同任务可排队,同节点串行、重复任务拒绝;实际点击检查更新,并在进行期间打开另一组件的安装确认。队列顺序、重复防护及故障恢复经过真实 MySQL 集成测试;本轮未实际执行整套组件升级。 | +| 环境配置页 | 删除“站点运行版本”;主机自己的运行版本在网站管理内设置。 | +| 套餐资源 | 八项独立展示,FTP 账号数与数据库数分开。 | +| DNS 服务商 | 增加西部数码、彩虹聚合 DNS;协议签名、记录识别/精确删除、响应处理均有模拟服务测试。 | +| DNS 域名选择 | 先输入票据并获取可管理域名,再选择保存;西部数码保留单域名密钥方式。验证令牌绑定凭据、域名、归属并限时,禁止替换域名标识。 | +| IP 地址池 | 统一统计、搜索、节点/类型筛选及添加表单;浏览器检查布局并修复搜索图标对齐。 | +| 对接 API | 已吊销密钥不再展示在“已签发密钥”列表;后端撤销机制保留。 | + +## 实测发现并修复的问题 + +1. 宝塔同步返回证书时没有订单编号,旧适配误报失败。现支持同步证书格式,验证证书与私钥、有效期、请求域名后安装,并保留原订单模式兼容。 +2. HTTP-01 的 Nginx 验证目录应与宝塔当前站点运行目录一致。现使用物理运行目录;在 Node.js 反向代理和 PHP `/public` 两种情况下,验证路径均实际返回正确内容。 +3. 手动接管或关闭 SSL 时,需要停止原生宝塔订单续期。特权代理仅保存并移除当前受管站点由系统申请的订单,不删除证书文件;实际接管后跟踪订单清空,自动续期关闭。 +4. 运行环境完成切换后,子表单曾持有旧网站对象。现使用刷新后的对象,当前版本不再被重复提交。 +5. 运行环境切换的独占锁曾被提示为“归属变更”。现说明可能是环境或归属变更,状态刷新遇到 423 时短间隔重试,成功后自动消除错误;测试覆盖卸载时取消重试。 +6. 原生语言项目启动后再次恢复受管目录隔离,避免宝塔启动操作影响独立身份所需权限。 + +## 验证范围 + +- Go 全套测试通过;最后一处仅调整提示文本,生产构建通过。 +- 前端 83 项测试通过,TypeScript / Vite 生产构建通过。 +- 真实 MySQL 临时数据库集成测试通过,完成后删除临时库;覆盖资源 CRUD、回收主机显式解绑、运行队列、权限及日志筛选。 +- HTTP-01 实际签发、证书安装、手动接管、原生续期取消通过。 +- 实际 Node.js 部署、HTTPS 内容、跨语言切换回 PHP、PHP 启动、两种环境下 HTTP-01 目录访问通过。 +- 客户日志只显示自身权限内的普通操作;管理员代入操作保留在管理员审计。 + +本轮界面验收时西部数码、彩虹 DNS 未提供真实票据,仅完成协议、界面及安全边界测试。当日后续彩虹真实账户的域名枚举与加密保存通过,首次 TXT 与 DNS-01 联调曾被上游配置错误阻断;用户修复后另修复了字符串 TTL 适配,真实 TXT 与 DNS-01 闭环已通过;详见 [彩虹 DNS 联调记录](dns-acceptance-2026-10-29.md)。西部数码仍未做真实账号联调。SMTP、SSO 本轮未做外部联调。本轮未声称实际完成所有语言的大版本升级或所有 DNS 服务商的公网签发。 + +一次待部署状态检查曾因把 HTTP 200 一律判为源码泄露而失败;复核正文没有测试源文件内容,已经修正为检查实际内容,不计为源码泄露发现。 + +## 清理与部署结果 + +- 原体验主机 #7 仍为运行状态,源站 HTTPS 返回 200。 +- 专用验收主机 #15 恢复 PHP 8.4、`/public`、原启动设置和原证书;关闭跨语言授权及 FTP,保持未绑定用户,重新回收到 7 天保留期。 +- 新建临时用户已软删除;原有 9 个用户账号及 2 台主机保留。 +- 本轮文件按原内容恢复,新测试文件移入文件回收站;测试产生的操作审计保留。 +- 测试语言项目和固定反向代理已移除,无排队、运行或待核验的环境任务。 +- 应用配置摘要不变,数据库迁移 27 项;API、隔离代理、面板代理运行正常,Nginx 配置检查通过。 +- 清理 50 个已确认属于本轮构建的临时上传文件;服务器保留私有恢复备份。 + +发布包 SHA-256:`107e59d48473e0f178e1d85f1b05f84ed576f253147458127c9be04c0358e47a`。 + +管理员实际操作时:在“用户管理”创建用户,在“虚拟主机”开通并按需绑定用户;进入主机后从“网站管理”选择已安装环境,跨语言选择需要管理员先开启该主机的授权。域名解析完成且站点运行后可点击 HTTP-01,DNS-01 与上传证书按需使用。 diff --git a/docs/web-acceptance-2026-10-26.md b/docs/web-acceptance-2026-10-26.md new file mode 100644 index 0000000..edfe349 --- /dev/null +++ b/docs/web-acceptance-2026-10-26.md @@ -0,0 +1,100 @@ +# Sea vHost 单机 Web 流程与权限验收(2026-10-26) + +> 历史验收记录:环境、版本、数量及结论仅适用于文中所列日期,不代表当前服务重新实测。当前状态见 [项目状态整理](project-status-2026-10-29.md)。 + +本轮在 `36.140.39.34`、控制台 `https://host.ser888.cn/` 完成。使用 Debian 13 / amd64、宝塔 Linux 12、本机 Nginx / MySQL / Pure-FTPd 和 Sea vHost 本机节点;没有操作旧 202 测试机。 + +**结论:本轮定义的 Web 创建、部署、管理、账号安全、主机到期回收和权限隔离流程通过,124 个验收检查点通过。** 未配置外部服务和未执行的功能见文末,不将其算作实测通过。 + +最终部署包 SHA-256: + +```text +7aff33da5ebf0a85be2584cc2e5797a046aa121cf9c6ee0bc2c7b40152200400 +``` + +数据库已应用 `016_administrator_impersonation.sql`;API、面板 broker、隔离 agent 均运行,`nginx -t` 通过,既有平台配置和体验主机保留。 + +## 测试方法 + +使用已有 Playwright 与 Microsoft Edge,通过正常登录、表单、文件选择器、按钮和弹窗操作 Web。套餐、用户、主机、附加网站、运行目录、文件写入、证书安装、域名提交/审核、密码/MFA、到期时间均由实际界面提交,没有用直接数据库插入代替 Web 创建。 + +接口请求仅用于读取结果、核对范围以及尝试应拒绝的越权请求;另外在独立临时 MySQL 库执行真实 HTTP 中间件和迁移集成测试。临时库测试后删除。 + +本机网络存在 Fake-IP DNS;浏览器仅为测试域名固定解析至 36,保留真实 Host / SNI,并开启 HTTPS 证书校验。手动证书测试使用自生成、域名匹配的短期测试证书,单独将该证书作为测试信任锚并核对实际服务证书指纹;没有关闭管理站点 TLS 校验。自定义测试域名只验证审核和 Nginx 绑定,不把它算作外部 DNS 解析联调。 + +## Web 流程结果 + +| 流程 | 实际操作及结果 | +| --- | --- | +| 管理员开通 | 创建 1 个测试套餐、2 个用户、3 台 PHP 主机;A 用户两台、B 用户一台,分别生成主机/FTP/MySQL 凭据 | +| 多主机管理 | A 用户可切换并写入自己的两台主机;主机详情展示实际套餐、目录、用量与网站入口 | +| 文件传输 | 文件选择器拒绝超过 20 MiB 的文件,实际上传 20 MiB 成功;Range 下载返回 206 和正确字节数;实际点击下载链接并校验完整文件 SHA-256;文本编辑、移入回收站和清空均通过 | +| 运行目录 | 主站从 `/public` 切换到 `/custom-webqa`,实际 HTTP 返回新目录内容,再恢复 `/public` | +| PHP | 正常执行 PHP 页面,主站通过 Web 停止和启动 | +| Node.js | 使用已安装 `v24.22.1`,通过 Web 建站、写入源码、检查入口、部署、访问、停止、启动、删除网站;删除后源码仍可读取,再由 Web 删除源码目录 | +| Python | 使用已安装 `3.12.15`,完成同样的 Web 生命周期,实际服务返回预期标记 | +| Go | 使用 `go1.27.3` 构建的 Linux 程序,通过文件选择器上传,完成同样的 Web 生命周期 | +| Java | 使用 `jdk-25.0.3` 与测试 JAR,通过文件选择器上传,完成同样的 Web 生命周期,实际 HTTP 返回成功 | +| MySQL | 查看授权凭据;通过 Web 部署的 PHP 程序创建表、写入并读取标记,访问 B 主机数据库得到 MySQL 权限拒绝;临时凭据文件和测试 PHP 入口随后清理/恢复 | +| SSL | Web 上传匹配的 PEM 证书/私钥,核对真实 HTTPS 证书与页面,再通过 Web 关闭 SSL 并验证 HTTP | +| 域名 | 用户从目标网站提交自定义域名,管理员可同时看到默认子域名和待审核域名,批准后目标 Nginx 站点实际响应正确内容 | +| 主机密码 | 用户在凭据窗口重置,生成新密码,旧主机会话及旧密码失效;新密码可登录;FTP/MySQL 密码不变 | +| 用户密码 | 从账号安全页改密,当前会话保留,其他同用户会话失效,新密码可重新登录 | +| MFA | 正常界面启用 TOTP、完成挑战登录、恢复码登录、拒绝重复使用恢复码、关闭 MFA 并注销全部会话,恢复密码登录 | +| 到期恢复 | Web 设置 A1 到期,后台进入宽限并停止;Web 写入返回明确 `423 host_not_writable`;A2 仍能运行和写入;续期后手动启动 A1,恢复页面和写入 | +| 自动回收 | 通过 Web 为三台测试主机设置已越过宽限/保留期限的到期时间,由正常生命周期任务回收;没有修改服务器时钟或用 SQL 删除主机代替该流程 | +| 管理页面 | 用户、主机、套餐、域名、DNS、IP、到期回收、系统设置、日志、节点、环境配置均实际打开;环境页显示五类可用组件和已安装版本 | +| 响应式与退出 | 390×844 下导航抽屉能进入真实主机详情;管理员与客户退出登录正常;退出后登录表单无残留账号 | + +所有完成阶段均未出现浏览器未捕获异常或管理 API 的 5xx 响应。预期失败请求(越权、旧密码、已使用恢复码、到期写入)不算成功业务请求。 + +## 日志和权限规则 + +| 身份 | 可管理/查看 | 不可查看/执行 | +| --- | --- | --- | +| 管理员 | 全局资源与审计;从用户/主机列表快捷进入目标账号 | 不通过客户接口绕过目标账号权限 | +| 普通用户 | 自身账号操作、名下全部主机及这些主机上的普通用户/主机账号操作;可按主机筛选日志 | 其他用户资源;管理员直接或代入操作日志;管理员 API;自行开通整台虚拟主机 | +| 主机账号 | 唯一绑定主机及其普通用户/主机账号操作 | 同用户其他主机、其他用户主机、用户级账号日志、管理员日志、用户 DNS API 凭据管理、主机密码重置 | +| 管理员代入用户 | 目标用户的业务读写范围;明显的代入提示和返回入口 | 管理员 API、嵌套代入、修改/绑定账号密码、MFA、SSO 等登录安全设置 | +| 管理员代入主机 | 唯一目标主机的业务读写范围 | 同用户其他主机、其他用户资源,以及上述管理员/账号安全能力 | + +实测 A 用户日志聚合包含 A1/A2,按 A1 筛选不含 A2;真实 A1 主机账号能看到 A 用户对 A1 的操作及自己的操作,不能看到 A2/B1。真实 A 用户也能看到 A1 主机账号的操作。管理员分别代入 A 用户和 A1 并通过 Web 写入文件,这些事件只进入管理员审计,保存实际管理员与被代入账号两个身份,不出现在客户日志中。 + +日志隔离由后端 SQL 约束,不依赖浏览器隐藏行。不能确认普通操作身份的历史记录也不返回客户。管理员审计在目标账号被回收后仍保留其 ID。 + +代入使用独立 `sea_impersonation` Cookie:HttpOnly、Secure、SameSite=Strict,最长 30 分钟,且不能超过原管理员会话有效期。原 `sea_session` 保持不变,退出代入后恢复原管理员身份。真实 MySQL / HTTP 集成测试还覆盖: + +- 未登录/普通用户不能发起代入,管理员不能成为目标。 +- 子令牌不能作为普通登录令牌使用;不能换绑同管理员的另一个会话或普通用户会话。 +- 目标改密、父会话注销、子会话过期或退出代入后,旧代入令牌失效。 +- 代入期间越权、账号安全和 OIDC 绑定请求被拒绝。 +- 代入失败操作同样只写入管理员审计。 +- 历史日志归属迁移可重复执行,无法可靠归属的记录不进入主机日志。 + +## 本轮修复 + +1. 管理员启动依赖的 `/admin/domains/pending` 被误作数字域名 ID 查询,导致 404 并阻断控制台加载;现仅在路由确实带 `id` 时建立域名上下文,并加入真实 HTTP 回归测试。 +2. 新增网站弹窗先于环境清单加载时,版本状态可能为空而选项已显示,导致创建按钮不可用;现清单到达后选择有效已安装版本,并增加前端回归测试。 +3. 客户日志原先包含管理员事件;现 SQL 层排除管理员和代入事件,并记录实际管理员/目标账号,后台可追责。 +4. 补齐管理员临时代入、显式提示、返回原会话和相关权限/撤销检查;客户控制台补充正常退出登录入口。 +5. 到期/身份未核验导致的文件写入限制原先被当作资源检查故障,返回 503;现返回业务限制 `423 host_not_writable` 并说明原因,实际 Web 到期与续期流程通过。 + +本地 Go 全套测试通过;前端 32 项测试通过;TypeScript/Vite 生产构建通过。两组 MySQL 集成测试在 36 的独立临时数据库中通过并清理,包含新增的到期写入状态回归。 + +## 清理与保留 + +- 三台临时主机的 Sea vHost 记录、宝塔站点、FTP、MySQL、主机目录与 Linux 身份均已清除,broker 登记表无残留。 +- 三份回收归档保留 14 天,核对文件、数据库数量、SQL 字节数与 SHA-256 清单;A1 的归档包含实际写入的数据库标记。本轮验证归档内容,未将该归档重新恢复到新主机。 +- 两名测试用户已禁用并撤销会话;保留必要用户归属元数据,使备份到期清理仍可正常调度。未引用的测试套餐已删除。 +- `sv8a500e52e9` 体验主机、原账号凭据和平台配置保留;最后重新验证其 HTTPS 与主机登录。另以该主机执行本机显式 FTPS:证书校验、上传/下载、Web 读取同一文件、根目录约束均通过,测试文件随后精确删除。 +- 临时浏览器账号文件、测试证书私钥与测试账号密码检查点已清理;报告和截图不包含密码、面板密钥或证书私钥。 + +## 本轮未计为实测通过的内容 + +- SMTP 实际投递、第三方 OIDC 服务绑定登录、外部 DNS API 和公网 ACME 自动签发/续期:没有本轮可用的外部服务配置,仅检查相应页面,未制造真实外部账号/解析变更。 +- 本轮使用已有语言环境,未重复安装 SDK、升级 PHP 补丁或迁移既有业务的运行版本。 +- 公网 FTPS 端口/NAT 联调未执行;按要求仅验证本机 FTPS。 +- 本轮验证单机现有安装,没有重复空白安装、两台物理宝塔节点联调、长时间负载或全面漏洞扫描,也未重复填满磁盘/数据库测试容量暂停。 +- 用户停用/删除、套餐编辑/删除尚没有完整 Web 入口。本轮测试用户禁用和未引用套餐删除由受控维护完成,不计作 Web 用户/套餐删除功能通过。 + +结构化结果与脱敏截图位于本次工作区外的验收产物目录:`C:/Users/canglan/.codex/visualizations/2026/10/06/01a11073-d571-7323-83e7-c88f0c7cc3cf/`,入口文件为 `webflow36-report.json`。 diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..248a14f --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,15 @@ + + + + + + + + + Sea vHost + + +
+ + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000..380b373 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,2382 @@ +{ + "name": "sea-vhost-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "sea-vhost-web", + "version": "0.1.0", + "dependencies": { + "@vitejs/plugin-react": "latest", + "lucide-react": "latest", + "react": "latest", + "react-dom": "latest" + }, + "devDependencies": { + "@testing-library/jest-dom": "latest", + "@testing-library/react": "latest", + "@types/react": "latest", + "@types/react-dom": "latest", + "jsdom": "latest", + "playwright": "^1.63.0", + "typescript": "latest", + "vite": "latest", + "vitest": "latest" + } + }, + "node_modules/@adobe/css-tools": { + "version": "4.5.0", + "resolved": "https://registry.npmmirror.com/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@asamuzakjp/css-color": { + "version": "7.1.3", + "resolved": "https://registry.npmmirror.com/@asamuzakjp/css-color/-/css-color-7.1.3.tgz", + "integrity": "sha512-1t1U8Cm3RBl9vh3RAZhjkPaduzLSvQJRToRrxpGR/eDRW99mOREleuu+mWfiFa795bUzjwht7NgphCKTs2ianQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.4.2", + "@csstools/css-color-parser": "^4.2.5", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "9.2.4", + "resolved": "https://registry.npmmirror.com/@asamuzakjp/dom-selector/-/dom-selector-9.2.4.tgz", + "integrity": "sha512-YnVzxDxLaqL0t7Q4wfcgHZjg55Wm6y5EaO7Bhu3q9J7wq/8iw3PhsnWiOQhYekx4VexnbkgWpTT6n+QIV7kczw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmmirror.com/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmmirror.com/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmmirror.com/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.6", + "resolved": "https://registry.npmmirror.com/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz", + "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.15", + "resolved": "https://registry.npmmirror.com/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz", + "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmmirror.com/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.152.0", + "resolved": "https://registry.npmmirror.com/@oxc-project/types/-/types-0.152.0.tgz", + "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz", + "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz", + "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz", + "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz", + "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz", + "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz", + "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz", + "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz", + "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz", + "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz", + "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz", + "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz", + "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz", + "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz", + "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz", + "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "license": "MIT" + }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmmirror.com/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "7.0.1", + "resolved": "https://registry.npmmirror.com/@testing-library/jest-dom/-/jest-dom-7.0.1.tgz", + "integrity": "sha512-oMDTC3oA+6CXSO2JZnvOI7CA6oVub6kij5ggk9ohwye5slmkwxYDXcPOVxgMw/RQlticjtO0C1RZkR97HgrWMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=22", + "npm": ">=6", + "yarn": ">=1" + }, + "peerDependencies": { + "@testing-library/dom": ">=10 <11", + "vitest": ">= 0.32" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmmirror.com/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmmirror.com/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmmirror.com/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmmirror.com/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmmirror.com/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.2", + "resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", + "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.152.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.3", + "resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-5.0.3.tgz", + "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.3", + "estree-walker": "^3.0.3", + "magic-string": "^1.2.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.3", + "resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-5.0.3.tgz", + "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmmirror.com/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmmirror.com/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmmirror.com/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmmirror.com/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmmirror.com/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmmirror.com/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmmirror.com/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmmirror.com/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/jsdom": { + "version": "30.1.2", + "resolved": "https://registry.npmmirror.com/jsdom/-/jsdom-30.1.2.tgz", + "integrity": "sha512-0FFE/jE1rppmVfUrJUgxqXjcwolZYIGtAgj1pTussMhNZxIxi7W/PvfWaMNroGi2B36X1IKHbexpZ9DhkoOPiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^9.2.4", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.11.2", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "canvas": "^3.2.3" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/lucide-react": { + "version": "1.52.0", + "resolved": "https://registry.npmmirror.com/lucide-react/-/lucide-react-1.52.0.tgz", + "integrity": "sha512-TUgPtl5ZI9WgxOcbu4ckaC5B3l1qxPQrCMgb6OfUB9owx/OvSJfcf93SMgUWAxRw5/1XDfh9uI5F5iNGXCcGDQ==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmmirror.com/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmmirror.com/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmmirror.com/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmmirror.com/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmmirror.com/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.3.0", + "resolved": "https://registry.npmmirror.com/react/-/react-19.3.0.tgz", + "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.0" + } + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmmirror.com/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rolldown": { + "version": "1.2.12", + "resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.12.tgz", + "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==", + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.152.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.12", + "@rolldown/binding-android-arm64": "1.2.12", + "@rolldown/binding-darwin-arm64": "1.2.12", + "@rolldown/binding-darwin-x64": "1.2.12", + "@rolldown/binding-freebsd-x64": "1.2.12", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", + "@rolldown/binding-linux-arm64-gnu": "1.2.12", + "@rolldown/binding-linux-arm64-musl": "1.2.12", + "@rolldown/binding-linux-ppc64-gnu": "1.2.12", + "@rolldown/binding-linux-s390x-gnu": "1.2.12", + "@rolldown/binding-linux-x64-gnu": "1.2.12", + "@rolldown/binding-linux-x64-musl": "1.2.12", + "@rolldown/binding-openharmony-arm64": "1.2.12", + "@rolldown/binding-win32-arm64-msvc": "1.2.12", + "@rolldown/binding-win32-x64-msvc": "1.2.12" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmmirror.com/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tinybench": { + "version": "6.2.0", + "resolved": "https://registry.npmmirror.com/tinybench/-/tinybench-6.2.0.tgz", + "integrity": "sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmmirror.com/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tldts": { + "version": "7.4.16", + "resolved": "https://registry.npmmirror.com/tldts/-/tldts-7.4.16.tgz", + "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.16" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.16", + "resolved": "https://registry.npmmirror.com/tldts-core/-/tldts-core-7.4.16.tgz", + "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici": { + "version": "8.11.2", + "resolved": "https://registry.npmmirror.com/undici/-/undici-8.11.2.tgz", + "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/vite": { + "version": "8.3.3", + "resolved": "https://registry.npmmirror.com/vite/-/vite-8.3.3.tgz", + "integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==", + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.11", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.3", + "resolved": "https://registry.npmmirror.com/vitest/-/vitest-5.0.3.tgz", + "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.3", + "chai": "^6.2.2", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.2.3", + "obug": "^2.1.4", + "picomatch": "^4.0.7", + "std-env": "^4.2.0", + "tinybench": "^6.1.4", + "tinyexec": "^1.3.0", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.3", + "@vitest/browser-preview": "5.0.3", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.3", + "@vitest/coverage-v8": "5.0.3", + "@vitest/ui": "5.0.3", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmmirror.com/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.2.0", + "resolved": "https://registry.npmmirror.com/whatwg-url/-/whatwg-url-17.2.0.tgz", + "integrity": "sha512-IhLIHNcBrzIixC5XXsbr4DxdjajyA5vQ5RwGZMtrUp+GbtE5Nrsge9QKau7jXrC0aTXLYGV0xiW7Tb4YS2aomw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..7848ce1 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,29 @@ +{ + "name": "sea-vhost-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite --host 0.0.0.0", + "build": "tsc -b && vite build", + "preview": "vite preview --host 0.0.0.0", + "test": "vitest run" + }, + "dependencies": { + "@vitejs/plugin-react": "latest", + "lucide-react": "latest", + "react": "latest", + "react-dom": "latest" + }, + "devDependencies": { + "@testing-library/jest-dom": "latest", + "@testing-library/react": "latest", + "@types/react": "latest", + "@types/react-dom": "latest", + "jsdom": "latest", + "playwright": "^1.63.0", + "typescript": "latest", + "vite": "latest", + "vitest": "latest" + } +} diff --git a/frontend/src/APIContracts.test.ts b/frontend/src/APIContracts.test.ts new file mode 100644 index 0000000..552f425 --- /dev/null +++ b/frontend/src/APIContracts.test.ts @@ -0,0 +1,17 @@ +import {afterEach,expect,it,vi} from 'vitest'; +import {api,type AdminSettings} from './api'; +afterEach(()=>vi.unstubAllGlobals()); +it('can save a read settings object without returning readonly server metadata',async()=>{ + const fetch=vi.fn().mockResolvedValue(new Response(null,{status:204}));vi.stubGlobal('fetch',fetch); + const settings:AdminSettings={domainApproval:true,filingRequired:false,cdnCnameTarget:'',graceDays:3,recycleDays:7,backupRetentionDays:14,smtp:{enabled:false,host:'mail.example.invalid',port:465,username:'test',from:'',adminRecipients:'',startTls:true,secretConfigured:true},oidc:{enabled:false,issuer:'',clientId:'',redirectUri:'',secretConfigured:true,bindingOnly:true,passwordLogin:true}}; + await api.saveAdminSettings(settings); + const body=JSON.parse(fetch.mock.calls[0][1].body); + expect(body.smtp).not.toHaveProperty('secretConfigured');expect(body.oidc).not.toHaveProperty('secretConfigured');expect(body.oidc).not.toHaveProperty('bindingOnly');expect(body.oidc).not.toHaveProperty('passwordLogin'); + expect(body.smtp).not.toHaveProperty('secret');expect(body.oidc).not.toHaveProperty('secret');expect(body.smtp.host).toBe(settings.smtp.host);expect(body.graceDays).toBe(3); +}); + +it('sends SSO login policies without readonly metadata',async()=>{ + const fetch=vi.fn().mockResolvedValue(new Response(null,{status:204}));vi.stubGlobal('fetch',fetch); + const input={domainApproval:true,filingRequired:false,cdnCnameTarget:'',graceDays:3,recycleDays:7,backupRetentionDays:14,smtp:{enabled:false,host:'',port:465,username:'',from:'',adminRecipients:'',startTls:true,secretConfigured:false},oidc:{enabled:true,issuer:'https://id.example.invalid',clientId:'vhost',redirectUri:'https://control.example.invalid/api/v1/auth/oidc/callback',secretConfigured:true,bindingOnly:false,passwordLogin:false,autoCreate:true,userPasswordLogin:false,adminPasswordLogin:true}} satisfies AdminSettings; + await api.saveAdminSettings(input);const body=JSON.parse(fetch.mock.calls[0][1].body);expect(body.oidc).toMatchObject({autoCreate:true,userPasswordLogin:false,adminPasswordLogin:true});expect(body.oidc).not.toHaveProperty('secretConfigured'); +}); diff --git a/frontend/src/AdminActions.test.tsx b/frontend/src/AdminActions.test.tsx new file mode 100644 index 0000000..9566d99 --- /dev/null +++ b/frontend/src/AdminActions.test.tsx @@ -0,0 +1,72 @@ +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 {AdminDomains,DomainPolicyForm} from './components/AdminDomains'; +import {AdminLogs} from './components/AdminLogs'; +import {ResourceCenter} from './components/ResourceCenter'; +import {api,type AdminProject,type DomainResource,type User} from './api'; +import {demoPlan} from './data'; +import {initialProjects} from './data'; + +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +it('retains a rejected plan form and explains the failure',async()=>{ + const create=vi.fn().mockRejectedValue(new Error('套餐名称重复')); + render();fireEvent.change(screen.getByLabelText('套餐名称'),{target:{value:'重复套餐'}});fireEvent.click(screen.getByRole('button',{name:'创建套餐'})); + expect(await screen.findByRole('alert')).toHaveTextContent('套餐名称重复');expect(screen.getByLabelText('套餐名称')).toHaveValue('重复套餐');expect(screen.getByRole('button',{name:'创建套餐'})).toBeEnabled(); +}); +it('shows a network save failure instead of closing or silently rejecting',async()=>{ + render(); + fireEvent.click(screen.getByRole('button',{name:'保存网络配置'}));expect(await screen.findByRole('alert')).toHaveTextContent('端口冲突');expect(screen.getByRole('button',{name:'保存网络配置'})).toBeEnabled(); +}); +it('blocks default settings from being edited after an initial admin read failure',async()=>{ + vi.spyOn(api,'adminOverview').mockRejectedValue(new Error('管理数据读取失败'));vi.spyOn(api,'adminSettings').mockRejectedValue(new Error('设置读取失败')); + render(); + expect(await screen.findByRole('alert')).toHaveTextContent('读取失败');expect(screen.getByRole('button',{name:'重新读取管理数据'})).toBeEnabled();expect(screen.queryByRole('heading',{name:'平台总览'})).not.toBeInTheDocument(); +}); +it('reports a rejected domain action and preserves the current approval switch',async()=>{ + render(); + fireEvent.click(screen.getByRole('switch',{name:'自定义域名审核'}));expect(await screen.findByRole('alert')).toHaveTextContent('策略保存失败');expect(screen.getByRole('switch')).toBeChecked(); +}); +it('saves explicit filing exemptions and preserves the form on rejection',async()=>{ + const save=vi.fn().mockRejectedValue(new Error('配置未保存')); + render(); + fireEvent.change(screen.getByLabelText('备案状态'),{target:{value:'exempt'}});fireEvent.click(screen.getByRole('button',{name:'保存域名配置'})); + expect(await screen.findByRole('alert')).toHaveTextContent('配置未保存');expect(save).toHaveBeenCalledWith(expect.objectContaining({filingStatus:'exempt',cnameTarget:'host.example.invalid'})); +}); +it('filters admin audit records on the server and disables empty exports',async()=>{ + const fetch=vi.spyOn(api,'adminAudit').mockResolvedValue({logs:[],total:0,page:1,limit:100}); + render(); + fireEvent.change(screen.getByLabelText('搜索日志'),{target:{value:'不存在的日志'}}); + await waitFor(()=>expect(fetch).toHaveBeenCalled());expect(await screen.findByText('暂无操作日志')).toBeInTheDocument();expect(screen.getByRole('button',{name:'导出 JSON'})).toBeDisabled(); + expect(fetch.mock.calls.at(-1)?.[0].get('q')).toBe('不存在的日志'); + fireEvent.change(screen.getByLabelText('每页条数'),{target:{value:'200'}});await waitFor(()=>expect(fetch.mock.calls.at(-1)?.[0].get('limit')).toBe('200')); +}); +it('does not manufacture live database rows when resource loading fails and supports retry',async()=>{ + vi.spyOn(api,'resources').mockRejectedValueOnce(new Error('资源读取失败')).mockResolvedValueOnce({sites:[],domains:[],ftpAccounts:[],databases:[]}); + render(); + expect(await screen.findByRole('alert')).toHaveTextContent('资源读取失败');expect(screen.queryByText('进入 phpMyAdmin')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'刷新资源'}));await waitFor(()=>expect(screen.getByText('暂无数据库')).toBeInTheDocument()); +}); + +it('copies exact plan quotas into a new editable form without changing the source',async()=>{ + const save=vi.fn().mockResolvedValue(undefined);const plan={...demoPlan,storageBytes:123*1024**2,bandwidthMbps:7,projectLimit:2}; + render();fireEvent.click(screen.getByRole('button',{name:'复制套餐 '+plan.name})); + expect(screen.getByLabelText('套餐名称')).toHaveValue(plan.name+' 副本');fireEvent.click(screen.getByRole('button',{name:'保存为新套餐'})); + await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({name:plan.name+' 副本',storageBytes:plan.storageBytes,bandwidthMbps:7,projectLimit:2}))); + expect(plan.name).toBe(demoPlan.name); +}); +it('explains plan deletion restrictions and retains a rejected deletion dialog',async()=>{ + vi.spyOn(api,'deletePlan').mockRejectedValue(new Error('套餐刚被主机使用')); + render(); + expect(screen.getByRole('button',{name:'删除套餐 '+demoPlan.name})).toBeDisabled();fireEvent.click(screen.getByRole('button',{name:'删除套餐 可删除套餐'}));expect(screen.getByRole('button',{name:'确认删除套餐'})).toBeDisabled();fireEvent.change(screen.getByLabelText('输入套餐名称确认删除'),{target:{value:'可删除套餐'}});fireEvent.click(screen.getByRole('button',{name:'确认删除套餐'}));expect(await screen.findByRole('alert')).toHaveTextContent('套餐刚被主机使用'); +}); +it('unbinds only a confirmed custom domain and never offers assigned-domain removal',async()=>{ + const domain={id:9,domain:'custom.example.invalid',kind:'custom',status:'pending'} as DomainResource;const unbind=vi.fn().mockResolvedValue(undefined); + render(); + expect(screen.getAllByRole('button',{name:/^解绑$/})).toHaveLength(1);fireEvent.click(screen.getByRole('button',{name:/^解绑$/}));expect(screen.getByRole('button',{name:'确认解绑'})).toBeDisabled();fireEvent.change(screen.getByLabelText('输入域名确认解绑'),{target:{value:domain.domain}});fireEvent.click(screen.getByRole('button',{name:'确认解绑'}));await waitFor(()=>expect(unbind).toHaveBeenCalledWith(domain)); +}); + +it('shows effective FTP quota suspension separately from the saved enable switch',async()=>{ + const project={...initialProjects[0],status:'quota_suspended' as const};vi.spyOn(api,'resources').mockResolvedValue({sites:[],domains:[],databases:[],ftpAccounts:[{id:1,projectId:project.id,hostName:project.hostName,projectName:project.name,username:project.hostName,rootPath:project.path,createdAt:project.createdAt,enabled:true}]}); + render();expect(await screen.findByText('配额暂停')).toBeInTheDocument();expect(screen.getByText('开关已启用,解除超额后自动恢复')).toBeInTheDocument();expect(screen.getByRole('button',{name:'重置密码'})).toBeDisabled();expect(screen.getByRole('button',{name:'停用'})).toBeEnabled(); +}); diff --git a/frontend/src/AdminBatches.test.tsx b/frontend/src/AdminBatches.test.tsx new file mode 100644 index 0000000..0bffcff --- /dev/null +++ b/frontend/src/AdminBatches.test.tsx @@ -0,0 +1,55 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {BatchComposer,BatchJobs} from './components/AdminBatches'; +import {api,type AdminBatch,type BatchPreviewRow} from './api'; +import {demoPlan} from './data'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +it('describes a start batch as an execution result without claiming it generated passwords',async()=>{ + const job:AdminBatch={id:9,administratorId:1,operation:'host_start',state:'completed',total:1,succeeded:1,failed:0,uncertain:0,pending:0,createdAt:new Date().toISOString(),secretsExpireAt:'2099-01-01T00:00:00Z',items:[]}; + vi.spyOn(api,'batches').mockResolvedValue({batches:[job]});vi.spyOn(api,'batch').mockResolvedValue({batch:job}); + render(); + fireEvent.click(await screen.findByRole('button',{name:'查看结果 #9'})); + expect(await screen.findByRole('link',{name:'下载结果 JSON'})).toHaveAttribute('href','/api/v1/admin/batches/9/download'); + expect(screen.getByText(/本次操作不会生成新密码/)).toBeInTheDocument(); + expect(screen.queryByRole('link',{name:'下载结果与凭据 JSON'})).not.toBeInTheDocument(); +}); +it('locks the batch draft while its preview is being verified',async()=>{ + let finish!:(value:{rows:BatchPreviewRow[]})=>void; + vi.spyOn(api,'previewBatch').mockReturnValue(new Promise(resolve=>{finish=resolve})); + render(); + fireEvent.click(screen.getByRole('button',{name:'验证并预览'})); + expect(screen.getByLabelText('名称前缀')).toBeDisabled(); + expect(screen.getByLabelText('输入方式')).toBeDisabled(); + expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled(); + finish({rows:[{row:1,label:'user',valid:true,detail:'可以执行'}]}); + await waitFor(()=>expect(screen.getByLabelText('名称前缀')).toBeEnabled()); + fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'changed-name'}}); + expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled(); +}); +it('defaults ownership changes to preserve credentials and stop sites, with explicit alternatives',async()=>{ + const preview=vi.spyOn(api,'previewBatch').mockResolvedValue({rows:[{row:1,label:'sv0123456789',valid:true,detail:'可以执行'}]}); + render(); + fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalledWith('assign_hosts',[expect.objectContaining({hostId:9,ownershipVersion:3,credentialMode:'preserve',stopServices:true,resumeOwnership:false,tenantId:0})])); + fireEvent.change(screen.getByLabelText('凭据处理'),{target:{value:'reset'}});fireEvent.click(screen.getByLabelText('变更前停止全部网站(默认)'));expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled(); + fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenLastCalledWith('assign_hosts',[expect.objectContaining({credentialMode:'reset',stopServices:false})])); +}); +it('requires preview before queueing users and only exposes credentials through the explicit download',async()=>{ + const preview=vi.spyOn(api,'previewBatch').mockResolvedValue({rows:[{row:1,label:'ui-batch-0001@vhost.ser888.cn',valid:true,detail:'可以执行'}]}); + const job:AdminBatch={id:31,administratorId:1,operation:'create_users',state:'completed',total:1,succeeded:1,failed:0,uncertain:0,pending:0,createdAt:new Date().toISOString(),secretsExpireAt:'2099-01-01T00:00:00Z',items:[]}; + const submit=vi.spyOn(api,'createBatch').mockResolvedValue({batch:job});vi.spyOn(api,'batch').mockResolvedValueOnce({batch:{...job,state:'running',secretsExpireAt:undefined}}).mockResolvedValue({batch:job}); + render(); + expect(screen.getByRole('button',{name:/提交.*项任务/})).toBeDisabled();fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-batch'}}); + fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalled());expect(preview.mock.calls[0][1][0]).toMatchObject({slug:'ui-batch-0001',email:'ui-batch-0001@vhost.ser888.cn'});expect(preview.mock.calls[0][1][0].password).toBeUndefined(); + fireEvent.click(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'); +}); +it('allows a host without a bound user and chooses the installed version after async catalog loading',async()=>{ + vi.spyOn(api,'nodes').mockResolvedValue({nodes:[{id:1,name:'本机',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true,lastError:''}]}); + vi.spyOn(api,'panelSites').mockResolvedValue({sites:[],versions:{PHP:['8.4'],'Node.js':[],Python:[],Go:[],Java:[]}}); + const preview=vi.spyOn(api,'previewBatch').mockResolvedValue({rows:[{row:1,label:'ui-host-0001',valid:true,detail:'可以执行'}]}); + render(); + fireEvent.change(screen.getByLabelText('创建数量'),{target:{value:'1'}});fireEvent.change(screen.getByLabelText('名称前缀'),{target:{value:'ui-host'}});await waitFor(()=>expect(screen.getByRole('combobox',{name:'批量运行版本'})).toHaveValue('8.4')); + fireEvent.click(screen.getByRole('button',{name:'验证并预览'}));await waitFor(()=>expect(preview).toHaveBeenCalledWith('create_hosts',[expect.objectContaining({name:'ui-host-0001',tenantId:0,nodeId:1,version:'8.4'})])); +}); diff --git a/frontend/src/AdminHosts.test.tsx b/frontend/src/AdminHosts.test.tsx new file mode 100644 index 0000000..8b6b72b --- /dev/null +++ b/frontend/src/AdminHosts.test.tsx @@ -0,0 +1,26 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,within} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {AdminHosts} from './components/AdminHosts'; +import type {AdminProject} from './api'; +import {demoPlan} from './data'; +afterEach(cleanup); +const projects:AdminProject[]=Array.from({length:12},(_,i)=>({id:i+1,tenantName:'用户',hostName:'sv'+String(i).padStart(10,'0'),name:'站点'+i,domain:'site'+i+'.vhost.ser888.cn',path:'/www/wwwroot/test',runPath:'/public',runtime:i%2?'PHP':'Python',version:i%2?'8.4':'3.12.15',status:'running',sslStatus:'off',siteCount:1,dedicatedIp:false,httpPort:80,httpsPort:443,createdAt:'',nodeId:1,planId:demoPlan.id,ownershipVersion:7})); +it('filters hosts, resets the filter and paginates without losing the selected batch target',()=>{ + const bulk=vi.fn();render(); + expect(screen.getAllByRole('checkbox')).toHaveLength(11); + fireEvent.click(screen.getByLabelText('选择主机 '+projects[0].hostName)); + expect(screen.getByLabelText('选择本页主机')).toBePartiallyChecked(); + fireEvent.click(screen.getByRole('button',{name:'下一页'})); + expect(screen.getAllByRole('checkbox')).toHaveLength(3); + fireEvent.click(screen.getByRole('button',{name:'绑定 / 解绑用户'})); + expect(bulk).toHaveBeenCalledWith({operation:'assign_hosts',rows:[{hostId:1,ownershipVersion:7}]}); + fireEvent.change(screen.getByLabelText('筛选运行环境'),{target:{value:'Python'}}); + expect(within(screen.getByRole('table')).getAllByRole('row')).toHaveLength(7); + expect(screen.getByText('1 / 1')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button',{name:'重置'})); + expect(screen.getByText('1 / 2')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button',{name:'清空选择'})); + expect(screen.getByRole('button',{name:'绑定 / 解绑用户'})).toBeDisabled(); + expect(screen.getByLabelText('选择本页主机')).not.toBePartiallyChecked(); +}); diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx new file mode 100644 index 0000000..a35d45e --- /dev/null +++ b/frontend/src/App.test.tsx @@ -0,0 +1,319 @@ +import '@testing-library/jest-dom/vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; +import {DNSCredentials} from './components/DNSCredentials'; +import { App } from './App'; +import { AdminConsole } from './components/AdminConsole'; +import { InstallWizard } from './components/InstallWizard'; +import { Overview } from './components/Overview'; +import { StartupError } from './components/StartupError'; +import { api } from './api'; +import { demoPlan, demoUsage, initialProjects } from './data'; + +beforeEach(()=>{ +vi.spyOn(api,'adminOverview').mockResolvedValue({users:[],projects:[],domains:[],ipAddresses:[],logs:[]}); +vi.spyOn(api,'adminSettings').mockResolvedValue({domainApproval:true,filingRequired:false,cdnCnameTarget:'',graceDays:3,recycleDays:7,backupRetentionDays:14,smtp:{enabled:false,host:'',port:465,username:'',from:'',adminRecipients:'',startTls:true,secretConfigured:false},oidc:{enabled:false,issuer:'',clientId:'',redirectUri:'',secretConfigured:false,bindingOnly:true,passwordLogin:true}}); +vi.spyOn(api,'nodes').mockResolvedValue({nodes:[{id:1,name:'本机节点',transport:'local',endpoint:'local',rootDomain:'vhost.ser888.cn',tenantRoot:'/www/wwwroot/seavHost/vHost',ftpCertificateDomain:'host.ser888.cn',enabled:true,lastError:''}]})}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe('Sea vHost', () => { + it('opens the create project workflow', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: /创建虚拟主机/ })); + expect(screen.getByRole('heading', { name: '创建虚拟主机' })).toBeInTheDocument(); + expect(screen.getByDisplayValue('<随机主机名>.vhost.ser888.cn')).toBeInTheDocument(); + expect(screen.getByDisplayValue('/')).toBeInTheDocument(); + expect(screen.getAllByDisplayValue('/www/wwwroot/seavHost/vHost/<随机主机名>')).toHaveLength(2); + expect(screen.queryByText('Docker')).not.toBeInTheDocument(); + expect(screen.queryByText('容器')).not.toBeInTheDocument(); + }); + + it('lets a tenant configure a host-relative run directory', () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '主站目录' })[0]); + expect(screen.getByRole('dialog', { name: '设置运行目录' })).toBeInTheDocument(); + const input = screen.getByDisplayValue('/public'); + fireEvent.change(input, { target: { value: '/../etc' } }); + expect(screen.getByRole('button', { name: '保存' })).toBeDisabled(); + }); + + it('opens file management for a selected project', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '文件' })[0]); + expect(screen.getByRole('heading', { name: '文件管理' })).toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: '选择虚拟主机' })).toHaveValue('1'); + }); + + it('adds another website with an independent runtime and directory', () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); + expect(screen.getByRole('dialog', { name: '主机网站' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: '新增网站' })); + fireEvent.change(screen.getByLabelText('网站名称'), { target: { value: 'docs-site' } }); + fireEvent.change(screen.getByLabelText(/^运行目录/), { target: { value: '/docs' } }); + fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } }); + expect(screen.getByLabelText('版本')).toHaveValue('v24.21.0'); + fireEvent.click(screen.getByRole('button', { name: '创建网站' })); + expect(screen.getByText('docs-site')).toBeInTheDocument(); + expect(screen.getByText('/docs')).toBeInTheDocument(); + }); + + it('checks and deploys an uploaded language project before reporting it running', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); + fireEvent.click(screen.getByRole('button', { name: '新增网站' })); + fireEvent.change(screen.getByLabelText('运行环境'), { target: { value: 'Node.js' } }); + fireEvent.click(screen.getByRole('button', { name: '创建网站' })); + fireEvent.click(screen.getByRole('button', { name: '部署检查 site-two' })); + expect(screen.getByLabelText('入口文件')).toHaveValue('package.json'); + fireEvent.click(screen.getByRole('button', { name: '检查文件' })); + expect(await screen.findByText('可以继续')).toBeInTheDocument(); + expect(screen.getByRole('status')).toHaveTextContent('创建宝塔语言项目并验证运行状态'); + fireEvent.click(screen.getByRole('button', { name: '开始部署' })); + await waitFor(() => expect(screen.queryByLabelText('入口文件')).not.toBeInTheDocument()); + expect(screen.getByText('site-two').closest('.sites-row')).toHaveTextContent('运行中'); + }); + + it('installs a manual certificate without retaining the private key form', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); + fireEvent.click(screen.getByRole('button', { name: '安装证书 main-site' })); + expect(screen.getByText(/私钥仅用于本次请求/)).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('证书链(PEM)'), { target: { value: '-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----' } }); + fireEvent.change(screen.getByLabelText('私钥(PEM,无口令)'), { target: { value: '-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----' } }); + fireEvent.click(screen.getByRole('button', { name: '校验并安装' })); + await waitFor(() => expect(screen.queryByLabelText('私钥(PEM,无口令)')).not.toBeInTheDocument()); + }); + + it('lets a tenant retry automatic certificate issuance for a managed site', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); + expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'HTTP-01 申请证书 main-site' })); + await waitFor(() => expect(screen.getByText(/SSL 已启用/)).toBeInTheDocument()); + }); + + it('lets a tenant explicitly disable SSL and automatic renewal', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); + fireEvent.click(screen.getByRole('button', { name: '关闭 SSL main-site' })); + fireEvent.click(screen.getByRole('button', { name: '确认继续' })); + await waitFor(() => expect(screen.getByText(/SSL 未启用/)).toBeInTheDocument()); + expect(screen.queryByRole('button', { name: '关闭 SSL main-site' })).not.toBeInTheDocument(); + }); + + it('shows reusable FTP and database credentials', () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]); + expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).not.toHaveTextContent('FTP 与数据库密码已加密保存'); + expect(screen.getByText('demo-ftp-password')).toBeInTheDocument(); + expect(screen.getByText('demo-database-password')).toBeInTheDocument(); + }); + + it('resets the independent host login password', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '凭据' })[0]); + fireEvent.click(screen.getByRole('button', { name: '重置主机密码' })); + fireEvent.click(screen.getByRole('button', { name: '确认继续' })); + expect(await screen.findByText('demo-host-password-reset')).toBeInTheDocument(); + }); + + it('stops and deletes an additional website without deleting host files', async () => { + render(); + fireEvent.click(screen.getAllByRole('button', { name: '网站' })[0]); + fireEvent.click(screen.getByRole('button', { name: '新增网站' })); + fireEvent.click(screen.getByRole('button', { name: '创建网站' })); + fireEvent.click(await screen.findByRole('button', { name: '停止 site-two' })); + expect(await screen.findByRole('button', { name: '启动 site-two' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: '删除 site-two' })); + fireEvent.click(screen.getByRole('button', { name: '确认继续' })); + await waitFor(()=>expect(screen.queryByText('site-two')).not.toBeInTheDocument()); + expect(screen.getByText(/保留主机目录中的文件/)).toBeInTheDocument(); + }); + + it('submits a custom domain for the selected website', async () => { + render(); + fireEvent.click(screen.getByRole('button', { name: '域名' })); + expect(screen.getByRole('heading', { name: '域名' })).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('自定义域名'), { target: { value: 'tenant.example.com' } }); + fireEvent.click(screen.getByRole('button', { name: '提交审核' })); + expect(await screen.findByText('tenant.example.com')).toBeInTheDocument(); + expect(screen.getByText('待审核')).toBeInTheDocument(); + }); + + it('opens encrypted credentials from the FTP resource page', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'FTP' })); + fireEvent.click(screen.getByRole('button', { name: /查看 FTP 凭据 sv8c0a6d2f91/ })); + expect(screen.getByRole('dialog', { name: '虚拟主机凭据' })).toHaveTextContent('demo-ftp-password'); + }); + + it('opens the mobile navigation and navigates to a resource page', () => { + render(); + const menu = screen.getByRole('button', { name: '打开导航' }); + fireEvent.click(menu); + expect(menu).toHaveAttribute('aria-expanded', 'true'); + fireEvent.click(screen.getByRole('button', { name: '数据库' })); + expect(screen.getByRole('heading', { name: '数据库' })).toBeInTheDocument(); + }); + + it('offers an encrypted tenant DNS credential form without displaying saved secrets', async () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'DNS API' })); + expect(screen.getByRole('heading', { name: 'DNS API', level: 1 })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: '新增凭据' })); + expect(screen.getByRole('heading', { name: '新增 DNS 凭据' })).toBeInTheDocument(); + expect(screen.getByLabelText('API Token')).toHaveAttribute('type', 'password'); + fireEvent.change(screen.getByLabelText('DNS 服务商'), { target: { value: 'aliyun' } }); + expect(screen.getByLabelText('AccessKey Secret')).toHaveAttribute('type', 'password'); + expect(screen.queryByLabelText('Zone ID')).not.toBeInTheDocument();expect(screen.getByRole('button',{name:'加密保存'})).toBeDisabled(); + }); + + it('discovers a DNS zone before saving and testing its credential',async()=>{ + const item={id:9,scope:'tenant:1',label:'站点 DNS',provider:'cloudflare' as const,zoneName:'customer.example',testStatus:'untested' as const,createdAt:'',updatedAt:''}; + vi.spyOn(api,'dnsCredentials').mockResolvedValue({credentials:[]}); + const discover=vi.spyOn(api,'discoverDNSZones').mockResolvedValue({zones:[{id:'zone12345678',name:'customer.example',verificationToken:'proof'}]}); + const save=vi.spyOn(api,'createDNSCredential').mockResolvedValue({credential:item}); + vi.spyOn(api,'testDNSCredential').mockResolvedValue({credential:{...item,testStatus:'passed'}}); + render();await waitFor(()=>expect(api.dnsCredentials).toHaveBeenCalled());fireEvent.click(screen.getByRole('button',{name:'新增凭据'})); + fireEvent.change(screen.getByLabelText('凭据名称'),{target:{value:'站点 DNS'}});fireEvent.change(screen.getByLabelText('API Token'),{target:{value:'token-12345678901234567890'}}); + expect(screen.getByRole('button',{name:'加密保存'})).toBeDisabled();fireEvent.click(screen.getByRole('button',{name:'读取可管理域名'}));await screen.findByLabelText('选择 DNS 域名'); + expect(discover).toHaveBeenCalled();fireEvent.click(screen.getByRole('button',{name:'加密保存'}));await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({zoneName:'customer.example',verificationToken:'proof',credential:{apiToken:'token-12345678901234567890',zoneId:'zone12345678'}}),false)); + fireEvent.click(await screen.findByRole('button',{name:'测试 站点 DNS'}));expect(await screen.findByText('测试通过')).toBeInTheDocument(); + });}); + +describe('安装向导', () => { + it('requires connection checks before completing a preview install', async () => { + render(); + fireEvent.change(screen.getByPlaceholderText('粘贴 SEA_SETUP_TOKEN'), { target: { value: '12345678901234567890123456789012' } }); + fireEvent.click(screen.getByRole('button', { name: /继续/ })); + fireEvent.change(screen.getByLabelText(/数据库密码/), { target: { value: 'database-secret' } }); + fireEvent.click(screen.getByRole('button', { name: '测试数据库连接' })); + expect(await screen.findByText('连接成功')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /继续/ })); + fireEvent.change(screen.getByLabelText(/宝塔 API 密钥/), { target: { value: '12345678901234567890123456789012' } }); + fireEvent.click(screen.getByRole('button', { name: '检查服务器组件' })); + expect(await screen.findByText('面板代理与隔离代理均正常')).toBeInTheDocument(); + expect(screen.getByLabelText('运行环境能力')).toHaveTextContent('v24.21.0'); + expect(screen.getByLabelText('运行环境能力')).toHaveTextContent('基础功能'); + fireEvent.change(screen.getByLabelText(/用户三级域名根域/), { target: { value: 'vhost.ser888.cn' } }); + fireEvent.change(screen.getByLabelText(/管理控制台域名/), { target: { value: 'host.ser888.cn' } }); + fireEvent.change(screen.getByLabelText(/FTP 证书来源域名/), { target: { value: 'host.ser888.cn' } }); + fireEvent.click(screen.getByRole('button', { name: /继续/ })); + fireEvent.change(screen.getByLabelText('管理员邮箱'), { target: { value: 'admin@example.com' } }); + fireEvent.change(screen.getByLabelText('密码'), { target: { value: 'correct-horse-battery' } }); + fireEvent.change(screen.getByLabelText('确认密码'), { target: { value: 'correct-horse-battery' } }); + fireEvent.click(screen.getByRole('button', { name: /确认并完成安装/ })); + expect(await screen.findByRole('heading', { name: 'Sea vHost 已安装完成' })).toBeInTheDocument(); + }); +}); + +describe('平台域名审核', () => { + it('submits a numeric bandwidth cap separately from monthly traffic', async () => { + const create = vi.fn().mockResolvedValue(undefined); + render( undefined} onReviewDomain={async () => undefined} + onCreate={async () => undefined} onCreatePlan={create} + onSecurity={() => undefined} onLogout={() => undefined} + />); + fireEvent.click(screen.getByRole('button', { name: '套餐管理' })); + fireEvent.click(await screen.findByRole('button', { name: '创建套餐' })); + fireEvent.change(screen.getByLabelText('套餐名称'), { target: { value: '限速测试套餐' } }); + const cap = screen.getByLabelText(/HTTP 每请求/); + expect(cap).toHaveAttribute('min', '0'); + fireEvent.change(cap, { target: { value: '5' } }); + fireEvent.submit(cap.closest('form')!); + await waitFor(() => expect(create).toHaveBeenCalledWith(expect.objectContaining({ bandwidthMbps: 5, bandwidthBytes: 500 * 1024 ** 3 }))); + }); + it('lets an administrator approve a pending domain', async () => { + vi.mocked(api.adminOverview).mockResolvedValue({users:[],projects:[],ipAddresses:[],logs:[],domains:[{id:9,projectId:2,siteId:3,tenantName:'示例用户',hostName:'svdemo',projectName:'官网',siteName:'主站',domain:'www.customer.example',kind:'custom',status:'pending',sslStatus:'off',createdAt:'2026-10-09T10:00:00+08:00'}]}); + const review = vi.fn().mockResolvedValue(undefined); + render( undefined} + onReviewDomain={review} + onCreate={async () => undefined} + onCreatePlan={async () => undefined} + onSecurity={() => undefined} + onLogout={() => undefined} + />); + fireEvent.click(await screen.findByRole('button', { name: '批准' })); + await waitFor(() => expect(review).toHaveBeenCalledWith(9, true)); + }); +}); + +describe('环境配置', () => { + it('shows only panel-advertised runtime versions to administrators', async () => { + vi.spyOn(api, 'runtimeMaintenance').mockResolvedValue({ sites: [], jobs: [] }); + vi.spyOn(api, 'runtimeEnvironments').mockResolvedValue({ environments: [ + { name: 'PHP', componentTitle: 'PHP 运行环境', componentStatus: 'installed', componentInstallable: false, installed: ['8.4'], available: [], installing: [] }, + { name: 'Node.js', componentTitle: 'Node.js 版本管理器', componentStatus: 'not_installed', componentInstallable: true, installed: [], available: [], installing: [], detail: '可安装宝塔官方免费 Node.js 版本管理器。' }, + { name: 'Python', componentTitle: 'Python 项目管理器', componentStatus: 'installed', componentInstallable: false, installed: ['3.12.3'], available: ['3.13.1', '3.12.3'], installing: [], recommended: '3.13.1' }, + ] }); + render( undefined} onReviewDomain={async () => undefined} + onCreate={async () => undefined} onCreatePlan={async () => undefined} + onSecurity={() => undefined} onLogout={() => undefined} + />); + fireEvent.click(screen.getByRole('button', { name: '环境配置' })); + expect(await screen.findByRole('heading', { name: '环境配置' })).toBeInTheDocument(); + expect(await screen.findByRole('button', { name: '安装免费组件' })).toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: 'Python 待安装版本' })).toHaveValue('3.13.1'); + expect(screen.queryByRole('textbox', { name: /版本/ })).not.toBeInTheDocument(); + }); +}); + +describe('宝塔站点迁移', () => { + it('handles an empty legacy response without blanking the console', async () => { + vi.spyOn(api, 'panelSites').mockResolvedValue({ sites: null, versions: null } as never); + render( undefined} + onReviewDomain={async () => undefined} + onCreate={async () => undefined} + onCreatePlan={async () => undefined} + onSecurity={() => undefined} + onLogout={() => undefined} + />); + fireEvent.click(screen.getByRole('button', { name: '虚拟主机' })); + fireEvent.click(await screen.findByRole('button', { name: '迁移宝塔站点' })); + expect(await screen.findByRole('heading', { name: '迁移宝塔站点' })).toBeInTheDocument(); + expect(await screen.findByText('没有可迁移的宝塔站点')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: '复制并接管' })).toBeDisabled(); + }); +}); + +describe('主机账号边界', () => { + it('不显示用户级聚合用量和创建主机入口', () => { + const noop = () => undefined; + render(); + expect(screen.queryByText('存储空间')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /创建虚拟主机/ })).not.toBeInTheDocument(); + expect(screen.queryByText('管理当前虚拟主机的网站、文件与访问凭据。')).not.toBeInTheDocument(); + }); +}); + +describe('启动错误', () => { + it('offers a retry action instead of silently showing login', () => { + let retried = false; + render( { retried = true; }} />); + fireEvent.click(screen.getByRole('button', { name: '重新连接' })); + expect(retried).toBe(true); + }); +}); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..1d5e830 --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,274 @@ +import {UserSchedules} from './components/UserSchedules'; +import {useLiveDashboard} from './useLiveDashboard'; +import {ResourceCharts} from './components/ResourceCharts'; +import { lazy,Suspense,type ComponentProps,useCallback, useEffect, useRef, useState } from 'react'; +import { api, type Credentials, type Dashboard, type DomainResource, type PlanInput, type Tenant, type User } from './api'; +const LazyAdminConsole=lazy(()=>import('./components/AdminConsole').then(module=>({default:module.AdminConsole}))); +function AdminConsole(props:ComponentProps){return 正在加载管理员控制台…

}>
} +import { AppShell } from './components/AppShell'; +import { CredentialsModal } from './components/CredentialsModal'; +import { CreateProject } from './components/CreateProject'; +import { DNSCredentials } from './components/DNSCredentials'; +import { FileManager } from './components/FileManager'; +import { Login } from './components/Login'; +import { HostSitesModal } from './components/HostSitesModal'; +import { HostDetails } from './components/HostDetails'; +import { ImpersonationBanner } from './components/ImpersonationBanner'; +import { InstallWizard } from './components/InstallWizard'; +import { Overview } from './components/Overview'; +import { RunPathModal } from './components/RunPathModal'; +import { SecurityModal } from './components/SecurityModal'; +import { ResourceCenter } from './components/ResourceCenter'; +import { StartupError } from './components/StartupError'; +import { demoActivities, demoPlan, demoRuntimeVersions, demoUsage, initialProjects } from './data'; +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'; + 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'); + const [projects, setProjects] = useState(initialProjects); + const changingProjects=useRef(new Set()),dashboardRevision=useRef(0);const [pendingProjectIDs,setPendingProjectIDs]=useState([]); + const [fileProjectID, setFileProjectID] = useState(); + const [runPathProject, setRunPathProject] = useState(); + const [sitesProject, setSitesProject] = useState(); + const [plan, setPlan] = useState(demoPlan); + const [usage, setUsage] = useState(demoUsage); + const [activities, setActivities] = useState(demoActivities); + const [hostScoped, setHostScoped] = useState(false); + const [runtimeVersions, setRuntimeVersions] = useState(demoRuntimeVersions); + const [rootDomain, setRootDomain] = useState('vhost.ser888.cn'); + const [projectRoot, setProjectRoot] = useState('/www/wwwroot/seavHost/vHost'); + const [toast, setToast] = useState(''); + const [user, setUser] = useState(null); + const [authChecked, setAuthChecked] = useState(!apiMode); + const [tenants, setTenants] = useState([]); + const [plans, setPlans] = useState([demoPlan]); + const [domainApproval, setDomainApproval] = useState(true); + const [pendingDomains, setPendingDomains] = useState([]); + const [credentials, setCredentials] = useState(null); + const [credentialProjectID, setCredentialProjectID] = useState(); + const [setupRequired, setSetupRequired] = useState(apiMode ? null : false); + const [bootError, setBootError] = useState('');const [bootStatus,setBootStatus]=useState(); + const [bootAttempt, setBootAttempt] = useState(0); + const [showSecurity, setShowSecurity] = useState(false); + + const applyDashboard=useCallback((dashboard:Dashboard)=>{ + setProjects(dashboard.projects.map(normalizeProject));setPlan(dashboard.plan);setUsage(dashboard.usage);setActivities(dashboard.activities);setHostScoped(dashboard.hostScoped);setDomainApproval(dashboard.domainApproval);setRootDomain(dashboard.rootDomain);setProjectRoot(dashboard.projectRoot); + },[]); + const dashboardSync=useLiveDashboard(apiMode&&authChecked&&!!user&&user.role!=='admin',`${user?.id}:${page}`,applyDashboard,dashboardRevision,changingProjects,()=>window.location.reload()); + + const loadAccount = useCallback(async (current: User) => { + if (current.role === 'admin') { + const [tenantResult, setting, planResult, pendingResult] = await Promise.all([api.tenants(), api.domainApproval(), api.plans(), api.pendingDomains()]); + setTenants(tenantResult.tenants); + setDomainApproval(setting.enabled); + setPlans(planResult.plans); + setPendingDomains(pendingResult.domains); + } else { + const dashboard = await api.dashboard(); + applyDashboard(dashboard); + if(dashboard.hostScoped)setPage('projects'); + setRuntimeVersions(normalizeCatalog({})); + } + setUser(current); + setAuthChecked(true); + }, [applyDashboard]); + + useEffect(() => { + if (!apiMode || setupPreview) return; + let active = true; + setBootError('');setBootStatus(undefined); + setAuthChecked(false); + setSetupRequired(null); + (async () => { + try { + const { required } = await api.setupStatus(); + if (!active) return; + setSetupRequired(required); + if (required) return; + try { + const { user: current } = await api.me(); + if (active) await loadAccount(current); + } catch (reason) { + if (httpStatus(reason) === 401) { + if (active) setAuthChecked(true); + return; + } + throw reason; + } + } catch (reason) { + if (!active) return; + setSetupRequired(false); + setAuthChecked(true); + setBootError(startupMessage(reason));setBootStatus(httpStatus(reason)); + } + })(); + return () => { active = false; }; + }, [apiMode, bootAttempt, loadAccount, setupPreview]); + + function notify(message: string) { + setToast(message); + window.setTimeout(() => setToast(''), 2600); + } + + async function createProject(draft: ProjectDraft) { + if (apiMode) { + try { + const result = await api.createProject(draft); + setProjects((current) => [normalizeProject(result.project), ...current]); + setCredentials(result.credentials); + setCredentialProjectID(result.project.id); + setPage('overview'); + notify('虚拟主机已创建,FTP 与数据库凭据可随时查看'); + } catch (reason) { notify(reason instanceof Error ? reason.message : '创建虚拟主机失败'); } + return; + } + 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')}`, + name: draft.name, + domain: '', + path: '', + runPath: draft.runPath, + runtime: draft.runtime, + version: draft.version, + status: 'provisioning', + ssl: draft.autoSSL, + trafficGB: 0, + createdAt: '刚刚', + }; + project.domain = draft.customDomain || `${project.hostName}.${rootDomain}`; + project.path = `${projectRoot}/${project.hostName}`; + setProjects((current) => [project, ...current]); + setPage('overview'); + notify('虚拟主机已进入部署队列'); + } + + + async function toggleProject(id:number){ + if(changingProjects.current.has(id))return; + const target=projects.find(p=>p.id===id); + if(!target||!['running','stopped'].includes(target.status)){notify('主站尚未完成部署,暂不能启停');return} + const enabled=target.status!=='running';dashboardRevision.current++;changingProjects.current.add(id);setPendingProjectIDs([...changingProjects.current]); + try{if(apiMode)await api.setProjectState(id,enabled);setProjects(current=>current.map(p=>p.id===id?{...p,status:enabled?'running':'stopped'}:p));notify('主站状态已更新')} + catch(e){notify(e instanceof Error?e.message:'状态更新失败')} + finally{dashboardRevision.current++;changingProjects.current.delete(id);setPendingProjectIDs([...changingProjects.current])} + } + + async function updateRunPath(runPath: string) { + if (!runPathProject) return; + if (apiMode) { + dashboardRevision.current++; + try { + const result = await api.setProjectRunPath(runPathProject.id, runPath); + const updated = normalizeProject(result.project); + setProjects((current) => current.map((project) => project.id === updated.id ? updated : project)); + } catch (reason) { + throw reason; + } finally { dashboardRevision.current++; } + } else { + setProjects((current) => current.map((project) => project.id === runPathProject.id ? { ...project, runPath } : project)); + } + setRunPathProject(undefined); + notify('运行目录已更新'); + } + + async function showCredentials(project: Project) { + setCredentialProjectID(project.id); + if (!apiMode) { + setCredentials({ hostLogin: project.hostName, ftpHost: project.domain, ftpTLSPolicy: 'explicit_tls_required', ftpUsername: project.hostName, ftpPassword: 'demo-ftp-password', databaseName: project.hostName, databaseUsername: project.hostName, databasePassword: 'demo-database-password' }); + return; + } + try { setCredentials((await api.projectCredentials(project.id)).credentials); } + catch (reason) { notify(reason instanceof Error ? reason.message : '无法读取主机凭据'); } + } + + async function resetHostPassword() { + if (!credentialProjectID) return; + const password = apiMode ? (await api.resetHostPassword(credentialProjectID)).password : 'demo-host-password-reset'; + setCredentials((current) => current ? { ...current, hostPassword: password } : current); + notify('主机登录密码已重置,旧会话已失效'); + } + + function showCredentialsByID(projectID: number) { + const project = projects.find((item) => item.id === projectID); + if (project) void showCredentials(project); + } + + function showSites(project: Project) { + setSitesProject(project); + setRuntimeVersions(apiMode ? normalizeCatalog({}) : demoRuntimeVersions); + if (apiMode) void api.runtimeCatalog(project.id).then(result => setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason => notify(reason instanceof Error ? reason.message : '节点环境读取失败')); + } + + if (adminPreview) return undefined} onReviewDomain={async () => undefined} onCreate={async () => undefined} onCreatePlan={async () => undefined} onSecurity={() => undefined} onLogout={() => undefined} />; + if (setupPreview) return ; + if (apiMode && setupRequired === true) return ; + if (apiMode && bootError) return setBootAttempt((value) => value + 1)} />; + if (apiMode && (!authChecked || setupRequired === null)) return
正在载入 Sea vHost…
; + if (apiMode && !user) return { const result = await api.login(email, password, totpCode); await loadAccount(result.user); }} />; + if (apiMode && user?.role === 'admin') return <>{setPlans((await api.plans()).plans)}} onImpersonate={async input=>{await api.startImpersonation(input);window.location.reload()}} user={user} tenants={tenants} plans={plans} pendingDomains={pendingDomains} approval={domainApproval} onApproval={async (enabled) => { await api.setDomainApproval(enabled); setDomainApproval(enabled); }} onReviewDomain={async (id, approved) => { await api.reviewDomain(id, approved); setPendingDomains((current) => current.filter((item) => item.id !== id)); }} onCreate={async (input) => { await api.createTenant(input); setTenants((await api.tenants()).tenants); }} onCreatePlan={async (input: PlanInput) => { await api.createPlan(input); setPlans((await api.plans()).plans); }} onSecurity={() => setShowSecurity(true)} onLogout={async () => { await api.logout(); window.location.reload(); }} />{showSecurity ? setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null}; + + return ( + {void api.logout().then(()=>window.location.reload()).catch(reason=>notify(reason instanceof Error?reason.message:'退出失败'))}} onSecurity={() => user?.impersonating?notify('请先返回管理员后操作账号安全'):setShowSecurity(true)}> + {user?.impersonating?:null} + {dashboardSync.error?

状态刷新失败:{dashboardSync.error}。

:null} + {page === 'overview' ? setPage('logs')} projects={projects} plan={plan} usage={usage} activities={activities} hostScoped={hostScoped} canCreate={!apiMode} onCreate={() => setPage('create')} onToggle={toggleProject} onFiles={(id) => { setFileProjectID(id); setPage('files'); }} onRunPath={(project) => setRunPathProject(project)} onSites={(project)=>{setRuntimeVersions(normalizeCatalog({}));setSitesProject(project);if(apiMode) void api.runtimeCatalog(project.id).then(result=>setRuntimeVersions(normalizeCatalog(result.versions))).catch(reason=>notify(reason instanceof Error?reason.message:"节点环境读取失败"));else setRuntimeVersions(demoRuntimeVersions);}} onCredentials={(project) => void showCredentials(project)} /> : null} + {page === 'create' ? setPage('overview')} onSubmit={createProject} /> : null} + {page==='schedules'&&!hostScoped?:null} + {page==='metrics'?:null} + {page === 'files' ? : null} + {page === 'projects' ? void showCredentials(project)} onFiles={id => { setFileProjectID(id); setPage('files'); }} /> : null} + {page === 'dns' && !hostScoped ? : null} + {['domains', 'databases', 'ftp', 'logs'].includes(page) ? : null} + {toast ?
{toast}
: null} + {credentials ? { setCredentials(null); setCredentialProjectID(undefined); }} /> : null} + {runPathProject ? setRunPathProject(undefined)} onSubmit={updateRunPath} /> : null} + {sitesProject ? {setSitesProject(undefined);dashboardSync.refresh()}} /> : null} + {showSecurity ? setShowSecurity(false)} onSessionEnded={() => { setShowSecurity(false); setUser(null); }} /> : null} +
+ ); +} + +const runtimes: Runtime[] = ['PHP', 'Node.js', 'Python', 'Go', 'Java']; + +function normalizeCatalog(catalog: Partial): RuntimeCatalog { + return Object.fromEntries(runtimes.map((runtime) => [runtime, Array.isArray(catalog?.[runtime]) ? catalog[runtime] : []])) as RuntimeCatalog; +} + +function normalizeProject(project: APIProject): Project { + const certificateReady = ['active', 'valid', 'issued', 'deployed'].includes(project.sslStatus?.toLowerCase()); + const knownStatuses: ProjectStatus[] = ['running', 'stopped', 'provisioning', 'awaiting_upload', 'failed', 'quota_suspended']; + return { + id: project.id, + allowRuntimeChange:project.allowRuntimeChange, + hostName: project.hostName, + name: project.name, + domain: project.domain, + path: project.path, + runPath: project.runPath || '/', + runtime: project.runtime, + version: project.version, + status: knownStatuses.includes(project.status as ProjectStatus) ? project.status as ProjectStatus : 'provisioning', + ssl: certificateReady, + trafficGB: Math.max(0,Number(project.bandwidthBytes)||0)/1024**3, + createdAt: project.createdAt, + }; +} + +function httpStatus(reason: unknown) { + return (reason as { status?: number } | null)?.status; +} + +function startupMessage(reason: unknown) { + const status = httpStatus(reason); + if(status===421)return '当前域名不是管理入口,或该网站尚未配置 HTTPS。请使用对应的管理域名或网站访问地址。'; + if (status) return `后端服务返回 HTTP ${status},请检查 sea-vhost-api 服务。`; + return '后端服务没有响应,请检查 sea-vhost-api 服务与 Nginx 反向代理。'; +} + +function CheckIcon() { + return ; +} diff --git a/frontend/src/FileManager.test.tsx b/frontend/src/FileManager.test.tsx new file mode 100644 index 0000000..b733f43 --- /dev/null +++ b/frontend/src/FileManager.test.tsx @@ -0,0 +1,89 @@ +import '@testing-library/jest-dom/vitest'; +import {act,cleanup,fireEvent,render,screen,waitFor,within} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {api,type FileListing} from './api'; +import {FileManager} from './components/FileManager'; +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('does not present binary filenames as buttons that cannot do anything',async()=>{ + vi.spyOn(api,'files').mockResolvedValue(listing('program.bin')); + render(); + await screen.findByText('program.bin'); + expect(screen.queryByRole('button',{name:'program.bin'})).not.toBeInTheDocument(); + expect(screen.getByRole('link',{name:'下载 program.bin'})).toBeInTheDocument(); + expect(screen.getByTitle('此类型不支持在线编辑,请下载或使用 FTP 处理')).toBeInTheDocument(); +}); + +it('requires the in-page confirmation before moving a file to trash and supports cancellation',async()=>{ + vi.spyOn(api,'files').mockResolvedValue(listing('index.txt')); + const trash=vi.spyOn(api,'trashFile').mockResolvedValue(undefined); + render(); + fireEvent.click(await screen.findByRole('button',{name:'删除 index.txt'})); + const dialog=screen.getByRole('alertdialog',{name:'移入回收站'}); + expect(trash).not.toHaveBeenCalled(); + fireEvent.click(within(dialog).getByRole('button',{name:'取消'})); + expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();expect(trash).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button',{name:'删除 index.txt'})); + fireEvent.click(screen.getByRole('button',{name:'移入回收站'})); + await waitFor(()=>expect(trash).toHaveBeenCalledWith(1,'index.txt')); +}); + +it('discards late responses from a previous host and hides stale directory actions',async()=>{ + let old!:(value:FileListing)=>void; + vi.spyOn(api,'files').mockImplementation(id=>id===1?new Promise(resolve=>{old=resolve}):Promise.resolve(listing('current.txt'))); + const view=render(); + view.rerender(); + expect(await screen.findByRole('button',{name:'current.txt'})).toBeInTheDocument(); + await act(async()=>old(listing('previous-secret.txt'))); + expect(screen.queryByText('previous-secret.txt')).not.toBeInTheDocument(); + expect(screen.getByRole('button',{name:'current.txt'})).toBeInTheDocument(); + expect(screen.getByLabelText('选择虚拟主机')).toHaveValue('2'); +}); + +it('allows a failed directory read to retry and displays save failures inside the editor',async()=>{ + const files=vi.spyOn(api,'files').mockRejectedValueOnce(new Error('目录读取失败')).mockResolvedValue(listing('index.txt')); + vi.spyOn(api,'fileText').mockResolvedValue('keep this content'); + const save=vi.spyOn(api,'writeFile').mockRejectedValue(new Error('磁盘空间不足')); + render(); + expect(await screen.findByRole('alert')).toHaveTextContent('目录读取失败'); + expect(screen.getByRole('button',{name:'刷新文件'})).toBeEnabled(); + expect(screen.queryByText('目录为空')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button',{name:'刷新文件'})); + fireEvent.click(await screen.findByRole('button',{name:'编辑 index.txt'})); + const editor=await screen.findByRole('dialog',{name:'编辑文本文件'}); + await waitFor(()=>expect(within(editor).getByLabelText('内容')).toHaveValue('keep this content')); + fireEvent.click(within(editor).getByRole('button',{name:'保存'})); + expect(await within(editor).findByRole('alert')).toHaveTextContent('磁盘空间不足'); + expect(within(editor).getByLabelText('内容')).toHaveValue('keep this content'); + expect(files).toHaveBeenCalledTimes(2); + expect(save).toHaveBeenCalledWith(1,'index.txt','keep this content',true); +}); + +it('does not open an old host file after the selected host changes',async()=>{ + let finish!:(content:string)=>void; + vi.spyOn(api,'files').mockImplementation(id=>Promise.resolve(listing(id===1?'old.txt':'new.txt'))); + vi.spyOn(api,'fileText').mockReturnValue(new Promise(resolve=>{finish=resolve})); + const view=render(); + fireEvent.click(await screen.findByRole('button',{name:'编辑 old.txt'})); + view.rerender(); + expect(await screen.findByRole('button',{name:'new.txt'})).toBeInTheDocument(); + await act(async()=>finish('previous host secret')); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); +}); + +it('does not reopen trash when an in-flight restore refresh finishes after closing',async()=>{ + vi.spyOn(api,'files').mockResolvedValue(listing('index.txt')); + const item={id:'qa-trash',name:'old.txt',originalPath:'old.txt',deletedAt:'2026-10-29T00:00:00Z',size:10}; + let finish!:(value:{entries:typeof item[]})=>void; + vi.spyOn(api,'fileTrash').mockResolvedValueOnce({entries:[item]}).mockReturnValueOnce(new Promise(resolve=>{finish=resolve})); + vi.spyOn(api,'fileAction').mockResolvedValue(undefined); + render(); + await screen.findByRole('button',{name:'index.txt'});fireEvent.click(screen.getByRole('button',{name:'回收站'})); + fireEvent.click(await screen.findByRole('button',{name:'恢复 old.txt'}));fireEvent.click(screen.getByRole('button',{name:'执行操作'})); + await waitFor(()=>expect(screen.queryByRole('dialog',{name:'恢复文件'})).not.toBeInTheDocument()); + fireEvent.click(screen.getByRole('button',{name:'关闭回收站'}));await act(async()=>finish({entries:[]})); + expect(screen.queryByRole('heading',{name:'主机回收站'})).not.toBeInTheDocument(); +}); diff --git a/frontend/src/HostDetails.test.tsx b/frontend/src/HostDetails.test.tsx new file mode 100644 index 0000000..fa21696 --- /dev/null +++ b/frontend/src/HostDetails.test.tsx @@ -0,0 +1,36 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {HostDetails} from './components/HostDetails'; +import {ResourceCenter} from './components/ResourceCenter'; +import {demoPlan,demoUsage,initialProjects} from './data'; +import {api} from './api'; +import {HostSitesModal} from './components/HostSitesModal'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +it('opens real host configuration controls with administrator-assigned limits',()=>{ + const onRunPath=vi.fn(),onSites=vi.fn();render(); + expect(screen.getByRole('heading',{name:'资源配置'})).toBeInTheDocument(); + expect(screen.getByText(demoPlan.name)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button',{name:'设置运行目录'}));expect(onRunPath).toHaveBeenCalledWith(initialProjects[0]); + fireEvent.click(screen.getByRole('button',{name:'网站管理'}));expect(onSites).toHaveBeenCalledWith(initialProjects[0]); +}); +it('loads and refreshes logs scoped to the signed-in host',async()=>{ + const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[{id:91,projectId:initialProjects[0].id,actor:'用户',action:'update',resourceType:'run_path',detail:'用户更新当前主机目录',success:true,createdAt:'2026-10-26T00:00:00Z'}]}); + render(); + expect(await screen.findByText('用户更新当前主机目录')).toBeInTheDocument();expect(load).toHaveBeenCalledWith(initialProjects[0].id); + expect(screen.queryByText('主机账号不显示用户级审计日志')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button',{name:'刷新日志'}));await waitFor(()=>expect(load).toHaveBeenCalledTimes(2)); +}); +it('filters the account log view by its selected host',async()=>{ + const load=vi.spyOn(api,'activities').mockResolvedValue({activities:[]});render(); + await waitFor(()=>expect(load).toHaveBeenCalledWith(undefined));fireEvent.change(screen.getByRole('combobox',{name:'日志范围'}),{target:{value:String(initialProjects[1].id)}});await waitFor(()=>expect(load).toHaveBeenLastCalledWith(initialProjects[1].id)); +}); +it('uses installed versions when the environment catalog arrives after opening website management',async()=>{ + const view=render(); + fireEvent.click(screen.getByRole('button',{name:'新增网站'})); + expect(screen.getByRole('button',{name:'创建网站'})).toBeDisabled(); + view.rerender(); + await waitFor(()=>expect(screen.getByRole('button',{name:'创建网站'})).toBeEnabled()); + const version=screen.getAllByRole('combobox').find(select=>select.querySelector('option')?.textContent==='8.4'); + expect(version).toHaveValue('8.4'); +}); diff --git a/frontend/src/Impersonation.test.tsx b/frontend/src/Impersonation.test.tsx new file mode 100644 index 0000000..4f413bd --- /dev/null +++ b/frontend/src/Impersonation.test.tsx @@ -0,0 +1,25 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {AdminConsole} from './components/AdminConsole'; +import {ImpersonationBanner} from './components/ImpersonationBanner'; +import {api,type AdminSettings,type Tenant,type AdminProject} from './api'; +import {demoPlan} from './data'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +it('routes each administrator entry to its exact tenant or host without asking for credentials',async()=>{ + const customer:Tenant={id:11,slug:'ui-qa',name:'界面测试用户',status:'active',planName:'测试',userCount:1,projectCount:1,createdAt:'2026-10-26T00:00:00Z'}; + const project:AdminProject={nodeId:1,planId:1,id:21,tenantName:customer.name,hostName:'sv0123456789',name:'ui-site',domain:'sv0123456789.example.invalid',path:'/www/wwwroot/seavHost/vHost/sv0123456789',runPath:'/public',runtime:'PHP',version:'8.4',status:'running',sslStatus:'off',siteCount:1,dedicatedIp:false,httpPort:80,httpsPort:443,createdAt:'2026-10-26T00:00:00Z'}; + vi.spyOn(api,'adminOverview').mockResolvedValue({users:[customer],projects:[project],domains:[],logs:[],ipAddresses:[]}); + vi.spyOn(api,'adminSettings').mockResolvedValue({domainApproval:true,filingRequired:false,cdnCnameTarget:'',graceDays:3,recycleDays:7,backupRetentionDays:14,smtp:{enabled:false,host:'',port:465,username:'',from:'',adminRecipients:'',startTls:true,secretConfigured:false},oidc:{enabled:false,issuer:'',clientId:'',redirectUri:'',secretConfigured:false,bindingOnly:true,passwordLogin:true}} satisfies AdminSettings); + const enter=vi.fn().mockResolvedValue(undefined); + render(); + fireEvent.click(screen.getByRole('button',{name:'用户管理'}));fireEvent.click(await screen.findByRole('button',{name:'进入用户 ui-qa'}));expect(enter).toHaveBeenCalledWith({tenantId:11}); + fireEvent.click(screen.getByRole('button',{name:'虚拟主机'}));fireEvent.click(await screen.findByRole('button',{name:'进入主机 sv0123456789'}));expect(enter).toHaveBeenLastCalledWith({projectId:21}); +}); +it('keeps an explicit return control and reports a failed return instead of hiding delegation',async()=>{ + vi.spyOn(api,'stopImpersonation').mockRejectedValue(new Error('返回暂时失败')); + render(); + expect(screen.getByLabelText('管理员代入状态')).toHaveTextContent('sv0123456789'); + fireEvent.click(screen.getByRole('button',{name:'返回管理视图'}));await waitFor(()=>expect(api.stopImpersonation).toHaveBeenCalledTimes(1));expect(await screen.findByRole('alert')).toHaveTextContent('返回暂时失败'); + expect(screen.getByRole('button',{name:'返回管理视图'})).toBeEnabled(); +}); diff --git a/frontend/src/ModalBackdrop.test.tsx b/frontend/src/ModalBackdrop.test.tsx new file mode 100644 index 0000000..5e70d23 --- /dev/null +++ b/frontend/src/ModalBackdrop.test.tsx @@ -0,0 +1,26 @@ +import '@testing-library/jest-dom/vitest'; +import {useState} from 'react'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it} from 'vitest'; +import {ModalBackdrop} from './components/ModalBackdrop'; +afterEach(()=>{cleanup();document.body.style.overflow='';document.body.style.paddingRight=''}); +it('labels dialogs, closes using Escape and restores scroll and the triggering control',async()=>{ + function Fixture(){const[open,setOpen]=useState(false);return <>{open?

安全设置

:null}} + document.body.style.overflow='scroll';render();const trigger=screen.getByRole('button',{name:'打开配置'});trigger.focus();fireEvent.click(trigger); + expect(screen.getByRole('dialog',{name:'安全设置'})).toHaveAttribute('aria-modal','true');expect(document.body.style.overflow).toBe('hidden'); + fireEvent.keyDown(document,{key:'Escape'}); + await waitFor(()=>expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(document.body.style.overflow).toBe('scroll');expect(trigger).toHaveFocus(); +}); + +it('makes background controls inert and restores them when nested dialogs close',()=>{ + function Fixture(){const[open,setOpen]=useState(false),[nested,setNested]=useState(false);return <>
{open?

外层配置

{nested?

内层配置

:null}
:null}} + render();const background=screen.getByTestId('background'); + fireEvent.click(screen.getByRole('button',{name:'打开外层'})); + expect(background).toHaveProperty('inert',true); + const outerButton=screen.getByRole('button',{name:'打开内层'}); + fireEvent.click(outerButton);expect(outerButton).toHaveProperty('inert',true); + fireEvent.click(screen.getByRole('button',{name:'关闭内层'})); + expect(outerButton).toHaveProperty('inert',false);expect(background).toHaveProperty('inert',true); + fireEvent.click(screen.getByRole('button',{name:'关闭外层'}));expect(background).toHaveProperty('inert',false); +}); diff --git a/frontend/src/ProjectState.test.tsx b/frontend/src/ProjectState.test.tsx new file mode 100644 index 0000000..2676866 --- /dev/null +++ b/frontend/src/ProjectState.test.tsx @@ -0,0 +1,30 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {App} from './App'; +import {api,type Dashboard,type User} from './api'; +import {demoPlan,demoUsage} from './data'; +import {RunPathModal} from './components/RunPathModal'; +import {initialProjects} from './data'; +afterEach(()=>{cleanup();vi.restoreAllMocks();vi.unstubAllEnvs()}); +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); + let finish!:()=>void;const pending=new Promise(resolve=>{finish=resolve});const update=vi.spyOn(api,'setProjectState').mockReturnValue(pending); + render();const start=await screen.findByRole('button',{name:'启动'});fireEvent.click(start);fireEvent.click(start);expect(update).toHaveBeenCalledTimes(1);expect(screen.getByRole('button',{name:'处理中…'})).toBeDisabled();finish();await waitFor(()=>expect(screen.getByRole('button',{name:'停止'})).toBeEnabled());expect(update).toHaveBeenCalledWith(9,true); +}); +it('keeps a rejected run directory visible with an inline reason',async()=>{ + render();fireEvent.click(screen.getByRole('button',{name:'保存'}));expect(await screen.findByRole('alert')).toHaveTextContent('目标目录不存在');expect(screen.getByRole('button',{name:'保存'})).toBeEnabled(); +}); + +it('explains an invalid management hostname without offering a pointless reconnect loop',async()=>{ + vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockRejectedValue(Object.assign(new Error('wrong host'),{status:421})); + render();expect(await screen.findByText(/当前域名不是管理入口/)).toBeInTheDocument();expect(screen.queryByRole('button',{name:'重新连接'})).not.toBeInTheDocument(); +}); + +it('refreshes a backend quota pause and shows measured per-host traffic',async()=>{ + vi.stubEnv('VITE_API_MODE','true');vi.spyOn(api,'setupStatus').mockResolvedValue({required:false});vi.spyOn(api,'me').mockResolvedValue({user:{id:8,role:'host',displayName:'主机账号'} as User}); + const project={id:15,hostName:'sv1111111111',name:'测试主机',domain:'qa.example.invalid',path:'/test',runPath:'/public',runtime:'PHP',version:'8.4',status:'running',sslStatus:'off',autoSSL:false,processLimit:20,createdAt:'2026-10-29T00:00:00Z',bandwidthBytes:36*1024**2};let paused=false; + vi.spyOn(api,'dashboard').mockImplementation(async()=>({plan:demoPlan,usage:demoUsage,projects:[{...project,status:paused?'quota_suspended':'running'}],activities:[],hostScoped:true,domainApproval:true,rootDomain:'example.invalid',projectRoot:'/test'} as Dashboard)); + render();expect(await screen.findByRole('button',{name:'停止主站'})).toBeEnabled();expect(screen.getByText('36 MB')).toBeInTheDocument();await screen.findByRole('button',{name:'刷新状态'});paused=true;fireEvent.click(screen.getByRole('button',{name:'刷新状态'}));expect(await screen.findByText('配额暂停')).toBeInTheDocument();expect(screen.getByRole('button',{name:'启动主站'})).toBeDisabled(); +}); diff --git a/frontend/src/ResourceEditors.test.tsx b/frontend/src/ResourceEditors.test.tsx new file mode 100644 index 0000000..afd9c4e --- /dev/null +++ b/frontend/src/ResourceEditors.test.tsx @@ -0,0 +1,38 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {AccountEditor,HostEditor,NodeEditor} from './components/ResourceEditors'; +import {api,type AdminProject,type ControlNode,type Tenant} from './api'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +const host={id:3,name:'测试主机',hostName:'sv1234567890',nodeId:1,path:'/www/wwwroot/seavHost/vHost/sv1234567890',runPath:'/web',tenantName:'用户'} as AdminProject; +it('requires the exact host identity and confirmation before recycling',async()=>{ + const remove=vi.spyOn(api,'recycleHost').mockResolvedValue();const changed=vi.fn().mockResolvedValue(undefined); + render(); + expect(screen.getByRole('button',{name:'回收主机'})).toBeDisabled(); + fireEvent.change(screen.getByLabelText('输入主机名确认回收'),{target:{value:host.hostName}}); + fireEvent.click(screen.getByRole('button',{name:'回收主机'}));expect(remove).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button',{name:'取消'}));expect(remove).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button',{name:'回收主机'}));fireEvent.click(screen.getByRole('button',{name:'确认回收'})); + await waitFor(()=>expect(remove).toHaveBeenCalledWith(3,host.hostName));expect(changed).toHaveBeenCalled(); +}); +it('offers restoration without allowing an ordinary rename of a recycled host',()=>{ + render(); + expect(screen.getByLabelText('主机显示名称')).toBeDisabled();expect(screen.getByRole('button',{name:'恢复主机'})).toBeEnabled(); +}); +it('does not expose editable user fields after a failed profile load',async()=>{ + vi.spyOn(api,'accountProfile').mockRejectedValue(new Error('读取失败')); + render(); + await screen.findByRole('alert');expect(screen.queryByLabelText('登录邮箱')).not.toBeInTheDocument();expect(screen.getByRole('button',{name:'重新读取'})).toBeEnabled(); +}); +it('blocks account deletion while hosts remain and saves only after loading',async()=>{ + const profile={id:4,slug:'customer',name:'用户甲',email:'qa@example.invalid',displayName:'联系人',projectCount:1}; + vi.spyOn(api,'accountProfile').mockResolvedValue(profile);const update=vi.spyOn(api,'updateAccount').mockResolvedValue(); + render(); + await screen.findByLabelText('用户名称');expect(screen.getByRole('button',{name:'删除用户'})).toBeDisabled(); + fireEvent.change(screen.getByLabelText('用户名称'),{target:{value:'新名称'}});fireEvent.click(screen.getByRole('button',{name:'保存用户资料'})); + await waitFor(()=>expect(update).toHaveBeenCalledWith(4,{...profile,name:'新名称'})); +}); +it('keeps local node transport and storage root immutable and disallows deletion',()=>{ + render(); + expect(screen.getByLabelText('执行入口')).toBeDisabled();expect(screen.getByLabelText('主机根目录')).toBeDisabled();expect(screen.getByRole('button',{name:'删除节点'})).toBeDisabled(); +}); diff --git a/frontend/src/RuntimeMaintenance.test.tsx b/frontend/src/RuntimeMaintenance.test.tsx new file mode 100644 index 0000000..e6a44fc --- /dev/null +++ b/frontend/src/RuntimeMaintenance.test.tsx @@ -0,0 +1,38 @@ +import '@testing-library/jest-dom/vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { api, type RuntimeEnvironment, type RuntimeMaintenanceSite } from './api'; +import { RuntimeMaintenancePanel } from './components/RuntimeMaintenancePanel'; + +afterEach(() => { cleanup(); vi.restoreAllMocks(); }); +const php: RuntimeEnvironment = { name: 'PHP', componentTitle: 'PHP', componentStatus: 'installed', componentInstallable: false, installed: ['8.4', '8.5'], available: [], installing: [], patches: [{ branch: '8.4', installed: '8.4.25', latest: '8.4.27', updateAvailable: true }] }; +const site: RuntimeMaintenanceSite = { site: { id: 7, projectId: 2, name: 'site', domain: 'app.example.com', runtime: 'Python', version: '3.12.0', status: 'running' }, hostName: 'sv0123456789', installedVersion: '3.12.0', runningVersion: '3.12.0', healthy: true, detail: '' }; +describe('运行环境维护', () => { + it('submits the advertised PHP patch after explicit confirmation', async () => { + vi.spyOn(api, 'runtimeMaintenance').mockResolvedValue({ sites: [], jobs: [] }); + const update = vi.spyOn(api, 'updatePHPPatch').mockResolvedValue({ jobId: 1 }); + render( undefined} />); + await screen.findByText('8.4.27'); + fireEvent.click(screen.getByRole('button', { name: '更新 PHP 8.4' })); + expect(screen.getByRole('alertdialog')).toHaveTextContent('Sea vHost 之外的网站'); + expect(update).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: '确认继续' })); + await waitFor(() => expect(update).toHaveBeenCalledWith('8.4', '8.4.27', 7)); + }); + it('keeps the environment page free of per-site selectors and accepts another queued update',async()=>{ + vi.spyOn(api,'runtimeMaintenance').mockResolvedValue({sites:[site],jobs:[{id:9,action:'php_patch',runtime:'PHP',fromVersion:'8.4.25',targetVersion:'8.4.27',status:'queued',phase:'queued',message:'',backupAvailable:false,createdAt:'',updatedAt:''}]}); + const check=vi.spyOn(api,'checkRuntimeUpdates').mockResolvedValue({jobId:10}); + render(undefined}/>); + await screen.findByText('待执行');expect(screen.queryByText('站点运行版本')).not.toBeInTheDocument();expect(screen.getByRole('button',{name:'更新 PHP 8.4'})).toBeDisabled();expect(screen.getByRole('button',{name:'检查更新'})).toBeEnabled(); + fireEvent.click(screen.getByRole('button',{name:'检查更新'}));await waitFor(()=>expect(check).toHaveBeenCalled()); + }); + it('keeps interrupted maintenance visible and blocks new upgrades until resumed', async () => { + vi.spyOn(api, 'runtimeMaintenance').mockResolvedValue({ sites: [], jobs: [{ id: 4, action: 'php_patch', runtime: 'PHP', fromVersion: '8.4.25', targetVersion: '8.4.27', status: 'interrupted', phase: 'installing', message: '服务重启', backupAvailable: true, createdAt: '', updatedAt: '' }] }); + const resume = vi.spyOn(api, 'resumeRuntimeMaintenance').mockResolvedValue({ ok: true }); + render( undefined} />); + expect(await screen.findByText('待核验')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: '更新 PHP 8.4' })).toBeDisabled(); + fireEvent.click(screen.getByRole('button', { name: '恢复核验' })); + await waitFor(() => expect(resume).toHaveBeenCalledWith(4, undefined)); + }); +}); diff --git a/frontend/src/SSOLogin.test.tsx b/frontend/src/SSOLogin.test.tsx new file mode 100644 index 0000000..e74e05c --- /dev/null +++ b/frontend/src/SSOLogin.test.tsx @@ -0,0 +1,29 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {api,type AdminSettings} from './api'; +import {Login} from './components/Login'; +import {SystemSettingsForm} from './components/SystemSettingsForm'; +vi.mock('./components/SystemScheduler',()=>({SystemScheduler:()=>null})); +afterEach(()=>{cleanup();vi.restoreAllMocks();window.history.replaceState(null,'','/')}); + +it('keeps a clearly named administrator and host password entry when user passwords are disabled',async()=>{ + vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:true,userPasswordLogin:false,adminPasswordLogin:true});render(); + expect(await screen.findByRole('button',{name:'管理员 / 主机密码登录'})).toBeInTheDocument();expect(screen.getByRole('button',{name:'SSO 账号登录'})).toBeInTheDocument(); +}); +it('lets an unbound SSO user bind an existing account and enforces the MFA step',async()=>{ + window.history.replaceState(null,'','/?oidc=complete');vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:true});vi.spyOn(api,'pendingOIDC').mockResolvedValue({pending:true,allowCreate:true,email:'verified@example.invalid'}); + const complete=vi.spyOn(api,'completeOIDC').mockRejectedValue(Object.assign(new Error('需要动态码'),{code:'mfa_required'}));render(); + const bind=await screen.findByRole('button',{name:'绑定已有账号并登录'});expect(screen.getByRole('button',{name:'创建普通用户并登录'})).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('已有用户或管理员账号'),{target:{value:'customer'}});fireEvent.change(screen.getByLabelText('密码'),{target:{value:'password-12345'}});fireEvent.click(bind); + await waitFor(()=>expect(complete).toHaveBeenCalledWith({action:'bind',identifier:'customer',password:'password-12345',totpCode:''}));expect(await screen.findByLabelText('动态验证码或恢复码')).toBeInTheDocument(); +}); +it('does not expose account creation when the backend disallows it',async()=>{ + window.history.replaceState(null,'','/?oidc=complete');vi.spyOn(api,'oidcStatus').mockResolvedValue({enabled:true});vi.spyOn(api,'pendingOIDC').mockResolvedValue({pending:true,allowCreate:false});render(); + expect(await screen.findByRole('button',{name:'绑定已有账号并登录'})).toBeInTheDocument();expect(screen.queryByRole('button',{name:'创建普通用户并登录'})).not.toBeInTheDocument(); +}); +it('saves independent administrator/user password policies and the creation switch',async()=>{ + const settings:AdminSettings={domainApproval:true,filingRequired:false,cdnCnameTarget:'',graceDays:3,recycleDays:7,backupRetentionDays:14,smtp:{enabled:false,host:'',port:465,username:'',from:'',adminRecipients:'',startTls:true,secretConfigured:false},oidc:{enabled:true,issuer:'https://id.example.invalid',clientId:'control',redirectUri:'https://control.example.invalid/api/v1/auth/oidc/callback',secretConfigured:true,bindingOnly:true,passwordLogin:true,userPasswordLogin:true,adminPasswordLogin:true,autoCreate:false}}; + const save=vi.fn().mockResolvedValue(undefined);render();fireEvent.click(screen.getByRole('checkbox',{name:/允许普通用户密码登录/}));fireEvent.click(screen.getByRole('checkbox',{name:/允许首次 SSO 登录创建用户/}));fireEvent.click(screen.getByRole('button',{name:'保存系统设置'})); + await waitFor(()=>expect(save).toHaveBeenCalledWith(expect.objectContaining({oidc:expect.objectContaining({autoCreate:true,userPasswordLogin:false,adminPasswordLogin:true})}))); +}); diff --git a/frontend/src/ScheduleAPI.test.ts b/frontend/src/ScheduleAPI.test.ts new file mode 100644 index 0000000..45b31f1 --- /dev/null +++ b/frontend/src/ScheduleAPI.test.ts @@ -0,0 +1,15 @@ +import {afterEach, expect, it, vi} from 'vitest'; +import {api, type UserSchedule} from './api'; + +afterEach(() => vi.unstubAllGlobals()); + +it('writes editable schedule fields without response-only metadata', async () => { + const fetchMock = vi.fn().mockResolvedValue(new Response('{"id":9}', {status:200,headers:{'Content-Type':'application/json'}})); + vi.stubGlobal('fetch',fetchMock); + const task:UserSchedule={id:9,projectId:3,siteId:7,name:'定时检查',kind:'php',version:'8.4',target:'task.php',cron:'*/5 * * * *',timezone:'Asia/Shanghai',arguments:[],useHTTPS:false,enabled:true,nextRunAt:'',lastState:'succeeded'}; + await api.saveSchedule(task); + const [url,init]=fetchMock.mock.calls[0]; + expect(url).toBe('/api/v1/schedules/9'); + expect(init.method).toBe('PUT'); + expect(JSON.parse(init.body)).toEqual({projectId:3,siteId:7,name:'定时检查',kind:'php',version:'8.4',target:'task.php',cron:'*/5 * * * *',timezone:'Asia/Shanghai',arguments:[],useHTTPS:false,enabled:true}); +}); diff --git a/frontend/src/SiteRuntime.test.tsx b/frontend/src/SiteRuntime.test.tsx new file mode 100644 index 0000000..4df776c --- /dev/null +++ b/frontend/src/SiteRuntime.test.tsx @@ -0,0 +1,21 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,it,expect,vi} from 'vitest'; +import {SiteRuntime} from './components/SiteRuntime'; +import {api} from './api'; +import type {Project,Site,RuntimeCatalog} from './types'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +const project={id:4,hostName:'sv0123456789',runtime:'Python'} as Project; +const site={id:8,name:'main',domain:'app.example.com',runtime:'Python',version:'3.12.15',status:'running'} as Site; +const catalog:RuntimeCatalog={PHP:['8.4','8.3'],'Node.js':['v26.12.1'],Python:['3.12.15','3.13.1'],Go:[],Java:[]}; +it('allows installed same-language versions without offering unauthorized languages',async()=>{ + vi.spyOn(api,'siteRuntimeJobs').mockResolvedValue({jobs:[]});const change=vi.spyOn(api,'changeSiteRuntime').mockResolvedValue({jobId:9}); + render(); + expect(screen.queryByRole('option',{name:'Node.js'})).not.toBeInTheDocument();fireEvent.change(screen.getByLabelText('运行版本'),{target:{value:'3.13.1'}});fireEvent.click(screen.getByRole('button',{name:'停止并切换'})); + expect(change).not.toHaveBeenCalled();expect(screen.getByRole('alertdialog')).toHaveTextContent('文件和数据库保留');fireEvent.click(screen.getByRole('button',{name:'确认继续'}));await waitFor(()=>expect(change).toHaveBeenCalledWith(4,8,'Python','3.13.1','')); +}); +it('offers cross-language selection only for a host with the explicit grant',async()=>{ + vi.spyOn(api,'siteRuntimeJobs').mockResolvedValue({jobs:[]});const change=vi.spyOn(api,'changeSiteRuntime').mockResolvedValue({jobId:9}); + render(); + fireEvent.change(screen.getByLabelText('运行环境'),{target:{value:'Node.js'}});expect(screen.getByLabelText('运行版本')).toHaveValue('v26.12.1');fireEvent.click(screen.getByRole('button',{name:'停止并切换'}));fireEvent.click(screen.getByRole('button',{name:'确认继续'}));await waitFor(()=>expect(change).toHaveBeenCalledWith(4,8,'Node.js','v26.12.1','')); +}); diff --git a/frontend/src/SiteTools.test.tsx b/frontend/src/SiteTools.test.tsx new file mode 100644 index 0000000..0e0188c --- /dev/null +++ b/frontend/src/SiteTools.test.tsx @@ -0,0 +1,33 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {api,type WebsiteSettings} from './api'; +import {SiteTools} from './components/SiteTools'; +import type {Site} from './types'; + +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +const site:Site={id:9,projectId:3,name:'php',runPath:'/public',domain:'site.vhost.ser888.cn',runtime:'PHP',version:'8.4',status:'running',sslStatus:'active',autoSSL:true,processLimit:10,primary:true,createdAt:''}; +const settings:WebsiteSettings={rewrite:'wordpress',redirectURL:'',redirectCode:301,forceHTTPS:true,index:['index.php'],error404:'404.html',error503:'',maintenance:false}; +it('blocks default settings after a failed read and saves the recovered configuration',async()=>{ + vi.spyOn(api,'websiteSettings').mockRejectedValueOnce(new Error('网站设置读取失败')).mockResolvedValue({settings}); + const save=vi.spyOn(api,'saveWebsiteSettings').mockResolvedValue(undefined); + render(undefined}/>); + expect(await screen.findByRole('alert')).toHaveTextContent('网站设置读取失败'); + expect(screen.getByRole('button',{name:'保存网站设置'})).toBeDisabled();expect(save).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button',{name:'重新读取设置'})); + await waitFor(()=>expect(screen.getByLabelText('默认首页(逗号分隔)')).toBeEnabled()); + expect(screen.getByLabelText('强制 HTTPS(需有效证书)')).toBeChecked(); + fireEvent.click(screen.getByRole('button',{name:'保存网站设置'})); + await waitFor(()=>expect(save).toHaveBeenCalledWith(3,9,settings)); +}); +it('renders separate log lines and prevents exporting stale lines after a read error',async()=>{ + vi.spyOn(api,'websiteSettings').mockResolvedValue({settings}); + vi.spyOn(api,'siteLog').mockResolvedValueOnce({lines:['first log line','second log line'],available:true}).mockRejectedValue(new Error('日志读取失败')); + render(undefined}/>); + fireEvent.click(screen.getByRole('button',{name:'网站日志'})); + await waitFor(()=>expect(document.querySelector('.site-log-view')?.textContent).toBe('first log line\nsecond log line')); + fireEvent.change(screen.getByLabelText('日志类型'),{target:{value:'access'}}); + expect(await screen.findByRole('alert')).toHaveTextContent('日志读取失败'); + expect(screen.queryByText('first log line',{exact:false})).not.toBeInTheDocument(); + expect(screen.getByRole('button',{name:'下载日志 JSON'})).toBeDisabled(); +}); diff --git a/frontend/src/StartupSettings.test.tsx b/frontend/src/StartupSettings.test.tsx new file mode 100644 index 0000000..2754f58 --- /dev/null +++ b/frontend/src/StartupSettings.test.tsx @@ -0,0 +1,34 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen,waitFor} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {api,type StartupSettings as Settings} from './api'; +import {StartupSettings} from './components/StartupSettings'; +import type {Site} from './types'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +it('blocks edits until existing encrypted startup settings have loaded',async()=>{ + let resolve!:(value:{startup:Settings})=>void; + vi.spyOn(api,'siteStartup').mockReturnValue(new Promise(r=>{resolve=r})); + const site:Site={id:9,projectId:3,name:'node',runPath:'/app',domain:'node.vhost.ser888.cn',runtime:'Node.js',version:'v26.12.1',status:'running',sslStatus:'off',autoSSL:false,processLimit:10,primary:false,createdAt:''}; + render(undefined}/>); + expect(screen.getByLabelText('工作子目录')).toBeDisabled(); + expect(screen.getByRole('button',{name:'保存并应用启动配置'})).toBeDisabled(); + resolve({startup:{entryFile:'package.json',workDir:'app',arguments:['--literal'],environment:{SECRET:'kept'}}}); + await waitFor(()=>expect(screen.getByLabelText('工作子目录')).toBeEnabled()); + expect(screen.getByLabelText('工作子目录')).toHaveValue('app'); + expect(screen.getByText('已配置 1 个变量,值已隐藏。')).toBeInTheDocument(); +}); + +it('keeps a failed initial read read-only and retries without overwriting saved settings',async()=>{ + const read=vi.spyOn(api,'siteStartup').mockRejectedValueOnce(new Error('读取失败,请重试')).mockResolvedValue({startup:{entryFile:'server.js',workDir:'app',arguments:[],environment:{EXISTING:'preserved'}}}); + const save=vi.spyOn(api,'saveSiteStartup').mockResolvedValue(undefined); + const site:Site={id:9,projectId:3,name:'node',runPath:'/app',domain:'node.vhost.ser888.cn',runtime:'Node.js',version:'v26.12.1',status:'running',sslStatus:'off',autoSSL:false,processLimit:10,primary:false,createdAt:''}; + render(undefined}/>); + expect(await screen.findByRole('alert')).toHaveTextContent('读取失败'); + expect(screen.getByRole('button',{name:'保存并应用启动配置'})).toBeDisabled(); + expect(save).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button',{name:'重新读取配置'})); + await waitFor(()=>expect(screen.getByLabelText('工作子目录')).toBeEnabled()); + expect(read).toHaveBeenCalledTimes(2); + fireEvent.click(screen.getByRole('button',{name:'保存并应用启动配置'})); + await waitFor(()=>expect(save).toHaveBeenCalledWith(3,9,expect.objectContaining({entryFile:'server.js',environment:{EXISTING:'preserved'}}))); +}); diff --git a/frontend/src/UserSchedules.test.tsx b/frontend/src/UserSchedules.test.tsx new file mode 100644 index 0000000..69a71e3 --- /dev/null +++ b/frontend/src/UserSchedules.test.tsx @@ -0,0 +1,11 @@ +import '@testing-library/jest-dom/vitest'; +import {cleanup,fireEvent,render,screen} from '@testing-library/react'; +import {afterEach,expect,it,vi} from 'vitest'; +import {UserSchedules} from './components/UserSchedules'; +import {api,type UserSchedule} from './api'; +import {initialProjects} from './data'; +afterEach(()=>{cleanup();vi.restoreAllMocks()}); +it('tells the user a manual schedule execution was queued rather than already executed',async()=>{ + vi.spyOn(api,'schedules').mockResolvedValue({schedules:[{id:1,projectId:1,siteId:1,name:'URL 检查',cron:'0 0 1 1 *',timezone:'Asia/Shanghai',enabled:true,lastState:'ready',nextRunAt:'2027-01-01T00:00:00Z'} as UserSchedule]});const run=vi.spyOn(api,'runSchedule').mockResolvedValue(); + render();fireEvent.click(await screen.findByRole('button',{name:'执行一次'}));expect(await screen.findByRole('status')).toHaveTextContent('已排队,将在下一次系统调度时执行');expect(run).toHaveBeenCalledWith(1); +}); diff --git a/frontend/src/api.ts b/frontend/src/api.ts new file mode 100644 index 0000000..6256e5e --- /dev/null +++ b/frontend/src/api.ts @@ -0,0 +1,250 @@ +import type { ActivityEntry, APIProject, DeploymentCheck, Plan, ProjectDraft, RuntimeCapabilities, RuntimeCatalog, Site, SiteDraft, Usage } from './types'; + +export interface UserSchedule{id:number;projectId:number;siteId:number;name:string;cron:string;timezone:string;kind:string;version:string;target:string;arguments:string[];useHTTPS:boolean;enabled:boolean;nextRunAt:string;lastState:string;} +export interface ScheduleRun{id:number;state:string;exitCode:number|null;startedAt:string;finishedAt?:string;output:string;} +export interface IntegrationKey{id:number;name:string;prefix:string;scopes:string[];expiresAt:string;revokedAt?:string;webhookURL:string;} +export interface IntegrationWebhook{id:number;eventId:string;batchId:number;state:string;attempts:number;status:number;lastError:string;} +export interface User { id: number; email: string; loginName: string; displayName: string; role: 'admin' | 'tenant' | 'host'; tenantName?: string; tenantSlug?: string; projectId?: number; mfaEnabled: boolean; impersonating?:boolean;impersonationExpiresAt?:string; } +export interface Credentials { ftpHost: string; ftpTLSPolicy: string; ftpUsername: string; ftpPassword: string; databaseName: string; databaseUsername: string; databasePassword: string; hostLogin: string; hostPassword?: string; } +export interface AccountSecurity { mfaEnabled: boolean; } +export interface OIDCAccount {canUnbind?:boolean; enabled: boolean; bound: boolean; email?: string; } +export interface DomainResource { id: number; projectId: number; siteId: number; tenantName?: string; hostName: string; projectName: string; siteName: string; domain: string; kind: 'assigned' | 'custom'; status: 'pending' | 'approved' | 'rejected'; resolutionMode?: 'direct' | 'cname' | 'cdn'; cnameTarget?: string; dnsCredentialId?: number; dnsRecordId?: string; dnsRecordType?: 'A' | 'AAAA' | 'CNAME'; dnsLastError?: string; filingStatus?: 'exempt' | 'pending' | 'approved' | 'rejected'; filingNumber?: string; filingNote?: string; sslStatus: string; createdAt: string; } +export interface FTPResource { enabled?:boolean; id: number; projectId: number; hostName: string; projectName: string; username: string; rootPath: string; createdAt: string; } +export interface DatabaseResource { id: number; projectId: number; hostName: string; projectName: string; name: string; username: string; sizeBytes: number; status: 'active' | 'quota_suspended'; createdAt: string; } +export interface 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 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 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 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[];} +export interface PanelSite { id: number; domain: string; path: string; phpVersion?: string; status: string; } +export interface RuntimeEnvironment { name: 'PHP' | 'Node.js' | 'Python' | 'Go' | 'Java'; componentTitle: string; componentStatus: 'installed' | 'not_installed' | 'probe_failed'; componentVersion?: string; componentLatestVersion?: string; componentUpdateAvailable?: boolean; componentInstallable: boolean; installed: string[]; available: string[]; installing: string[]; recommended?: string; detail?: string; patches?: { branch: string; installed: string; latest: string; updateAvailable: boolean }[]; } +export interface RuntimeMaintenanceJob { id: number; action: string; runtime: string; fromVersion: string; targetVersion: string; siteId?: number; status: string; phase: string; message: string; backupAvailable: boolean; createdAt: string; updatedAt: string; } +export interface RuntimeMaintenanceSite { site: { id: number; projectId: number; name: string; domain: string; runtime: string; version: string; status: string }; hostName: string; installedVersion: string; runningVersion: string; healthy: boolean; detail: string; checkedAt?: string; } +export interface IPAddress {nodeId:number; id: number; address: string; family: 'ipv4' | 'ipv6'; allocationMode: 'shared' | 'dedicated'; label: string; enabled: boolean; assignedSites: number; createdAt: string; } +export interface AdminActivity { administratorId?:number;impersonatedUserId?:number;impersonatedUserName?:string; id: number; userName?: string; action: string; resourceType: string; resourceId?: string; ipAddress?: string; success: boolean; detail: string; createdAt: string; } +export interface AdminOverview { users: Tenant[]; projects: AdminProject[]; domains: DomainResource[]; ipAddresses: IPAddress[]; logs: AdminActivity[]; } +export interface AdminSettings { domainApproval: boolean; filingRequired: boolean; cdnCnameTarget: string; graceDays: number; recycleDays: number; backupRetentionDays: number; smtp: { enabled: boolean; host: string; port: number; username: string; from: string; adminRecipients: string; startTls: boolean; secretConfigured: boolean; secret?: string }; oidc: { enabled: boolean; issuer: string; clientId: string; redirectUri: string; secretConfigured: boolean; secret?: string; bindingOnly: boolean; passwordLogin: boolean; autoCreate?:boolean; userPasswordLogin?:boolean; adminPasswordLogin?:boolean }; } +export interface PlanInput { name: string; storageBytes: number; databaseBytes: number; bandwidthBytes: number; bandwidthMbps?: number; processLimit: number; ftpLimit: number; databaseLimit: number; projectLimit: number; } +export interface TrashEntry {id:string;originalPath:string;name:string;deletedAt:string;size:number;} +export interface StartupSettings {entryFile:string;workDir:string;arguments:string[];environment:Record;} +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 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; } +export type DNSProvider = 'cloudflare' | 'aliyun' | 'tencent' | 'west' | 'dnsmgr'; +export interface DNSZoneChoice{id:string;name:string;verificationToken:string} +export interface DNSCredential { id: number; scope: string; label: string; provider: DNSProvider; zoneName: string; testStatus: 'untested' | 'testing' | 'passed' | 'failed'; lastTestedAt?: string; testError?: string; createdAt: string; updatedAt: string; } +export interface DNSCredentialInput { + verificationToken?:string; + label: string; + provider: DNSProvider; + zoneName: string; + credential: {endpoint?:string;userId?:string;apiKey?:string;username?:string;domainKey?:string; apiToken?: string; zoneId?: string; accessKeyId?: string; accessKeySecret?: string; secretId?: string; secretKey?: string }; +} +export interface CertificateAutomation { siteId: number; mode: 'off' | 'manual' | 'http-01' | 'dns-01'; expiresAt?: string; lastAttemptAt?: string; nextAttemptAt?: string; lastError?: string; } +export interface InstallSetup { + controllerOnly?:boolean; + database: DatabaseSetup; + panel: PanelSetup; + rootDomain: string; + managementDomain: string; + ftpDomain: string; + domainApproval: boolean; + adminEmail: string; + adminName: string; + adminPassword: string; +} + +export interface Dashboard { + plan: Plan; + usage: Usage; + projects: APIProject[]; + activities: ActivityEntry[]; + hostScoped: boolean; + domainApproval: boolean; + rootDomain: string; + projectRoot: string; +} + +async function request(path: string, init?: RequestInit): Promise { + const response = await fetch(path, { credentials: 'same-origin', ...init, headers: { 'Content-Type': 'application/json', ...init?.headers } }); + if (!response.ok) { + throw await responseError(response); + } + if (response.status === 204) return undefined as T; + return response.json() as Promise; +} + +async function responseError(response: Response) { + const payload = await response.json().catch(() => null) as { error?: { message?: string; code?: string } } | null; + const error = new Error(payload?.error?.message || `请求失败(${response.status})`) as Error & { status?: number; code?: string }; + error.status = response.status; + error.code = payload?.error?.code; + return error; +} + +function fileURL(projectID: number, path: string, download = false) { + const query = new URLSearchParams({ path }); + if (download) query.set('download', '1'); + return `/api/v1/projects/${projectID}/files?${query}`; +} + +function nodeQuery(nodeId?:number){return nodeId ? '?nodeId='+nodeId : ''} +export interface NodeTask{projectId?:number;id:number;nodeId:number;operation:string;state:string;detail:string;startedAt:string} +export const api = { + integrationKeys:()=>request<{keys:IntegrationKey[];scopes:string[];webhooks:IntegrationWebhook[]}>('/api/v1/admin/integration-keys'), + createIntegrationKey:(v:{name:string;scopes:string[];expiresAt:string;webhookURL:string})=>request<{token:string;webhookSecret:string}>('/api/v1/admin/integration-keys',{method:'POST',body:JSON.stringify(v)}), + revokeIntegrationKey:(id:number)=>request(`/api/v1/admin/integration-keys/${id}`,{method:'DELETE'}), + + schedules:()=>request<{schedules:UserSchedule[]}>('/api/v1/schedules'), + saveSchedule:(v:UserSchedule)=>{const{id,nextRunAt:_next,lastState:_state,...input}=v;return request<{id:number}>('/api/v1/schedules'+(id?'/'+id:''),{method:id?'PUT':'POST',body:JSON.stringify(input)})}, + deleteSchedule:(id:number)=>request(`/api/v1/schedules/${id}`,{method:'DELETE'}), + deletePlan:(id:number,confirmation:string)=>request(`/api/v1/admin/plans/${id}`,{method:'DELETE',body:JSON.stringify({confirmation})}), + unbindDomain:(id:number,confirmation:string,admin=false)=>request(`/api/v1/${admin?'admin/':''}domains/${id}`,{method:'DELETE',body:JSON.stringify({confirmation})}), + runSchedule:(id:number)=>request(`/api/v1/schedules/${id}/run`,{method:'POST'}), + scheduleRuns:(id:number)=>request<{runs:ScheduleRun[]}>(`/api/v1/schedules/${id}/runs`), + scheduler:()=>request<{nodeId:number;lastTick?:string}>('/api/v1/admin/scheduler'), + configureScheduler:(nodeId:number)=>request('/api/v1/admin/scheduler',{method:'POST',body:JSON.stringify({nodeId})}), + manageFTP:(id:number,action:string)=>request<{password?:string}>(`/api/v1/projects/${id}/ftp`,{method:'POST',body:JSON.stringify({action})}), + + previewBatch:(operation:BatchOperation,rows:BatchRow[])=>request<{rows:BatchPreviewRow[]}>('/api/v1/admin/batches/preview',{method:'POST',body:JSON.stringify({operation,rows})}), + createBatch:(operation:BatchOperation,rows:BatchRow[],requestKey:string)=>request<{batch:AdminBatch}>('/api/v1/admin/batches',{method:'POST',body:JSON.stringify({operation,rows,requestKey})}), + batches:()=>request<{batches:AdminBatch[]}>('/api/v1/admin/batches',{cache:'no-store'}), + batch:(id:number)=>request<{batch:AdminBatch}>(`/api/v1/admin/batches/${id}`,{cache:'no-store'}), + cancelBatch:(id:number)=>request(`/api/v1/admin/batches/${id}/cancel`,{method:'POST'}), + batchDownloadURL:(id:number)=>`/api/v1/admin/batches/${id}/download`, + startImpersonation:(input:{tenantId?:number;projectId?:number})=>request<{user:User}>('/api/v1/admin/impersonation',{method:'POST',body:JSON.stringify(input)}), + stopImpersonation:()=>request<{user:User}>('/api/v1/auth/impersonation/stop',{method:'POST'}), + nodeTasks:(id:number)=>request<{tasks:NodeTask[]}>('/api/v1/admin/nodes/'+id+'/tasks'), + resolveNodeTask:(node:number,id:number,note:string)=>request('/api/v1/admin/nodes/'+node+'/tasks/'+id+'/resolve',{method:'POST',body:JSON.stringify({note})}), + reconcileNode:(id:number)=>request('/api/v1/admin/nodes/'+id+'/reconcile',{method:'POST'}), + + accountProfile:(id:number)=>request('/api/v1/admin/tenants/'+id), + updateAccount:(id:number,p:AccountProfile)=>request('/api/v1/admin/tenants/'+id,{method:'PUT',body:JSON.stringify(p)}), + deleteAccount:(id:number,confirmation:string)=>request('/api/v1/admin/tenants/'+id,{method:'DELETE',body:JSON.stringify({confirmation})}), + detachRecycledHost:(host:AdminProject)=>request(`/api/v1/admin/projects/${host.id}/recycled-owner`,{method:'DELETE',body:JSON.stringify({confirmation:host.hostName,ownershipVersion:host.ownershipVersion})}), + renameHost:(id:number,name:string,allowRuntimeChange?:boolean)=>request('/api/v1/admin/projects/'+id,{method:'PUT',body:JSON.stringify({name,allowRuntimeChange})}), + recycleHost:(id:number,confirmation:string)=>request('/api/v1/admin/projects/'+id,{method:'DELETE',body:JSON.stringify({confirmation})}), + restoreHost:(id:number)=>request('/api/v1/admin/projects/'+id+'/restore',{method:'POST'}), + updateNode:(id:number,input:Record)=>request('/api/v1/admin/nodes/'+id,{method:'PATCH',body:JSON.stringify(input)}), + deleteNode:(id:number,confirmation:string)=>request('/api/v1/admin/nodes/'+id,{method:'DELETE',body:JSON.stringify({confirmation})}), + nodes:()=>request<{nodes:ControlNode[]}>('/api/v1/admin/nodes'), + createNode:(input:Record)=>request<{id:number}>('/api/v1/admin/nodes',{method:'POST',body:JSON.stringify(input)}), + pairNode:(id:number)=>request>('/api/v1/admin/nodes/'+id+'/pair',{method:'POST'}), + probeNode:(id:number)=>request('/api/v1/admin/nodes/'+id+'/probe',{method:'POST'}), + enableNode:(id:number,enabled:boolean)=>request('/api/v1/admin/nodes/'+id,{method:'PUT',body:JSON.stringify({enabled})}), + createHost:(input:Record)=>request<{project:APIProject;credentials:Credentials}>('/api/v1/admin/projects',{method:'POST',body:JSON.stringify(input)}), + hostSubscription:(id:number,planId:number,expiresAt?:string)=>request('/api/v1/admin/projects/'+id+'/subscription',{method:'PUT',body:JSON.stringify({planId,expiresAt:expiresAt||null})}), + + setupStatus: () => request<{required:boolean;controllerOnly?:boolean}>('/api/v1/setup/status', { cache: 'no-store' }), + testDatabase: (token: string, database: DatabaseSetup) => request<{ ok: boolean; message: string }>('/api/v1/setup/test-database', { method: 'POST', headers: { 'X-Setup-Token': token }, body: JSON.stringify(database) }), + testPanel: (token: string, panel: PanelSetup) => request<{ ok: boolean; message: string; versions: RuntimeCatalog; runtimes: RuntimeCapabilities }>('/api/v1/setup/test-panel', { method: 'POST', headers: { 'X-Setup-Token': token }, body: JSON.stringify(panel) }), + install: (token: string, input: InstallSetup) => request<{ ok: boolean; message: string }>('/api/v1/setup/install', { method: 'POST', headers: { 'X-Setup-Token': token }, body: JSON.stringify(input) }), + me: () => request<{ user: User }>('/api/v1/me'), + login: (identifier: string, password: string, totpCode = '') => request<{ user: User }>('/api/v1/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpCode }) }), + oidcStatus: () => request<{ enabled: boolean; autoCreate?:boolean;userPasswordLogin?:boolean;adminPasswordLogin?:boolean;hostPasswordLogin?:boolean }>('/api/v1/auth/oidc/status'), + pendingOIDC:()=>request<{pending:boolean;allowCreate?:boolean;email?:string;displayName?:string}>('/api/v1/auth/oidc/pending'), + completeOIDC:(input:{action:'bind'|'create';identifier?:string;password?:string;totpCode?:string})=>request<{completed:boolean}>('/api/v1/auth/oidc/complete',{method:'POST',body:JSON.stringify(input)}), + beginOIDC: (mode: 'login' | 'bind') => request<{ url: string }>(`/api/v1/auth/oidc/start?mode=${mode}`), + logout: () => request('/api/v1/auth/logout', { method: 'POST' }), + accountSecurity: () => request('/api/v1/account/security'), + accountOIDC: () => request('/api/v1/account/oidc'), + unbindOIDC: (currentPassword: string) => request('/api/v1/account/oidc', { method: 'DELETE', body: JSON.stringify({ currentPassword }) }), + changePassword: (currentPassword: string, newPassword: string) => request('/api/v1/account/password', { method: 'PUT', body: JSON.stringify({ currentPassword, newPassword }) }), + setupMFA: (currentPassword: string) => request<{ secret: string; otpauthURI: string }>('/api/v1/account/mfa/setup', { method: 'POST', body: JSON.stringify({ currentPassword }) }), + enableMFA: (code: string) => request<{ recoveryCodes: string[] }>('/api/v1/account/mfa/enable', { method: 'POST', body: JSON.stringify({ code }) }), + disableMFA: (currentPassword: string, code: string) => request('/api/v1/account/mfa/disable', { method: 'POST', body: JSON.stringify({ currentPassword, code }) }), + dashboard: (projectID?: number) => request('/api/v1/dashboard' + (projectID ? '?projectId=' + projectID : '')), + adminAudit: (query:URLSearchParams) => request<{logs:AdminActivity[];total:number;page:number;limit:number}>('/api/v1/admin/audit?'+query.toString(),{cache:'no-store'}), + activities: (projectID?: number) => request<{ activities: ActivityEntry[] }>('/api/v1/activities' + (projectID ? '?projectId=' + projectID : ''), { cache: 'no-store' }), + runtimeCatalog: (projectId?:number) => request<{ versions: RuntimeCatalog }>('/api/v1/runtime-catalog'+(projectId ? "?projectId="+projectId : "")), + createProject: (draft: ProjectDraft) => request<{ project: APIProject; credentials: Credentials }>('/api/v1/projects', { method: 'POST', body: JSON.stringify(draft) }), + setProjectState: (id: number, enabled: boolean) => request(`/api/v1/projects/${id}/state`, { method: 'POST', body: JSON.stringify({ enabled }) }), + siteRuntimeJobs:(id:number,site:number)=>request<{jobs:RuntimeMaintenanceJob[]}>(`/api/v1/projects/${id}/sites/${site}/runtime`,{cache:'no-store'}), + changeSiteRuntime:(id:number,site:number,runtime:string,version:string,entryFile:string) => request<{jobId:number}>(`/api/v1/projects/${id}/sites/${site}/runtime`,{method:'PUT',body:JSON.stringify({runtime,version,entryFile})}), + setProjectRunPath: (id: number, runPath: string) => request<{ project: APIProject }>(`/api/v1/projects/${id}/run-path`, { method: 'PUT', body: JSON.stringify({ runPath }) }), + projectCredentials: (id: number) => request<{ credentials: Credentials }>(`/api/v1/projects/${id}/credentials`), + resetHostPassword: (id: number) => request<{ password: string }>(`/api/v1/projects/${id}/host-password/reset`, { method: 'POST' }), + projectSites: (id: number) => request<{ sites: Site[] }>(`/api/v1/projects/${id}/sites`), + createSite: (id: number, input: SiteDraft) => request<{ site: Site }>(`/api/v1/projects/${id}/sites`, { method: 'POST', body: JSON.stringify(input) }), + setSiteState: (projectID: number, siteID: number, enabled: boolean) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/state`, { method: 'POST', body: JSON.stringify({ enabled }) }), + checkSiteDeployment: (projectID: number, siteID: number, entryFile: string) => request<{ check: DeploymentCheck }>(`/api/v1/projects/${projectID}/sites/${siteID}/deployment/check`, { method: 'POST', body: JSON.stringify({ entryFile }) }), + deploySite: (projectID: number, siteID: number, entryFile: string) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/deployment`, { method: 'POST', body: JSON.stringify({ entryFile }) }), + requestAutoCertificate: (projectID: number, siteID: number) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate/auto`, { method: 'POST' }), + requestDNSCertificate: (projectID: number, siteID: number) => request<{ site: Site; automation: CertificateAutomation }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate/dns`, { method: 'POST' }), + certificateAutomation: (projectID: number, siteID: number) => request<{ automation: CertificateAutomation }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate`), + installManualCertificate: (projectID: number, siteID: number, certificate: string, privateKey: string) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate/manual`, { method: 'PUT', body: JSON.stringify({ certificate, privateKey }) }), + disableCertificate: (projectID: number, siteID: number) => request<{ site: Site }>(`/api/v1/projects/${projectID}/sites/${siteID}/certificate`, { method: 'DELETE' }), + deleteSite: (projectID: number, siteID: number) => request(`/api/v1/projects/${projectID}/sites/${siteID}`, { method: 'DELETE' }), + resources: () => request('/api/v1/resources'), + bindDomain: (projectID: number, domain: string) => request<{ domain: DomainResource }>(`/api/v1/projects/${projectID}/domains`, { method: 'POST', body: JSON.stringify({ domain }) }), + bindSiteDomain: (projectID: number, siteID: number, domain: string) => request<{ domain: DomainResource }>(`/api/v1/projects/${projectID}/sites/${siteID}/domains`, { method: 'POST', body: JSON.stringify({ domain }) }), + files: (projectID: number, path: string) => request(fileURL(projectID, path)), + fileText: async (projectID: number, path: string) => { + const response = await fetch(fileURL(projectID, path, true), { credentials: 'same-origin' }); + if (!response.ok) throw await responseError(response); + return response.text(); + }, + fileDownloadURL: (projectID: number, path: string) => fileURL(projectID, path, true), + 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 }); + if (!response.ok) throw await responseError(response); + return response.json() as Promise<{ name: string; size: number }>; + }, + writeFile: (projectID: number, path: string, content: string, overwrite: boolean) => request(`/api/v1/projects/${projectID}/files`, { method: 'PUT', body: JSON.stringify({ path, content, overwrite }) }), + siteStartup:(id:number,site:number)=>request<{startup:StartupSettings}>(`/api/v1/projects/${id}/sites/${site}/startup`), + saveSiteStartup:(id:number,site:number,startup:StartupSettings)=>request(`/api/v1/projects/${id}/sites/${site}/startup`,{method:'PUT',body:JSON.stringify(startup)}), + websiteSettings:(id:number,site:number)=>request<{settings:WebsiteSettings}>(`/api/v1/projects/${id}/sites/${site}/settings`), + saveWebsiteSettings:(id:number,site:number,settings:WebsiteSettings)=>request(`/api/v1/projects/${id}/sites/${site}/settings`,{method:'PUT',body:JSON.stringify(settings)}), + siteLog:(id:number,site:number,kind:string,search='')=>request<{lines:string[];available:boolean}>(`/api/v1/projects/${id}/sites/${site}/logs?`+new URLSearchParams({kind,search,lines:'500'})), + hostMetrics:(id:number,days:number)=>request<{samples:HostMetric[]}>(`/api/v1/projects/${id}/metrics?days=${days}`), + fileAction:(id:number,action:string,path:string,to='')=>request(`/api/v1/projects/${id}/file-actions`,{method:'POST',body:JSON.stringify({action,path,to})}), + fileTrash:(id:number)=>request<{entries:TrashEntry[]}>(`/api/v1/projects/${id}/file-actions`), + trashFile: (projectID: number, path: string) => request(fileURL(projectID, path), { method: 'DELETE' }), + emptyTrash: (projectID: number) => request(`/api/v1/projects/${projectID}/files?emptyTrash=1`, { method: 'DELETE' }), + tenants: () => request<{ tenants: Tenant[] }>('/api/v1/admin/tenants'), + createTenant: (input: Record) => request<{ id: number }>('/api/v1/admin/tenants', { method: 'POST', body: JSON.stringify(input) }), + plans: () => request<{ plans: Plan[] }>('/api/v1/admin/plans'), + createPlan: (input: PlanInput) => request<{ id: number }>('/api/v1/admin/plans', { method: 'POST', body: JSON.stringify(input) }), + domainApproval: () => request<{ enabled: boolean }>('/api/v1/admin/settings/domain-approval'), + setDomainApproval: (enabled: boolean) => request('/api/v1/admin/settings/domain-approval', { method: 'PUT', body: JSON.stringify({ enabled }) }), + pendingDomains: () => request<{ domains: DomainResource[] }>('/api/v1/admin/domains/pending'), + reviewDomain: (id: number, approved: boolean) => request<{ domain: DomainResource }>(`/api/v1/admin/domains/${id}/review`, { method: 'POST', body: JSON.stringify({ approved }) }), + adminOverview: () => request('/api/v1/admin/overview'), + adminSettings: () => request('/api/v1/admin/settings'), + saveAdminSettings: (input: AdminSettings) => { + const {domainApproval,filingRequired,cdnCnameTarget,graceDays,recycleDays,backupRetentionDays,smtp,oidc}=input; + return request('/api/v1/admin/settings',{method:'PUT',body:JSON.stringify({domainApproval,filingRequired,cdnCnameTarget,graceDays,recycleDays,backupRetentionDays,smtp:{enabled:smtp.enabled,host:smtp.host,port:smtp.port,username:smtp.username,secret:smtp.secret,from:smtp.from,adminRecipients:smtp.adminRecipients,startTls:smtp.startTls},oidc:{enabled:oidc.enabled,issuer:oidc.issuer,clientId:oidc.clientId,secret:oidc.secret,redirectUri:oidc.redirectUri,autoCreate:oidc.autoCreate===true,userPasswordLogin:oidc.userPasswordLogin!==false,adminPasswordLogin:oidc.adminPasswordLogin!==false}})}); + }, + addIPAddress: (input: {nodeId?:number; address: string; allocationMode: 'shared' | 'dedicated'; label: string }) => request<{ id: number }>('/api/v1/admin/ip-addresses'+nodeQuery(input.nodeId), { method: 'POST', body: JSON.stringify({...input,nodeId:undefined}) }), + deleteIPAddress: (id: number) => request(`/api/v1/admin/ip-addresses/${id}`, { method: 'DELETE' }), + setProjectNetwork: (id: number, input: { ipId?: number; dedicated: boolean; httpPort: number; httpsPort: number }) => request(`/api/v1/admin/projects/${id}/network`, { method: 'PUT', body: JSON.stringify(input) }), + panelSites: (nodeId?:number) => request<{ sites: PanelSite[]; versions: RuntimeCatalog }>('/api/v1/admin/panel-sites'+nodeQuery(nodeId)), + runtimeEnvironments: (nodeId?:number) => request<{ environments: RuntimeEnvironment[] }>('/api/v1/admin/runtime-environments'+nodeQuery(nodeId), { cache: 'no-store' }), + runtimeMaintenance: (nodeId?:number) => request<{ sites: RuntimeMaintenanceSite[]; jobs: RuntimeMaintenanceJob[] }>('/api/v1/admin/runtime-maintenance'+nodeQuery(nodeId), { cache: 'no-store' }), + checkRuntimeUpdates: (nodeId?:number) => request<{ jobId: number }>('/api/v1/admin/runtime-maintenance/check'+nodeQuery(nodeId), { method: 'POST' }), + updatePHPPatch: (branch: string, target: string,nodeId?:number) => request<{ jobId: number }>('/api/v1/admin/runtime-maintenance/php'+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify({ branch, target }) }), + migrateSiteRuntime: (siteID: number, version: string, allowBranchChange = false, entryFile = '') => request<{ jobId: number }>(`/api/v1/admin/runtime-maintenance/sites/${siteID}`, { method: 'POST', body: JSON.stringify({ version, allowBranchChange, entryFile }) }), + resumeRuntimeMaintenance: (id: number,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-maintenance/jobs/${id}/resume`+nodeQuery(nodeId), { method: 'POST' }), + installRuntimeComponent: (runtime: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-components/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST' }), + installRuntimeEnvironment: (runtime: string, version: string,nodeId?:number) => request<{ ok: boolean }>(`/api/v1/admin/runtime-environments/${encodeURIComponent(runtime)}/install`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify({ version }) }), + adoptPanelSite: (id: number, input: { tenantId: number; name: string; runtime: string; version: string; runPath: string; autoSSL: boolean;planId:number },nodeId?:number) => request<{ project: APIProject; credentials: Credentials }>(`/api/v1/admin/panel-sites/${id}/adopt`+nodeQuery(nodeId), { method: 'POST', body: JSON.stringify(input) }), + updateDomainMetadata: (id: number, input: Record) => request(`/api/v1/admin/domains/${id}/metadata`, { method: 'PUT', body: JSON.stringify(input) }), + provisionDomainDNS: (id: number, admin = false) => request<{ domain: DomainResource }>(`${admin ? '/api/v1/admin' : '/api/v1'}/domains/${id}/dns`, { method: 'POST' }), + removeDomainDNS: (id: number, admin = false) => request<{ domain: DomainResource }>(`${admin ? '/api/v1/admin' : '/api/v1'}/domains/${id}/dns`, { method: 'DELETE' }), + setTenantExpiry: (id: number, expiresAt?: string) => request(`/api/v1/admin/tenants/${id}/expiry`, { method: 'PUT', body: JSON.stringify({ expiresAt: expiresAt || null }) }), + discoverDNSZones:(input:DNSCredentialInput,admin=false)=>request<{zones:DNSZoneChoice[]}>(`${admin?'/api/v1/admin':'/api/v1'}/dns-credentials/discover`,{method:'POST',body:JSON.stringify(input)}), + dnsCredentials: (admin = false) => request<{ credentials: DNSCredential[] }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials`), + createDNSCredential: (input: DNSCredentialInput, admin = false) => request<{ credential: DNSCredential }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials`, { method: 'POST', body: JSON.stringify(input) }), + updateDNSCredential: (id: number, input: DNSCredentialInput, admin = false) => request<{ credential: DNSCredential }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials/${id}`, { method: 'PUT', body: JSON.stringify(input) }), + testDNSCredential: (id: number, admin = false) => request<{ credential: DNSCredential }>(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials/${id}/test`, { method: 'POST' }), + deleteDNSCredential: (id: number, admin = false) => request(`${admin ? '/api/v1/admin' : '/api/v1'}/dns-credentials/${id}`, { method: 'DELETE' }), +}; diff --git a/frontend/src/batchJSON.test.ts b/frontend/src/batchJSON.test.ts new file mode 100644 index 0000000..bb8bcf1 --- /dev/null +++ b/frontend/src/batchJSON.test.ts @@ -0,0 +1,5 @@ +import {expect,it} from 'vitest'; +import {batchTemplate,parseBatchJSON} from './batchJSON'; +it('imports typed JSON and preserves supplied passwords exactly',()=>{const input=batchTemplate('create_users');input.rows[0].password=' =secret,with\nquotes" ';expect(parseBatchJSON('\uFEFF'+JSON.stringify(input),'create_users')[0].password).toBe(input.rows[0].password)}); +it('rejects result files, wrong operations, untyped booleans and prototype keys',()=>{for(const input of ['{}','[]','{"format":"sea-vhost.batch-result","version":1,"operation":"create_users","rows":[{}]}',JSON.stringify(batchTemplate('create_hosts')),'{"format":"sea-vhost.batch","version":1,"operation":"create_users","rows":[{"autoSSL":"false"}]}','{"format":"sea-vhost.batch","version":1,"operation":"create_users","rows":[{"__proto__":{"admin":true}}]}'])expect(()=>parseBatchJSON(input,'create_users')).toThrow()}); +it('explicitly unbinds owners and accepts expiry null without losing boolean values',()=>{const input=batchTemplate('assign_hosts');input.rows[0].stopServices=false;const row=parseBatchJSON(JSON.stringify(input),'assign_hosts')[0];expect(row).toMatchObject({tenantId:0,owner:'',stopServices:false});expect(parseBatchJSON(JSON.stringify(batchTemplate('host_subscription')),'host_subscription')[0]).toMatchObject({expiresAt:null,setExpiry:true})}); diff --git a/frontend/src/batchJSON.ts b/frontend/src/batchJSON.ts new file mode 100644 index 0000000..da41f65 --- /dev/null +++ b/frontend/src/batchJSON.ts @@ -0,0 +1,42 @@ +import type {BatchOperation,BatchRow} from './api'; + +const strings=new Set(['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']); + +export function parseBatchJSON(source:string,operation:BatchOperation):BatchRow[]{ + if(new TextEncoder().encode(source).length>256*1024)throw new Error('JSON 文件不能超过 256 KiB'); + let data:unknown;try{data=JSON.parse(source.replace(/^\uFEFF/,''))}catch{throw new Error('JSON 格式错误,请使用下载的模板')} + if(!data||typeof data!=='object'||Array.isArray(data))throw new Error('JSON 顶层必须为批量模板对象'); + const envelope=data as Record; + if(Object.keys(envelope).some(key=>!['format','version','operation','rows'].includes(key))||envelope.format!=='sea-vhost.batch'||envelope.version!==1||envelope.operation!==operation)throw new Error('JSON 模板类型、版本或操作不匹配'); + if(!Array.isArray(envelope.rows)||envelope.rows.length<1||envelope.rows.length>500)throw new Error('JSON rows 需要 1–500 条记录,请按操作上限分批导入'); + return envelope.rows.map((record,index)=>{ + if(!record||typeof record!=='object'||Array.isArray(record))throw new Error(`第 ${index+1} 条必须为对象`); + const out:Record={}; + for(const [field,value]of Object.entries(record)){ + if(strings.has(field)){if(field==='owner'&&value===null){out.owner='';continue}if(typeof value!=='string')throw new Error(`第 ${index+1} 条 ${field} 必须为字符串`);out[field]=field==='password'?value:value.trim()} + else if(numbers.has(field)){if(typeof value!=='number'||!Number.isSafeInteger(value)||value<0)throw new Error(`第 ${index+1} 条 ${field} 必须为非负安全整数`);out[field]=value} + else if(booleans.has(field)){if(typeof value!=='boolean')throw new Error(`第 ${index+1} 条 ${field} 必须为布尔值`);out[field]=value} + else if(field==='expiresAt'){if(value!==null&&(typeof value!=='string'||Number.isNaN(new Date(value).getTime())))throw new Error(`第 ${index+1} 条到期时间无效`);out.expiresAt=value===null?null:new Date(value as string).toISOString();out.setExpiry=true} + else throw new Error(`第 ${index+1} 条包含未知字段:${field}`); + } + if('owner'in out)out.tenantId=0; + if(operation==='create_users'&&!out.displayName)out.displayName=out.name; + return out as BatchRow; + }); +} + +export function batchTemplate(operation:BatchOperation){ + const row:BatchRow=operation==='create_users'?{slug:'demo-0001',name:'示例用户',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} + :operation==='host_subscription'?{host:'sv0123456789',expiresAt:null,setExpiry:true} + :{host:'sv0123456789'}; + return {format:'sea-vhost.batch',version:1,operation,rows:[row]}; +} +export function downloadBatchTemplate(operation:BatchOperation){ + const url=URL.createObjectURL(new Blob([JSON.stringify(batchTemplate(operation),null,2)+'\n'],{type:'application/json;charset=utf-8'})); + const link=document.createElement('a');link.href=url;link.download=`sea-vhost-${operation}-template.json`;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); +} diff --git a/frontend/src/components/AdminBatches.tsx b/frontend/src/components/AdminBatches.tsx new file mode 100644 index 0000000..ef3e147 --- /dev/null +++ b/frontend/src/components/AdminBatches.tsx @@ -0,0 +1,83 @@ +import {PageHeader} from './UI'; +import {useConfirmation} from './Confirmation'; +import {ModalBackdrop} from './ModalBackdrop'; +import {useEffect,useRef,useState} from 'react'; +import {Download,Layers,RefreshCw,Upload,X} from 'lucide-react'; +import {api,type AdminBatch,type AdminProject,type BatchOperation,type BatchPreviewRow,type BatchRow,type ControlNode,type Tenant} from '../api'; +import type {Plan,Runtime,RuntimeCatalog} from '../types'; +import {downloadBatchTemplate,parseBatchJSON} from '../batchJSON'; + +export const batchOperationNames:Record={create_users:'批量创建用户',create_hosts:'批量创建主机',assign_hosts:'批量绑定 / 解绑用户',host_subscription:'批量修改套餐与到期',host_start:'批量启动主机',host_stop:'批量停止主机',host_password_reset:'重置主机登录密码',user_enable:'批量启用用户',user_disable:'批量停用用户'}; +const states:Record={queued:'排队中',running:'执行中',completed:'已完成',partial:'部分完成',pending:'待执行',succeeded:'成功',failed:'失败',uncertain:'待核验',cancelled:'已取消'}; +const emptyCatalog:RuntimeCatalog={PHP:[],'Node.js':[],Python:[],Go:[],Java:[]}; +const message=(reason:unknown)=>reason instanceof Error?reason.message:'操作失败,请稍后重试'; +function key(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),byte=>byte.toString(16).padStart(2,'0')).join('')} +export interface BatchSelection {operation:BatchOperation;rows?:BatchRow[];} +interface ComposerProps extends BatchSelection {users:Tenant[];projects:AdminProject[];plans:Plan[];onClose:()=>void;onChanged:()=>Promise;} + +export function BatchComposer({operation,rows:selection=[],users,projects,plans,onClose,onChanged}:ComposerProps){ + const creating=operation==='create_users'||operation==='create_hosts'; + const [mode,setMode]=useState<'quantity'|'json'|'selection'>(creating?'quantity':selection.length?'selection':'json'); + const [count,setCount]=useState(3),[start,setStart]=useState(1),[prefix,setPrefix]=useState(()=>`batch-${key().slice(0,6)}`),[displayPrefix,setDisplayPrefix]=useState('批量用户'),[emailDomain,setEmailDomain]=useState('vhost.ser888.cn'); + const pending=selection.length===1?projects.find(p=>p.id===selection[0].hostId)?.pendingOwnership:undefined; + const [credentialMode,setCredentialMode]=useState(pending?.credentialMode||'preserve'),[stopServices,setStopServices]=useState(pending?.stopServices??true),[resumeOwnership,setResumeOwnership]=useState(false); + const [owner,setOwner]=useState(pending?.targetOwnerId||0),[plan,setPlan]=useState(operation==='host_subscription'?0:plans[0]?.id||0),[node,setNode]=useState(0),[nodes,setNodes]=useState([]); + const [runtime,setRuntime]=useState('PHP'),[version,setVersion]=useState(''),[catalog,setCatalog]=useState(emptyCatalog),[runPath,setRunPath]=useState('/'),[expiry,setExpiryValue]=useState(''),[changeExpiry,setChangeExpiry]=useState(false),[autoSSL,setAutoSSL]=useState(true); + const [imported,setImported]=useState([]),[fileName,setFileName]=useState(''),[preview,setPreview]=useState([]),[prepared,setPrepared]=useState([]),[requestKey,setRequestKey]=useState(''),[job,setJob]=useState(); + const [busy,setBusy]=useState(false),[catalogBusy,setCatalogBusy]=useState(false),[error,setError]=useState(''); + function invalidate(){setPreview([]);setPrepared([]);setRequestKey('');setError('')} + useEffect(()=>{if(operation!=='create_hosts')return;let active=true;api.nodes().then(result=>{if(active){setNodes(result.nodes.filter(n=>n.enabled));setNode(result.nodes.find(n=>n.enabled)?.id||0)}}).catch(reason=>{if(active)setError(message(reason))});return()=>{active=false}},[operation]); + useEffect(()=>{if(operation!=='create_hosts'||!node)return;let active=true;setCatalogBusy(true);setCatalog(emptyCatalog);api.panelSites(node).then(result=>{if(active)setCatalog(result.versions)}).catch(reason=>{if(active)setError(message(reason))}).finally(()=>{if(active)setCatalogBusy(false)});return()=>{active=false}},[node,operation]); + useEffect(()=>{setVersion(current=>catalog[runtime]?.includes(current)?current:catalog[runtime]?.[0]||'')},[catalog,runtime]); + function defaults():BatchRow{return {credentialMode,stopServices,resumeOwnership,tenantId:owner,nodeId:node,planId:plan,runtime,version:catalog[runtime]?.includes(version)?version:catalog[runtime]?.[0]||'',runPath,expiresAt:expiry?new Date(expiry).toISOString():null,setExpiry:operation==='host_subscription'?changeExpiry:!!expiry,autoSSL}} + function buildRows():BatchRow[]{ + const shared=defaults(); + if(mode==='selection')return selection.map(row=>({...row,...shared})); + 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}}) + } + async function prepare(){setBusy(true);setError('');setPreview([]);try{const rows=buildRows();if(operation==='host_subscription'&&!plan&&!changeExpiry)throw new Error('请选择新套餐,或勾选修改到期时间');const result=await api.previewBatch(operation,rows);setPrepared(rows);setPreview(result.rows);setRequestKey(key())}catch(reason){setError(message(reason))}finally{setBusy(false)}} + async function submit(){setBusy(true);setError('');try{const result=await api.createBatch(operation,prepared,requestKey);setJob(result.batch);setImported([]);setPrepared([])}catch(reason){setError(message(reason))}finally{setBusy(false)}} + async function importFile(file?:File){invalidate();if(!file)return;setBusy(true);try{if(file.size>256*1024)throw new Error('JSON 文件不能超过 256 KiB');const data=parseBatchJSON(await file.text(),operation);setImported(data);setFileName(file.name)}catch(reason){setImported([]);setFileName('');setError(message(reason))}finally{setBusy(false)}} + const validCount=preview.filter(row=>row.valid).length; + return

{batchOperationNames[operation]}

+ {job?:<> +

先验证预览,再提交后台执行。每条独立记录结果;部分失败不会撤销成功项。离开页面后可在“批量任务”继续查看。

+
+ + {mode==='quantity'?<>:null} + {operation==='create_users'&&mode==='quantity'?<>:null} + {operation==='create_hosts'||operation==='assign_hosts'?:null} + {operation==='assign_hosts'?<>:null} + {operation==='create_hosts'?<>:null} + {operation==='create_hosts'||operation==='host_subscription'?<>{operation==='host_subscription'?:null}:null} + {operation==='create_hosts'?:null} +
+ {mode==='json'?
{fileName?`${fileName} · ${imported.length} 条`:'支持 UTF-8 JSON 模板;空密码独立随机生成'}
:null} + {operation==='assign_hosts'?

一台主机最多绑定一个用户;用户可管理多台主机。归属变更不改变目录、Linux 身份和资源限额。JSON 中 owner 留空表示解绑。保留密码时,旧持有者仍可使用原主机密码重新登录,也可继续访问 FTP 或数据库;重置后需更新程序的数据库密码。变更会注销旧主机会话,并关闭自动证书续期,现有证书继续使用,可由新管理者重新配置。

:null} + {operation==='user_disable'?

停用用户会注销用户登录和代入会话;独立主机账号及运行中的网站不因此停止。

:null} + {operation==='host_stop'?

将停止所选主机的网站;文件和数据库保留。

:null} + {operation==='host_password_reset'?

将随机重置主机登录密码,并注销该主机的旧登录及代入会话;FTP 和数据库密码保持不变。新登录密码通过结果 JSON 下载。

:null} +
{error?

{error}

:null} + {preview.length?

执行预览 · {validCount} 项可执行 / {preview.length-validCount} 项需修正

{preview.map(row=>)}
行号账号 / 主机操作说明
{row.row}{row.label}{batchOperationNames[operation]}{row.detail}{operation==='create_users'&&row.valid?' · 密码不在预览中显示':''}
:null} +
+ } +
+} + +function BatchProgress({id,onChanged}:{id:number;onChanged:()=>Promise}){ + const {confirm,confirmation}=useConfirmation(); + const [job,setJob]=useState(),[error,setError]=useState(''),[busy,setBusy]=useState(false);const changed=useRef(false);const mayContainCredentials=!!job&&['create_users','create_hosts','assign_hosts','host_password_reset'].includes(job.operation); + useEffect(()=>{let active=true;let timer:ReturnType|undefined;async function load(){try{const result=await api.batch(id);if(!active)return;setJob(result.batch);setError('');if(result.batch.pending>0||['queued','running'].includes(result.batch.state))timer=setTimeout(()=>void load(),1500);else if(!changed.current){changed.current=true;await onChanged()}}catch(reason){if(active){setError(message(reason));timer=setTimeout(()=>void load(),3000)}}}void load();return()=>{active=false;if(timer)clearTimeout(timer)}},[id,onChanged]); + async function cancel(){if(!await confirm('只取消尚未执行的条目,执行中条目继续完成,是否取消?',{title:'取消剩余任务'}))return;setBusy(true);try{await api.cancelBatch(id);const result=await api.batch(id);setJob(result.batch)}catch(reason){setError(message(reason))}finally{setBusy(false)}} + return
{confirmation}{error?

{error}

:null}{!job?

正在读取批次…

:<>
批次 #{id} · {states[job.state]||job.state}成功 {job.succeeded} · 失败/取消 {job.failed} · 待核验 {job.uncertain} · 待完成 {job.pending}

{mayContainCredentials?'结果可能包含登录、FTP 和数据库密码,加密保留 24 小时,需主动下载 JSON。不要把凭据文件发给无关人员;过期后可在主机中查看 FTP/数据库凭据并重置登录密码。':'下载结果 JSON 可查看每一项的执行状态与说明,本次操作不会生成新密码。'}

{job.pending===0&&['queued','running'].includes(job.state)?正在保存任务结果…:job.pending>0?:job.secretsExpireAt&&new Date(job.secretsExpireAt)>new Date()?{mayContainCredentials?'下载结果与凭据 JSON':'下载结果 JSON'}:{mayContainCredentials?'批次凭据已过期':'结果下载已过期'}}
{job.items?.map(item=>)}
行号账号 / 主机资源 ID状态说明
{item.row}{item.label}{item.resourceId||'—'}{states[item.state]||item.state}{item.detail}
}
+} + +export function BatchJobs({create,onChanged}:{create:(selection:BatchSelection)=>void;onChanged:()=>Promise}){ + const [jobs,setJobs]=useState([]),[selected,setSelected]=useState(),[error,setError]=useState(''),[version,setVersion]=useState(0); + useEffect(()=>{let active=true;let timer:ReturnType|undefined;async function load(){try{const result=await api.batches();if(!active)return;setJobs(result.batches);setError('');if(result.batches.some(job=>job.pending>0||['queued','running'].includes(job.state)))timer=setTimeout(()=>void load(),2500)}catch(reason){if(active)setError(message(reason))}}void load();return()=>{active=false;if(timer)clearTimeout(timer)}},[version]); + return
}/>
{error?

{error}

:null}
{jobs.map(job=>)}
批次操作状态成功 / 总数创建时间操作
#{job.id}{batchOperationNames[job.operation]}{states[job.state]||job.state}{job.succeeded} / {job.total}{new Date(job.createdAt).toLocaleString('zh-CN')}
{!jobs.length?

暂无批量任务

:null}
{selected?

批量任务 #{selected}

:null}
+} + diff --git a/frontend/src/components/AdminConsole.tsx b/frontend/src/components/AdminConsole.tsx new file mode 100644 index 0000000..a18e258 --- /dev/null +++ b/frontend/src/components/AdminConsole.tsx @@ -0,0 +1,107 @@ +import {SystemSettingsForm as SettingsPage} from './SystemSettingsForm'; +import {AdminLogs} from './AdminLogs'; +import {AdminDomains as Domains} from './AdminDomains'; +import {AccountEditor} from './ResourceEditors'; +import {ModalBackdrop} from './ModalBackdrop'; +import {AdminHosts as Hosts} from './AdminHosts'; +import {PageHeader} from './UI'; +import {useNavigationOverlay} from './overlay'; +import {HostProvisioning} from './HostProvisioning'; +import {IntegrationAPI} from './IntegrationAPI'; +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'; +import {NodeIPPool} from './NodeIPPool'; +import { NodeManagement,NodeEnvironment } from './NodeManagement'; +import {BatchComposer,BatchJobs,type BatchSelection} from './AdminBatches'; + +interface Props { onPlansChanged?:()=>Promise; onImpersonate?:(input:{tenantId?:number;projectId?:number})=>Promise; user: User; tenants: Tenant[]; plans: Plan[]; pendingDomains: DomainResource[]; approval: boolean; onApproval: (value: boolean) => Promise; onReviewDomain: (id: number, approved: boolean) => Promise; onCreate: (input: Record) => Promise; onCreatePlan: (input: PlanInput) => Promise; onLogout: () => void; onSecurity: () => void; } +type Page = 'integration' | 'batches' | 'nodes' | 'overview' | 'users' | 'hosts' | 'environment' | 'plans' | 'domains' | 'dns' | 'ips' | 'lifecycle' | 'settings' | 'logs'; +const navigation: Array<{ id: Page; label: string; icon: typeof LayoutGrid }> = [ + { id: 'overview', label: '总览', icon: LayoutGrid }, {id:'batches',label:'批量任务',icon:Boxes}, { id: 'users', label: '用户管理', icon: UsersRound }, + {id:'nodes',label:'节点管理',icon:Network}, { id: 'hosts', label: '虚拟主机', icon: Server }, { id: 'environment', label: '环境配置', icon: Cpu }, { id: 'plans', label: '套餐管理', icon: Boxes }, + { id: 'domains', label: '域名管理', icon: Globe2 }, { id: 'dns', label: 'DNS 管理', icon: CloudCog }, + { id: 'ips', label: 'IP 地址池', icon: Network }, { id: 'lifecycle', label: '到期与回收', icon: Activity }, + {id:'integration',label:'对接 API',icon:KeyRound},{ id: 'settings', label: '系统设置', icon: Settings }, { id: 'logs', label: '操作日志', icon: Database }, +]; +const emptyOverview: AdminOverview = { users: [], projects: [], domains: [], ipAddresses: [], logs: [] }; +const defaultSettings: AdminSettings = { domainApproval: true, filingRequired: false, cdnCnameTarget: '', graceDays: 3, recycleDays: 7, backupRetentionDays: 14, smtp: { enabled: false, host: '', port: 465, username: '', from: '', adminRecipients: '', startTls: true, secretConfigured: false }, oidc: { enabled: false, issuer: '', clientId: '', redirectUri: '', secretConfigured: false, bindingOnly: true, passwordLogin: true,autoCreate:false,userPasswordLogin:true,adminPasswordLogin:true } }; + +export function AdminConsole(props: Props) { + const [page, setPage] = useState('overview'); const [overview, setOverview] = useState(() => ({ ...emptyOverview, users: props.tenants, domains: props.pendingDomains })); const [settings, setSettings] = useState(() => ({ ...defaultSettings, domainApproval: props.approval })); + const [loading, setLoading] = useState(true); const [loadError,setLoadError]=useState(''); const [notice, setNotice] = useState(''); const [query, setQuery] = useState(''); + const [showUserForm, setShowUserForm] = useState(false); const [showPlanForm, setShowPlanForm] = useState(false); const [networkProject, setNetworkProject] = useState(); + const [showAdoption, setShowAdoption] = useState(false); + const [batch,setBatch]=useState(); + const [mobileNavOpen,setMobileNavOpen]=useState(false); + useNavigationOverlay(mobileNavOpen,setMobileNavOpen); + function navigate(next:Page){setPage(next);setQuery('');setMobileNavOpen(false)} + const refresh = useCallback(async () => { try { const [data, config] = await Promise.all([api.adminOverview(), api.adminSettings()]); setOverview(data); setSettings(config);setLoadError(''); } catch(reason) {setLoadError(reason instanceof Error?reason.message:'管理数据读取失败');} finally { setLoading(false); } }, [props.pendingDomains, props.tenants]); + useEffect(() => { void refresh().catch(()=>{}); }, [refresh]); + const users = overview.users; const domains = overview.domains; + const title = navigation.find((item) => item.id === page)?.label || '总览'; const notify = (message: string) => { setNotice(message); window.setTimeout(() => setNotice(''), 2600); }; + return
)}
管理员控制台
Sea vHost/{title}
{props.user.displayName.slice(0, 1)}{props.user.displayName}平台管理员
{loading ?
正在读取管理数据…
: null}{loadError?
{loadError}
:null}{!loading&&!loadError ? : null}
{showUserForm ? setShowUserForm(false)} onCreate={async (input) => { await props.onCreate(input); setShowUserForm(false); await refresh(); }} /> : null}{showPlanForm ? setShowPlanForm(false)} onCreate={async (input) => { await props.onCreatePlan(input); setShowPlanForm(false); }} /> : null}{showAdoption ? setShowAdoption(false)} onComplete={async () => { setShowAdoption(false); await refresh(); notify('宝塔站点已迁移并分配'); }} /> : null}{networkProject ? setNetworkProject(undefined)} onSave={async (input) => { await api.setProjectNetwork(networkProject.id, input); setNetworkProject(undefined); await refresh(); notify('网络配置已保存'); }} /> : null}{batch?{setBatch(undefined);void refresh().catch(()=>{})}} onChanged={refresh}/>:null}{notice ?
{notice}
: null}
; +} + +function AdminPage({ page, users, domains, overview, settings, plans, query, setQuery, setPage, setShowUserForm, setShowPlanForm, setNetworkProject, setShowAdoption, setSettings, refresh, notify, openBatch, props }: { page: Page; users: Tenant[]; domains: DomainResource[]; overview: AdminOverview; settings?: AdminSettings; plans: Plan[]; query: string; setQuery: (v: string) => void; setPage: (v: Page) => void; setShowUserForm: (v: boolean) => void; setShowPlanForm: (v: boolean) => void; setNetworkProject: (v: AdminProject) => void; setShowAdoption: (v: boolean) => void; setSettings: (v: AdminSettings) => void; refresh: () => Promise; notify: (v: string) => void; openBatch:(selection:BatchSelection)=>void; props: Props }) { + if (page === 'overview') return ; + if (page === 'batches') return ; + if (page === 'users') return {if(props.onImpersonate)void props.onImpersonate({tenantId:id}).catch(reason=>notify(reason instanceof Error?reason.message:'进入失败'))}} users={users} query={query} setQuery={setQuery} create={() => setShowUserForm(true)} expiry={async (id, value) => { await api.setTenantExpiry(id, value); await refresh(); notify('用户到期时间已更新'); }} />; + if(page==='nodes') return ; + if (page === 'hosts') return {if(props.onImpersonate)void props.onImpersonate({projectId:id}).catch(reason=>notify(reason instanceof Error?reason.message:'进入失败'))}} users={users} plans={plans} refresh={refresh} projects={overview.projects} query={query} setQuery={setQuery} network={setNetworkProject} adopt={() => setShowAdoption(true)} />; + if (page === 'environment') return ; + if (page === 'plans') return setShowPlanForm(true)} save={props.onCreatePlan} changed={props.onPlansChanged} />; + if (page === 'domains') return {await api.unbindDomain(item.id,item.domain,true);await refresh();notify('自定义域名已解绑')}} domains={domains} approval={settings?.domainApproval ?? props.approval} approvalChange={async (value) => { await props.onApproval(value); if (settings) setSettings({ ...settings, domainApproval: value }); }} review={async (id, approved) => { await props.onReviewDomain(id, approved); await refresh(); }} metadata={async (id, input) => { await api.updateDomainMetadata(id, input); await refresh(); notify('域名策略已更新'); }} dns={async (id, remove) => { if (remove) await api.removeDomainDNS(id, true); else await api.provisionDomainDNS(id, true); await refresh(); notify(remove ? '托管 DNS 记录已删除' : 'CNAME 记录已创建'); }} />; + if (page === 'dns') return
; + if (page === 'ips') return ; + if (page === 'lifecycle') return setPage('hosts')} />; + if(page==='integration')return ; + if (page === 'settings' && settings) return { await api.saveAdminSettings(value); setSettings(value); notify('系统设置已保存'); }} />; + if (page === 'logs') return ; + return
; +} + +function Heading({ title, description, action }: { title: string; description: string; action?: ReactNode }) { return ; } +function KPI({ icon: Icon, label, value, note }: { icon: typeof UsersRound; label: string; value: number; note: string }) { return
{label}{value}{note}
; } +function Empty({ text }: { text: string }) { return
{text}
; } +function SearchBox({ value, change, placeholder }: { value: string; change: (v: string) => void; placeholder: string }) { return ; } + +function Overview({ users, projects, domains, logs, navigate, review }: { users: Tenant[]; projects: AdminProject[]; domains: DomainResource[]; logs: AdminOverview['logs']; navigate: (v: Page) => void; review: (id: number, approved: boolean) => Promise }) { + const running = projects.filter((item) => item.status === 'running').length; const pending = domains.filter((item) => item.status === 'pending').length; const expiring = users.filter((item) => item.expiresAt && new Date(item.expiresAt).getTime() < Date.now() + 7 * 86400000).length; + return
{pending ?

待审核域名

{domains.filter((item) => item.status === 'pending').slice(0, 4).map((item) =>
{item.domain}{item.tenantName} · {item.hostName}
)}
: null}

虚拟主机状态

{projects.slice(0, 6).map((item) =>
{item.hostName}{item.tenantName} · {item.runtime} {item.version}{item.domain}
)}{!projects.length ? : null}

最近操作

{logs.slice(0, 6).map((item) =>
{item.success ? '成功' : '失败'}{item.detail}{dateText(item.createdAt)}
)}{!logs.length ? : null}
; +} + +function Users({users,query,setQuery,create,enter,bulk,refresh}:{refresh:()=>Promise;users:Tenant[];query:string;setQuery:(value:string)=>void;create:()=>void;expiry:(id:number,value?:string)=>Promise;enter?:(id:number)=>void;bulk:(selection:BatchSelection)=>void}){ + const [editing,setEditing]=useState(),[deleting,setDeleting]=useState(); + const [selected,setSelected]=useState([]);const list=users.filter(item=>`${item.name} ${item.slug}`.toLowerCase().includes(query.toLowerCase()));const ids=selected.filter(id=>users.some(item=>item.id===id)); + const change=(id:number,checked:boolean)=>setSelected(current=>checked?[...new Set([...current,id])]:current.filter(value=>value!==id)); + const run=(operation:'user_enable'|'user_disable',targets=ids)=>bulk({operation,rows:targets.map(accountId=>({accountId}))}); + return <>
}/>
共 {list.length} 个用户 · 已选 {ids.length} 个
{list.map(item=>)}
0&&list.every(item=>ids.includes(item.id))} onChange={event=>setSelected(event.target.checked?list.map(item=>item.id):[])}/>用户虚拟主机状态操作
change(item.id,event.target.checked)}/>{item.name}{item.slug}{item.projectCount}{item.status==='active'?'正常':'已停用'}
{deleting?setDeleting(undefined)} onChanged={refresh}/>:null}{editing?setEditing(undefined)} onChanged={refresh}/>:null}; +} + + +export function Plans({ plans, create,save,changed }: { plans: Plan[]; create: () => void;save:(input:PlanInput)=>Promise;changed?:()=>Promise }) { + const [copy,setCopy]=useState(),[removing,setRemoving]=useState(),[confirmation,setConfirmation]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[hidden,setHidden]=useState([]); + return
创建套餐} />
{plans.filter(p=>!hidden.includes(p.id)).map((plan) =>

{plan.name}

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

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

:null}
)}
{copy?setCopy(undefined)} onCreate={async input=>{await save(input);setCopy(undefined)}}/>:null}{removing?
{e.preventDefault();if(busy||confirmation!==removing.name)return;setBusy(true);setError('');try{await api.deletePlan(removing.id,confirmation);setHidden(v=>[...v,removing.id]);setRemoving(undefined);await changed?.()}catch(e){setError(e instanceof Error?e.message:'删除套餐失败')}finally{setBusy(false)}}}>

删除未使用套餐

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

{error?

{error}

:null}
:null}
; } + +function Lifecycle({projects,onManage}:{projects:AdminProject[];onManage:()=>void}){return
管理主机 / 恢复}/>{projects.map(p=>)}
虚拟主机用户 / 节点当前阶段到期时间
{p.hostName}{p.tenantName} / #{p.nodeId}{p.expiresAt?dateText(p.expiresAt):"长期使用"}
} + +function Table({ children }: { children: ReactNode }) { return
{children}
; } + +function UserForm({ plans, onClose, onCreate }: { plans: Plan[]; onClose: () => void; onCreate: (input: Record) => Promise }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(''); return
{ event.preventDefault(); setBusy(true); const form = new FormData(event.currentTarget); try { await onCreate({ slug: form.get('slug'), name: form.get('name'), email: form.get('email'), displayName: form.get('displayName'), password: form.get('password'), planId: plans[0]?.id }); } catch (reason) { setError(reason instanceof Error ? reason.message : '创建失败'); setBusy(false); } }}>

创建用户

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

{error ?

{error}

: null}
; } +export function PlanForm({ onClose, onCreate,initial }: { initial?:Plan; onClose: () => void; onCreate: (input: PlanInput) => Promise }) { const [busy, setBusy] = useState(false);const [error,setError]=useState(''); return
{ event.preventDefault(); setBusy(true);setError(''); const form = new FormData(event.currentTarget); const gib = 1024 ** 3; try { await onCreate({ name: String(form.get('name')), storageBytes: Number(form.get('storageGB')) * gib, databaseBytes: Number(form.get('databaseGB')) * gib, bandwidthBytes: Number(form.get('bandwidthGB')) * gib, bandwidthMbps: Number(form.get('bandwidthMbps')), processLimit: Number(form.get('processLimit')), projectLimit: Number(form.get('projectLimit')), ftpLimit: Number(form.get('ftpLimit')), databaseLimit: Number(form.get('databaseLimit')) }); } catch(e){setError(e instanceof Error?e.message:'套餐保存失败')} finally { setBusy(false); } }}>

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

{[['storageGB', '存储空间(GB)', initial?initial.storageBytes/1024**3:50], ['databaseGB', '数据库空间(GB)', initial?initial.databaseBytes/1024**3:20], ['bandwidthGB', '月流量(GB)', initial?initial.bandwidthBytes/1024**3:500], ['bandwidthMbps', 'HTTP 每请求 / FTP 每会话限速(Mbps,0 不限)', initial?.bandwidthMbps??0], ['processLimit', '进程数', initial?.processLimit??100], ['projectLimit', '每主机网站数', initial?.projectLimit??10], ['ftpLimit', 'FTP 账号数', initial?.ftpLimit??10], ['databaseLimit', '数据库数', initial?.databaseLimit??10]].map(([name, label, value]) => )}
{error?

{error}

:null}
; } + +function AdoptionForm({users,plans,onClose,onComplete}:{users:Tenant[];plans:Plan[];onClose:()=>void;onComplete:()=>Promise}){return } + +export function NetworkForm({ project, ips, onClose, onSave }: { project: AdminProject; ips: AdminOverview['ipAddresses']; onClose: () => void; onSave: (input: { ipId?: number; dedicated: boolean; httpPort: number; httpsPort: number }) => Promise }) { const [busy,setBusy]=useState(false),[error,setError]=useState(''); const [dedicated, setDedicated] = useState(project.dedicatedIp); const [ipId, setIPID] = useState(() => ips.find((item) => item.address === project.ipAddress)?.id); const [httpPort, setHTTPPort] = useState(project.httpPort || 80); const [httpsPort, setHTTPSPort] = useState(project.httpsPort || 443); return
{ event.preventDefault(); if(busy)return;setBusy(true);setError('');try{await onSave({ ipId: dedicated ? ipId : undefined, dedicated, httpPort, httpsPort });}catch(e){setError(e instanceof Error?e.message:'网络配置保存失败')}finally{setBusy(false)} }}>

公开网络配置

{project.hostName} · 内部反向代理端口与公开端口相互独立。

{dedicated ? : null}
{error?

{error}

:null}
; } + +function LifecycleBadge({ state = 'active' }: { state?: Tenant['lifecycleState'] }) { return {state === 'grace' ? '宽限期' : state === 'recycle' ? '回收区' : state === 'purged' ? '已清理' : '正常'}; } +function statusText(v: string) { return ({ running: '运行中', stopped: '已停止', awaiting_upload: '待上传', quota_suspended: '配额停用', provisioning: '创建中', failed: '失败' } as Record)[v] || v; } +function filingText(v?: string) { return v === 'approved' ? '已备案' : v === 'pending' ? '待审核' : v === 'rejected' ? '未通过' : '免备案'; } +function dateText(v?: string) { return v ? new Date(v).toLocaleString('zh-CN', { hour12: false }) : '—'; } +function toLocalInput(v: string) { const date = new Date(v); return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); } diff --git a/frontend/src/components/AdminDomains.tsx b/frontend/src/components/AdminDomains.tsx new file mode 100644 index 0000000..1fb6a76 --- /dev/null +++ b/frontend/src/components/AdminDomains.tsx @@ -0,0 +1,23 @@ +import {useState} from 'react'; +import type {DomainResource} from '../api'; +import {PageHeader} from './UI'; +import {ModalBackdrop} from './ModalBackdrop'; +import {useConfirmation} from './Confirmation'; +import {UnbindDomainDialog} from './UnbindDomainDialog'; + +interface Props {domains:DomainResource[];approval:boolean;approvalChange:(v:boolean)=>Promise;review:(id:number,approved:boolean)=>Promise;metadata:(id:number,input:Record)=>Promise;dns:(id:number,remove:boolean)=>Promise;unbind?:(domain:DomainResource)=>Promise} +export function AdminDomains({domains,approval,approvalChange,review,metadata,dns,unbind}:Props){ + const [removing,setRemoving]=useState(); + const [kind,setKind]=useState('all'),[busy,setBusy]=useState(''),[error,setError]=useState(''),[editing,setEditing]=useState();const {confirm,confirmation}=useConfirmation(); + const list=domains.filter(v=>kind==='all'||v.kind===kind); + async function perform(key:string,action:()=>Promise){setBusy(key);setError('');try{await action()}catch(e){setError(e instanceof Error?e.message:'操作失败')}finally{setBusy('')}} + async function dnsAction(v:DomainResource){if(v.dnsRecordId&&!await confirm(`删除 Sea vHost 托管的「${v.domain}」DNS 记录?域名绑定和网站文件保留。`,{title:'删除托管解析',danger:true}))return;await perform('dns'+v.id,()=>dns(v.id,!!v.dnsRecordId))} + return
自定义域名审核}/> + {error?

{error}

:null}
{[['all','全部'],['assigned','默认子域名'],['custom','自绑定']].map(([v,label])=>)}
共 {list.length} 个域名
{list.map(v=>)}
域名用户 / 主机类型解析备案网站 SSL操作
{v.domain}{v.siteName}{v.tenantName}{v.hostName}{v.kind==='assigned'?'默认子域名':'自绑定'}{v.dnsRecordId?`托管 ${v.dnsRecordType}`:v.resolutionMode==='cdn'?'CDN':v.resolutionMode==='cname'?'CNAME':'直接解析'}{v.dnsLastError||v.cnameTarget}{filingLabel(v.filingStatus)}{v.filingNumber}{v.status!=='approved'?'审核后配置':({active:'已启用',pending:'待签发',failed:'失败',off:'未启用'} as Record)[v.sslStatus]||v.sslStatus}{v.kind==='assigned'?随主机管理:{unbind?:null}{v.status==='pending'?<>:v.status==='approved'?:审核未通过}}
{!list.length?

暂无域名

:null}
+ {editing?setEditing(undefined)} onSave={async input=>{await metadata(editing.id,input);setEditing(undefined)}}/>:null}{removing&&unbind?setRemoving(undefined)} onUnbind={()=>unbind(removing)}/>:null}{confirmation}
; +} +export function DomainPolicyForm({domain,onClose,onSave}:{domain:DomainResource;onClose:()=>void;onSave:(input:Record)=>Promise}){ + const [mode,setMode]=useState(domain.resolutionMode||'cname'),[target,setTarget]=useState(domain.cnameTarget||''),[filing,setFiling]=useState(domain.filingStatus||'exempt'),[number,setNumber]=useState(domain.filingNumber||''),[note,setNote]=useState(domain.filingNote||''),[busy,setBusy]=useState(false),[error,setError]=useState(''); + return
{e.preventDefault();if(busy)return;setBusy(true);setError('');try{await onSave({resolutionMode:mode,cnameTarget:mode==='direct'?'':target,filingStatus:filing,filingNumber:number,filingNote:note})}catch(e){setError(e instanceof Error?e.message:'域名配置保存失败')}finally{setBusy(false)}}}>

域名配置

{domain.domain}

{mode!=='direct'?:null}