From 56b2cd6969532328d01c16936d208df91e1e38c6 Mon Sep 17 00:00:00 2001 From: Keegan Bozde <112920194+azzliang6@users.noreply.github.com> Date: Fri, 11 Sep 2026 07:02:55 +0000 Subject: [PATCH 1/3] Harden credential storage and SSH connection lifecycle --- .dockerignore | 10 + .gitignore | 1 + CLAUDE.md | 39 +-- Dockerfile | 20 +- Makefile | 25 +- README.md | 92 +++++-- README_CN.md | 93 +++++-- go.mod | 16 +- go.sum | 15 +- internal/api/auth_handler.go | 59 +++-- internal/api/connection.go | 85 ++++++ internal/api/connection_db_test.go | 67 +++++ internal/api/connection_test.go | 61 +++++ internal/api/rate_limit.go | 45 ++++ internal/api/router.go | 108 ++++---- internal/api/security_test.go | 110 ++++++++ internal/api/server_handler.go | 293 ++++++++------------- internal/api/sftp_handler.go | 121 +++++---- internal/api/sftp_handler_test.go | 65 +++++ internal/api/terminal_handler.go | 326 +++++++++++------------- internal/api/terminal_handler_test.go | 158 ++++++++++++ internal/auth/auth.go | 2 +- internal/auth/auth_test.go | 54 ++++ internal/config/config.go | 107 ++++++-- internal/config/config_test.go | 98 +++++++ internal/crypto/encryption.go | 6 +- internal/crypto/encryption_test.go | 37 +++ internal/database/credentials.go | 70 +++++ internal/database/database.go | 25 +- internal/database/database_test.go | 130 ++++++++++ internal/database/migrations.go | 83 +++++- internal/models/models_test.go | 77 ++++++ internal/models/server.go | 69 +++-- internal/models/user.go | 22 ++ internal/sftpclient/client.go | 157 +++++++----- internal/sftpclient/client_test.go | 206 +++++++++++++++ internal/sftpclient/context_test.go | 46 ++++ internal/sftpclient/permissions_test.go | 44 ++++ internal/sftpclient/upload_test.go | 100 ++++++++ internal/sshclient/client.go | 212 +++++++++------ internal/sshclient/client_test.go | 287 +++++++++++++++++++++ internal/sshclient/session.go | 102 ++++---- internal/sshclient/session_test.go | 60 +++++ internal/terminal/manager.go | 50 ++-- main.go | 62 ++++- 45 files changed, 3027 insertions(+), 888 deletions(-) create mode 100644 .dockerignore create mode 100644 internal/api/connection.go create mode 100644 internal/api/connection_db_test.go create mode 100644 internal/api/connection_test.go create mode 100644 internal/api/rate_limit.go create mode 100644 internal/api/security_test.go create mode 100644 internal/api/sftp_handler_test.go create mode 100644 internal/api/terminal_handler_test.go create mode 100644 internal/auth/auth_test.go create mode 100644 internal/config/config_test.go create mode 100644 internal/crypto/encryption_test.go create mode 100644 internal/database/credentials.go create mode 100644 internal/database/database_test.go create mode 100644 internal/models/models_test.go create mode 100644 internal/sftpclient/client_test.go create mode 100644 internal/sftpclient/context_test.go create mode 100644 internal/sftpclient/permissions_test.go create mode 100644 internal/sftpclient/upload_test.go create mode 100644 internal/sshclient/client_test.go create mode 100644 internal/sshclient/session_test.go diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e2e5626 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +.github +ui/node_modules +ui/dist +*.db +*.db-wal +*.db-shm +*.secrets.json +opsup +opsup-arm64 diff --git a/.gitignore b/.gitignore index 9d0f7e6..23b3f15 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ opsup-arm64 *.db *.db-shm *.db-wal +*.secrets.json # Frontend ui/node_modules/ diff --git a/CLAUDE.md b/CLAUDE.md index c633e28..cede1fd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,28 +33,28 @@ CGO is required because of `mattn/go-sqlite3`. Frontend must be built first — ## Architecture -**Startup flow** (main.go): `config.Load()` → `database.Init()` → `api.SetupRouter()` → `router.Run()` +**Startup flow** (main.go): load persistent configuration → versioned SQLite migrations → validate/upgrade credential encryption → HTTP server with request cancellation and graceful shutdown. **Backend** (internal/): -- `config/` — Environment variable config (DB path, JWT secret, encryption key, listen address) -- `database/` — SQLite init with WAL mode, auto-migrations in `migrations.go` +- `config/` — Environment overrides and persistent random secrets +- `database/` — SQLite WAL, transactional schema migrations and legacy credential upgrade - `models/` — User and Server CRUD (parameterized queries) - `auth/` — JWT sign/verify + bcrypt hashing + Gin middleware -- `crypto/` — AES-256-GCM encrypt/decrypt for private key storage -- `sshclient/` — SSH dial (direct + jump host via `DialViaJump`) and PTY session -- `terminal/` — In-memory registry of active terminal sessions (sync.Mutex) -- `api/` — Gin router with handlers: auth, server CRUD, WebSocket terminal, SFTP +- `crypto/` — AES-256-GCM credential storage +- `sshclient/` — Pinned SSH identities, context-bound direct/jump connections and PTY sessions +- `terminal/` — Registry helper; handlers currently own their connections directly +- `api/` — Authentication, server CRUD, bounded WebSocket terminals and atomic SFTP uploads -**Frontend** (ui/): React 19 + Ant Design 6 + xterm.js 6. Key pages: LoginPage, SetupPage, MainPage (server sidebar + terminal tabs). +**Frontend** (ui/): React 19 + Ant Design 6 + xterm.js 6. MainPage, terminals and dialogs are lazy-loaded; inactive terminal tabs stay mounted. -**WebSocket terminal protocol**: Binary frames, first byte is message type (0x00=data, 0x01=resize, 0x02=error, 0x03=status, 0x04=connected). JWT auth via query param. +**WebSocket terminal protocol**: Binary frames, first byte is message type (0x00=data, 0x01=resize, 0x02=error, 0x03=status, 0x04=connected). JWT auth via query param. Messages are limited to 64 KiB; frontend stdin payloads are chunked to 16 KiB. ## Key Design Decisions -- Private keys never reach the browser — key reuse (`copy_key_from`) copies encrypted data server-side -- Server jump chains use self-referential `jump_server_id` foreign key +- Credential reuse (`copy_key_from`) copies encrypted data server-side; API responses omit all credentials +- One direct jump host is supported via `jump_server_id`; nested jump chains are rejected - Frontend embedded as `//go:embed ui/dist` for single-binary deployment -- SQLite with WAL mode for concurrent read/write +- SQLite uses WAL and a single pooled connection with a busy timeout ## Deploy to Target Device @@ -75,7 +75,16 @@ Service restart: `ssh root@192.168.100.1 "/etc/init.d/opsup restart"` | Variable | Default | Description | |----------|---------|-------------| -| `OPSUP_DB_PATH` | `./opsup.db` | SQLite database path | -| `OPSUP_JWT_SECRET` | random | JWT signing secret | -| `OPSUP_ENCRYPTION_KEY` | random | 64-char hex for AES-256-GCM | +| `OPSUP_DB_PATH` | executable directory/opsup.db | SQLite database path | +| `OPSUP_JWT_SECRET` | persisted random | At least 32 bytes when overridden | +| `OPSUP_ENCRYPTION_KEY` | persisted random | 64-char hex for AES-256-GCM; preserve custom keys during upgrades | +| `OPSUP_SECRETS_PATH` | .secrets.json | Auto-created 0600 key file; back up with the database | | `OPSUP_LISTEN` | `:8080` | HTTP listen address | + +## Safety and verification + +- Read README_CN.md or README.md before upgrading data. Old default-key credentials are transactionally re-encrypted on startup; custom encryption keys must stay unchanged. +- SSH endpoints require independently verified SHA256 host fingerprints, including jump hosts. Never bypass host-key verification to make a connection work. +- `make clean` preserves data. `make reset-data` is explicitly destructive and requires `CONFIRM=DELETE` and `DB_PATH`. +- Run `make test` for frontend typecheck/build/tests plus Go vet/race tests. Build the frontend before testing the root Go package because of `go:embed`. +- Login and setup are rate-limited; initialize privately before enabling public HTTPS access. Proxy logs must redact WebSocket query tokens. diff --git a/Dockerfile b/Dockerfile index 830b569..d0bcc4f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,39 +1,27 @@ -# ---- 构建阶段 ---- -FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend - +FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend WORKDIR /build/ui COPY ui/package.json ui/package-lock.json ./ RUN npm ci COPY ui/ ./ RUN npm run build -FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS backend - -ARG TARGETPLATFORM +FROM golang:1.25-alpine AS backend RUN apk add --no-cache gcc musl-dev - WORKDIR /build COPY go.mod go.sum ./ RUN go mod download COPY main.go . COPY internal/ internal/ COPY --from=frontend /build/ui/dist/ ui/dist/ +RUN CGO_ENABLED=1 go build -trimpath -ldflags="-s -w" -o opsup . -RUN CGO_ENABLED=1 go build -ldflags="-s -w" -o opsup . - -# ---- 运行阶段 ---- FROM alpine:3.21 - RUN apk add --no-cache ca-certificates tzdata - WORKDIR /app COPY --from=backend /build/opsup . - VOLUME /data - ENV OPSUP_DB_PATH=/data/opsup.db ENV OPSUP_LISTEN=:8080 - +ENV GIN_MODE=release EXPOSE 8080 - ENTRYPOINT ["./opsup"] diff --git a/Makefile b/Makefile index caceb4f..f448e3e 100644 --- a/Makefile +++ b/Makefile @@ -1,20 +1,27 @@ -.PHONY: init tidy build build-frontend dev clean +.PHONY: init tidy build build-frontend dev test clean reset-data -init: - go mod tidy - -tidy: +init tidy: go mod tidy build-frontend: - cd ui && npm install && npm run build + cd ui && npm ci && npm run build build: build-frontend - CGO_ENABLED=1 go build -o opsup . + CGO_ENABLED=1 go build -trimpath -o opsup . dev: - go run main.go + OPSUP_DB_PATH="$${OPSUP_DB_PATH:-$(CURDIR)/dev-data/opsup.db}" go run . + +test: build-frontend + go vet ./... + go test -race ./... + cd ui && npm test clean: - rm -f opsup opsup.db + rm -f opsup opsup-arm64 rm -rf ui/dist ui/node_modules + +reset-data: + @test "$(CONFIRM)" = "DELETE" || (printf '%s\n' 'Destructive: stop OpsUp, back up your data, then run make reset-data CONFIRM=DELETE DB_PATH=/path/to/opsup.db'; exit 1) + @test -n "$(DB_PATH)" || (printf '%s\n' 'DB_PATH is required'; exit 1) + rm -f -- "$(DB_PATH)" "$(DB_PATH)-wal" "$(DB_PATH)-shm" diff --git a/README.md b/README.md index 1bbc60d..a576b32 100644 --- a/README.md +++ b/README.md @@ -138,39 +138,89 @@ Binary frames, first byte is message type: ## Quick Start +Requires Go 1.25+, a C compiler for SQLite/CGO, make, and Node.js 22.22.2+ (or 24.15+). + ```bash -# Build (frontend + backend) make build +# Initialize the administrator locally before exposing the service through HTTPS. +OPSUP_LISTEN=127.0.0.1:8080 OPSUP_DB_PATH=./data/opsup.db ./opsup +``` -# Run (default port 8080) -./opsup - -# Custom configuration -OPSUP_LISTEN=:9090 \ -OPSUP_JWT_SECRET=your-secret \ -OPSUP_ENCRYPTION_KEY=0123456789abcdef...(64-char hex) \ -./opsup +For development, run `make build-frontend` first, then run these in separate terminals: -# Development mode (run separately) -cd ui && npm run dev # Frontend at localhost:5173 -go run main.go # Backend at localhost:8080 +```bash +cd ui && npm run dev +# From the repository root; keep data outside go run's temporary executable directory. +OPSUP_DB_PATH="$PWD/dev-data/opsup.db" go run . ``` -### Docker +Vite proxies both HTTP and WebSocket requests under `/api`. + +### Configuration and backups + +| Variable | Default / requirement | +|---|---| +| `OPSUP_DB_PATH` | `opsup.db` next to the executable | +| `OPSUP_LISTEN` | `:8080` | +| `OPSUP_SECRETS_PATH` | `.secrets.json`, generated once with mode `0600` | +| `OPSUP_JWT_SECRET` | Persistent random secret when unset; overrides require at least 32 bytes and must not use the old default | +| `OPSUP_ENCRYPTION_KEY` | Persistent random key when unset; overrides require 64 hexadecimal characters | + +**Back up the database and its encryption key together.** Never regenerate or delete the key on restart. Environment-provided keys must remain stable in your deployment's secret manager. Keep secret files out of Git. No secret file is created when both keys are supplied through the environment. + +Docker's `/data` volume persists both the default database and secret file: ```bash docker build -t opsup . -docker run -d -p 8080:8080 -v opsup-data:/data opsup +docker run -d -p 127.0.0.1:8080:8080 -v opsup-data:/data opsup ``` -## Security +### Upgrading existing installations + +1. Stop the old service and back up the database (including any remaining WAL files) and any custom encryption key. +2. If you previously configured a custom `OPSUP_ENCRYPTION_KEY`, continue supplying that exact key. +3. If you used the old public default key, remove any explicit old-default setting. Startup generates a persistent random key and transactionally re-encrypts legacy credentials. +4. If any credential cannot be decrypted, startup stops without partially changing credentials. Restore the original key and retry; do not delete data or the secret file. +5. The default JWT key changes, requiring login again. Enroll trusted SSH fingerprints for each target and jump server before connecting. + +### SSH host fingerprints + +Enter the expected `SHA256:…` host fingerprint in the server form. Verify it through a trusted console, for example: + +```bash +for key in /etc/ssh/ssh_host_*_key.pub; do + ssh-keygen -lf "$key" +done +``` + +Connections without an enrolled fingerprint are rejected and report the observed fingerprint for comparison. **Do not trust that observation without independent verification.** Changed keys are rejected too; update the saved fingerprint only after confirming a legitimate rotation. Targets and jump hosts are checked independently. + +### SFTP uploads and connection limits + +- One direct jump host is supported; nested jump chains are rejected. +- Upload request bodies are capped at 256 MiB, including multipart overhead. Each SFTP operation has a fifteen-minute limit. +- Uploads write private temporary files before publishing. Replacing a regular file preserves permissions and UID/GID; metadata failures abort replacement. New files use `0600`; symlinks are not overwritten. +- Servers without POSIX rename support accept new files only, not overwrites. Transport loss may leave `.opsup-upload-*` files; remove them only after confirming no upload is active. + +## Verification and maintenance + +```bash +make test # Frontend typecheck/build/tests and Go vet/race tests +make clean # Build/dependency cleanup only; preserves data and secrets +# Destructive: stop the service and back up data first. +make reset-data CONFIRM=DELETE DB_PATH=/absolute/path/to/opsup.db +``` + +GitHub Actions verifies tests, Go formatting, types, binary builds, and Docker builds. + +## Security boundaries -- **Encrypted private key storage**: AES-256-GCM, key loaded from environment variable -- **Password hashing**: bcrypt -- **JWT authentication**: 24-hour expiry, WebSocket auth via query param -- **SQL injection prevention**: Parameterized queries throughout -- **WebSocket concurrency safety**: Write operations serialized via sync.Mutex -- **No client-side key exposure**: Key reuse copies encrypted data server-side, never sent to the browser +- SSH private keys and passwords use AES-256-GCM storage. APIs return neither credentials nor their ciphertext. Administrator passwords use bcrypt. +- New administrator passwords require at least 12 characters and at most 72 UTF-8 bytes. First-user creation is atomic under concurrent requests. +- Login and setup are rate-limited by source IP. Forwarded IP headers are not trusted by default, so clients behind a reverse proxy share its quota. +- JWTs expire after 24 hours. WebSocket authentication still uses a query parameter. Application access logs omit query strings; **configure reverse-proxy logs to redact tokens or omit full terminal request URLs too**. +- The application is same-origin, without wildcard CORS. Use HTTPS and never expose an uninitialized installation to the public internet. +- This remains a shared-administrator server manager, not a multi-tenant authorization system. SFTP access is limited by the remote SSH account's permissions. ## License diff --git a/README_CN.md b/README_CN.md index 904474c..2e39a69 100644 --- a/README_CN.md +++ b/README_CN.md @@ -138,29 +138,86 @@ sessions (id, user_id, server_id, started_at, ended_at, client_ip) ## 快速开始 +需要 Go 1.25+、C 编译器(SQLite 使用 CGO)、make 和 Node.js 22.22.2+(或 24.15+)。 + ```bash -# 构建 make build +# 先在受信任网络或本机完成管理员初始化,再通过 HTTPS 反向代理开放访问 +OPSUP_LISTEN=127.0.0.1:8080 OPSUP_DB_PATH=./data/opsup.db ./opsup +``` + +开发时先运行 `make build-frontend`,然后在两个终端分别运行: + +```bash +cd ui && npm run dev +# 在项目根目录;显式指定数据库,避免 go run 的临时可执行文件目录 +OPSUP_DB_PATH="$PWD/dev-data/opsup.db" go run . +``` + +Vite 的 `/api` 代理同时支持 HTTP 和 WebSocket。 -# 运行(默认端口 8080) -./opsup +### 配置与备份 -# 自定义配置 -OPSUP_LISTEN=:9090 \ -OPSUP_JWT_SECRET=your-secret \ -OPSUP_ENCRYPTION_KEY=0123456789abcdef...(64位hex) \ -./opsup +| 变量 | 默认值 / 要求 | +|---|---| +| `OPSUP_DB_PATH` | 可执行文件旁的 `opsup.db` | +| `OPSUP_LISTEN` | `:8080` | +| `OPSUP_SECRETS_PATH` | `<数据库路径>.secrets.json`,自动生成并以 `0600` 权限保存 | +| `OPSUP_JWT_SECRET` | 不设置则使用持久化的随机密钥;自定义值至少 32 字节,不得使用旧默认值 | +| `OPSUP_ENCRYPTION_KEY` | 不设置则使用持久化的随机密钥;自定义值必须是 64 位十六进制 | -# 开发模式(前后端分别启动) -cd ui && npm run dev # 前端 localhost:5173 -go run main.go # 后端 localhost:8080 +**数据库与加密密钥必须一起备份。** 不要删除或每次启动重新生成密钥。通过环境变量配置的密钥应由部署系统持久保存;不要把密钥文件提交到 Git。两项密钥都由环境变量指定时,不会创建密钥文件。 + +Docker 的 `/data` 卷会同时保存默认数据库与密钥文件: + +```bash +docker build -t opsup . +docker run -d -p 127.0.0.1:8080:8080 -v opsup-data:/data opsup ``` -## 安全设计 +### 从旧版本升级 + +1. 停止旧服务,备份数据库(包括仍存在的 WAL 文件)和原有自定义加密密钥。 +2. 原来使用自定义 `OPSUP_ENCRYPTION_KEY` 的部署必须继续提供同一个值。 +3. 原来未配置密钥、使用旧公开默认值的部署,移除显式的旧默认值配置。新版本首次启动生成持久化随机密钥,并在事务中重新加密旧凭据。 +4. 任何凭据无法解密时,升级会终止,不会部分改写凭据。恢复原始密钥后重试,不要删除数据库或密钥文件。 +5. 默认 JWT 密钥会改变,需要重新登录;为每台服务器和跳板机配置可信主机指纹后才能连接。 + +### SSH 主机指纹 + +在服务器编辑表单中填入 `SHA256:…` 主机指纹。请通过可信控制台核对,例如: + +```bash +for key in /etc/ssh/ssh_host_*_key.pub; do + ssh-keygen -lf "$key" +done +``` + +首次连接未配置指纹时会拒绝连接,并显示观察到的指纹供核对。**不要仅凭失败提示就信任该指纹**。主机密钥变更也会拒绝连接,确认是合法更换后再更新配置。跳板机和目标机分别验证。 + +### SFTP 上传与连接限制 + +- 支持一个直连跳板机,不支持嵌套跳板链。 +- 上传请求体上限 256 MiB(包含 multipart 开销),单次 SFTP 操作上限 15 分钟。 +- 上传先写私有临时文件,再发布;覆盖现有普通文件时保留权限及 UID/GID,不能安全保留元数据时失败而不覆盖。新文件权限为 `0600`,不覆盖符号链接。 +- 不支持 POSIX rename 扩展的服务器只允许上传新文件,拒绝覆盖。连接中断时远端可能残留 `.opsup-upload-*` 临时文件,确认没有进行中的上传后可清理。 + +## 验证与维护 + +```bash +make test # 前端类型检查、构建、测试;Go vet 与 race 测试 +make clean # 只清理构建产物和前端依赖,不删除数据库或密钥 +# 确认已停止服务并备份后,才执行显式的数据重置 +make reset-data CONFIRM=DELETE DB_PATH=/absolute/path/to/opsup.db +``` + +GitHub Actions 检查前后端测试、Go 格式、类型、构建及 Docker 构建。 + +## 安全边界 -- **私钥加密存储**:AES-256-GCM,密钥从环境变量加载 -- **密码哈希**:bcrypt -- **JWT 认证**:24 小时过期,WebSocket 通过 query param 认证 -- **SQL 注入防护**:全程参数化查询 -- **WebSocket 并发安全**:写操作通过 sync.Mutex 序列化 -- **前端不暴露私钥**:密钥复用在后端直接拷贝加密数据,不经浏览器 +- 私钥与 SSH 密码使用 AES-256-GCM 存储,API 不返回凭据或凭据密文;管理员登录密码使用 bcrypt。 +- 新管理员密码至少 12 个字符,最多 72 个 UTF-8 字节。初始化采用原子写入,防止并发创建多个首位管理员。 +- 登录与初始化按来源 IP 限流。默认不信任代理传入的来源 IP 头;代理后面的客户端会共享该代理 IP 的额度。 +- JWT 有效期 24 小时。WebSocket 仍通过查询参数认证,应用访问日志不记录查询参数;**反向代理也必须过滤 token,或不要记录终端请求的完整 URL**。 +- 应用按同源方式使用,不开放通配 CORS。请使用 HTTPS,不要把尚未初始化的实例直接暴露到公网。 +- 当前仍是共享管理员的服务器管理工具,不提供多租户隔离;SFTP 可访问范围由远端 SSH 账号权限决定。 diff --git a/go.mod b/go.mod index fd3cce7..cd7bf9d 100644 --- a/go.mod +++ b/go.mod @@ -2,39 +2,41 @@ module github.com/azzliang6/opsup go 1.25.0 +require ( + github.com/gin-gonic/gin v1.12.0 + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/gorilla/websocket v1.5.3 + github.com/mattn/go-sqlite3 v1.14.42 + github.com/pkg/sftp v1.13.10 + golang.org/x/crypto v0.50.0 +) + require ( github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/gabriel-vasile/mimetype v1.4.12 // indirect - github.com/gin-contrib/cors v1.7.7 // indirect github.com/gin-contrib/sse v1.1.0 // indirect - github.com/gin-gonic/gin v1.12.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.30.1 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect - github.com/golang-jwt/jwt/v5 v5.3.1 // indirect - github.com/gorilla/websocket v1.5.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/kr/fs v0.1.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-sqlite3 v1.14.42 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect - github.com/pkg/sftp v1.13.10 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect golang.org/x/arch v0.23.0 // indirect - golang.org/x/crypto v0.50.0 // indirect golang.org/x/net v0.52.0 // indirect golang.org/x/sys v0.43.0 // indirect golang.org/x/text v0.36.0 // indirect diff --git a/go.sum b/go.sum index 71a7212..031bc07 100644 --- a/go.sum +++ b/go.sum @@ -7,15 +7,16 @@ github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCc github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= -github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q= -github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= @@ -28,6 +29,8 @@ github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -52,6 +55,7 @@ github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0 github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU= github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= @@ -66,12 +70,16 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg= golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= @@ -81,10 +89,13 @@ golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY= +golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY= golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/api/auth_handler.go b/internal/api/auth_handler.go index 046805e..c138e3f 100644 --- a/internal/api/auth_handler.go +++ b/internal/api/auth_handler.go @@ -1,11 +1,12 @@ package api import ( + "errors" "net/http" - "github.com/gin-gonic/gin" "github.com/azzliang6/opsup/internal/auth" "github.com/azzliang6/opsup/internal/models" + "github.com/gin-gonic/gin" ) type loginRequest struct { @@ -14,57 +15,57 @@ type loginRequest struct { } type setupRequest struct { - Username string `json:"username" binding:"required,min=3"` - Password string `json:"password" binding:"required,min=6"` + Username string `json:"username" binding:"required,min=3,max=64"` + Password string `json:"password" binding:"required,min=12"` } -// AuthStatus checks if the system has been initialized. func AuthStatus(c *gin.Context) { count, err := models.CountUsers(getDB(c)) if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read initialization status"}) return } c.JSON(http.StatusOK, gin.H{"initialized": count > 0}) } -// AuthSetup creates the first admin user. func AuthSetup(jwtSecret string) gin.HandlerFunc { return func(c *gin.Context) { - count, _ := models.CountUsers(getDB(c)) + count, err := models.CountUsers(getDB(c)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read initialization status"}) + return + } if count > 0 { c.JSON(http.StatusForbidden, gin.H{"error": "already initialized"}) return } - var req setupRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - + if len(req.Password) > 72 { + c.JSON(http.StatusBadRequest, gin.H{"error": "password must not exceed 72 UTF-8 bytes"}) + return + } hash, err := auth.HashPassword(req.Password) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to hash password"}) return } - - user, err := models.CreateUser(getDB(c), req.Username, hash) + user, err := models.CreateFirstUser(getDB(c), req.Username, hash) + if errors.Is(err, models.ErrAlreadyInitialized) { + c.JSON(http.StatusForbidden, gin.H{"error": "already initialized"}) + return + } if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create administrator"}) return } - - token, expiresAt, _ := auth.GenerateToken(user.ID, user.Username, jwtSecret) - c.JSON(http.StatusOK, gin.H{ - "token": token, - "expires_at": expiresAt, - "username": user.Username, - }) + respondWithToken(c, user, jwtSecret) } } -// AuthLogin authenticates a user. func AuthLogin(jwtSecret string) gin.HandlerFunc { return func(c *gin.Context) { var req loginRequest @@ -72,22 +73,24 @@ func AuthLogin(jwtSecret string) gin.HandlerFunc { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - user, err := models.GetUserByUsername(getDB(c), req.Username) if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to authenticate"}) return } if user == nil || !auth.CheckPassword(req.Password, user.Password) { c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"}) return } + respondWithToken(c, user, jwtSecret) + } +} - token, expiresAt, _ := auth.GenerateToken(user.ID, user.Username, jwtSecret) - c.JSON(http.StatusOK, gin.H{ - "token": token, - "expires_at": expiresAt, - "username": user.Username, - }) +func respondWithToken(c *gin.Context, user *models.User, secret string) { + token, expiresAt, err := auth.GenerateToken(user.ID, user.Username, secret) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create session"}) + return } + c.JSON(http.StatusOK, gin.H{"token": token, "expires_at": expiresAt, "username": user.Username}) } diff --git a/internal/api/connection.go b/internal/api/connection.go new file mode 100644 index 0000000..23e8df1 --- /dev/null +++ b/internal/api/connection.go @@ -0,0 +1,85 @@ +package api + +import ( + "context" + "database/sql" + "fmt" + + "github.com/azzliang6/opsup/internal/crypto" + "github.com/azzliang6/opsup/internal/models" + "github.com/azzliang6/opsup/internal/sshclient" +) + +// loadConnectionServer reads only connection fields and can be interrupted +// while waiting for a database connection or executing the query. +func loadConnectionServer(ctx context.Context, db *sql.DB, id int64) (*models.Server, error) { + var server models.Server + err := db.QueryRowContext(ctx, + `SELECT id, host, port, username, auth_type, host_key, private_key, password, jump_server_id FROM servers WHERE id = ?`, id, + ).Scan(&server.ID, &server.Host, &server.Port, &server.Username, &server.AuthType, &server.HostKey, &server.PrivateKey, &server.Password, &server.JumpServerID) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return &server, nil +} + +func connectionConfig(server *models.Server, encKey string) (sshclient.Config, error) { + cfg := sshclient.Config{Host: server.Host, Port: server.Port, Username: server.Username, AuthType: server.AuthType, HostKey: server.HostKey} + var err error + if server.PrivateKey != "" { + cfg.PrivateKey, err = crypto.Decrypt(server.PrivateKey, encKey) + if err != nil { + return cfg, fmt.Errorf("server %d: decrypt private key: %w", server.ID, err) + } + } + if server.Password != "" { + password, err := crypto.Decrypt(server.Password, encKey) + if err != nil { + return cfg, fmt.Errorf("server %d: decrypt password: %w", server.ID, err) + } + cfg.Password = string(password) + } + return cfg, nil +} + +// dialServer owns all transports until Close or cancellation of ctx. A jump +// record must be direct: silently ignoring additional hops would bypass pins. +func dialServer(ctx context.Context, db *sql.DB, server *models.Server, encKey string) (*sshclient.Client, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if server == nil { + return nil, fmt.Errorf("server not found") + } + target, err := connectionConfig(server, encKey) + if err != nil { + return nil, err + } + if server.JumpServerID == nil || *server.JumpServerID == 0 { + return sshclient.Dial(ctx, target) + } + if *server.JumpServerID == server.ID { + return nil, fmt.Errorf("server cannot jump through itself") + } + jump, err := loadConnectionServer(ctx, db, *server.JumpServerID) + if err != nil { + return nil, fmt.Errorf("load jump server: %w", err) + } + if jump == nil { + return nil, fmt.Errorf("jump server not found") + } + if jump.JumpServerID != nil && *jump.JumpServerID != 0 { + return nil, fmt.Errorf("only one jump host is supported") + } + jumpConfig, err := connectionConfig(jump, encKey) + if err != nil { + return nil, fmt.Errorf("jump host: %w", err) + } + if err := ctx.Err(); err != nil { + return nil, err + } + return sshclient.DialViaJump(ctx, jumpConfig, target) +} diff --git a/internal/api/connection_db_test.go b/internal/api/connection_db_test.go new file mode 100644 index 0000000..a3ade6a --- /dev/null +++ b/internal/api/connection_db_test.go @@ -0,0 +1,67 @@ +package api + +import ( + "context" + "database/sql" + "errors" + "strings" + "testing" + "time" + + "github.com/azzliang6/opsup/internal/models" + _ "github.com/mattn/go-sqlite3" +) + +func connectionTestDB(t *testing.T) *sql.DB { + t.Helper() + db, err := sql.Open("sqlite3", ":memory:") + if err != nil { + t.Fatal(err) + } + db.SetMaxOpenConns(1) + t.Cleanup(func() { _ = db.Close() }) + _, err = db.Exec(`CREATE TABLE servers (id INTEGER PRIMARY KEY, host TEXT NOT NULL DEFAULT '127.0.0.1', port INTEGER NOT NULL DEFAULT 22, username TEXT NOT NULL DEFAULT 'test', auth_type TEXT NOT NULL DEFAULT 'password', host_key TEXT NOT NULL DEFAULT '', private_key TEXT NOT NULL DEFAULT '', password TEXT NOT NULL DEFAULT '', jump_server_id INTEGER)`) + if err != nil { + t.Fatal(err) + } + return db +} + +func TestConnectionLoadCancelsWhileWaitingForDatabase(t *testing.T) { + db := connectionTestDB(t) + held, err := db.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + defer held.Close() + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err = loadConnectionServer(ctx, db, 1) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("database wait did not honor cancellation: %v", err) + } +} + +func TestDialServerPropagatesJumpCredentialFailure(t *testing.T) { + db := connectionTestDB(t) + if _, err := db.Exec(`INSERT INTO servers(id,password) VALUES(2,'corrupt')`); err != nil { + t.Fatal(err) + } + jumpID := int64(2) + _, err := dialServer(context.Background(), db, &models.Server{ID: 1, JumpServerID: &jumpID}, strings.Repeat("ab", 32)) + if err == nil || !strings.Contains(err.Error(), "jump host: server 2: decrypt password") { + t.Fatalf("jump credential failure was swallowed: %v", err) + } +} + +func TestDialServerRejectsMultipleJumps(t *testing.T) { + db := connectionTestDB(t) + if _, err := db.Exec(`INSERT INTO servers(id,jump_server_id) VALUES(2,3)`); err != nil { + t.Fatal(err) + } + jumpID := int64(2) + _, err := dialServer(context.Background(), db, &models.Server{ID: 1, JumpServerID: &jumpID}, strings.Repeat("ab", 32)) + if err == nil || !strings.Contains(err.Error(), "only one jump") { + t.Fatalf("unsupported jump chain was ignored: %v", err) + } +} diff --git a/internal/api/connection_test.go b/internal/api/connection_test.go new file mode 100644 index 0000000..5982345 --- /dev/null +++ b/internal/api/connection_test.go @@ -0,0 +1,61 @@ +package api + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/azzliang6/opsup/internal/crypto" + "github.com/azzliang6/opsup/internal/models" +) + +func TestConnectionConfigPropagatesDecryptionFailure(t *testing.T) { + for _, field := range []string{"private key", "password"} { + t.Run(field, func(t *testing.T) { + server := &models.Server{ID: 9, AuthType: "password"} + if field == "private key" { + server.PrivateKey = "invalid" + } else { + server.Password = "invalid" + } + _, err := connectionConfig(server, strings.Repeat("ab", 32)) + if err == nil || !strings.Contains(err.Error(), "decrypt "+field) { + t.Fatalf("decryption error swallowed: %v", err) + } + }) + } +} + +func TestConnectionConfigPreservesPinAndCredentials(t *testing.T) { + key := strings.Repeat("ab", 32) + ciphertext, err := crypto.Encrypt([]byte("secret"), key) + if err != nil { + t.Fatal(err) + } + server := &models.Server{Host: "example.invalid", Port: 22, Username: "test", AuthType: "password", Password: ciphertext, HostKey: "SHA256:pin"} + cfg, err := connectionConfig(server, key) + if err != nil { + t.Fatal(err) + } + if cfg.Password != "secret" || cfg.HostKey != server.HostKey || cfg.Host != server.Host { + t.Fatal("connection config was not preserved") + } +} + +func TestDialServerHonorsAlreadyCancelledContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := dialServer(ctx, nil, &models.Server{}, "") + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected cancellation, got %v", err) + } +} + +func TestDialServerRejectsSelfJump(t *testing.T) { + id := int64(9) + _, err := dialServer(context.Background(), nil, &models.Server{ID: id, JumpServerID: &id}, strings.Repeat("ab", 32)) + if err == nil || !strings.Contains(err.Error(), "itself") { + t.Fatalf("self-jump accepted: %v", err) + } +} diff --git a/internal/api/rate_limit.go b/internal/api/rate_limit.go new file mode 100644 index 0000000..07e6b84 --- /dev/null +++ b/internal/api/rate_limit.go @@ -0,0 +1,45 @@ +package api + +import ( + "net/http" + "strconv" + "sync" + "time" + + "github.com/gin-gonic/gin" +) + +func authRateLimit(limit int, window time.Duration) gin.HandlerFunc { + type bucket struct { + until time.Time + count int + } + var mu sync.Mutex + clients := make(map[string]bucket) + return func(c *gin.Context) { + now := time.Now() + ip := c.ClientIP() + mu.Lock() + for key, value := range clients { + if !now.Before(value.until) { + delete(clients, key) + } + } + value, exists := clients[ip] + if !exists { + value.until = now.Add(window) + } + blocked := value.count >= limit || (!exists && len(clients) >= 4096) + if !blocked { + value.count++ + clients[ip] = value + } + mu.Unlock() + if blocked { + c.Header("Retry-After", strconv.Itoa(max(1, int(time.Until(value.until).Seconds())+1))) + c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "too many authentication attempts; try again later"}) + return + } + c.Next() + } +} diff --git a/internal/api/router.go b/internal/api/router.go index f492c22..b168951 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -3,12 +3,16 @@ package api import ( "database/sql" "embed" + "fmt" + "io" "io/fs" + "log" "net/http" + "strings" + "time" - "github.com/gin-contrib/cors" - "github.com/gin-gonic/gin" "github.com/azzliang6/opsup/internal/auth" + "github.com/gin-gonic/gin" ) type AppConfig struct { @@ -19,88 +23,86 @@ type AppConfig struct { } func SetupRouter(cfg AppConfig) *gin.Engine { - r := gin.Default() - - // Inject DB into all contexts + r := gin.New() + r.SetTrustedProxies(nil) + r.Use(gin.LoggerWithFormatter(func(p gin.LogFormatterParams) string { + return fmt.Sprintf("%s %s %q %d %s\n", p.TimeStamp.Format(time.RFC3339), p.Method, p.Request.URL.Path, p.StatusCode, p.Latency) + })) + // Gin's default panic dump includes the request URL, which can contain a WS token. + r.Use(gin.CustomRecoveryWithWriter(io.Discard, func(c *gin.Context, recovered any) { + log.Printf("request panic: %v", recovered) + c.AbortWithStatus(http.StatusInternalServerError) + })) r.Use(func(c *gin.Context) { c.Set("db", cfg.DB) + c.Header("X-Content-Type-Options", "nosniff") + c.Header("Referrer-Policy", "no-referrer") + c.Header("X-Frame-Options", "DENY") + if strings.HasPrefix(c.Request.URL.Path, "/api/") { + c.Header("Cache-Control", "no-store") + if !strings.HasSuffix(c.Request.URL.Path, "/files/upload") { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<20) + } + } c.Next() }) - // CORS for development - r.Use(cors.New(cors.Config{ - AllowOrigins: []string{"*"}, - AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, - AllowHeaders: []string{"Authorization", "Content-Type"}, - ExposeHeaders: []string{"Content-Length"}, - AllowCredentials: true, - })) - api := r.Group("/api") { authGroup := api.Group("/auth") - { - authGroup.GET("/status", AuthStatus) - authGroup.POST("/setup", AuthSetup(cfg.JWTSecret)) - authGroup.POST("/login", AuthLogin(cfg.JWTSecret)) - } - - protected := api.Group("") - protected.Use(auth.JWTAuthMiddleware(cfg.JWTSecret)) - { - servers := protected.Group("/servers") - { - servers.GET("", ListServers) - servers.POST("", CreateServer(cfg.EncryptionKey)) - servers.GET("/:id", GetServer) - servers.PUT("/:id", UpdateServer(cfg.EncryptionKey)) - servers.DELETE("/:id", DeleteServer) - servers.POST("/:id/test", TestConnection(cfg.EncryptionKey)) + authGroup.GET("/status", AuthStatus) + limited := authGroup.Group("", authRateLimit(10, time.Minute)) + limited.POST("/setup", AuthSetup(cfg.JWTSecret)) + limited.POST("/login", AuthLogin(cfg.JWTSecret)) - // SFTP file management - files := servers.Group("/:id/files") - { - files.GET("", SFTPList(cfg.EncryptionKey)) - files.POST("/upload", SFTPUpload(cfg.EncryptionKey)) - files.GET("/download", SFTPDownload(cfg.EncryptionKey)) - files.POST("/mkdir", SFTPMkdir(cfg.EncryptionKey)) - files.DELETE("", SFTPDelete(cfg.EncryptionKey)) - } - } - } - - // Terminal WebSocket: validates JWT from query param (browsers can't set WS headers) + protected := api.Group("", auth.JWTAuthMiddleware(cfg.JWTSecret)) + servers := protected.Group("/servers") + servers.GET("", ListServers) + servers.POST("", CreateServer(cfg.EncryptionKey)) + servers.GET("/:id", GetServer) + servers.PUT("/:id", UpdateServer(cfg.EncryptionKey)) + servers.DELETE("/:id", DeleteServer) + servers.POST("/:id/test", TestConnection(cfg.EncryptionKey)) + files := servers.Group("/:id/files") + files.GET("", SFTPList(cfg.EncryptionKey)) + files.POST("/upload", SFTPUpload(cfg.EncryptionKey)) + files.GET("/download", SFTPDownload(cfg.EncryptionKey)) + files.POST("/mkdir", SFTPMkdir(cfg.EncryptionKey)) + files.DELETE("", SFTPDelete(cfg.EncryptionKey)) api.GET("/terminal/:serverId", TerminalHandler(cfg)) } - // Serve embedded SPA distFS, err := fs.Sub(cfg.DistFS, "ui/dist") if err == nil { fileServer := http.FileServer(http.FS(distFS)) r.NoRoute(func(c *gin.Context) { path := c.Request.URL.Path + if path == "/api" || strings.HasPrefix(path, "/api/") { + c.JSON(http.StatusNotFound, gin.H{"error": "not found"}) + return + } if path != "/" && fileExists(distFS, path) { + if strings.HasPrefix(path, "/assets/") { + c.Header("Cache-Control", "public, max-age=31536000, immutable") + } else { + c.Header("Cache-Control", "no-cache") + } fileServer.ServeHTTP(c.Writer, c.Request) return } + c.Header("Cache-Control", "no-cache") c.Request.URL.Path = "/" fileServer.ServeHTTP(c.Writer, c.Request) }) } - return r } func fileExists(fsys fs.FS, path string) bool { - if len(path) > 0 && path[0] == '/' { - path = path[1:] - } + path = strings.TrimPrefix(path, "/") if path == "" { return false } info, err := fs.Stat(fsys, path) - if err != nil { - return false - } - return !info.IsDir() + return err == nil && !info.IsDir() } diff --git a/internal/api/security_test.go b/internal/api/security_test.go new file mode 100644 index 0000000..ddadc2e --- /dev/null +++ b/internal/api/security_test.go @@ -0,0 +1,110 @@ +package api + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/azzliang6/opsup/internal/auth" + "github.com/azzliang6/opsup/internal/database" + "github.com/azzliang6/opsup/internal/models" + "github.com/gin-gonic/gin" +) + +func securityRouter(t *testing.T) (*gin.Engine, AppConfig) { + t.Helper() + gin.SetMode(gin.TestMode) + db, err := database.Init(filepath.Join(t.TempDir(), "opsup.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + cfg := AppConfig{DB: db, JWTSecret: strings.Repeat("s", 32), EncryptionKey: strings.Repeat("ab", 32)} + return SetupRouter(cfg), cfg +} + +func performRequest(r http.Handler, method, path, body, token string) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + if token != "" { + request.Header.Set("Authorization", "Bearer "+token) + } + response := httptest.NewRecorder() + r.ServeHTTP(response, request) + return response +} + +func TestSetupLoginAndInitializationLock(t *testing.T) { + r, _ := securityRouter(t) + body := `{"username":"admin","password":"a-strong-test-password"}` + if response := performRequest(r, "POST", "/api/auth/setup", body, ""); response.Code != 200 { + t.Fatalf("setup: %d %s", response.Code, response.Body) + } + if response := performRequest(r, "POST", "/api/auth/setup", body, ""); response.Code != 403 { + t.Fatalf("second setup: %d", response.Code) + } + if response := performRequest(r, "POST", "/api/auth/login", body, ""); response.Code != 200 { + t.Fatalf("login: %d", response.Code) + } + if response := performRequest(r, "POST", "/api/auth/login", `{"username":"admin","password":"wrong"}`, ""); response.Code != 401 { + t.Fatalf("bad password: %d", response.Code) + } +} + +func TestAuthenticationRateLimitAndProxySpoofing(t *testing.T) { + r, _ := securityRouter(t) + for i := 0; i < 11; i++ { + request := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"username":"none","password":"wrong"}`)) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-Forwarded-For", "198.51.100."+string(rune('a'+i))) + response := httptest.NewRecorder() + r.ServeHTTP(response, request) + if i < 10 && response.Code != 401 { + t.Fatalf("attempt %d: %d", i, response.Code) + } + if i == 10 && (response.Code != 429 || response.Header().Get("Retry-After") == "") { + t.Fatalf("limiter: %d", response.Code) + } + } +} + +func TestServerResponsesAndHostKeyValidation(t *testing.T) { + r, cfg := securityRouter(t) + token, _, err := auth.GenerateToken(1, "admin", cfg.JWTSecret) + if err != nil { + t.Fatal(err) + } + fingerprint := "SHA256:" + base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)) + payload := map[string]any{"name": "server", "host": "localhost", "username": "user", "auth_type": "password", "password": "remote-secret", "host_key": fingerprint} + encoded, _ := json.Marshal(payload) + response := performRequest(r, "POST", "/api/servers", string(encoded), token) + if response.Code != 201 { + t.Fatalf("create: %d %s", response.Code, response.Body) + } + for _, path := range []string{"/api/servers", "/api/servers/1"} { + response := performRequest(r, "GET", path, "", token) + if response.Code != 200 || strings.Contains(response.Body.String(), `"password":`) || strings.Contains(response.Body.String(), "remote-secret") { + t.Fatalf("unsafe response: %d %s", response.Code, response.Body) + } + if !strings.Contains(response.Body.String(), fingerprint) { + t.Fatal("host key missing from response") + } + } + stored, err := models.GetServer(cfg.DB, 1) + if err != nil || stored.Password == "remote-secret" || stored.Password == "" { + t.Fatalf("credential storage: %v", err) + } + payload["host_key"] = "not-a-fingerprint" + encoded, _ = json.Marshal(payload) + if response := performRequest(r, "PUT", "/api/servers/1", string(encoded), token); response.Code != 400 { + t.Fatalf("bad fingerprint: %d", response.Code) + } + if response := performRequest(r, "GET", "/api/servers", "", ""); response.Code != 401 { + t.Fatalf("unauthenticated: %d", response.Code) + } +} diff --git a/internal/api/server_handler.go b/internal/api/server_handler.go index 89a4bb2..2ebe612 100644 --- a/internal/api/server_handler.go +++ b/internal/api/server_handler.go @@ -2,14 +2,15 @@ package api import ( "database/sql" + "encoding/base64" "fmt" "net/http" "strconv" + "strings" - "github.com/gin-gonic/gin" "github.com/azzliang6/opsup/internal/crypto" "github.com/azzliang6/opsup/internal/models" - "github.com/azzliang6/opsup/internal/sshclient" + "github.com/gin-gonic/gin" ) type serverCreateReq struct { @@ -18,6 +19,7 @@ type serverCreateReq struct { Port int `json:"port"` Username string `json:"username" binding:"required"` AuthType string `json:"auth_type"` + HostKey string `json:"host_key"` PrivateKey string `json:"private_key"` Password string `json:"password"` CopyKeyFrom int64 `json:"copy_key_from"` @@ -26,6 +28,32 @@ type serverCreateReq struct { Description string `json:"description"` } +func (r *serverCreateReq) validate() error { + if r.Port == 0 { + r.Port = 22 + } + if r.Port < 1 || r.Port > 65535 { + return fmt.Errorf("port must be between 1 and 65535") + } + if r.AuthType == "" { + r.AuthType = "key" + } + if r.AuthType != "key" && r.AuthType != "password" { + return fmt.Errorf("auth_type must be key or password") + } + r.HostKey = strings.TrimSpace(r.HostKey) + if r.HostKey != "" { + decoded, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(r.HostKey, "SHA256:")) + if !strings.HasPrefix(r.HostKey, "SHA256:") || err != nil || len(decoded) != 32 { + return fmt.Errorf("host_key must be an SHA256 SSH host fingerprint") + } + } + if r.JumpServerID != nil && *r.JumpServerID <= 0 { + return fmt.Errorf("invalid jump_server_id") + } + return nil +} + func ListServers(c *gin.Context) { servers, err := models.ListServers(getDB(c)) if err != nil { @@ -54,180 +82,123 @@ func GetServer(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) return } - server.PrivateKey = "" - c.JSON(http.StatusOK, server) + c.JSON(http.StatusOK, server.ToListItem()) } -func resolveEncryptedKey(c *gin.Context, req *serverCreateReq, encKeyHex string) (string, error) { - if req.AuthType == "password" { - return "", nil - } - if req.PrivateKey != "" { - return crypto.Encrypt([]byte(req.PrivateKey), encKeyHex) +func resolveCredentials(db *sql.DB, req *serverCreateReq, current *models.Server, key string) (string, string, error) { + privateKey, password := "", "" + if current != nil { + privateKey, password = current.PrivateKey, current.Password } - if req.CopyKeyFrom > 0 { - src, err := models.GetServer(getDB(c), req.CopyKeyFrom) - if err != nil || src == nil { - return "", nil + var err error + if req.AuthType == "password" { + if req.Password != "" { + password, err = crypto.Encrypt([]byte(req.Password), key) + } + if err == nil && password == "" { + err = fmt.Errorf("password is required for password auth") + } + } else { + if req.PrivateKey != "" { + privateKey, err = crypto.Encrypt([]byte(req.PrivateKey), key) + } else if req.CopyKeyFrom > 0 { + source, queryErr := models.GetServer(db, req.CopyKeyFrom) + if queryErr != nil { + return "", "", queryErr + } + if source == nil || source.PrivateKey == "" { + return "", "", fmt.Errorf("source server has no private key") + } + privateKey = source.PrivateKey + } + if err == nil && privateKey == "" { + err = fmt.Errorf("private_key or copy_key_from is required") } - return src.PrivateKey, nil } - return "", nil + return privateKey, password, err } -func resolveEncryptedPassword(req *serverCreateReq, encKeyHex string) (string, error) { - if req.AuthType != "password" || req.Password == "" { - return "", nil - } - return crypto.Encrypt([]byte(req.Password), encKeyHex) +func CreateServer(encKey string) gin.HandlerFunc { + return saveServer(encKey, false) } -func CreateServer(encKey string) gin.HandlerFunc { +func UpdateServer(encKey string) gin.HandlerFunc { + return saveServer(encKey, true) +} + +func saveServer(encKey string, update bool) gin.HandlerFunc { return func(c *gin.Context) { var req serverCreateReq if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - - if req.Port == 0 { - req.Port = 22 - } - if req.AuthType == "" { - req.AuthType = "key" + if err := req.validate(); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return } - - var encPrivKey, encPassword string - var err error - - if req.AuthType == "password" { - if req.Password == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "password is required for password auth"}) + var current *models.Server + var id int64 + if update { + var err error + id, err = strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"}) return } - encPassword, err = resolveEncryptedPassword(&req, encKey) + current, err = models.GetServer(getDB(c), id) if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "encryption failed"}) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - } else { - encPrivKey, err = resolveEncryptedKey(c, &req, encKey) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "encryption failed"}) + if current == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) return } - if encPrivKey == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "private_key or copy_key_from is required"}) + } + if req.JumpServerID != nil { + if *req.JumpServerID == id { + c.JSON(http.StatusBadRequest, gin.H{"error": "server cannot jump through itself"}) + return + } + jump, err := models.GetServer(getDB(c), *req.JumpServerID) + if err != nil || jump == nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "jump server not found"}) return } } - - s := &models.Server{ - Name: req.Name, - Host: req.Host, - Port: req.Port, - Username: req.Username, - AuthType: req.AuthType, - PrivateKey: encPrivKey, - Password: encPassword, - Description: req.Description, - Group: req.Group, - JumpServerID: req.JumpServerID, - } - - if err := models.CreateServer(getDB(c), s); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - - c.JSON(http.StatusCreated, s.ToListItem()) - } -} - -func UpdateServer(encKey string) gin.HandlerFunc { - return func(c *gin.Context) { - id, _ := strconv.ParseInt(c.Param("id"), 10, 64) - - var req serverCreateReq - if err := c.ShouldBindJSON(&req); err != nil { + privateKey, password, err := resolveCredentials(getDB(c), &req, current, encKey) + if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - - if req.Port == 0 { - req.Port = 22 + server := &models.Server{ + ID: id, Name: req.Name, Host: req.Host, Port: req.Port, + Username: req.Username, AuthType: req.AuthType, HostKey: req.HostKey, + PrivateKey: privateKey, Password: password, Description: req.Description, + Group: req.Group, JumpServerID: req.JumpServerID, } - if req.AuthType == "" { - req.AuthType = "key" - } - - // Get current server for fallback values - current, err := models.GetServer(getDB(c), id) - if err != nil || current == nil { - c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) - return - } - - var encPrivKey, encPassword string - - if req.AuthType == "password" { - // Password auth: keep existing key, handle password - encPrivKey = current.PrivateKey - if req.Password != "" { - encPassword, err = crypto.Encrypt([]byte(req.Password), encKey) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "encryption failed"}) - return - } - } else { - encPassword = current.Password - } + status := http.StatusCreated + if update { + err = models.UpdateServer(getDB(c), server) + status = http.StatusOK } else { - // Key auth - encPassword = current.Password - if req.PrivateKey != "" { - encPrivKey, err = crypto.Encrypt([]byte(req.PrivateKey), encKey) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "encryption failed"}) - return - } - } else if req.CopyKeyFrom > 0 { - src, err := models.GetServer(getDB(c), req.CopyKeyFrom) - if err != nil || src == nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "source server not found"}) - return - } - encPrivKey = src.PrivateKey - } else { - encPrivKey = current.PrivateKey - } + err = models.CreateServer(getDB(c), server) } - - s := &models.Server{ - ID: id, - Name: req.Name, - Host: req.Host, - Port: req.Port, - Username: req.Username, - AuthType: req.AuthType, - PrivateKey: encPrivKey, - Password: encPassword, - Description: req.Description, - Group: req.Group, - JumpServerID: req.JumpServerID, - } - - if err := models.UpdateServer(getDB(c), s); err != nil { + if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, s.ToListItem()) + c.JSON(status, server.ToListItem()) } } func DeleteServer(c *gin.Context) { - id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"}) + return + } if err := models.DeleteServer(getDB(c), id); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return @@ -235,24 +206,6 @@ func DeleteServer(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "deleted"}) } -func decryptServerKey(server *models.Server, encKey string) ([]byte, error) { - if server.PrivateKey == "" { - return nil, nil - } - return crypto.Decrypt(server.PrivateKey, encKey) -} - -func decryptServerPassword(server *models.Server, encKey string) (string, error) { - if server.Password == "" { - return "", nil - } - plain, err := crypto.Decrypt(server.Password, encKey) - if err != nil { - return "", err - } - return string(plain), nil -} - func TestConnection(encKey string) gin.HandlerFunc { return func(c *gin.Context) { id, _ := strconv.ParseInt(c.Param("id"), 10, 64) @@ -261,31 +214,12 @@ func TestConnection(encKey string) gin.HandlerFunc { c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) return } - - privateKey, _ := decryptServerKey(server, encKey) - password, _ := decryptServerPassword(server, encKey) - - var testErr error - if server.JumpServerID != nil && *server.JumpServerID != 0 { - jumpServer, err := models.GetServer(getDB(c), *server.JumpServerID) - if err != nil || jumpServer == nil { - c.JSON(http.StatusOK, gin.H{"success": false, "error": "jump server not found"}) - return - } - jumpKey, _ := decryptServerKey(jumpServer, encKey) - jumpPassword, _ := decryptServerPassword(jumpServer, encKey) - testErr = sshclient.TestDialViaJump( - jumpServer.Host, jumpServer.Port, jumpServer.Username, jumpServer.AuthType, jumpKey, jumpPassword, - server.Host, server.Port, server.Username, server.AuthType, privateKey, password, - ) - } else { - testErr = sshclient.TestDial(server.Host, server.Port, server.Username, server.AuthType, privateKey, password) - } - - if testErr != nil { - c.JSON(http.StatusOK, gin.H{"success": false, "error": testErr.Error()}) + client, err := dialServer(c.Request.Context(), getDB(c), server, encKey) + if err != nil { + c.JSON(http.StatusOK, gin.H{"success": false, "error": err.Error()}) return } + client.Close() c.JSON(http.StatusOK, gin.H{"success": true}) } } @@ -293,6 +227,3 @@ func TestConnection(encKey string) gin.HandlerFunc { func getDB(c *gin.Context) *sql.DB { return c.MustGet("db").(*sql.DB) } - -// Ensure fmt import is used -var _ = fmt.Sprintf diff --git a/internal/api/sftp_handler.go b/internal/api/sftp_handler.go index 71ded59..4f11556 100644 --- a/internal/api/sftp_handler.go +++ b/internal/api/sftp_handler.go @@ -1,18 +1,18 @@ package api import ( + "context" + "errors" "fmt" - "io" + "mime" "net/http" "path" - "path/filepath" "strconv" + "strings" "time" - "github.com/gin-gonic/gin" - "github.com/azzliang6/opsup/internal/crypto" - "github.com/azzliang6/opsup/internal/models" "github.com/azzliang6/opsup/internal/sftpclient" + "github.com/gin-gonic/gin" ) type fileInfo struct { @@ -24,48 +24,46 @@ type fileInfo struct { Path string `json:"path"` } -func connectSFTP(c *gin.Context, encKey string) (*sftpclient.Client, error) { - id, _ := strconv.ParseInt(c.Param("id"), 10, 64) - server, err := models.GetServer(getDB(c), id) - if err != nil || server == nil { - return nil, fmt.Errorf("server not found") +const maxUploadBody = 256 * 1024 * 1024 +const sftpOperationTimeout = 15 * time.Minute + +func sftpOperation(c *gin.Context) context.CancelFunc { + ctx, cancel := context.WithTimeout(c.Request.Context(), sftpOperationTimeout) + c.Request = c.Request.WithContext(ctx) + deadline, _ := ctx.Deadline() + controller := http.NewResponseController(c.Writer) + _ = controller.SetReadDeadline(deadline) + _ = controller.SetWriteDeadline(deadline) + return func() { + cancel() + _ = controller.SetReadDeadline(time.Time{}) + _ = controller.SetWriteDeadline(time.Time{}) } +} - privateKey, _ := crypto.Decrypt(server.PrivateKey, encKey) - var passwordStr string - if server.Password != "" { - pwBytes, err := crypto.Decrypt(server.Password, encKey) - if err == nil { - passwordStr = string(pwBytes) - } +func connectSFTP(c *gin.Context, encKey string) (*sftpclient.Client, error) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + return nil, fmt.Errorf("invalid server id") } - - if server.JumpServerID != nil && *server.JumpServerID != 0 { - jumpServer, err := models.GetServer(getDB(c), *server.JumpServerID) - if err != nil || jumpServer == nil { - return nil, fmt.Errorf("jump server not found") - } - jumpKey, _ := crypto.Decrypt(jumpServer.PrivateKey, encKey) - var jumpPassword string - if jumpServer.Password != "" { - jpBytes, err := crypto.Decrypt(jumpServer.Password, encKey) - if err == nil { - jumpPassword = string(jpBytes) - } - } - return sftpclient.NewSFTPClientViaJump( - jumpServer.Host, jumpServer.Port, jumpServer.Username, jumpServer.AuthType, jumpKey, jumpPassword, - server.Host, server.Port, server.Username, server.AuthType, privateKey, passwordStr, - ) + server, err := loadConnectionServer(c.Request.Context(), getDB(c), id) + if err != nil { + return nil, fmt.Errorf("load server: %w", err) } - - return sftpclient.NewSFTPClient( - server.Host, server.Port, server.Username, server.AuthType, privateKey, passwordStr, - ) + if server == nil { + return nil, fmt.Errorf("server not found") + } + owner, err := dialServer(c.Request.Context(), getDB(c), server, encKey) + if err != nil { + return nil, err + } + return sftpclient.NewClient(c.Request.Context(), owner) } func SFTPList(encKey string) gin.HandlerFunc { return func(c *gin.Context) { + cancel := sftpOperation(c) + defer cancel() dirPath := c.Query("path") if dirPath == "" { dirPath = "/" @@ -102,17 +100,37 @@ func SFTPList(encKey string) gin.HandlerFunc { func SFTPUpload(encKey string) gin.HandlerFunc { return func(c *gin.Context) { - dirPath := c.PostForm("path") + cancel := sftpOperation(c) + defer cancel() + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxUploadBody) + err := c.Request.ParseMultipartForm(8 * 1024 * 1024) + if c.Request.MultipartForm != nil { + defer c.Request.MultipartForm.RemoveAll() + } + if err != nil { + status := http.StatusBadRequest + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + status = http.StatusRequestEntityTooLarge + } + c.JSON(status, gin.H{"error": "invalid upload or request exceeds 256 MiB"}) + return + } + dirPath := c.Request.FormValue("path") if dirPath == "" { dirPath = "/" } - file, header, err := c.Request.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "no file provided"}) return } defer file.Close() + filename := path.Base(strings.ReplaceAll(header.Filename, "\\", "/")) + if filename == "." || filename == "/" || filename == ".." || strings.ContainsRune(filename, 0) { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"}) + return + } client, err := connectSFTP(c, encKey) if err != nil { @@ -121,16 +139,9 @@ func SFTPUpload(encKey string) gin.HandlerFunc { } defer client.Close() - remotePath := path.Join(dirPath, header.Filename) - dst, err := client.Create(remotePath) - if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("create file: %v", err)}) - return - } - defer dst.Close() - - if _, err := io.Copy(dst, file); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("upload: %v", err)}) + remotePath := path.Join(dirPath, filename) + if err := client.Upload(remotePath, file); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } @@ -140,6 +151,8 @@ func SFTPUpload(encKey string) gin.HandlerFunc { func SFTPDownload(encKey string) gin.HandlerFunc { return func(c *gin.Context) { + cancel := sftpOperation(c) + defer cancel() filePath := c.Query("path") if filePath == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "path is required"}) @@ -166,7 +179,7 @@ func SFTPDownload(encKey string) gin.HandlerFunc { return } - c.Header("Content-Disposition", "attachment; filename="+filepath.Base(filePath)) + c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": path.Base(filePath)})) c.Header("Content-Length", strconv.FormatInt(stat.Size(), 10)) c.DataFromReader(http.StatusOK, stat.Size(), "application/octet-stream", remoteFile, nil) } @@ -174,6 +187,8 @@ func SFTPDownload(encKey string) gin.HandlerFunc { func SFTPMkdir(encKey string) gin.HandlerFunc { return func(c *gin.Context) { + cancel := sftpOperation(c) + defer cancel() var req struct { Path string `json:"path" binding:"required"` } @@ -200,6 +215,8 @@ func SFTPMkdir(encKey string) gin.HandlerFunc { func SFTPDelete(encKey string) gin.HandlerFunc { return func(c *gin.Context) { + cancel := sftpOperation(c) + defer cancel() filePath := c.Query("path") if filePath == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "path is required"}) diff --git a/internal/api/sftp_handler_test.go b/internal/api/sftp_handler_test.go new file mode 100644 index 0000000..e8ad6e0 --- /dev/null +++ b/internal/api/sftp_handler_test.go @@ -0,0 +1,65 @@ +package api + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" +) + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +func TestUploadCapsBodyBeforeMultipartParsing(t *testing.T) { + gin.SetMode(gin.TestMode) + prefix := "--upload\r\nContent-Disposition: form-data; name=\"file\"; filename=\"large.bin\"\r\nContent-Type: application/octet-stream\r\n\r\n" + body := io.MultiReader(strings.NewReader(prefix), io.LimitReader(zeroReader{}, maxUploadBody+1), strings.NewReader("\r\n--upload--\r\n")) + request := httptest.NewRequest(http.MethodPost, "/servers/1/upload", body) + request.Header.Set("Content-Type", "multipart/form-data; boundary=upload") + response := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(response) + ctx.Request = request + // No DB is installed. An oversized request must fail before connecting. + SFTPUpload("")(ctx) + if response.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("want 413, got %d: %s", response.Code, response.Body.String()) + } +} + +type deadlineWriter struct { + *httptest.ResponseRecorder + readDeadline time.Time + writeDeadline time.Time +} + +func (w *deadlineWriter) SetReadDeadline(deadline time.Time) error { + w.readDeadline = deadline + return nil +} +func (w *deadlineWriter) SetWriteDeadline(deadline time.Time) error { + w.writeDeadline = deadline + return nil +} + +func TestSFTPOperationBoundsAndRestoresHTTPDeadlines(t *testing.T) { + writer := &deadlineWriter{ResponseRecorder: httptest.NewRecorder()} + ctx, _ := gin.CreateTestContext(writer) + ctx.Request = httptest.NewRequest(http.MethodGet, "/", nil) + cancel := sftpOperation(ctx) + deadline, ok := ctx.Request.Context().Deadline() + if !ok || time.Until(deadline) > sftpOperationTimeout || writer.readDeadline != deadline || writer.writeDeadline != deadline { + t.Fatal("request and transport deadlines not installed") + } + cancel() + if ctx.Request.Context().Err() == nil || !writer.readDeadline.IsZero() || !writer.writeDeadline.IsZero() { + t.Fatal("operation cleanup did not restore deadlines") + } +} diff --git a/internal/api/terminal_handler.go b/internal/api/terminal_handler.go index b42474c..4c2946e 100644 --- a/internal/api/terminal_handler.go +++ b/internal/api/terminal_handler.go @@ -1,40 +1,37 @@ package api import ( + "context" "encoding/json" "fmt" - "log" + "io" "net/http" "strconv" "sync" "time" - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" - "golang.org/x/crypto/ssh" "github.com/azzliang6/opsup/internal/auth" - "github.com/azzliang6/opsup/internal/crypto" - "github.com/azzliang6/opsup/internal/models" "github.com/azzliang6/opsup/internal/sshclient" + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" ) const ( - msgTypeStdin = 0x00 - msgTypeResize = 0x01 - msgTypeStdout = 0x00 - msgTypeStderr = 0x01 - msgTypeError = 0x02 - msgTypeStatus = 0x03 - msgTypeConnectd = 0x04 + msgTypeStdin = 0x00 + msgTypeResize = 0x01 + msgTypeStdout = 0x00 + msgTypeStderr = 0x01 + msgTypeError = 0x02 + msgTypeStatus = 0x03 + msgTypeConnectd = 0x04 + maxTerminalMessage = 64 * 1024 + terminalInputQueue = 32 + wsWriteTimeout = 5 * time.Second ) -var upgrader = websocket.Upgrader{ - ReadBufferSize: 8192, - WriteBufferSize: 8192, - CheckOrigin: func(r *http.Request) bool { return true }, -} +// A nil CheckOrigin uses Gorilla's same-origin policy, including port checks. +var upgrader = websocket.Upgrader{ReadBufferSize: 8192, WriteBufferSize: 8192} -// wsWriter serializes all WebSocket writes through a channel. type wsWriter struct { conn *websocket.Conn mu sync.Mutex @@ -43,214 +40,175 @@ type wsWriter struct { func (w *wsWriter) write(msgType int, data []byte) error { w.mu.Lock() defer w.mu.Unlock() + if err := w.conn.SetWriteDeadline(time.Now().Add(wsWriteTimeout)); err != nil { + return err + } return w.conn.WriteMessage(msgType, data) } func TerminalHandler(cfg AppConfig) gin.HandlerFunc { return func(c *gin.Context) { - serverID, _ := strconv.ParseInt(c.Param("serverId"), 10, 64) - log.Printf("[terminal] connection request for server %d from %s", serverID, c.ClientIP()) - - // 1. Validate JWT - tokenStr := c.Query("token") - if tokenStr == "" { - c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"}) + serverID, err := strconv.ParseInt(c.Param("serverId"), 10, 64) + if err != nil || serverID <= 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid server id"}) return } - claims, err := auth.ValidateToken(tokenStr, cfg.JWTSecret) - if err != nil { - log.Printf("[terminal] invalid token: %v", err) + token := c.Query("token") + if _, err := auth.ValidateToken(token, cfg.JWTSecret); err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"}) return } - log.Printf("[terminal] user %s authenticated for server %d", claims.Username, serverID) - - // 2. Lookup server - server, err := models.GetServer(getDB(c), serverID) + db := getDB(c) + server, err := loadConnectionServer(c.Request.Context(), db, serverID) if err != nil || server == nil { c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) return } - log.Printf("[terminal] server %s (%s:%d)", server.Name, server.Host, server.Port) - - // 3. Decrypt credentials - privateKey, _ := crypto.Decrypt(server.PrivateKey, cfg.EncryptionKey) - var passwordStr string - if server.Password != "" { - pwBytes, err := crypto.Decrypt(server.Password, cfg.EncryptionKey) - if err == nil { - passwordStr = string(pwBytes) - } - } - - // 4. WebSocket upgrade ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { - log.Printf("[terminal] ws upgrade failed: %v", err) return } - defer ws.Close() - - w := &wsWriter{conn: ws} - - // Set read deadline and pong handler for keepalive - ws.SetReadDeadline(time.Time{}) // no deadline, we use ping/pong - ws.SetPongHandler(func(string) error { - ws.SetReadDeadline(time.Now().Add(60 * time.Second)) - return nil + runTerminal(c.Request.Context(), ws, server.Host, func(ctx context.Context) (*sshclient.Client, error) { + return dialServer(ctx, db, server, cfg.EncryptionKey) }) - ws.SetReadDeadline(time.Now().Add(60 * time.Second)) - - // 5. SSH connect (direct or via jump host) - var client *ssh.Client - if server.JumpServerID != nil && *server.JumpServerID != 0 { - // Connect through jump host - jumpServer, err := models.GetServer(getDB(c), *server.JumpServerID) - if err != nil || jumpServer == nil { - log.Printf("[terminal] jump server %d not found", *server.JumpServerID) - sendTypedMsg(w, msgTypeError, []byte("jump server not found")) - return - } - jumpKey, _ := crypto.Decrypt(jumpServer.PrivateKey, cfg.EncryptionKey) - var jumpPassword string - if jumpServer.Password != "" { - jpBytes, err := crypto.Decrypt(jumpServer.Password, cfg.EncryptionKey) - if err == nil { - jumpPassword = string(jpBytes) - } - } - log.Printf("[terminal] dialing SSH %s@%s:%d via jump %s@%s:%d ...", - server.Username, server.Host, server.Port, - jumpServer.Username, jumpServer.Host, jumpServer.Port) - client, err = sshclient.DialViaJump( - jumpServer.Host, jumpServer.Port, jumpServer.Username, jumpServer.AuthType, jumpKey, jumpPassword, - server.Host, server.Port, server.Username, server.AuthType, privateKey, passwordStr, - ) - if err != nil { - log.Printf("[terminal] SSH dial via jump failed: %v", err) - sendTypedMsg(w, msgTypeError, []byte(fmt.Sprintf("SSH connection via jump failed: %v", err))) - return - } - } else { - log.Printf("[terminal] dialing SSH %s@%s:%d ...", server.Username, server.Host, server.Port) - var err error - client, err = sshclient.Dial(server.Host, server.Port, server.Username, server.AuthType, privateKey, passwordStr) - if err != nil { - log.Printf("[terminal] SSH dial failed: %v", err) - sendTypedMsg(w, msgTypeError, []byte(fmt.Sprintf("SSH connection failed: %v", err))) - return - } - } - defer client.Close() - log.Printf("[terminal] SSH connected") + } +} - sess, err := sshclient.NewSession(client, 80, 24) +func readTerminalInput(ctx context.Context, ws *websocket.Conn, input chan<- []byte, cancel context.CancelFunc) { + defer cancel() + ws.SetReadLimit(maxTerminalMessage) + _ = ws.SetReadDeadline(time.Now().Add(60 * time.Second)) + ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(60 * time.Second)) }) + for { + kind, msg, err := ws.ReadMessage() if err != nil { - log.Printf("[terminal] session failed: %v", err) - sendTypedMsg(w, msgTypeError, []byte(fmt.Sprintf("SSH session failed: %v", err))) return } - defer sess.Close() - log.Printf("[terminal] session started, sending connected") - - // 6. Send connected - connectedMsg, _ := json.Marshal(map[string]interface{}{"host": server.Host, "cols": 80, "rows": 24}) - sendTypedMsg(w, msgTypeConnectd, connectedMsg) - - // Shared done signal - done := make(chan struct{}) - var once sync.Once + if kind != websocket.BinaryMessage || len(msg) == 0 { + continue + } + select { + case input <- msg: + case <-ctx.Done(): + return + default: + // Never stop reading behind a blocked SSH write: disconnect and reclaim + // transports instead of accumulating unbounded input or missing WS closure. + return + } + } +} - // 7. Pump: SSH stdout -> WebSocket (serialized via mutex) - go func() { - buf := make([]byte, 8192) - for { - n, err := sess.Stdout().Read(buf) - if err != nil { - log.Printf("[terminal] stdout ended: %v", err) - once.Do(func() { close(done) }) - return - } - msg := make([]byte, 1+n) - msg[0] = msgTypeStdout - copy(msg[1:], buf[:n]) - if err := w.write(websocket.BinaryMessage, msg); err != nil { - once.Do(func() { close(done) }) +func runTerminal(parent context.Context, ws *websocket.Conn, host string, dial func(context.Context) (*sshclient.Client, error)) { + ctx, cancel := context.WithCancel(parent) + defer cancel() + defer ws.Close() + stop := context.AfterFunc(ctx, func() { _ = ws.Close() }) + defer stop() + w := &wsWriter{conn: ws} + input := make(chan []byte, terminalInputQueue) + go readTerminalInput(ctx, ws, input, cancel) + go func() { + ticker := time.NewTicker(15 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if err := w.write(websocket.PingMessage, nil); err != nil { + cancel() return } } - }() - - // 8. Pump: SSH stderr -> WebSocket - go func() { - buf := make([]byte, 8192) - for { - n, err := sess.Stderr().Read(buf) - if err != nil { - return - } - msg := make([]byte, 1+n) - msg[0] = msgTypeStderr - copy(msg[1:], buf[:n]) - w.write(websocket.BinaryMessage, msg) + } + }() + client, err := dial(ctx) + if err != nil { + _ = sendTypedMsg(w, msgTypeError, []byte(fmt.Sprintf("SSH connection failed: %v", err))) + return + } + defer client.Close() + sess, err := sshclient.NewSession(ctx, client, 80, 24) + if err != nil { + _ = sendTypedMsg(w, msgTypeError, []byte(fmt.Sprintf("SSH session failed: %v", err))) + return + } + defer sess.Close() + connected, _ := json.Marshal(map[string]interface{}{"host": host, "cols": 80, "rows": 24}) + if err := sendTypedMsg(w, msgTypeConnectd, connected); err != nil { + return + } + var output sync.WaitGroup + output.Add(2) + for _, stream := range []struct { + reader io.Reader + kind byte + }{{sess.Stdout(), msgTypeStdout}, {sess.Stderr(), msgTypeStderr}} { + go func(reader io.Reader, kind byte) { + defer output.Done() + if err := pumpTerminalOutput(w, reader, kind); err != nil { + cancel() } - }() - - // 9. Pump: WebSocket -> SSH stdin - go func() { - for { - _, msg, err := ws.ReadMessage() - if err != nil { - log.Printf("[terminal] ws read ended: %v", err) - once.Do(func() { close(done) }) - return - } - if len(msg) < 1 { - continue - } + }(stream.reader, stream.kind) + } + go func() { output.Wait(); cancel() }() + go func() { + defer cancel() + for { + select { + case <-ctx.Done(): + return + case msg := <-input: + var err error switch msg[0] { case msgTypeStdin: - if len(msg) > 1 { - sess.Write(msg[1:]) - } + err = sess.Write(msg[1:]) case msgTypeResize: - var resize struct { + var size struct { Cols int `json:"cols"` Rows int `json:"rows"` } - if err := json.Unmarshal(msg[1:], &resize); err == nil { - sess.Resize(resize.Cols, resize.Rows) + if json.Unmarshal(msg[1:], &size) != nil { + return } + err = sess.Resize(size.Cols, size.Rows) + default: + return } - } - }() - - // 10. Keepalive: ping + SSH keepalive - ticker := time.NewTicker(15 * time.Second) - defer ticker.Stop() - - log.Printf("[terminal] session active, keepalive loop started") - for { - select { - case <-done: - log.Printf("[terminal] session ended") - disconnectMsg, _ := json.Marshal(map[string]interface{}{"connected": false, "message": "session ended"}) - w.write(websocket.BinaryMessage, append([]byte{msgTypeStatus}, disconnectMsg...)) - return - case <-ticker.C: - // Send WebSocket ping - if err := w.write(websocket.PingMessage, nil); err != nil { - log.Printf("[terminal] ping failed: %v", err) + if err != nil { return } } } + }() + <-ctx.Done() + // Transport cleanup is independent of a final browser write. The socket close + // is the disconnect notification, including when the browser stops reading. + _ = client.Close() +} + +func pumpTerminalOutput(w *wsWriter, reader io.Reader, kind byte) error { + buf := make([]byte, 8192) + for { + n, err := reader.Read(buf) + if n > 0 { + if writeErr := sendTypedMsg(w, kind, buf[:n]); writeErr != nil { + return writeErr + } + } + if err == io.EOF { + return nil + } + if err != nil { + return err + } } } -func sendTypedMsg(w *wsWriter, msgType byte, payload []byte) { +func sendTypedMsg(w *wsWriter, kind byte, payload []byte) error { msg := make([]byte, 1+len(payload)) - msg[0] = msgType + msg[0] = kind copy(msg[1:], payload) - w.write(websocket.BinaryMessage, msg) + return w.write(websocket.BinaryMessage, msg) } diff --git a/internal/api/terminal_handler_test.go b/internal/api/terminal_handler_test.go new file mode 100644 index 0000000..f0db1d9 --- /dev/null +++ b/internal/api/terminal_handler_test.go @@ -0,0 +1,158 @@ +package api + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/azzliang6/opsup/internal/sshclient" + "github.com/gorilla/websocket" +) + +func wsTestURL(server *httptest.Server) string { return "ws" + strings.TrimPrefix(server.URL, "http") } + +func TestTerminalOriginPolicy(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err == nil { + _ = conn.Close() + } + })) + defer server.Close() + for _, origin := range []string{server.URL, "", "https://attacker.invalid"} { + t.Run(origin, func(t *testing.T) { + headers := http.Header{} + if origin != "" { + headers.Set("Origin", origin) + } + conn, response, err := websocket.DefaultDialer.Dial(wsTestURL(server), headers) + if origin == "https://attacker.invalid" { + if err == nil { + conn.Close() + t.Fatal("cross-origin connection accepted") + } + if response == nil || response.StatusCode != http.StatusForbidden { + t.Fatalf("unexpected rejection: %v", response) + } + } else { + if err != nil { + t.Fatal(err) + } + _ = conn.Close() + } + if response != nil { + _ = response.Body.Close() + } + }) + } +} + +func TestTerminalDisconnectCancelsSetup(t *testing.T) { + started := make(chan struct{}) + ended := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + runTerminal(r.Context(), ws, "test", func(ctx context.Context) (*sshclient.Client, error) { + close(started) + <-ctx.Done() + close(ended) + return nil, ctx.Err() + }) + })) + defer server.Close() + conn, _, err := websocket.DefaultDialer.Dial(wsTestURL(server), nil) + if err != nil { + t.Fatal(err) + } + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("dial did not start") + } + _ = conn.Close() + select { + case <-ended: + case <-time.After(2 * time.Second): + t.Fatal("disconnect did not cancel SSH setup") + } +} + +func TestTerminalMessageLimitAndQueueOverflow(t *testing.T) { + for _, mode := range []string{"oversized", "queue-overflow"} { + t.Run(mode, func(t *testing.T) { + ended := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + runTerminal(r.Context(), ws, "test", func(ctx context.Context) (*sshclient.Client, error) { + <-ctx.Done() + close(ended) + return nil, ctx.Err() + }) + })) + defer server.Close() + conn, _, err := websocket.DefaultDialer.Dial(wsTestURL(server), nil) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + _ = conn.SetWriteDeadline(time.Now().Add(2 * time.Second)) + if mode == "oversized" { + _ = conn.WriteMessage(websocket.BinaryMessage, make([]byte, maxTerminalMessage+1)) + } else { + for i := 0; i < terminalInputQueue+1; i++ { + _ = conn.WriteMessage(websocket.BinaryMessage, []byte{msgTypeStdin, 'x'}) + } + } + select { + case <-ended: + case <-time.After(2 * time.Second): + t.Fatal("input was not bounded") + } + }) + } +} + +type finalReader struct{ done bool } + +func (r *finalReader) Read(p []byte) (int, error) { + if r.done { + return 0, io.EOF + } + r.done = true + return copy(p, "final bytes"), io.EOF +} + +func TestTerminalDeliversDataAlongsideEOF(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer ws.Close() + _ = pumpTerminalOutput(&wsWriter{conn: ws}, &finalReader{}, msgTypeStdout) + })) + defer server.Close() + conn, _, err := websocket.DefaultDialer.Dial(wsTestURL(server), nil) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second)) + _, data, err := conn.ReadMessage() + if err != nil { + t.Fatal(err) + } + if string(data) != "\x00final bytes" { + t.Fatalf("lost final output: %q", data) + } +} diff --git a/internal/auth/auth.go b/internal/auth/auth.go index bc39c82..963c5c9 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -48,7 +48,7 @@ func ValidateToken(tokenString, secret string) (*Claims, error) { return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) } return []byte(secret), nil - }) + }, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}), jwt.WithIssuer("opsup"), jwt.WithExpirationRequired()) if err != nil { return nil, err } diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go new file mode 100644 index 0000000..812e58a --- /dev/null +++ b/internal/auth/auth_test.go @@ -0,0 +1,54 @@ +package auth + +import ( + "strings" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" +) + +func TestTokenValidation(t *testing.T) { + secret := strings.Repeat("s", 32) + token, _, err := GenerateToken(1, "admin", secret) + if err != nil { + t.Fatal(err) + } + claims, err := ValidateToken(token, secret) + if err != nil || claims.UserID != 1 { + t.Fatalf("valid token: %v", err) + } + if _, err := ValidateToken(token, "wrong secret"); err == nil { + t.Fatal("wrong key accepted") + } + for _, tc := range []struct { + name, issuer string + expiry *jwt.NumericDate + method jwt.SigningMethod + }{ + {"no expiry", "opsup", nil, jwt.SigningMethodHS256}, + {"expired", "opsup", jwt.NewNumericDate(time.Now().Add(-time.Minute)), jwt.SigningMethodHS256}, + {"wrong issuer", "another-app", jwt.NewNumericDate(time.Now().Add(time.Hour)), jwt.SigningMethodHS256}, + {"wrong method", "opsup", jwt.NewNumericDate(time.Now().Add(time.Hour)), jwt.SigningMethodHS512}, + } { + t.Run(tc.name, func(t *testing.T) { + token, err := jwt.NewWithClaims(tc.method, Claims{UserID: 1, RegisteredClaims: jwt.RegisteredClaims{Issuer: tc.issuer, ExpiresAt: tc.expiry}}).SignedString([]byte(secret)) + if err != nil { + t.Fatal(err) + } + if _, err := ValidateToken(token, secret); err == nil { + t.Fatal("invalid claims accepted") + } + }) + } +} + +func TestPasswordHash(t *testing.T) { + hash, err := HashPassword("strong-password") + if err != nil { + t.Fatal(err) + } + if hash == "strong-password" || !CheckPassword("strong-password", hash) || CheckPassword("wrong", hash) { + t.Fatal("invalid bcrypt behavior") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index a8bff2a..e7438b5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,9 +1,14 @@ package config import ( + "crypto/rand" + "encoding/hex" + "encoding/json" "fmt" "os" "path/filepath" + + "github.com/azzliang6/opsup/internal/crypto" ) type Config struct { @@ -11,11 +16,16 @@ type Config struct { JWTSecret string EncryptionKey string Listen string + SecretsPath string +} + +type secrets struct { + JWTSecret string `json:"jwt_secret"` + EncryptionKey string `json:"encryption_key"` } func Load() (*Config, error) { dbPath := getEnv("OPSUP_DB_PATH", "") - if dbPath == "" { exe, err := os.Executable() if err != nil { @@ -25,26 +35,91 @@ func Load() (*Config, error) { } } - jwtSecret := os.Getenv("OPSUP_JWT_SECRET") - encKey := os.Getenv("OPSUP_ENCRYPTION_KEY") - listen := getEnv("OPSUP_LISTEN", ":8080") + cfg := &Config{ + DBPath: dbPath, + JWTSecret: os.Getenv("OPSUP_JWT_SECRET"), + EncryptionKey: os.Getenv("OPSUP_ENCRYPTION_KEY"), + Listen: getEnv("OPSUP_LISTEN", ":8080"), + SecretsPath: getEnv("OPSUP_SECRETS_PATH", dbPath+".secrets.json"), + } + if cfg.JWTSecret == "" || cfg.EncryptionKey == "" { + stored, err := loadOrCreateSecrets(cfg.SecretsPath) + if err != nil { + return nil, err + } + if cfg.JWTSecret == "" { + cfg.JWTSecret = stored.JWTSecret + } + if cfg.EncryptionKey == "" { + cfg.EncryptionKey = stored.EncryptionKey + } + } + if len(cfg.JWTSecret) < 32 || cfg.JWTSecret == "opsup-default-jwt-secret-change-me-in-prod" { + return nil, fmt.Errorf("OPSUP_JWT_SECRET must be a non-default secret of at least 32 bytes") + } + key, err := hex.DecodeString(cfg.EncryptionKey) + if err != nil || len(key) != 32 { + return nil, fmt.Errorf("OPSUP_ENCRYPTION_KEY must be 64 hex characters (32 bytes)") + } + cfg.EncryptionKey = hex.EncodeToString(key) + if cfg.EncryptionKey == crypto.LegacyEncryptionKey { + return nil, fmt.Errorf("the old default encryption key is unsafe; unset OPSUP_ENCRYPTION_KEY to generate a persistent key and migrate legacy credentials") + } + return cfg, nil +} - if jwtSecret == "" { - jwtSecret = "opsup-default-jwt-secret-change-me-in-prod" +func loadOrCreateSecrets(path string) (*secrets, error) { + data, err := os.ReadFile(path) + if err == nil { + var stored secrets + if err := json.Unmarshal(data, &stored); err != nil { + return nil, fmt.Errorf("read secrets file %s: %w (restore the original file; do not regenerate it)", path, err) + } + if err := os.Chmod(path, 0600); err != nil { + return nil, fmt.Errorf("secure secrets file: %w", err) + } + return &stored, nil + } + if !os.IsNotExist(err) { + return nil, fmt.Errorf("read secrets file: %w", err) + } + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return nil, fmt.Errorf("create secrets directory: %w", err) + } + jwt, err := randomSecret() + if err != nil { + return nil, err } - if encKey == "" { - encKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + key, err := randomSecret() + if err != nil { + return nil, err } - if len(encKey) != 64 { - return nil, fmt.Errorf("OPSUP_ENCRYPTION_KEY must be 64 hex characters (32 bytes), got %d", len(encKey)) + stored := &secrets{JWTSecret: jwt, EncryptionKey: key} + data, err = json.MarshalIndent(stored, "", " ") + if err != nil { + return nil, err } + // Exclusive creation never replaces the key of an existing database. + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return nil, fmt.Errorf("create secrets file: %w", err) + } + defer file.Close() + if _, err := file.Write(append(data, '\n')); err != nil { + return nil, fmt.Errorf("write secrets file: %w", err) + } + if err := file.Sync(); err != nil { + return nil, fmt.Errorf("sync secrets file: %w", err) + } + return stored, nil +} - return &Config{ - DBPath: dbPath, - JWTSecret: jwtSecret, - EncryptionKey: encKey, - Listen: listen, - }, nil +func randomSecret() (string, error) { + var value [32]byte + if _, err := rand.Read(value[:]); err != nil { + return "", fmt.Errorf("generate secret: %w", err) + } + return hex.EncodeToString(value[:]), nil } func getEnv(key, fallback string) string { diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..00c687d --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,98 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/azzliang6/opsup/internal/crypto" +) + +func isolatedConfig(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "opsup.db") + t.Setenv("OPSUP_DB_PATH", path) + t.Setenv("OPSUP_SECRETS_PATH", "") + t.Setenv("OPSUP_JWT_SECRET", "") + t.Setenv("OPSUP_ENCRYPTION_KEY", "") + return path + ".secrets.json" +} + +func TestGeneratedSecretsPersist(t *testing.T) { + path := isolatedConfig(t) + first, err := Load() + if err != nil { + t.Fatal(err) + } + second, err := Load() + if err != nil { + t.Fatal(err) + } + if first.JWTSecret != second.JWTSecret || first.EncryptionKey != second.EncryptionKey { + t.Fatal("keys changed across restart") + } + if first.EncryptionKey == crypto.LegacyEncryptionKey || first.EncryptionKey == first.JWTSecret { + t.Fatal("generated keys must be independent and non-default") + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0600 { + t.Fatalf("secret permissions: %o", info.Mode().Perm()) + } + isolatedConfig(t) + third, err := Load() + if err != nil { + t.Fatal(err) + } + if first.EncryptionKey == third.EncryptionKey { + t.Fatal("installations share an encryption key") + } +} + +func TestInvalidStoredSecretsAreNotReplaced(t *testing.T) { + path := isolatedConfig(t) + original := []byte("{broken") + if err := os.WriteFile(path, original, 0600); err != nil { + t.Fatal(err) + } + if _, err := Load(); err == nil { + t.Fatal("expected malformed secret error") + } + actual, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(actual) != string(original) { + t.Fatal("existing key file overwritten") + } +} + +func TestExplicitSecretsAndValidation(t *testing.T) { + path := isolatedConfig(t) + t.Setenv("OPSUP_JWT_SECRET", strings.Repeat("s", 32)) + t.Setenv("OPSUP_ENCRYPTION_KEY", strings.Repeat("ab", 32)) + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.EncryptionKey != strings.Repeat("ab", 32) { + t.Fatal("environment override ignored") + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatal("unnecessary secrets file created") + } + for _, key := range []string{"short", strings.Repeat("z", 64), crypto.LegacyEncryptionKey, strings.ToUpper(crypto.LegacyEncryptionKey)} { + t.Setenv("OPSUP_ENCRYPTION_KEY", key) + if _, err := Load(); err == nil { + t.Fatalf("accepted invalid key %q", key) + } + } + t.Setenv("OPSUP_ENCRYPTION_KEY", strings.Repeat("ab", 32)) + t.Setenv("OPSUP_JWT_SECRET", "opsup-default-jwt-secret-change-me-in-prod") + if _, err := Load(); err == nil { + t.Fatal("accepted legacy JWT secret") + } +} diff --git a/internal/crypto/encryption.go b/internal/crypto/encryption.go index ec31a3f..0909e3e 100644 --- a/internal/crypto/encryption.go +++ b/internal/crypto/encryption.go @@ -9,8 +9,10 @@ import ( "io" ) -// Encrypt encrypts plaintext using AES-256-GCM with the given hex-encoded key. -// Returns base64(nonce || ciphertext || tag). +// LegacyEncryptionKey is accepted only by the one-way storage migration. +const LegacyEncryptionKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + +// Encrypt returns hex(nonce || ciphertext || tag) using AES-256-GCM. func Encrypt(plaintext []byte, hexKey string) (string, error) { key, err := hex.DecodeString(hexKey) if err != nil { diff --git a/internal/crypto/encryption_test.go b/internal/crypto/encryption_test.go new file mode 100644 index 0000000..0ab27e6 --- /dev/null +++ b/internal/crypto/encryption_test.go @@ -0,0 +1,37 @@ +package crypto + +import ( + "strings" + "testing" +) + +func TestEncryptionRoundTripAndAuthentication(t *testing.T) { + key := strings.Repeat("ab", 32) + ciphertext, err := Encrypt([]byte("private credential"), key) + if err != nil { + t.Fatal(err) + } + plaintext, err := Decrypt(ciphertext, key) + if err != nil || string(plaintext) != "private credential" { + t.Fatalf("round trip: %q %v", plaintext, err) + } + second, err := Encrypt(plaintext, key) + if err != nil { + t.Fatal(err) + } + if second == ciphertext { + t.Fatal("nonce reused") + } + if _, err := Decrypt(ciphertext, strings.Repeat("cd", 32)); err == nil { + t.Fatal("wrong key accepted") + } + tampered := "00" + ciphertext[2:] + if tampered == ciphertext { + tampered = "01" + ciphertext[2:] + } + for _, value := range []string{tampered, "bad hex", "00", ""} { + if _, err := Decrypt(value, key); err == nil { + t.Fatalf("invalid ciphertext accepted: %q", value) + } + } +} diff --git a/internal/database/credentials.go b/internal/database/credentials.go new file mode 100644 index 0000000..a697cf4 --- /dev/null +++ b/internal/database/credentials.go @@ -0,0 +1,70 @@ +package database + +import ( + "database/sql" + "fmt" + + "github.com/azzliang6/opsup/internal/crypto" +) + +// UpgradeCredentials validates the active key and atomically retires the old default key. +func UpgradeCredentials(db *sql.DB, key string) (int, error) { + tx, err := db.Begin() + if err != nil { + return 0, err + } + defer tx.Rollback() + rows, err := tx.Query("SELECT id, private_key, COALESCE(password, '') FROM servers") + if err != nil { + return 0, err + } + type update struct { + id int64 + privateKey, password string + } + var updates []update + for rows.Next() { + var item update + if err := rows.Scan(&item.id, &item.privateKey, &item.password); err != nil { + rows.Close() + return 0, err + } + changed := false + for _, value := range []*string{&item.privateKey, &item.password} { + if *value == "" { + continue + } + if _, err := crypto.Decrypt(*value, key); err == nil { + continue + } + plaintext, err := crypto.Decrypt(*value, crypto.LegacyEncryptionKey) + if err != nil { + rows.Close() + return 0, fmt.Errorf("cannot decrypt credentials for server %d; restore the original OPSUP_ENCRYPTION_KEY or secrets file; no credentials were changed", item.id) + } + *value, err = crypto.Encrypt(plaintext, key) + if err != nil { + rows.Close() + return 0, err + } + changed = true + } + if changed { + updates = append(updates, item) + } + } + err = rows.Err() + rows.Close() + if err != nil { + return 0, err + } + for _, item := range updates { + if _, err := tx.Exec("UPDATE servers SET private_key=?, password=? WHERE id=?", item.privateKey, item.password, item.id); err != nil { + return 0, err + } + } + if err := tx.Commit(); err != nil { + return 0, err + } + return len(updates), nil +} diff --git a/internal/database/database.go b/internal/database/database.go index baba7b8..f9f4817 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -3,30 +3,31 @@ package database import ( "database/sql" "fmt" + "net/url" + "path/filepath" _ "github.com/mattn/go-sqlite3" ) func Init(dbPath string) (*sql.DB, error) { - db, err := sql.Open("sqlite3", dbPath+"?_journal_mode=WAL&_foreign_keys=on") + absolute, err := filepath.Abs(dbPath) + if err != nil { + return nil, fmt.Errorf("database path: %w", err) + } + dsn := (&url.URL{Scheme: "file", Path: absolute}).String() + db, err := sql.Open("sqlite3", dsn+"?_journal_mode=WAL&_foreign_keys=on&_busy_timeout=5000&_txlock=immediate") if err != nil { return nil, fmt.Errorf("open database: %w", err) } - + db.SetMaxOpenConns(1) + db.SetMaxIdleConns(1) if err := db.Ping(); err != nil { + db.Close() return nil, fmt.Errorf("ping database: %w", err) } - - // Create tables (safe for existing) - _, err = db.Exec(migrationsSQL) - if err != nil { + if err := migrate(db); err != nil { + db.Close() return nil, fmt.Errorf("run migrations: %w", err) } - - // Run incremental migrations (add columns if missing) - for _, m := range incrementalMigrations { - db.Exec(m) - } - return db, nil } diff --git a/internal/database/database_test.go b/internal/database/database_test.go new file mode 100644 index 0000000..72139cc --- /dev/null +++ b/internal/database/database_test.go @@ -0,0 +1,130 @@ +package database + +import ( + "database/sql" + "path/filepath" + "strings" + "testing" + + "github.com/azzliang6/opsup/internal/crypto" +) + +func TestAdoptLegacySchemaAndReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "legacy.db") + old, err := sql.Open("sqlite3", path) + if err != nil { + t.Fatal(err) + } + if _, err := old.Exec(migrationsSQL); err != nil { + t.Fatal(err) + } + if _, err := old.Exec("ALTER TABLE servers ADD COLUMN auth_type TEXT NOT NULL DEFAULT 'key'"); err != nil { + t.Fatal(err) + } + if _, err := old.Exec("INSERT INTO servers (name,host,username,private_key) VALUES ('old','host','root','')"); err != nil { + t.Fatal(err) + } + old.Close() + for i := 0; i < 2; i++ { + db, err := Init(path) + if err != nil { + t.Fatal(err) + } + var version int + var name, password, fingerprint string + if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil { + t.Fatal(err) + } + if version != len(migrations) { + t.Fatalf("schema version: %d", version) + } + if err := db.QueryRow("SELECT name,password,host_key FROM servers").Scan(&name, &password, &fingerprint); err != nil { + t.Fatal(err) + } + if name != "old" || password != "" || fingerprint != "" { + t.Fatal("legacy data changed") + } + db.Close() + } +} + +func TestFailedMigrationRollsBack(t *testing.T) { + path := filepath.Join(t.TempDir(), "bad.db") + db, err := sql.Open("sqlite3", path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec("CREATE VIEW servers AS SELECT 1 AS id"); err != nil { + t.Fatal(err) + } + if _, err := Init(path); err == nil { + t.Fatal("migration error was swallowed") + } + var version, users int + if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil { + t.Fatal(err) + } + if err := db.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE name='users'").Scan(&users); err != nil { + t.Fatal(err) + } + if version != 0 || users != 0 { + t.Fatal("failed migration was partially committed") + } +} + +func TestUpgradeLegacyCredentialsIsAtomicAndIdempotent(t *testing.T) { + db, err := Init(filepath.Join(t.TempDir(), "opsup.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + legacy, err := crypto.Encrypt([]byte("secret"), crypto.LegacyEncryptionKey) + if err != nil { + t.Fatal(err) + } + insert := "INSERT INTO servers(name,host,username,private_key,password) VALUES ('server','host','root',?,?)" + if _, err := db.Exec(insert, legacy, legacy); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(insert, "corrupt", ""); err != nil { + t.Fatal(err) + } + key := strings.Repeat("ab", 32) + if _, err := UpgradeCredentials(db, key); err == nil { + t.Fatal("corrupt credential accepted") + } + var stored string + if err := db.QueryRow("SELECT private_key FROM servers WHERE id=1").Scan(&stored); err != nil { + t.Fatal(err) + } + if stored != legacy { + t.Fatal("partial migration modified credentials") + } + if _, err := db.Exec("DELETE FROM servers WHERE id=2"); err != nil { + t.Fatal(err) + } + count, err := UpgradeCredentials(db, key) + if err != nil || count != 1 { + t.Fatalf("upgrade: %d %v", count, err) + } + var password string + if err := db.QueryRow("SELECT private_key,password FROM servers WHERE id=1").Scan(&stored, &password); err != nil { + t.Fatal(err) + } + for _, value := range []string{stored, password} { + plaintext, err := crypto.Decrypt(value, key) + if err != nil || string(plaintext) != "secret" { + t.Fatalf("migrated credential: %q %v", plaintext, err) + } + if _, err := crypto.Decrypt(value, crypto.LegacyEncryptionKey); err == nil { + t.Fatal("legacy key still works") + } + } + if count, err := UpgradeCredentials(db, key); err != nil || count != 0 { + t.Fatalf("repeat: %d %v", count, err) + } + if _, err := UpgradeCredentials(db, strings.Repeat("cd", 32)); err == nil { + t.Fatal("lost encryption key went undetected") + } +} diff --git a/internal/database/migrations.go b/internal/database/migrations.go index 8d99972..362f7fd 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -1,5 +1,10 @@ package database +import ( + "database/sql" + "fmt" +) + const migrationsSQL = ` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -8,7 +13,6 @@ CREATE TABLE IF NOT EXISTS users ( created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); - CREATE TABLE IF NOT EXISTS servers ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, @@ -22,7 +26,6 @@ CREATE TABLE IF NOT EXISTS servers ( created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); - CREATE TABLE IF NOT EXISTS sessions ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL REFERENCES users(id), @@ -33,10 +36,74 @@ CREATE TABLE IF NOT EXISTS sessions ( ); ` -// incrementalMigrations adds columns to existing tables. -var incrementalMigrations = []string{ - `ALTER TABLE servers ADD COLUMN jump_server_id INTEGER DEFAULT NULL`, - `ALTER TABLE servers ADD COLUMN group_name TEXT DEFAULT ''`, - `ALTER TABLE servers ADD COLUMN auth_type TEXT NOT NULL DEFAULT 'key'`, - `ALTER TABLE servers ADD COLUMN password TEXT DEFAULT ''`, +var migrations = []func(*sql.Tx) error{ + func(tx *sql.Tx) error { + if _, err := tx.Exec(migrationsSQL); err != nil { + return err + } + // The unversioned release may already contain some or all of these columns. + for _, column := range []struct{ name, definition string }{ + {"jump_server_id", "INTEGER DEFAULT NULL"}, + {"group_name", "TEXT DEFAULT ''"}, + {"auth_type", "TEXT NOT NULL DEFAULT 'key'"}, + {"password", "TEXT DEFAULT ''"}, + } { + if err := addServerColumn(tx, column.name, column.definition); err != nil { + return err + } + } + return nil + }, + func(tx *sql.Tx) error { + return addServerColumn(tx, "host_key", "TEXT NOT NULL DEFAULT ''") + }, +} + +func migrate(db *sql.DB) error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + var version int + if err := tx.QueryRow("PRAGMA user_version").Scan(&version); err != nil { + return err + } + if version > len(migrations) { + return fmt.Errorf("database version %d is newer than supported version %d", version, len(migrations)) + } + for i := version; i < len(migrations); i++ { + if err := migrations[i](tx); err != nil { + return fmt.Errorf("migration %d: %w", i+1, err) + } + if _, err := tx.Exec(fmt.Sprintf("PRAGMA user_version = %d", i+1)); err != nil { + return err + } + } + return tx.Commit() +} + +func addServerColumn(tx *sql.Tx, name, definition string) error { + rows, err := tx.Query("PRAGMA table_info(servers)") + if err != nil { + return err + } + found := false + for rows.Next() { + var cid, notNull, pk int + var column, kind string + var defaultValue sql.NullString + if err := rows.Scan(&cid, &column, &kind, ¬Null, &defaultValue, &pk); err != nil { + rows.Close() + return err + } + found = found || column == name + } + err = rows.Err() + rows.Close() + if err != nil || found { + return err + } + _, err = tx.Exec("ALTER TABLE servers ADD COLUMN " + name + " " + definition) + return err } diff --git a/internal/models/models_test.go b/internal/models/models_test.go new file mode 100644 index 0000000..3739302 --- /dev/null +++ b/internal/models/models_test.go @@ -0,0 +1,77 @@ +package models + +import ( + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/azzliang6/opsup/internal/database" +) + +func TestOnlyOneFirstAdministrator(t *testing.T) { + db, err := database.Init(filepath.Join(t.TempDir(), "opsup.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var succeeded atomic.Int32 + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + _, err := CreateFirstUser(db, fmt.Sprintf("admin%d", i), "hash") + if err == nil { + succeeded.Add(1) + } else if !errors.Is(err, ErrAlreadyInitialized) { + t.Errorf("setup: %v", err) + } + }(i) + } + wg.Wait() + count, err := CountUsers(db) + if err != nil || count != 1 || succeeded.Load() != 1 { + t.Fatalf("users=%d succeeded=%d err=%v", count, succeeded.Load(), err) + } +} + +func TestServerRoundTripDoesNotSerializeCredentials(t *testing.T) { + db, err := database.Init(filepath.Join(t.TempDir(), "opsup.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + s := &Server{Name: "test", Host: "localhost", Port: 22, Username: "user", AuthType: "key", HostKey: "SHA256:fingerprint", PrivateKey: "encrypted-key", Password: "encrypted-password"} + if err := CreateServer(db, s); err != nil { + t.Fatal(err) + } + stored, err := GetServer(db, s.ID) + if err != nil { + t.Fatal(err) + } + if stored.HostKey != s.HostKey || stored.PrivateKey != s.PrivateKey { + t.Fatal("server data lost") + } + stored.HostKey = "SHA256:changed" + if err := UpdateServer(db, stored); err != nil { + t.Fatal(err) + } + list, err := ListServers(db) + if err != nil || len(list) != 1 || list[0].HostKey != stored.HostKey { + t.Fatalf("list: %#v %v", list, err) + } + for _, value := range []any{stored, stored.ToListItem(), list} { + encoded, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "encrypted-") || strings.Contains(string(encoded), "private_key") || strings.Contains(string(encoded), `"password":`) { + t.Fatalf("credentials exposed: %s", encoded) + } + } +} diff --git a/internal/models/server.go b/internal/models/server.go index 4918ada..2b5c18c 100644 --- a/internal/models/server.go +++ b/internal/models/server.go @@ -3,51 +3,50 @@ package models import ( "database/sql" "fmt" - "time" ) type Server struct { - ID int64 `json:"id"` - Name string `json:"name"` - Host string `json:"host"` - Port int `json:"port"` - Username string `json:"username"` - AuthType string `json:"auth_type"` - PrivateKey string `json:"private_key,omitempty"` - Password string `json:"password,omitempty"` - Description string `json:"description"` - Group string `json:"group"` - JumpServerID *int64 `json:"jump_server_id"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` + ID int64 `json:"id"` + Name string `json:"name"` + Host string `json:"host"` + Port int `json:"port"` + Username string `json:"username"` + AuthType string `json:"auth_type"` + HostKey string `json:"host_key"` + PrivateKey string `json:"-"` + Password string `json:"-"` + Description string `json:"description"` + Group string `json:"group"` + JumpServerID *int64 `json:"jump_server_id"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` } func ListServers(db *sql.DB) ([]Server, error) { rows, err := db.Query( - "SELECT id, name, host, port, username, auth_type, description, group_name, jump_server_id, created_at, updated_at FROM servers ORDER BY group_name, name", + "SELECT id, name, host, port, username, auth_type, host_key, description, group_name, jump_server_id, created_at, updated_at FROM servers ORDER BY group_name, name", ) if err != nil { return nil, err } defer rows.Close() - var servers []Server for rows.Next() { var s Server - if err := rows.Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.Description, &s.Group, &s.JumpServerID, &s.CreatedAt, &s.UpdatedAt); err != nil { + if err := rows.Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.HostKey, &s.Description, &s.Group, &s.JumpServerID, &s.CreatedAt, &s.UpdatedAt); err != nil { return nil, err } servers = append(servers, s) } - return servers, nil + return servers, rows.Err() } func GetServer(db *sql.DB, id int64) (*Server, error) { var s Server err := db.QueryRow( - "SELECT id, name, host, port, username, auth_type, private_key, password, description, group_name, jump_server_id, created_at, updated_at FROM servers WHERE id = ?", + "SELECT id, name, host, port, username, auth_type, host_key, private_key, password, description, group_name, jump_server_id, created_at, updated_at FROM servers WHERE id = ?", id, - ).Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.PrivateKey, &s.Password, &s.Description, &s.Group, &s.JumpServerID, &s.CreatedAt, &s.UpdatedAt) + ).Scan(&s.ID, &s.Name, &s.Host, &s.Port, &s.Username, &s.AuthType, &s.HostKey, &s.PrivateKey, &s.Password, &s.Description, &s.Group, &s.JumpServerID, &s.CreatedAt, &s.UpdatedAt) if err == sql.ErrNoRows { return nil, nil } @@ -59,20 +58,20 @@ func GetServer(db *sql.DB, id int64) (*Server, error) { func CreateServer(db *sql.DB, s *Server) error { result, err := db.Exec( - "INSERT INTO servers (name, host, port, username, auth_type, private_key, password, description, group_name, jump_server_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - s.Name, s.Host, s.Port, s.Username, s.AuthType, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, + "INSERT INTO servers (name, host, port, username, auth_type, host_key, private_key, password, description, group_name, jump_server_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + s.Name, s.Host, s.Port, s.Username, s.AuthType, s.HostKey, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, ) if err != nil { return fmt.Errorf("insert server: %w", err) } - s.ID, _ = result.LastInsertId() - return nil + s.ID, err = result.LastInsertId() + return err } func UpdateServer(db *sql.DB, s *Server) error { _, err := db.Exec( - "UPDATE servers SET name=?, host=?, port=?, username=?, auth_type=?, private_key=?, password=?, description=?, group_name=?, jump_server_id=?, updated_at=datetime('now') WHERE id=?", - s.Name, s.Host, s.Port, s.Username, s.AuthType, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, s.ID, + "UPDATE servers SET name=?, host=?, port=?, username=?, auth_type=?, host_key=?, private_key=?, password=?, description=?, group_name=?, jump_server_id=?, updated_at=datetime('now') WHERE id=?", + s.Name, s.Host, s.Port, s.Username, s.AuthType, s.HostKey, s.PrivateKey, s.Password, s.Description, s.Group, s.JumpServerID, s.ID, ) return err } @@ -89,6 +88,7 @@ type ServerListItem struct { Port int `json:"port"` Username string `json:"username"` AuthType string `json:"auth_type"` + HostKey string `json:"host_key"` Description string `json:"description"` Group string `json:"group"` JumpServerID *int64 `json:"jump_server_id"` @@ -98,18 +98,9 @@ type ServerListItem struct { func (s *Server) ToListItem() ServerListItem { return ServerListItem{ - ID: s.ID, - Name: s.Name, - Host: s.Host, - Port: s.Port, - Username: s.Username, - AuthType: s.AuthType, - Description: s.Description, - Group: s.Group, - JumpServerID: s.JumpServerID, - CreatedAt: s.CreatedAt, - UpdatedAt: s.UpdatedAt, + ID: s.ID, Name: s.Name, Host: s.Host, Port: s.Port, + Username: s.Username, AuthType: s.AuthType, HostKey: s.HostKey, + Description: s.Description, Group: s.Group, JumpServerID: s.JumpServerID, + CreatedAt: s.CreatedAt, UpdatedAt: s.UpdatedAt, } } - -var _ time.Time diff --git a/internal/models/user.go b/internal/models/user.go index 04af00f..b33a90a 100644 --- a/internal/models/user.go +++ b/internal/models/user.go @@ -2,6 +2,7 @@ package models import ( "database/sql" + "errors" "fmt" ) @@ -19,6 +20,27 @@ func CountUsers(db *sql.DB) (int, error) { return count, err } +var ErrAlreadyInitialized = errors.New("already initialized") + +func CreateFirstUser(db *sql.DB, username, passwordHash string) (*User, error) { + result, err := db.Exec( + "INSERT INTO users (username, password) SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM users)", + username, passwordHash, + ) + if err != nil { + return nil, fmt.Errorf("create first user: %w", err) + } + n, err := result.RowsAffected() + if err != nil { + return nil, err + } + if n == 0 { + return nil, ErrAlreadyInitialized + } + id, err := result.LastInsertId() + return &User{ID: id, Username: username}, err +} + func CreateUser(db *sql.DB, username, passwordHash string) (*User, error) { result, err := db.Exec( "INSERT INTO users (username, password) VALUES (?, ?)", diff --git a/internal/sftpclient/client.go b/internal/sftpclient/client.go index 0901d60..d56d66e 100644 --- a/internal/sftpclient/client.go +++ b/internal/sftpclient/client.go @@ -1,87 +1,128 @@ package sftpclient import ( + "context" + "crypto/rand" + "encoding/hex" "fmt" "io" "os" + "path" + "sync" - "github.com/pkg/sftp" "github.com/azzliang6/opsup/internal/sshclient" - "golang.org/x/crypto/ssh" + "github.com/pkg/sftp" ) type Client struct { - sshClient *ssh.Client + sshClient *sshclient.Client sftpClient *sftp.Client + once sync.Once + stop func() bool } -func NewSFTPClient(host string, port int, username string, authType string, privateKey []byte, password string) (*Client, error) { - sshClient, err := sshclient.Dial(host, port, username, authType, privateKey, password) - if err != nil { - return nil, err - } - - sftpClient, err := sftp.NewClient(sshClient) +// NewClient takes ownership of the SSH connection, including on failure. +func NewClient(ctx context.Context, owner *sshclient.Client) (*Client, error) { + setup, cancel := context.WithTimeout(ctx, sshclient.SetupTimeout) + defer cancel() + stop := context.AfterFunc(setup, func() { _ = owner.Close() }) + defer stop() + client, err := sftp.NewClient(owner.Client) if err != nil { - sshClient.Close() + _ = owner.Close() + if setup.Err() != nil { + err = setup.Err() + } return nil, fmt.Errorf("sftp init: %w", err) } - - return &Client{sshClient: sshClient, sftpClient: sftpClient}, nil + c := &Client{sshClient: owner, sftpClient: client, stop: context.AfterFunc(ctx, func() { _ = owner.Close() })} + if !stop() || setup.Err() != nil { + _ = c.Close() + return nil, setup.Err() + } + return c, nil } -func NewSFTPClientViaJump( - jumpHost string, jumpPort int, jumpUser string, jumpAuthType string, jumpKey []byte, jumpPassword string, - targetHost string, targetPort int, targetUser string, targetAuthType string, targetKey []byte, targetPassword string, -) (*Client, error) { - sshClient, err := sshclient.DialViaJump( - jumpHost, jumpPort, jumpUser, jumpAuthType, jumpKey, jumpPassword, - targetHost, targetPort, targetUser, targetAuthType, targetKey, targetPassword, - ) +func (c *Client) ReadDir(path string) ([]os.FileInfo, error) { return c.sftpClient.ReadDir(path) } +func (c *Client) Open(path string) (*sftp.File, error) { return c.sftpClient.Open(path) } +func (c *Client) MkdirAll(path string) error { return c.sftpClient.MkdirAll(path) } +func (c *Client) Remove(path string) error { return c.sftpClient.Remove(path) } +func (c *Client) RemoveDirectory(path string) error { return c.sftpClient.RemoveDirectory(path) } +func (c *Client) Stat(path string) (os.FileInfo, error) { return c.sftpClient.Stat(path) } + +// Upload writes a sibling temporary file and only publishes after a successful +// close. SFTP v3 rename must reject existing destinations; the POSIX extension +// permits atomic replacement. Never fall back after a failed POSIX rename. +func (c *Client) Upload(remotePath string, src io.Reader) (err error) { + mode := os.FileMode(0600) + var ownership *sftp.FileStat + if existing, statErr := c.sftpClient.Lstat(remotePath); statErr == nil { + if !existing.Mode().IsRegular() { + return fmt.Errorf("upload destination must be a regular file") + } + mode = existing.Mode().Perm() + ownership, _ = existing.Sys().(*sftp.FileStat) + } else if !os.IsNotExist(statErr) { + return fmt.Errorf("check destination: %w", statErr) + } + var nonce [16]byte + if _, err = rand.Read(nonce[:]); err != nil { + return err + } + temp := path.Join(path.Dir(remotePath), ".opsup-upload-"+hex.EncodeToString(nonce[:])) + dst, err := c.sftpClient.OpenFile(temp, os.O_WRONLY|os.O_CREATE|os.O_EXCL) if err != nil { - return nil, err + return fmt.Errorf("create temporary file: %w", err) + } + published := false + defer func() { + if !published { + _ = c.sftpClient.Remove(temp) + } + }() + if err := dst.Chmod(0600); err != nil { + _ = dst.Close() + return fmt.Errorf("secure temporary file: %w", err) + } + _, copyErr := io.Copy(dst, src) + if copyErr == nil && ownership != nil { + copyErr = dst.Chown(int(ownership.UID), int(ownership.GID)) + } + if copyErr == nil { + copyErr = dst.Chmod(mode) + } + closeErr := dst.Close() + if copyErr != nil { + return fmt.Errorf("upload: %w", copyErr) + } + if closeErr != nil { + return fmt.Errorf("close upload: %w", closeErr) + } + if _, supported := c.sftpClient.HasExtension("posix-rename@openssh.com"); supported { + err = c.sftpClient.PosixRename(temp, remotePath) + } else { + // Lstat also detects dangling symlinks; Rename supplies the race-safe + // no-overwrite behavior required by SFTP v3 after this early check. + if _, statErr := c.sftpClient.Lstat(remotePath); statErr == nil { + return fmt.Errorf("atomic overwrite unsupported by this SFTP server") + } else if !os.IsNotExist(statErr) { + return fmt.Errorf("check destination: %w", statErr) + } + err = c.sftpClient.Rename(temp, remotePath) } - - sftpClient, err := sftp.NewClient(sshClient) if err != nil { - sshClient.Close() - return nil, fmt.Errorf("sftp init: %w", err) + return fmt.Errorf("publish upload: %w", err) } - - return &Client{sshClient: sshClient, sftpClient: sftpClient}, nil -} - -func (c *Client) ReadDir(path string) ([]os.FileInfo, error) { - return c.sftpClient.ReadDir(path) -} - -func (c *Client) Create(path string) (*sftp.File, error) { - return c.sftpClient.Create(path) -} - -func (c *Client) Open(path string) (*sftp.File, error) { - return c.sftpClient.Open(path) -} - -func (c *Client) MkdirAll(path string) error { - return c.sftpClient.MkdirAll(path) -} - -func (c *Client) Remove(path string) error { - return c.sftpClient.Remove(path) -} - -func (c *Client) RemoveDirectory(path string) error { - return c.sftpClient.RemoveDirectory(path) -} - -func (c *Client) Stat(path string) (os.FileInfo, error) { - return c.sftpClient.Stat(path) + published = true + return nil } func (c *Client) Close() error { - c.sftpClient.Close() - c.sshClient.Close() + c.once.Do(func() { + c.stop() + _ = c.sshClient.Close() + _ = c.sftpClient.Close() + }) return nil } diff --git a/internal/sftpclient/client_test.go b/internal/sftpclient/client_test.go new file mode 100644 index 0000000..0c7cff5 --- /dev/null +++ b/internal/sftpclient/client_test.go @@ -0,0 +1,206 @@ +package sftpclient + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "errors" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/azzliang6/opsup/internal/sshclient" + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" +) + +func sftpPeer(t *testing.T, mode string) (sshclient.Config, <-chan struct{}) { + t.Helper() + _, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + signer, err := ssh.NewSignerFromKey(key) + if err != nil { + t.Fatal(err) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + host, port, _ := net.SplitHostPort(listener.Addr().String()) + n, _ := strconv.Atoi(port) + done := make(chan struct{}) + go func() { + defer close(done) + raw, err := listener.Accept() + if err != nil { + return + } + defer raw.Close() + t.Cleanup(func() { _ = raw.Close() }) + config := &ssh.ServerConfig{NoClientAuth: true} + config.AddHostKey(signer) + conn, channels, requests, err := ssh.NewServerConn(raw, config) + if err != nil { + return + } + defer conn.Close() + go ssh.DiscardRequests(requests) + var sessions sync.WaitGroup + defer sessions.Wait() + for incoming := range channels { + if incoming.ChannelType() != "session" { + _ = incoming.Reject(ssh.UnknownChannelType, "unsupported") + continue + } + ch, requests, err := incoming.Accept() + if err != nil { + continue + } + sessions.Add(1) + go func() { + defer sessions.Done() + defer ch.Close() + for req := range requests { + if req.Type != "subsystem" { + _ = req.Reply(false, nil) + continue + } + if mode == "stall" { + continue + } + _ = req.Reply(true, nil) + if mode == "stall-io" { + _, _ = ch.Write([]byte{0, 0, 0, 5, 2, 0, 0, 0, 3}) + _, _ = io.Copy(io.Discard, ch) + return + } + if mode == "close-error" { + handlers := sftp.InMemHandler() + handlers.FilePut = closeFailureWriter{handlers.FilePut} + server := sftp.NewRequestServer(ch, handlers) + _ = server.Serve() + _ = server.Close() + return + } + server, err := sftp.NewServer(ch) + if err != nil { + return + } + _ = server.Serve() + _ = server.Close() + return + } + }() + } + }() + return sshclient.Config{Host: host, Port: n, Username: "test", AuthType: "password", Password: "test", HostKey: ssh.FingerprintSHA256(signer.PublicKey())}, done +} + +func newTestClient(t *testing.T, modes ...string) *Client { + t.Helper() + mode := "" + if len(modes) > 0 { + mode = modes[0] + } + cfg, done := sftpPeer(t, mode) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + owner, err := sshclient.Dial(ctx, cfg) + if err != nil { + t.Fatal(err) + } + client, err := NewClient(ctx, owner) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = client.Close() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Error("SFTP peer did not close") + } + }) + return client +} + +type failedSource struct{ sent bool } + +func (r *failedSource) Read(p []byte) (int, error) { + if r.sent { + return 0, errors.New("source failed") + } + r.sent = true + return copy(p, "partial replacement"), errors.New("source failed") +} + +func TestUploadPreservesDestinationOnSourceFailure(t *testing.T) { + client := newTestClient(t) + dir := t.TempDir() + dest := filepath.Join(dir, "existing") + if err := os.WriteFile(dest, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + if err := client.Upload(dest, &failedSource{}); err == nil { + t.Fatal("expected failed upload") + } + content, err := os.ReadFile(dest) + if err != nil || string(content) != "original" { + t.Fatalf("destination changed: %q, %v", content, err) + } + files, err := os.ReadDir(dir) + if err != nil || len(files) != 1 { + t.Fatalf("temporary file leaked: %v, %v", files, err) + } +} + +func TestUploadAtomicallyReplacesDestination(t *testing.T) { + client := newTestClient(t) + dir := t.TempDir() + dest := filepath.Join(dir, "existing") + if err := os.WriteFile(dest, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + if err := client.Upload(dest, strings.NewReader("replacement")); err != nil { + t.Fatal(err) + } + content, err := os.ReadFile(dest) + if err != nil || string(content) != "replacement" { + t.Fatalf("incorrect upload: %q, %v", content, err) + } + files, err := os.ReadDir(dir) + if err != nil || len(files) != 1 { + t.Fatalf("temporary file leaked: %v, %v", files, err) + } +} + +func TestCancelledSubsystemSetup(t *testing.T) { + cfg, closed := sftpPeer(t, "stall") + owner, err := sshclient.Dial(context.Background(), cfg) + if err != nil { + t.Fatal(err) + } + defer owner.Close() + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _, err = NewClient(ctx, owner) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline exceeded, got %v", err) + } + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("subsystem setup leaked connection") + } +} + +var _ io.Reader = (*failedSource)(nil) diff --git a/internal/sftpclient/context_test.go b/internal/sftpclient/context_test.go new file mode 100644 index 0000000..e5ce902 --- /dev/null +++ b/internal/sftpclient/context_test.go @@ -0,0 +1,46 @@ +package sftpclient + +import ( + "context" + "testing" + "time" + + "github.com/azzliang6/opsup/internal/sshclient" +) + +func TestCancelledOperationUnblocksSFTPRead(t *testing.T) { + cfg, closed := sftpPeer(t, "stall-io") + owner, err := sshclient.Dial(context.Background(), cfg) + if err != nil { + t.Fatal(err) + } + defer owner.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + client, err := NewClient(ctx, owner) + if err != nil { + t.Fatal(err) + } + defer client.Close() + result := make(chan error, 1) + go func() { _, err := client.ReadDir("/"); result <- err }() + select { + case <-result: + t.Fatal("test requires blocked SFTP operation") + case <-time.After(50 * time.Millisecond): + } + cancel() + select { + case err := <-result: + if err == nil { + t.Fatal("cancelled read succeeded") + } + case <-time.After(2 * time.Second): + t.Fatal("cancelled SFTP operation remained blocked") + } + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("cancelled SFTP leaked transport") + } +} diff --git a/internal/sftpclient/permissions_test.go b/internal/sftpclient/permissions_test.go new file mode 100644 index 0000000..9116bc6 --- /dev/null +++ b/internal/sftpclient/permissions_test.go @@ -0,0 +1,44 @@ +package sftpclient + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestUploadPreservesPermissionsAndRejectsSymlinks(t *testing.T) { + client := newTestClient(t) + dir := t.TempDir() + for _, mode := range []os.FileMode{0600, 0750} { + dest := filepath.Join(dir, "existing") + if err := os.WriteFile(dest, []byte("old"), mode); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dest, mode); err != nil { + t.Fatal(err) + } + if err := client.Upload(dest, strings.NewReader("new")); err != nil { + t.Fatal(err) + } + info, err := os.Stat(dest) + if err != nil || info.Mode().Perm() != mode { + t.Fatalf("changed permissions: %v %v", info, err) + } + } + fresh := filepath.Join(dir, "fresh") + if err := client.Upload(fresh, strings.NewReader("private")); err != nil { + t.Fatal(err) + } + info, err := os.Stat(fresh) + if err != nil || info.Mode().Perm() != 0600 { + t.Fatalf("new file is not private: %v %v", info, err) + } + link := filepath.Join(dir, "link") + if err := os.Symlink(fresh, link); err != nil { + t.Fatal(err) + } + if err := client.Upload(link, strings.NewReader("overwrite")); err == nil { + t.Fatal("symlink overwritten") + } +} diff --git a/internal/sftpclient/upload_test.go b/internal/sftpclient/upload_test.go new file mode 100644 index 0000000..b3c2ce8 --- /dev/null +++ b/internal/sftpclient/upload_test.go @@ -0,0 +1,100 @@ +package sftpclient + +import ( + "errors" + "io" + "os" + "path" + "path/filepath" + "strings" + "testing" + + "github.com/pkg/sftp" +) + +type closeFailureWriter struct{ sftp.FileWriter } + +func (w closeFailureWriter) Filewrite(request *sftp.Request) (io.WriterAt, error) { + writer, err := w.FileWriter.Filewrite(request) + if err != nil { + return nil, err + } + if strings.HasPrefix(path.Base(request.Filepath), ".opsup-upload-") { + return closeFailureFile{writer}, nil + } + return writer, nil +} + +type closeFailureFile struct{ io.WriterAt } + +func (f closeFailureFile) Close() error { + if closer, ok := f.WriterAt.(io.Closer); ok { + _ = closer.Close() + } + return errors.New("disk flush failed") +} + +func TestUploadChecksRemoteCloseBeforePublish(t *testing.T) { + client := newTestClient(t, "close-error") + initial, err := client.sftpClient.OpenFile("/existing", os.O_WRONLY|os.O_CREATE) + if err != nil { + t.Fatal(err) + } + if _, err := initial.Write([]byte("original")); err != nil { + t.Fatal(err) + } + if err := initial.Close(); err != nil { + t.Fatal(err) + } + err = client.Upload("/existing", strings.NewReader("replacement")) + if err == nil || !strings.Contains(err.Error(), "close upload") { + t.Fatalf("ignored close error: %v", err) + } + file, err := client.Open("/existing") + if err != nil { + t.Fatal(err) + } + defer file.Close() + content, err := io.ReadAll(file) + if err != nil || string(content) != "original" { + t.Fatalf("destination changed: %q %v", content, err) + } + files, err := client.ReadDir("/") + if err != nil || len(files) != 1 { + t.Fatalf("temporary file leaked: %v, %v", files, err) + } +} + +func TestUploadWithoutPosixRenameRejectsOverwrite(t *testing.T) { + if err := sftp.SetSFTPExtensions(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = sftp.SetSFTPExtensions("hardlink@openssh.com", "posix-rename@openssh.com", "statvfs@openssh.com") + }) + client := newTestClient(t) + dir := t.TempDir() + dest := filepath.Join(dir, "existing") + if err := os.WriteFile(dest, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + if err := client.Upload(dest, strings.NewReader("replacement")); err == nil { + t.Fatal("unsafe overwrite accepted") + } + content, err := os.ReadFile(dest) + if err != nil || string(content) != "original" { + t.Fatalf("destination changed: %q %v", content, err) + } + newPath := filepath.Join(dir, "new") + if err := client.Upload(newPath, strings.NewReader("new data")); err != nil { + t.Fatalf("new file upload failed: %v", err) + } + content, err = os.ReadFile(newPath) + if err != nil || string(content) != "new data" { + t.Fatalf("new file missing: %q %v", content, err) + } + files, err := os.ReadDir(dir) + if err != nil || len(files) != 2 { + t.Fatalf("temporary file leaked: %v, %v", files, err) + } +} diff --git a/internal/sshclient/client.go b/internal/sshclient/client.go index 81ef202..ea36d6b 100644 --- a/internal/sshclient/client.go +++ b/internal/sshclient/client.go @@ -1,119 +1,167 @@ package sshclient import ( + "context" + "crypto/subtle" "fmt" "net" + "strconv" + "sync" "time" "golang.org/x/crypto/ssh" ) -// TestDial attempts to connect to the SSH server and returns an error if it fails. -func TestDial(host string, port int, username string, authType string, privateKey []byte, password string) error { - config, err := makeConfig(username, authType, privateKey, password) - if err != nil { - return err - } - client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), config) - if err != nil { - return err - } - client.Close() - return nil +const SetupTimeout = 15 * time.Second + +type Config struct { + Host string + Port int + Username string + AuthType string + PrivateKey []byte + Password string + HostKey string } -// TestDialViaJump tests connection through a jump host. -func TestDialViaJump(jumpHost string, jumpPort int, jumpUser string, jumpAuthType string, jumpKey []byte, jumpPassword string, targetHost string, targetPort int, targetUser string, targetAuthType string, targetKey []byte, targetPassword string) error { - jumpClient, err := Dial(jumpHost, jumpPort, jumpUser, jumpAuthType, jumpKey, jumpPassword) - if err != nil { - return fmt.Errorf("jump host: %w", err) +// Client owns the target and, when present, the jump transport. Close tears down +// the physical socket first so blocked SSH channel writes cannot delay cleanup. +type Client struct { + *ssh.Client + transport net.Conn + jump *Client + done chan struct{} + once sync.Once +} + +func (c *Client) Close() error { + var err error + c.once.Do(func() { + close(c.done) + if c.jump != nil { + _ = c.jump.Close() + } + err = c.transport.Close() + }) + return err +} + +func (c *Client) watch(ctx context.Context) { + go func() { + select { + case <-ctx.Done(): + _ = c.Close() + case <-c.done: + } + }() +} + +func hostKeyCallback(pin string) ssh.HostKeyCallback { + return func(hostname string, _ net.Addr, key ssh.PublicKey) error { + observed := ssh.FingerprintSHA256(key) + if pin == "" { + return fmt.Errorf("host key not pinned for %s; observed %s; independently verify this fingerprint before saving it", hostname, observed) + } + if subtle.ConstantTimeCompare([]byte(pin), []byte(observed)) != 1 { + return fmt.Errorf("host key mismatch for %s: expected %s, observed %s; independently verify the server identity", hostname, pin, observed) + } + return nil } - defer jumpClient.Close() +} - conn, err := dialThroughJump(jumpClient, targetHost, targetPort, targetUser, targetAuthType, targetKey, targetPassword) - if err != nil { - return err +func makeConfig(cfg Config) (*ssh.ClientConfig, error) { + var method ssh.AuthMethod + switch cfg.AuthType { + case "password": + if cfg.Password == "" { + return nil, fmt.Errorf("no password available") + } + method = ssh.Password(cfg.Password) + case "key": + signer, err := ssh.ParsePrivateKey(cfg.PrivateKey) + if err != nil { + return nil, fmt.Errorf("parse private key: %w", err) + } + method = ssh.PublicKeys(signer) + default: + return nil, fmt.Errorf("unsupported authentication type %q", cfg.AuthType) } - conn.Close() - return nil + return &ssh.ClientConfig{User: cfg.Username, Auth: []ssh.AuthMethod{method}, HostKeyCallback: hostKeyCallback(cfg.HostKey)}, nil } -// Dial establishes a direct SSH connection. -func Dial(host string, port int, username string, authType string, privateKey []byte, password string) (*ssh.Client, error) { - config, err := makeConfig(username, authType, privateKey, password) +func Dial(ctx context.Context, cfg Config) (*Client, error) { + config, err := makeConfig(cfg) if err != nil { return nil, err } - conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), config) + setup, cancel := context.WithTimeout(ctx, SetupTimeout) + defer cancel() + addr := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)) + conn, err := (&net.Dialer{}).DialContext(setup, "tcp", addr) if err != nil { - return nil, fmt.Errorf("ssh dial %s:%d: %w", host, port, err) + return nil, fmt.Errorf("ssh dial %s: %w", addr, err) } - return conn, nil -} - -// DialViaJump establishes an SSH connection through a jump host. -// Returns the final SSH client connected to the target. -func DialViaJump(jumpHost string, jumpPort int, jumpUser string, jumpAuthType string, jumpKey []byte, jumpPassword string, targetHost string, targetPort int, targetUser string, targetAuthType string, targetKey []byte, targetPassword string) (*ssh.Client, error) { - jumpClient, err := Dial(jumpHost, jumpPort, jumpUser, jumpAuthType, jumpKey, jumpPassword) + owner := &Client{transport: conn, done: make(chan struct{})} + stop := context.AfterFunc(setup, func() { _ = owner.Close() }) + defer stop() + deadline, _ := setup.Deadline() + _ = conn.SetDeadline(deadline) + ncc, chans, reqs, err := ssh.NewClientConn(conn, addr, config) if err != nil { - return nil, fmt.Errorf("jump host %s:%d: %w", jumpHost, jumpPort, err) + _ = owner.Close() + if setup.Err() != nil { + err = setup.Err() + } + return nil, fmt.Errorf("ssh handshake %s: %w", addr, err) } - - targetClient, err := dialThroughJump(jumpClient, targetHost, targetPort, targetUser, targetAuthType, targetKey, targetPassword) - if err != nil { - jumpClient.Close() - return nil, fmt.Errorf("target %s:%d via jump: %w", targetHost, targetPort, err) + owner.Client = ssh.NewClient(ncc, chans, reqs) + if !stop() || setup.Err() != nil { + _ = owner.Close() + return nil, setup.Err() } - - return targetClient, nil + _ = conn.SetDeadline(time.Time{}) + owner.watch(ctx) + return owner, nil } -// dialThroughJump dials the target through an existing jump client connection. -func dialThroughJump(jumpClient *ssh.Client, targetHost string, targetPort int, targetUser string, targetAuthType string, targetKey []byte, targetPassword string) (*ssh.Client, error) { - targetConfig, err := makeConfig(targetUser, targetAuthType, targetKey, targetPassword) +func DialViaJump(ctx context.Context, jump, target Config) (*Client, error) { + targetConfig, err := makeConfig(target) if err != nil { return nil, err } - - // Open a TCP connection to the target through the jump host - targetAddr := fmt.Sprintf("%s:%d", targetHost, targetPort) - conn, err := jumpClient.Dial("tcp", targetAddr) + jumpClient, err := Dial(ctx, jump) if err != nil { - return nil, fmt.Errorf("jump dial to %s: %w", targetAddr, err) + return nil, fmt.Errorf("jump host: %w", err) } - - // Upgrade the TCP connection to SSH - ncc, chans, reqs, err := ssh.NewClientConn(conn, targetAddr, targetConfig) + setup, cancel := context.WithTimeout(ctx, SetupTimeout) + defer cancel() + // SSH forwarded connections do not implement deadlines. Closing the physical + // jump socket bounds both channel-open and nested SSH handshake operations. + stop := context.AfterFunc(setup, func() { _ = jumpClient.Close() }) + defer stop() + addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port)) + conn, err := jumpClient.Dial("tcp", addr) if err != nil { - conn.Close() - return nil, fmt.Errorf("ssh handshake to %s: %w", targetAddr, err) + _ = jumpClient.Close() + if setup.Err() != nil { + err = setup.Err() + } + return nil, fmt.Errorf("jump dial %s: %w", addr, err) } - - return ssh.NewClient(ncc, chans, reqs), nil -} - -func makeConfig(username string, authType string, privateKey []byte, password string) (*ssh.ClientConfig, error) { - var authMethods []ssh.AuthMethod - - if authType == "password" && password != "" { - authMethods = append(authMethods, ssh.Password(password)) - } else if len(privateKey) > 0 { - signer, err := ssh.ParsePrivateKey(privateKey) - if err != nil { - return nil, fmt.Errorf("parse private key: %w", err) + ncc, chans, reqs, err := ssh.NewClientConn(conn, addr, targetConfig) + if err != nil { + _ = jumpClient.Close() + _ = conn.Close() + if setup.Err() != nil { + err = setup.Err() } - authMethods = append(authMethods, ssh.PublicKeys(signer)) - } else { - return nil, fmt.Errorf("no authentication method available") + return nil, fmt.Errorf("target handshake %s: %w", addr, err) } - - return &ssh.ClientConfig{ - User: username, - Auth: authMethods, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - Timeout: 10 * time.Second, - }, nil + owner := &Client{Client: ssh.NewClient(ncc, chans, reqs), transport: conn, jump: jumpClient, done: make(chan struct{})} + if !stop() || setup.Err() != nil { + _ = owner.Close() + return nil, setup.Err() + } + owner.watch(ctx) + return owner, nil } - -// Ensure net import is available -var _ net.Conn diff --git a/internal/sshclient/client_test.go b/internal/sshclient/client_test.go new file mode 100644 index 0000000..f283fc0 --- /dev/null +++ b/internal/sshclient/client_test.go @@ -0,0 +1,287 @@ +package sshclient + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "errors" + "io" + "net" + "strconv" + "strings" + "testing" + "time" + + "golang.org/x/crypto/ssh" +) + +type testPeer struct { + config Config + closed chan struct{} +} + +func startPeer(t *testing.T, mode string) testPeer { + t.Helper() + _, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + signer, err := ssh.NewSignerFromKey(key) + if err != nil { + t.Fatal(err) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + host, port, _ := net.SplitHostPort(listener.Addr().String()) + portNum, _ := strconv.Atoi(port) + peer := testPeer{config: Config{Host: host, Port: portNum, Username: "test", AuthType: "password", Password: "test", HostKey: ssh.FingerprintSHA256(signer.PublicKey())}, closed: make(chan struct{})} + go func() { + defer close(peer.closed) + raw, err := listener.Accept() + if err != nil { + return + } + defer raw.Close() + t.Cleanup(func() { _ = raw.Close() }) + config := &ssh.ServerConfig{NoClientAuth: true} + config.AddHostKey(signer) + conn, channels, requests, err := ssh.NewServerConn(raw, config) + if err != nil { + return + } + defer conn.Close() + go ssh.DiscardRequests(requests) + for incoming := range channels { + switch incoming.ChannelType() { + case "direct-tcpip": + if mode == "stall-forward" { + continue + } + var dest struct { + Host string + Port uint32 + Origin string + OriginPort uint32 + } + if ssh.Unmarshal(incoming.ExtraData(), &dest) != nil { + _ = incoming.Reject(ssh.ConnectionFailed, "bad target") + continue + } + target, err := net.Dial("tcp", net.JoinHostPort(dest.Host, strconv.Itoa(int(dest.Port)))) + if err != nil { + _ = incoming.Reject(ssh.ConnectionFailed, "unreachable") + continue + } + ch, requests, err := incoming.Accept() + if err != nil { + _ = target.Close() + continue + } + go ssh.DiscardRequests(requests) + go func() { _, _ = io.Copy(target, ch); _ = target.Close(); _ = ch.Close() }() + go func() { _, _ = io.Copy(ch, target); _ = ch.Close(); _ = target.Close() }() + case "session": + if mode == "stall-session" { + continue + } + ch, requests, err := incoming.Accept() + if err != nil { + continue + } + go func() { + defer ch.Close() + for req := range requests { + if mode == "stall-pty" { + continue + } + _ = req.Reply(true, nil) + } + }() + default: + _ = incoming.Reject(ssh.UnknownChannelType, "unsupported") + } + } + }() + return peer +} + +func awaitClosed(t *testing.T, closed <-chan struct{}) { + t.Helper() + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("transport did not close") + } +} + +func TestHostKeyPins(t *testing.T) { + for _, name := range []string{"missing", "mismatch", "match"} { + t.Run(name, func(t *testing.T) { + peer := startPeer(t, "") + cfg := peer.config + observed := cfg.HostKey + if name == "missing" { + cfg.HostKey = "" + } + if name == "mismatch" { + cfg.HostKey = "SHA256:wrong" + } + client, err := Dial(context.Background(), cfg) + if name == "match" { + if err != nil { + t.Fatal(err) + } + _ = client.Close() + } else if err == nil || !strings.Contains(err.Error(), observed) { + if client != nil { + _ = client.Close() + } + t.Fatalf("expected rejection containing observed fingerprint, got %v", err) + } + awaitClosed(t, peer.closed) + }) + } +} + +func TestJumpOwnsBothTransports(t *testing.T) { + target := startPeer(t, "") + jump := startPeer(t, "") + client, err := DialViaJump(context.Background(), jump.config, target.config) + if err != nil { + t.Fatal(err) + } + _ = client.Close() + _ = client.Close() + awaitClosed(t, target.closed) + awaitClosed(t, jump.closed) +} + +func TestJumpVerifiesTargetAndClosesOnFailure(t *testing.T) { + target := startPeer(t, "") + jump := startPeer(t, "") + cfg := target.config + cfg.HostKey = "" + client, err := DialViaJump(context.Background(), jump.config, cfg) + if client != nil { + _ = client.Close() + } + if err == nil || !strings.Contains(err.Error(), target.config.HostKey) { + t.Fatalf("unexpected result: %v", err) + } + awaitClosed(t, target.closed) + awaitClosed(t, jump.closed) +} + +func TestJumpVerifiesJumpBeforeForwarding(t *testing.T) { + jump := startPeer(t, "") + cfg := jump.config + cfg.HostKey = "" + _, err := DialViaJump(context.Background(), cfg, jump.config) + if err == nil || !strings.Contains(err.Error(), jump.config.HostKey) { + t.Fatalf("unexpected result: %v", err) + } + awaitClosed(t, jump.closed) +} + +func TestCancelledStalledHandshake(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + accepted := make(chan struct{}) + closed := make(chan struct{}) + go func() { + defer close(closed) + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + close(accepted) + _, _ = io.Copy(io.Discard, conn) + }() + host, port, _ := net.SplitHostPort(listener.Addr().String()) + n, _ := strconv.Atoi(port) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + result := make(chan error, 1) + go func() { + _, err := Dial(ctx, Config{Host: host, Port: n, Username: "test", AuthType: "password", Password: "test"}) + result <- err + }() + awaitClosed(t, accepted) + cancel() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Fatalf("want cancellation, got %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("handshake remained blocked") + } + awaitClosed(t, closed) +} + +func TestCancelledStalledJumpChannel(t *testing.T) { + jump := startPeer(t, "stall-forward") + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _, err := DialViaJump(ctx, jump.config, jump.config) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("want deadline exceeded, got %v", err) + } + awaitClosed(t, jump.closed) +} + +func TestCancelledSessionSetup(t *testing.T) { + for _, mode := range []string{"stall-session", "stall-pty"} { + t.Run(mode, func(t *testing.T) { + peer := startPeer(t, mode) + client, err := Dial(context.Background(), peer.config) + if err != nil { + t.Fatal(err) + } + defer client.Close() + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _, err = NewSession(ctx, client, 80, 24) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("want deadline exceeded, got %v", err) + } + awaitClosed(t, peer.closed) + }) + } +} + +func TestSessionCloseUnblocksReadAndWrite(t *testing.T) { + peer := startPeer(t, "") + client, err := Dial(context.Background(), peer.config) + if err != nil { + t.Fatal(err) + } + defer client.Close() + session, err := NewSession(context.Background(), client, 80, 24) + if err != nil { + t.Fatal(err) + } + writeDone := make(chan struct{}) + readDone := make(chan struct{}) + go func() { _ = session.Write(bytes.Repeat([]byte("x"), 8*1024*1024)); close(writeDone) }() + go func() { _, _ = session.Stdout().Read(make([]byte, 1)); close(readDone) }() + select { + case <-writeDone: + t.Fatal("test requires a blocked write") + case <-time.After(100 * time.Millisecond): + } + closeDone := make(chan struct{}) + go func() { session.Close(); close(closeDone) }() + awaitClosed(t, closeDone) + awaitClosed(t, writeDone) + awaitClosed(t, readDone) + awaitClosed(t, peer.closed) +} diff --git a/internal/sshclient/session.go b/internal/sshclient/session.go index 1326512..b9ebf20 100644 --- a/internal/sshclient/session.go +++ b/internal/sshclient/session.go @@ -1,6 +1,7 @@ package sshclient import ( + "context" "fmt" "io" "sync" @@ -11,103 +12,94 @@ import ( const defaultTerm = "xterm-256color" type Session struct { - client *ssh.Client + client *Client session *ssh.Session stdin io.WriteCloser stdout io.Reader stderr io.Reader - mu sync.Mutex - closed bool + once sync.Once + stop func() bool } -func NewSession(client *ssh.Client, cols, rows int) (*Session, error) { +func NewSession(ctx context.Context, client *Client, cols, rows int) (*Session, error) { + setup, cancel := context.WithTimeout(ctx, SetupTimeout) + defer cancel() + stop := context.AfterFunc(setup, func() { _ = client.Close() }) + defer stop() + sess, err := newSession(client, cols, rows) + if err != nil { + _ = client.Close() + if setup.Err() != nil { + return nil, setup.Err() + } + return nil, err + } + sess.stop = context.AfterFunc(ctx, func() { _ = client.Close() }) + if !stop() || setup.Err() != nil { + sess.Close() + return nil, setup.Err() + } + return sess, nil +} + +func newSession(client *Client, cols, rows int) (*Session, error) { sess, err := client.NewSession() if err != nil { return nil, fmt.Errorf("new session: %w", err) } - + fail := func(err error) (*Session, error) { + _ = client.Close() + _ = sess.Close() + return nil, err + } stdin, err := sess.StdinPipe() if err != nil { - sess.Close() - return nil, fmt.Errorf("stdin pipe: %w", err) + return fail(fmt.Errorf("stdin pipe: %w", err)) } - stdout, err := sess.StdoutPipe() if err != nil { - sess.Close() - return nil, fmt.Errorf("stdout pipe: %w", err) + return fail(fmt.Errorf("stdout pipe: %w", err)) } - stderr, err := sess.StderrPipe() if err != nil { - sess.Close() - return nil, fmt.Errorf("stderr pipe: %w", err) + return fail(fmt.Errorf("stderr pipe: %w", err)) } - if cols <= 0 { cols = 80 } if rows <= 0 { rows = 24 } - if err := sess.RequestPty(defaultTerm, rows, cols, ssh.TerminalModes{ - ssh.ECHO: 1, - ssh.TTY_OP_ISPEED: 14400, - ssh.TTY_OP_OSPEED: 14400, + ssh.ECHO: 1, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400, }); err != nil { - sess.Close() - return nil, fmt.Errorf("request pty: %w", err) + return fail(fmt.Errorf("request pty: %w", err)) } - if err := sess.Shell(); err != nil { - sess.Close() - return nil, fmt.Errorf("start shell: %w", err) + return fail(fmt.Errorf("start shell: %w", err)) } - - return &Session{ - client: client, - session: sess, - stdin: stdin, - stdout: stdout, - stderr: stderr, - }, nil + return &Session{client: client, session: sess, stdin: stdin, stdout: stdout, stderr: stderr}, nil } func (s *Session) Write(data []byte) error { - s.mu.Lock() - defer s.mu.Unlock() - if s.closed { - return io.EOF - } _, err := s.stdin.Write(data) return err } func (s *Session) Resize(cols, rows int) error { - s.mu.Lock() - defer s.mu.Unlock() - if s.closed { - return nil + if cols < 1 || rows < 1 || cols > 1000 || rows > 1000 { + return fmt.Errorf("invalid terminal dimensions") } return s.session.WindowChange(rows, cols) } -func (s *Session) Stdout() io.Reader { - return s.stdout -} - -func (s *Session) Stderr() io.Reader { - return s.stderr -} +func (s *Session) Stdout() io.Reader { return s.stdout } +func (s *Session) Stderr() io.Reader { return s.stderr } func (s *Session) Close() { - s.mu.Lock() - defer s.mu.Unlock() - if s.closed { - return - } - s.closed = true - s.session.Close() - s.client.Close() + s.once.Do(func() { + s.stop() + _ = s.client.Close() + _ = s.session.Close() + }) } diff --git a/internal/sshclient/session_test.go b/internal/sshclient/session_test.go new file mode 100644 index 0000000..2f1d230 --- /dev/null +++ b/internal/sshclient/session_test.go @@ -0,0 +1,60 @@ +package sshclient + +import ( + "bytes" + "context" + "testing" + "time" +) + +func TestSessionContextClosesLiveTransport(t *testing.T) { + peer := startPeer(t, "") + client, err := Dial(context.Background(), peer.config) + if err != nil { + t.Fatal(err) + } + defer client.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + session, err := NewSession(ctx, client, 80, 24) + if err != nil { + t.Fatal(err) + } + defer session.Close() + finished := make(chan struct{}) + go func() { _, _ = session.Stdout().Read(make([]byte, 1)); close(finished) }() + cancel() + select { + case <-finished: + case <-time.After(2 * time.Second): + t.Fatal("cancelled session read remained blocked") + } + awaitClosed(t, peer.closed) +} + +func TestJumpSessionCloseUnblocksWrite(t *testing.T) { + target := startPeer(t, "") + jump := startPeer(t, "") + client, err := DialViaJump(context.Background(), jump.config, target.config) + if err != nil { + t.Fatal(err) + } + defer client.Close() + session, err := NewSession(context.Background(), client, 80, 24) + if err != nil { + t.Fatal(err) + } + writeDone := make(chan struct{}) + go func() { _ = session.Write(bytes.Repeat([]byte("x"), 8*1024*1024)); close(writeDone) }() + select { + case <-writeDone: + t.Fatal("test requires blocked write") + case <-time.After(100 * time.Millisecond): + } + closeDone := make(chan struct{}) + go func() { session.Close(); close(closeDone) }() + awaitClosed(t, closeDone) + awaitClosed(t, writeDone) + awaitClosed(t, target.closed) + awaitClosed(t, jump.closed) +} diff --git a/internal/terminal/manager.go b/internal/terminal/manager.go index 6677524..9c6ef88 100644 --- a/internal/terminal/manager.go +++ b/internal/terminal/manager.go @@ -6,37 +6,53 @@ import ( "github.com/azzliang6/opsup/internal/sshclient" ) +type entry struct { + serverID int64 + session *sshclient.Session +} + type Manager struct { mu sync.Mutex - sessions map[string]*sshclient.Session + sessions map[string]entry } -func NewManager() *Manager { - return &Manager{ - sessions: make(map[string]*sshclient.Session), - } -} +func NewManager() *Manager { return &Manager{sessions: make(map[string]entry)} } -func (m *Manager) Register(id string, sess *sshclient.Session) { +func (m *Manager) Register(id string, sess *sshclient.Session, serverID ...int64) { + var sid int64 + if len(serverID) > 0 { + sid = serverID[0] + } m.mu.Lock() - defer m.mu.Unlock() - m.sessions[id] = sess + old, exists := m.sessions[id] + m.sessions[id] = entry{serverID: sid, session: sess} + m.mu.Unlock() + if exists && old.session != sess { + old.session.Close() + } } func (m *Manager) Unregister(id string) { m.mu.Lock() - defer m.mu.Unlock() - if s, ok := m.sessions[id]; ok { - s.Close() - delete(m.sessions, id) + old, exists := m.sessions[id] + delete(m.sessions, id) + m.mu.Unlock() + if exists { + old.session.Close() } } func (m *Manager) CloseAllForServer(serverID int64) { + var sessions []*sshclient.Session m.mu.Lock() - defer m.mu.Unlock() - for id, s := range m.sessions { - _ = s - delete(m.sessions, id) + for id, entry := range m.sessions { + if entry.serverID == serverID { + sessions = append(sessions, entry.session) + delete(m.sessions, id) + } + } + m.mu.Unlock() + for _, session := range sessions { + session.Close() } } diff --git a/main.go b/main.go index 70a0c44..7128898 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,17 @@ package main import ( + "context" "embed" + "errors" + "fmt" "log" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" "github.com/azzliang6/opsup/internal/api" "github.com/azzliang6/opsup/internal/config" @@ -13,26 +22,55 @@ import ( var distFS embed.FS func main() { + if err := run(); err != nil { + log.Fatal(err) + } +} + +func run() error { cfg, err := config.Load() if err != nil { - log.Fatalf("config error: %v", err) + return fmt.Errorf("config: %w", err) } - db, err := database.Init(cfg.DBPath) if err != nil { - log.Fatalf("database error: %v", err) + return fmt.Errorf("database: %w", err) } defer db.Close() + count, err := database.UpgradeCredentials(db, cfg.EncryptionKey) + if err != nil { + return fmt.Errorf("credential upgrade: %w", err) + } + if count > 0 { + log.Printf("migrated credentials for %d servers; back up the database and its encryption key together", count) + } - router := api.SetupRouter(api.AppConfig{ - JWTSecret: cfg.JWTSecret, - EncryptionKey: cfg.EncryptionKey, - DistFS: distFS, - DB: db, - }) - + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + server := &http.Server{ + Addr: cfg.Listen, + Handler: api.SetupRouter(api.AppConfig{ + JWTSecret: cfg.JWTSecret, EncryptionKey: cfg.EncryptionKey, DistFS: distFS, DB: db, + }), + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + BaseContext: func(net.Listener) context.Context { return ctx }, + } + errorsCh := make(chan error, 1) + go func() { errorsCh <- server.ListenAndServe() }() log.Printf("OpsUp starting on %s", cfg.Listen) - if err := router.Run(cfg.Listen); err != nil { - log.Fatalf("server error: %v", err) + select { + case err := <-errorsCh: + if !errors.Is(err, http.ErrServerClosed) { + return err + } + case <-ctx.Done(): + shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := server.Shutdown(shutdown); err != nil { + server.Close() + return fmt.Errorf("shutdown: %w", err) + } } + return nil } From b03257e698cabb3e6337b23a1018a390a2e4bff1 Mon Sep 17 00:00:00 2001 From: Keegan Bozde <112920194+azzliang6@users.noreply.github.com> Date: Fri, 11 Sep 2026 07:02:55 +0000 Subject: [PATCH 2/3] Optimize frontend loading and interaction reliability with CI --- .github/workflows/ci.yml | 43 + ui/package-lock.json | 1624 ++++++++++++++++--- ui/package.json | 14 +- ui/src/App.tsx | 8 +- ui/src/api/files.ts | 4 +- ui/src/components/FileManager.test.tsx | 22 + ui/src/components/FileManager.tsx | 99 +- ui/src/components/ServerFormModal.test.tsx | 42 + ui/src/components/ServerFormModal.tsx | 31 +- ui/src/components/ServerSidebar.tsx | 63 +- ui/src/components/TerminalTab.tsx | 257 +-- ui/src/components/TerminalTabs.test.tsx | 37 + ui/src/components/TerminalTabs.tsx | 268 +-- ui/src/contexts/ThemeContext.tsx | 2 +- ui/src/hooks/useDirectory.test.tsx | 93 ++ ui/src/hooks/useDirectory.ts | 55 + ui/src/hooks/useTerminalConnection.test.tsx | 155 ++ ui/src/hooks/useTerminalConnection.ts | 188 +++ ui/src/pages/LoginPage.tsx | 7 +- ui/src/pages/MainPage.tsx | 51 +- ui/src/pages/SetupPage.test.tsx | 27 + ui/src/pages/SetupPage.tsx | 13 +- ui/src/styles/global.css | 21 +- ui/src/test/setup.ts | 23 + ui/src/types/index.ts | 2 + ui/src/utils/hostKey.ts | 1 + ui/vite.config.ts | 2 +- ui/vitest.config.ts | 12 + 28 files changed, 2379 insertions(+), 785 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 ui/src/components/FileManager.test.tsx create mode 100644 ui/src/components/ServerFormModal.test.tsx create mode 100644 ui/src/components/TerminalTabs.test.tsx create mode 100644 ui/src/hooks/useDirectory.test.tsx create mode 100644 ui/src/hooks/useDirectory.ts create mode 100644 ui/src/hooks/useTerminalConnection.test.tsx create mode 100644 ui/src/hooks/useTerminalConnection.ts create mode 100644 ui/src/pages/SetupPage.test.tsx create mode 100644 ui/src/test/setup.ts create mode 100644 ui/src/utils/hostKey.ts create mode 100644 ui/vitest.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5d0030b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + cache-dependency-path: ui/package-lock.json + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Install frontend dependencies + working-directory: ui + run: npm ci + - name: Frontend tests + working-directory: ui + run: npm test + - name: Typecheck and build frontend + working-directory: ui + run: npm run build + - name: Check Go formatting + run: test -z "$(gofmt -l main.go internal)" + - name: Vet and race-test Go + run: | + go vet ./... + go test -race ./... + - name: Build binary + run: CGO_ENABLED=1 go build -trimpath -o opsup . + - name: Build container + run: docker build -t opsup:ci . diff --git a/ui/package-lock.json b/ui/package-lock.json index f373c12..ba6a653 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -20,13 +20,24 @@ "react-router-dom": "^7.14.1" }, "devDependencies": { + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.3", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.1", + "jsdom": "^26.1.0", "typescript": "^6.0.3", - "vite": "^8.0.9" + "vite": "^8.0.9", + "vitest": "^4.1.11" } }, + "node_modules/@adobe/css-tools": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@ant-design/colors": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/@ant-design/colors/-/colors-8.0.1.tgz", @@ -120,6 +131,47 @@ "react-dom": "^0.14.0 || ^15.0.1 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@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.npmjs.org/@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.2", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", @@ -129,38 +181,119 @@ "node": ">=6.9.0" } }, - "node_modules/@emnapi/core": { - "version": "1.9.2", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz", - "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==", + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" } }, - "node_modules/@emnapi/runtime": { - "version": "1.9.2", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz", - "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==", + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], "license": "MIT", - "optional": true, "dependencies": { - "tslib": "^2.4.0" + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" } }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" } }, "node_modules/@emotion/hash": { @@ -175,33 +308,21 @@ "integrity": "sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==", "license": "MIT" }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", - "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==", + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.1" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" - } + "license": "MIT" }, "node_modules/@oxc-project/types": { - "version": "0.126.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.126.0.tgz", - "integrity": "sha512-oGfVtjAgwQVVpfBrbtk4e1XDyWHRFta6BS3GWVzrF8xYBT2VGQAk39yJS/wFSMrZqoiCU4oghT3Ch0HaHGIHcQ==", + "version": "0.149.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz", + "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==", "dev": true, "license": "MIT", "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" } }, "node_modules/@rc-component/async-validator": { @@ -917,10 +1038,27 @@ "react-dom": ">=16.9.0" } }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz", + "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.16.tgz", - "integrity": "sha512-rhY3k7Bsae9qQfOtph2Pm2jZEA+s8Gmjoz4hhmx70K9iMQ/ddeae+xhRQcM5IuVx5ry1+bGfkvMn7D6MJggVSA==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz", + "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==", "cpu": [ "arm64" ], @@ -935,9 +1073,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.16.tgz", - "integrity": "sha512-rNz0yK078yrNn3DrdgN+PKiMOW8HfQ92jQiXxwX8yW899ayV00MLVdaCNeVBhG/TbH3ouYVObo8/yrkiectkcQ==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz", + "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==", "cpu": [ "arm64" ], @@ -952,9 +1090,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.16.tgz", - "integrity": "sha512-r/OmdR00HmD4i79Z//xO06uEPOq5hRXdhw7nzkxQxwSavs3PSHa1ijntdpOiZ2mzOQ3fVVu8C1M19FoNM+dMUQ==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz", + "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==", "cpu": [ "x64" ], @@ -969,9 +1107,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.16.tgz", - "integrity": "sha512-KcRE5w8h0OnjUatG8pldyD14/CQ5Phs1oxfR+3pKDjboHRo9+MkqQaiIZlZRpsxC15paeXme/I127tUa9TXJ6g==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz", + "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==", "cpu": [ "x64" ], @@ -986,9 +1124,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.16.tgz", - "integrity": "sha512-bT0guA1bpxEJ/ZhTRniQf7rNF8ybvXOuWbNIeLABaV5NGjx4EtOWBTSRGWFU9ZWVkPOZ+HNFP8RMcBokBiZ0Kg==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz", + "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==", "cpu": [ "arm" ], @@ -1003,9 +1141,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.16.tgz", - "integrity": "sha512-+tHktCHWV8BDQSjemUqm/Jl/TPk3QObCTIjmdDy/nlupcujZghmKK2962LYrqFpWu+ai01AN/REOH3NEpqvYQg==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz", + "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==", "cpu": [ "arm64" ], @@ -1023,9 +1161,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.16.tgz", - "integrity": "sha512-3fPzdREH806oRLxpTWW1Gt4tQHs0TitZFOECB2xzCFLPKnSOy90gwA7P29cksYilFO6XVRY1kzga0cL2nRjKPg==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz", + "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==", "cpu": [ "arm64" ], @@ -1043,9 +1181,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.16.tgz", - "integrity": "sha512-EKwI1tSrLs7YVw+JPJT/G2dJQ1jl9qlTTTEG0V2Ok/RdOenRfBw2PQdLPyjhIu58ocdBfP7vIRN/pvMsPxs/AQ==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz", + "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==", "cpu": [ "ppc64" ], @@ -1063,9 +1201,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.16.tgz", - "integrity": "sha512-Uknladnb3Sxqu6SEcqBldQyJUpk8NleooZEc0MbRBJ4inEhRYWZX0NJu12vNf2mqAq7gsofAxHrGghiUYjhaLQ==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz", + "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==", "cpu": [ "s390x" ], @@ -1083,9 +1221,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.16.tgz", - "integrity": "sha512-FIb8+uG49sZBtLTn+zt1AJ20TqVcqWeSIyoVt0or7uAWesgKaHbiBh6OpA/k9v0LTt+PTrb1Lao133kP4uVxkg==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz", + "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==", "cpu": [ "x64" ], @@ -1103,9 +1241,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.16.tgz", - "integrity": "sha512-RuERhF9/EgWxZEXYWCOaViUWHIboceK4/ivdtQ3R0T44NjLkIIlGIAVAuCddFxsZ7vnRHtNQUrt2vR2n2slB2w==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz", + "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==", "cpu": [ "x64" ], @@ -1123,9 +1261,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.16.tgz", - "integrity": "sha512-mXcXnvd9GpazCxeUCCnZ2+YF7nut+ZOEbE4GtaiPtyY6AkhZWbK70y1KK3j+RDhjVq5+U8FySkKRb/+w0EeUwA==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz", + "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==", "cpu": [ "arm64" ], @@ -1139,29 +1277,10 @@ "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.16.tgz", - "integrity": "sha512-3Q2KQxnC8IJOLqXmUMoYwyIPZU9hzRbnHaoV3Euz+VVnjZKcY8ktnNP8T9R4/GGQtb27C/UYKABxesKWb8lsvQ==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.9.2", - "@emnapi/runtime": "1.9.2", - "@napi-rs/wasm-runtime": "^1.1.4" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.16.tgz", - "integrity": "sha512-tj7XRemQcOcFwv7qhpUxMTBbI5mWMlE4c1Omhg5+h8GuLXzyj8HviYgR+bB2DMDgRqUE+jiDleqSCRjx4aYk/Q==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz", + "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==", "cpu": [ "arm64" ], @@ -1176,9 +1295,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.16.tgz", - "integrity": "sha512-PH5DRZT+F4f2PTXRXR8uJxnBq2po/xFtddyabTJVJs/ZYVHqXPEgNIr35IHTEa6bpa0Q8Awg+ymkTaGnKITw4g==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz", + "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==", "cpu": [ "x64" ], @@ -1199,17 +1318,122 @@ "dev": true, "license": "MIT" }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", - "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/dom": { + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", + "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==", + "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": "6.9.1", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz", + "integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==", + "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": ">=14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/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.npmjs.org/@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.npmjs.org/@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.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", "dev": true, "license": "MIT", - "optional": true, "dependencies": { - "tslib": "^2.4.0" + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@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.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/react": { "version": "19.2.14", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", @@ -1256,6 +1480,119 @@ } } }, + "node_modules/@vitest/expect": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.11", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "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/pretty-format": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.11", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xterm/addon-fit": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", @@ -1277,6 +1614,43 @@ "addons/*" ] }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/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.npmjs.org/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/antd": { "version": "6.3.6", "resolved": "https://registry.npmjs.org/antd/-/antd-6.3.6.tgz", @@ -1341,20 +1715,41 @@ "react-dom": ">=18.0.0" } }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/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.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "license": "MIT" }, "node_modules/axios": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.1.tgz", - "integrity": "sha512-WOG+Jj8ZOvR0a3rAn+Tuf1UQJRxw5venr6DgdbJzngJE3qG7X0kL83CZGpdHMxEm+ZK3seAbvFsw4FfOfP9vxg==", + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.11", - "form-data": "^4.0.5", + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, @@ -1371,6 +1766,16 @@ "node": ">= 0.4" } }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -1398,6 +1803,13 @@ "integrity": "sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==", "license": "MIT" }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, "node_modules/cookie": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", @@ -1411,18 +1823,77 @@ "url": "https://opencollective.com/express" } }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/dayjs": { "version": "1.11.20", "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.20.tgz", "integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==", "license": "MIT" }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -1432,6 +1903,16 @@ "node": ">=0.4.0" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/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.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1442,6 +1923,14 @@ "node": ">=8" } }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -1456,6 +1945,19 @@ "node": ">= 0.4" } }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -1474,10 +1976,17 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -1501,6 +2010,26 @@ "node": ">= 0.4" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/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.npmjs.org/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.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -1540,16 +2069,16 @@ } }, "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -1656,9 +2185,9 @@ } }, "node_modules/hasown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", - "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -1667,12 +2196,164 @@ "node": ">= 0.4" } }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-mobile": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/is-mobile/-/is-mobile-5.0.0.tgz", "integrity": "sha512-Tz/yndySvLAEXh+Uk8liFCxOwVH6YutuR74utvOcu7I9Di+DwM0mtdPVZNaVvvBUM2OXxne/NhOs1zAO7riusQ==", "license": "MIT" }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/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.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/jsdom/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/json2mq": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/json2mq/-/json2mq-0.2.0.tgz", @@ -1683,9 +2364,9 @@ } }, "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", "dependencies": { @@ -1699,23 +2380,23 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" + "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.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", "cpu": [ "arm64" ], @@ -1734,9 +2415,9 @@ } }, "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", "cpu": [ "arm64" ], @@ -1755,9 +2436,9 @@ } }, "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", "cpu": [ "x64" ], @@ -1776,9 +2457,9 @@ } }, "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", "cpu": [ "x64" ], @@ -1797,9 +2478,9 @@ } }, "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", "cpu": [ "arm" ], @@ -1818,9 +2499,9 @@ } }, "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", "cpu": [ "arm64" ], @@ -1842,9 +2523,9 @@ } }, "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", "cpu": [ "arm64" ], @@ -1866,9 +2547,9 @@ } }, "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", "cpu": [ "x64" ], @@ -1890,9 +2571,9 @@ } }, "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", "cpu": [ "x64" ], @@ -1914,9 +2595,9 @@ } }, "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", "cpu": [ "arm64" ], @@ -1935,9 +2616,9 @@ } }, "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", "cpu": [ "x64" ], @@ -1955,6 +2636,34 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/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": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1985,10 +2694,26 @@ "node": ">= 0.6" } }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", "dev": true, "funding": [ { @@ -2004,6 +2729,47 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/nwsapi": { + "version": "2.2.27", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.27.tgz", + "integrity": "sha512-gQPNF78qebCQ6tvVFBYrvJdBNOrYZm90ZlXgpIFm06p6qHDHq/XC4TnJftN6OMbxVE0UTBAoRgcsDeJBBooITw==", + "dev": true, + "license": "MIT" + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/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": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2012,9 +2778,9 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -2025,9 +2791,9 @@ } }, "node_modules/postcss": { - "version": "8.5.10", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.10.tgz", - "integrity": "sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==", + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", "dev": true, "funding": [ { @@ -2045,7 +2811,7 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.11", + "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -2053,6 +2819,30 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/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/pretty-format/node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -2062,6 +2852,16 @@ "node": ">=10" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/react": { "version": "19.2.5", "resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz", @@ -2090,9 +2890,9 @@ "license": "MIT" }, "node_modules/react-router": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.14.1.tgz", - "integrity": "sha512-5BCvFskyAAVumqhEKh/iPhLOIkfxcEUz8WqFIARCkMg8hZZzDYX9CtwxXA0e+qT8zAxmMC0x3Ckb9iMONwc5jg==", + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.3.tgz", + "integrity": "sha512-gyXgtdr5uACJ5b1Q4udzjVV+tb/rlHIMJKuJ0e89R4Kzgz47z/rgP0dIKxktqIEUhDHluGTPJJH/wRha7CyqsA==", "license": "MIT", "dependencies": { "cookie": "^1.0.1", @@ -2112,12 +2912,12 @@ } }, "node_modules/react-router-dom": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.14.1.tgz", - "integrity": "sha512-ZkrQuwwhGibjQLqH1eCdyiZyLWglPxzxdl5tgwgKEyCSGC76vmAjleGocRe3J/MLfzMUIKwaFJWpFVJhK3d2xA==", + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.3.tgz", + "integrity": "sha512-ytVbyBBM7vMfRCam25r0WMhSVSom909A8p+8m0/f1w853dz/xfFu6etAT2SEbVoSnI+ZoPRDqIsQXVT89gp7kg==", "license": "MIT", "dependencies": { - "react-router": "7.14.1" + "react-router": "7.18.3" }, "engines": { "node": ">=20.0.0" @@ -2127,15 +2927,29 @@ "react-dom": ">=18" } }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/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/rolldown": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.16.tgz", - "integrity": "sha512-rzi5WqKzEZw3SooTt7cgm4eqIoujPIyGcJNGFL7iPEuajQw7vxMHUkXylu4/vhCkJGXsgRmxqMKXUpT6FEgl0g==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", + "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.126.0", - "@rolldown/pluginutils": "1.0.0-rc.16" + "@oxc-project/types": "=0.149.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { "rolldown": "bin/cli.mjs" @@ -2144,30 +2958,57 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.16", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.16", - "@rolldown/binding-darwin-x64": "1.0.0-rc.16", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.16", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.16", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.16", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.16", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.16", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.16", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.16", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.16", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.16", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.16", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.16", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.16" + "@rolldown/binding-android-arm-eabi": "1.2.8", + "@rolldown/binding-android-arm64": "1.2.8", + "@rolldown/binding-darwin-arm64": "1.2.8", + "@rolldown/binding-darwin-x64": "1.2.8", + "@rolldown/binding-freebsd-x64": "1.2.8", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", + "@rolldown/binding-linux-arm64-gnu": "1.2.8", + "@rolldown/binding-linux-arm64-musl": "1.2.8", + "@rolldown/binding-linux-ppc64-gnu": "1.2.8", + "@rolldown/binding-linux-s390x-gnu": "1.2.8", + "@rolldown/binding-linux-x64-gnu": "1.2.8", + "@rolldown/binding-linux-x64-musl": "1.2.8", + "@rolldown/binding-openharmony-arm64": "1.2.8", + "@rolldown/binding-win32-arm64-msvc": "1.2.8", + "@rolldown/binding-win32-x64-msvc": "1.2.8" } }, "node_modules/rolldown/node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.16", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.16.tgz", - "integrity": "sha512-45+YtqxLYKDWQouLKCrpIZhke+nXxhsw+qAHVzHDVwttyBlHNBVs2K25rDXrZzhpTp9w1FlAlvweV1H++fdZoA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, "license": "MIT" }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/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.27.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", @@ -2189,6 +3030,13 @@ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", "license": "MIT" }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -2199,18 +3047,52 @@ "node": ">=0.10.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, "node_modules/string-convert": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/string-convert/-/string-convert-0.2.1.tgz", "integrity": "sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A==", "license": "MIT" }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/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/stylis": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.4.0.tgz", "integrity": "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==", "license": "MIT" }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/throttle-debounce": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-5.0.2.tgz", @@ -2220,10 +3102,27 @@ "node": ">=12.22" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/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.16", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", - "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "dev": true, "license": "MIT", "dependencies": { @@ -2237,13 +3136,61 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "node_modules/tinyrainbow": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", + "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", "dev": true, - "license": "0BSD", - "optional": true + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } }, "node_modules/typescript": { "version": "6.0.3", @@ -2260,17 +3207,17 @@ } }, "node_modules/vite": { - "version": "8.0.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.9.tgz", - "integrity": "sha512-t7g7GVRpMXjNpa67HaVWI/8BWtdVIQPCL2WoozXXA7LBGEFK4AkkKkHx2hAQf5x1GZSlcmEDPkVLSGahxnEEZw==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", + "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", "dev": true, "license": "MIT", "dependencies": { - "lightningcss": "^1.32.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.10", - "rolldown": "1.0.0-rc.16", - "tinyglobby": "^0.2.16" + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.6", + "tinyglobby": "^0.2.17" }, "bin": { "vite": "bin/vite.js" @@ -2286,7 +3233,7 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.1.0", + "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", @@ -2336,6 +3283,213 @@ "optional": true } } + }, + "node_modules/vitest": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.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": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/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.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" } } } diff --git a/ui/package.json b/ui/package.json index 5b5b46f..63dd420 100644 --- a/ui/package.json +++ b/ui/package.json @@ -5,13 +5,15 @@ "main": "index.js", "scripts": { "dev": "vite", - "build": "vite build", - "preview": "vite preview" + "build": "npm run typecheck && vite build", + "preview": "vite preview", + "typecheck": "tsc --noEmit", + "test": "vitest run" }, "keywords": [], "author": "", "license": "ISC", - "type": "commonjs", + "type": "module", "dependencies": { "@ant-design/icons": "^6.1.1", "@xterm/addon-fit": "^0.11.0", @@ -24,10 +26,14 @@ "react-router-dom": "^7.14.1" }, "devDependencies": { + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.3", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.1", + "jsdom": "^26.1.0", "typescript": "^6.0.3", - "vite": "^8.0.9" + "vite": "^8.0.9", + "vitest": "^4.1.11" } } diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 517fe35..73b052d 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -1,8 +1,10 @@ +import { lazy, Suspense } from 'react' +import Spin from 'antd/es/spin' import { Routes, Route, Navigate } from 'react-router-dom' -import { ConfigProvider } from 'antd' +import ConfigProvider from 'antd/es/config-provider' import LoginPage from './pages/LoginPage' import SetupPage from './pages/SetupPage' -import MainPage from './pages/MainPage' +const MainPage = lazy(() => import('./pages/MainPage')) import { ThemeProvider, useTheme } from './contexts/ThemeContext' function PrivateRoute({ children }: { children: React.ReactNode }) { @@ -21,7 +23,7 @@ function ThemedApp() { path="/*" element={ - + }> } /> diff --git a/ui/src/api/files.ts b/ui/src/api/files.ts index 4657d4f..647d70f 100644 --- a/ui/src/api/files.ts +++ b/ui/src/api/files.ts @@ -9,8 +9,8 @@ export interface FileEntry { path: string } -export function listFiles(serverId: number, path: string = '/') { - return client.get(`/servers/${serverId}/files`, { params: { path } }) +export function listFiles(serverId: number, path: string = '/', signal?: AbortSignal) { + return client.get(`/servers/${serverId}/files`, { params: { path }, signal }) } export function uploadFile(serverId: number, dirPath: string, file: File) { diff --git a/ui/src/components/FileManager.test.tsx b/ui/src/components/FileManager.test.tsx new file mode 100644 index 0000000..5f4fc8b --- /dev/null +++ b/ui/src/components/FileManager.test.tsx @@ -0,0 +1,22 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { beforeEach, expect, it, vi } from 'vitest' +import FileManager from './FileManager' +import { ThemeProvider } from '../contexts/ThemeContext' +import * as filesApi from '../api/files' + +vi.mock('../api/files', () => ({ listFiles: vi.fn(), deleteFile: vi.fn(), uploadFile: vi.fn(), createDir: vi.fn(), downloadFile: vi.fn() })) +beforeEach(() => vi.mocked(filesApi.listFiles).mockReset()) + +it('paginates large directories and exposes folders as keyboard buttons', async () => { + const entries = Array.from({ length: 125 }, (_, index) => ({ name: `folder-${index}`, path: `/folder-${index}`, isDir: true, mode: '', modTime: '', size: 0 })) + vi.mocked(filesApi.listFiles).mockResolvedValue({ data: entries } as any) + render( {}} />) + expect(await screen.findByText('folder-0')).toBeEnabled() + expect(screen.queryByText('folder-50')).not.toBeInTheDocument() + fireEvent.click(screen.getByTitle('2')) + expect(await screen.findByText('folder-50')).toBeInTheDocument() + expect(screen.queryByText('folder-0')).not.toBeInTheDocument() + fireEvent.click(screen.getByText('folder-50')) + await waitFor(() => expect(filesApi.listFiles).toHaveBeenLastCalledWith(1, '/folder-50', expect.any(AbortSignal))) + expect(screen.getByLabelText('目录路径')).toHaveValue('/folder-50') +}) diff --git a/ui/src/components/FileManager.tsx b/ui/src/components/FileManager.tsx index 5626c1f..2be258a 100644 --- a/ui/src/components/FileManager.tsx +++ b/ui/src/components/FileManager.tsx @@ -1,5 +1,12 @@ import { useEffect, useState, useRef } from 'react' -import { Modal, Table, Button, Input, message, Upload, Space, Tooltip, Popconfirm } from 'antd' +import Modal from 'antd/es/modal' +import Table from 'antd/es/table' +import Button from 'antd/es/button' +import Input from 'antd/es/input' +import message from 'antd/es/message' +import Space from 'antd/es/space' +import Tooltip from 'antd/es/tooltip' +import Popconfirm from 'antd/es/popconfirm' import { FolderOutlined, FileOutlined, @@ -10,6 +17,7 @@ import { ReloadOutlined, HomeOutlined, } from '@ant-design/icons' +import { useDirectory } from '../hooks/useDirectory' import * as filesApi from '../api/files' import type { FileEntry } from '../api/files' import { useTheme } from '../contexts/ThemeContext' @@ -41,41 +49,16 @@ function formatTime(t: string): string { export default function FileManager({ open, serverId, serverName, onClose }: Props) { const { colors } = useTheme() - const [files, setFiles] = useState([]) - const [currentPath, setCurrentPath] = useState('/') - const [loading, setLoading] = useState(false) + const { files, currentPath, loading, ready, loadFiles, capture } = useDirectory(open, serverId) const [pathInput, setPathInput] = useState('/') - const [selectedRows, setSelectedRows] = useState>(new Set()) const [uploading, setUploading] = useState(false) + const [page, setPage] = useState(1) const fileInputRef = useRef(null) - - const loadFiles = async (dirPath: string) => { - setLoading(true) - try { - const res = await filesApi.listFiles(serverId, dirPath) - setFiles(res.data || []) - setCurrentPath(dirPath) - setPathInput(dirPath) - } catch (e: any) { - message.error(e.response?.data?.error || '加载文件列表失败') - } finally { - setLoading(false) - } - } - - useEffect(() => { - if (open) { - loadFiles('/') - } - }, [open, serverId]) - - const navigateTo = (dirPath: string) => { - loadFiles(dirPath) - setSelectedRows(new Set()) - } + useEffect(() => { setPathInput(currentPath); setPage(1) }, [currentPath, serverId, open]) + const navigateTo = (path: string) => { void loadFiles(path) } const handleNavigate = (record: FileEntry) => { - if (record.isDir) { + if (ready && record.isDir && capture().isCurrent()) { navigateTo(record.path) } } @@ -87,14 +70,18 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro } const handleUpload = async (e: React.ChangeEvent) => { - const fileList = e.target.files + if (!ready) return + const target = capture() + if (!target.isCurrent()) return + const input = e.target + const fileList = input.files if (!fileList || fileList.length === 0) return setUploading(true) let success = 0 for (let i = 0; i < fileList.length; i++) { try { - await filesApi.uploadFile(serverId, currentPath, fileList[i]) + await filesApi.uploadFile(target.serverId, target.path, fileList[i]) success++ } catch (e: any) { message.error(`${fileList[i].name}: ${e.response?.data?.error || '上传失败'}`) @@ -102,13 +89,14 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro } if (success > 0) { message.success(`已上传 ${success} 个文件`) - loadFiles(currentPath) + target.refresh() } setUploading(false) - e.target.value = '' + input.value = '' } const handleDownload = async (record: FileEntry) => { + if (!ready || !capture().isCurrent()) return try { const res = await filesApi.downloadFile(serverId, record.path) const url = URL.createObjectURL(res.data) @@ -123,16 +111,22 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro } const handleDelete = async (record: FileEntry) => { + if (!ready || !files.some(file => file.path === record.path)) return + const target = capture() + if (!target.isCurrent()) return try { await filesApi.deleteFile(serverId, record.path) message.success('已删除') - loadFiles(currentPath) + target.refresh() } catch (e: any) { message.error(e.response?.data?.error || '删除失败') } } const handleMkdir = async () => { + if (!ready) return + const target = capture() + if (!target.isCurrent()) return const dirName = await new Promise((resolve) => { let value = '' Modal.confirm({ @@ -152,11 +146,11 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro }) }) - if (dirName) { + if (dirName && target.isCurrent()) { try { - await filesApi.createDir(serverId, currentPath === '/' ? `/${dirName}` : `${currentPath}/${dirName}`) + await filesApi.createDir(target.serverId, target.path === '/' ? `/${dirName}` : `${target.path}/${dirName}`) message.success('已创建') - loadFiles(currentPath) + target.refresh() } catch (e: any) { message.error(e.response?.data?.error || '创建失败') } @@ -172,7 +166,10 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro dataIndex: 'name', key: 'name', render: (name: string, record: FileEntry) => ( -
handleNavigate(record)} style={{ cursor: record.isDir ? 'pointer' : 'default', @@ -189,7 +186,7 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro {name} -
+ ), }, { @@ -214,12 +211,12 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro handleDelete(record)} okText="删除" cancelText="取消"> - {pathParts.map((part, i) => { const fullPath = '/' + pathParts.slice(0, i + 1).join('/') return ( / - navigateTo(fullPath)}> + ) })} @@ -270,10 +268,10 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro {/* Toolbar */}
- - @@ -286,7 +284,8 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro rowKey="path" loading={loading} size="small" - pagination={false} + pagination={{ current: page, pageSize: 50, showSizeChanger: false, onChange: setPage, showTotal: total => `共 ${total} 项` }} + scroll={{ x: 560, y: '45vh' }} style={{ maxHeight: '50vh', overflow: 'auto' }} onRow={(record) => ({ onDoubleClick: () => handleNavigate(record), diff --git a/ui/src/components/ServerFormModal.test.tsx b/ui/src/components/ServerFormModal.test.tsx new file mode 100644 index 0000000..d1033ad --- /dev/null +++ b/ui/src/components/ServerFormModal.test.tsx @@ -0,0 +1,42 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { beforeEach, expect, it, vi } from 'vitest' +import ServerFormModal from './ServerFormModal' +import { ThemeProvider } from '../contexts/ThemeContext' +import { HOST_KEY_PATTERN } from '../utils/hostKey' +import * as serverApi from '../api/servers' +import type { Server } from '../types' + +vi.mock('../api/servers', () => ({ listServers: vi.fn(), updateServer: vi.fn(), createServer: vi.fn() })) +const fingerprint = `SHA256:${'a'.repeat(43)}` +const server: Server = { id: 1, name: 'test', host: 'localhost', host_key: fingerprint, port: 22, username: 'root', auth_type: 'password', description: '', group: '', jump_server_id: null, created_at: '', updated_at: '' } +beforeEach(() => { + vi.mocked(serverApi.listServers).mockResolvedValue([]) + vi.mocked(serverApi.updateServer).mockReset().mockResolvedValue(server) +}) +function form() { return render( {}} onCancel={() => {}} />) } + +it('preserves the saved fingerprint on edit and explains independent verification', async () => { + form() + expect(screen.getByLabelText('SSH 主机密钥指纹')).toHaveValue(fingerprint) + expect(screen.getByText('ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub')).toBeInTheDocument() + expect(screen.getByText(/请勿直接信任或自动接受/)).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: '更 新' })) + await waitFor(() => expect(serverApi.updateServer).toHaveBeenCalledWith(1, expect.objectContaining({ host_key: fingerprint }))) +}) + +it('rejects malformed fingerprints but allows an empty saved value', async () => { + form() + fireEvent.change(screen.getByLabelText('SSH 主机密钥指纹'), { target: { value: 'SHA256:invalid' } }) + fireEvent.click(screen.getByRole('button', { name: '更 新' })) + expect(await screen.findByText('请输入 SHA256: 后跟 43 位 Base64 字符的指纹')).toBeInTheDocument() + expect(serverApi.updateServer).not.toHaveBeenCalled() + fireEvent.change(screen.getByLabelText('SSH 主机密钥指纹'), { target: { value: '' } }) + fireEvent.click(screen.getByRole('button', { name: '更 新' })) + await waitFor(() => expect(serverApi.updateServer).toHaveBeenCalledWith(1, expect.objectContaining({ host_key: '' }))) +}) + +it('validates the exact backend fingerprint format', () => { + expect(HOST_KEY_PATTERN.test(fingerprint)).toBe(true) + expect(HOST_KEY_PATTERN.test(`SHA256:${'+/'.repeat(21)}a`)).toBe(true) + for (const value of ['SHA256:abc', `${fingerprint}=`, fingerprint.toLowerCase(), `SHA256:${'a'.repeat(44)}`, `SHA256:${'_'.repeat(43)}`]) expect(HOST_KEY_PATTERN.test(value)).toBe(false) +}) diff --git a/ui/src/components/ServerFormModal.tsx b/ui/src/components/ServerFormModal.tsx index 3870a47..542364e 100644 --- a/ui/src/components/ServerFormModal.tsx +++ b/ui/src/components/ServerFormModal.tsx @@ -1,8 +1,17 @@ import { useEffect, useState, useRef } from 'react' -import { Modal, Form, Input, InputNumber, Select, Button, Radio, AutoComplete, message } from 'antd' +import Modal from 'antd/es/modal' +import Form from 'antd/es/form' +import Input from 'antd/es/input' +import InputNumber from 'antd/es/input-number' +import Select from 'antd/es/select' +import Button from 'antd/es/button' +import Radio from 'antd/es/radio' +import AutoComplete from 'antd/es/auto-complete' +import message from 'antd/es/message' import { CopyOutlined, EditOutlined, SwapOutlined, UploadOutlined, KeyOutlined, LockOutlined } from '@ant-design/icons' import * as serverApi from '../api/servers' import { useTheme } from '../contexts/ThemeContext' +import { HOST_KEY_PATTERN } from '../utils/hostKey' import type { Server, ServerForm } from '../types' interface Props { @@ -48,13 +57,15 @@ export default function ServerFormModal({ open, server, onOk, onCancel }: Props) } useEffect(() => { + let active = true if (open) { - serverApi.listServers().then((list) => setExistingServers(list || [])) + serverApi.listServers().then((list) => { if (active) setExistingServers(list || []) }).catch(() => { if (active) message.error('加载服务器列表失败') }) if (server) { form.setFieldsValue({ name: server.name, host: server.host, + host_key: server.host_key || '', port: server.port, username: server.username, auth_type: server.auth_type || 'key', @@ -72,7 +83,7 @@ export default function ServerFormModal({ open, server, onOk, onCancel }: Props) setJumpServerId(server.jump_server_id || null) } else { form.resetFields() - form.setFieldsValue({ port: 22, auth_type: 'key' }) + form.setFieldsValue({ port: 22, auth_type: 'key', host_key: '' }) setAuthType('key') setKeySource(existingServers.length > 0 ? 'reuse' : 'new') setReuseServerId(null) @@ -80,12 +91,14 @@ export default function ServerFormModal({ open, server, onOk, onCancel }: Props) setJumpServerId(null) } } + return () => { active = false } }, [open, server, form]) const handleSubmit = async () => { try { const values = await form.validateFields() values.auth_type = authType + values.host_key = (values.host_key || '').trim() if (authType === 'password') { values.private_key = '' @@ -170,6 +183,16 @@ export default function ServerFormModal({ open, server, onOk, onCancel }: Props) + value.trim()} + rules={[{ pattern: HOST_KEY_PATTERN, message: '请输入 SHA256: 后跟 43 位 Base64 字符的指纹' }]} + extra={可留空保存,但未验证指纹时无法连接。请通过独立可信控制台核对主机公钥,例如 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub。实际协商也可能使用 ECDSA 或 RSA,需核对对应公钥文件的 SHA256 指纹。连接错误中的观测指纹仅供比对,请勿直接信任或自动接受。} + > + + + {/* Auth type selector */} - option?.value?.toLowerCase().includes(input.toLowerCase()) + option?.value?.toLowerCase().includes(input.toLowerCase()) ?? false } /> diff --git a/ui/src/components/ServerSidebar.tsx b/ui/src/components/ServerSidebar.tsx index a30996d..f9c1df3 100644 --- a/ui/src/components/ServerSidebar.tsx +++ b/ui/src/components/ServerSidebar.tsx @@ -1,7 +1,14 @@ -import { useState, useEffect, useCallback } from 'react' -import { Input, Button, Modal, message, Empty, Spin } from 'antd' +import { useState, useEffect, useCallback, lazy, Suspense } from 'react' +import Input from 'antd/es/input' +import Button from 'antd/es/button' +import Modal from 'antd/es/modal' +import message from 'antd/es/message' +import Empty from 'antd/es/empty' +import Spin from 'antd/es/spin' +import Dropdown from 'antd/es/dropdown' import { PlusOutlined, + MoreOutlined, SearchOutlined, DesktopOutlined, EditOutlined, @@ -13,10 +20,10 @@ import { RightOutlined, DownOutlined, } from '@ant-design/icons' -import { theme } from 'antd' +import theme from 'antd/es/theme' import * as serverApi from '../api/servers' -import ServerFormModal from './ServerFormModal' -import FileManager from './FileManager' +const ServerFormModal = lazy(() => import('./ServerFormModal')) +const FileManager = lazy(() => import('./FileManager')) import { useTheme } from '../contexts/ThemeContext' import type { Server } from '../types' @@ -187,7 +194,9 @@ export default function ServerSidebar({ onConnect }: Props) { {groups.map((group) => (
{/* Group header */} -
toggleGroup(group.name)} style={{ display: 'flex', @@ -203,10 +212,10 @@ export default function ServerSidebar({ onConnect }: Props) { letterSpacing: '0.3px', }} onMouseEnter={(e) => { - ;(e.currentTarget as HTMLDivElement).style.background = colors.fillSubtle + ;(e.currentTarget).style.background = colors.fillSubtle }} onMouseLeave={(e) => { - ;(e.currentTarget as HTMLDivElement).style.background = 'transparent' + ;(e.currentTarget).style.background = 'transparent' }} > {collapsed[group.name] ? ( @@ -217,7 +226,7 @@ export default function ServerSidebar({ onConnect }: Props) { {group.name} ({group.servers.length}) -
+ {/* Group servers */} {!collapsed[group.name] && ( @@ -225,7 +234,6 @@ export default function ServerSidebar({ onConnect }: Props) { {group.servers.map((server) => (
onConnect(server)} onContextMenu={(e) => handleContextMenu(e, server)} style={{ padding: '8px 12px', @@ -237,12 +245,13 @@ export default function ServerSidebar({ onConnect }: Props) { marginLeft: 12, }} onMouseEnter={(e) => { - ;(e.currentTarget as HTMLDivElement).style.background = colors.fillHover + ;(e.currentTarget).style.background = colors.fillHover }} onMouseLeave={(e) => { - ;(e.currentTarget as HTMLDivElement).style.background = colors.fillSubtle + ;(e.currentTarget).style.background = colors.fillSubtle }} > + +
+
))}
@@ -262,7 +283,7 @@ export default function ServerSidebar({ onConnect }: Props) {
)} - 加载服务器表单…}> + />} {/* Context Menu */} {contextMenu && ( @@ -300,12 +321,12 @@ export default function ServerSidebar({ onConnect }: Props) { {/* File Manager Modal */} {fileManagerServer && ( - 加载文件管理…}> setFileManagerServer(null)} - /> + /> )} ) @@ -313,9 +334,11 @@ export default function ServerSidebar({ onConnect }: Props) { function CtxItem({ icon, label, danger, colors, onClick }: { icon: React.ReactNode; label: string; danger?: boolean; colors: any; onClick: () => void }) { return ( -
((e.target as HTMLDivElement).style.background = danger ? 'rgba(255,77,79,0.1)' : colors.fillHover)} - onMouseLeave={(e) => ((e.target as HTMLDivElement).style.background = 'transparent')} + onMouseEnter={(e) => ((e.currentTarget).style.background = danger ? 'rgba(255,77,79,0.1)' : colors.fillHover)} + onMouseLeave={(e) => ((e.currentTarget).style.background = 'transparent')} > {icon} {label} -
+ ) } diff --git a/ui/src/components/TerminalTab.tsx b/ui/src/components/TerminalTab.tsx index a111eaf..551850c 100644 --- a/ui/src/components/TerminalTab.tsx +++ b/ui/src/components/TerminalTab.tsx @@ -1,26 +1,18 @@ -import { useEffect, useRef, useState, useCallback, useMemo } from 'react' -import { Terminal } from '@xterm/xterm' -import { FitAddon } from '@xterm/addon-fit' -import { WebLinksAddon } from '@xterm/addon-web-links' -import { Spin, Button } from 'antd' +import { useEffect, useState, useMemo } from 'react' +import { useTerminalConnection, type ConnectionStatus } from '../hooks/useTerminalConnection' +import Spin from 'antd/es/spin' +import Button from 'antd/es/button' import { ReloadOutlined, DisconnectOutlined } from '@ant-design/icons' import '@xterm/xterm/css/xterm.css' import '../styles/terminal.css' import { useTheme } from '../contexts/ThemeContext' -const MSG_STDIN = 0x00 -const MSG_RESIZE = 0x01 -const MSG_STDOUT = 0x00 -const MSG_STDERR = 0x01 -const MSG_ERROR = 0x02 -const MSG_STATUS = 0x03 -const MSG_CONNECTED = 0x04 - interface Props { serverId: number serverName: string isActive: boolean fontSize: number + onStatusChange?: (status: ConnectionStatus) => void } const TERM_THEMES = { @@ -118,230 +110,16 @@ const SHORTCUTS = [ { label: 'Ctrl+R', data: '\x12' }, ] -export default function TerminalTab({ serverId, serverName, isActive, fontSize }: Props) { - const containerRef = useRef(null) - const termRef = useRef(null) - const wsRef = useRef(null) - const fitAddonRef = useRef(null) - const closedRef = useRef(false) - const [status, setStatus] = useState<'connecting' | 'connected' | 'error'>('connecting') - const [errorMsg, setErrorMsg] = useState('') +export default function TerminalTab({ serverId, serverName, isActive, fontSize, onStatusChange }: Props) { const { mode, colors } = useTheme() const [showBar, setShowBar] = useState(true) - - const sendShortcut = useCallback((data: string) => { - const ws = wsRef.current - if (!ws || ws.readyState !== WebSocket.OPEN) return - const encoder = new TextEncoder() - const dataBytes = encoder.encode(data) - const msg = new Uint8Array(1 + dataBytes.length) - msg[0] = MSG_STDIN - msg.set(dataBytes, 1) - ws.send(msg) - }, []) - - const termTheme = useMemo(() => { - const base = { ...TERM_THEMES[mode] } - base.cursor = colors.colorPrimary - const rgb = hexToRgb(colors.colorPrimary) - base.selectionBackground = mode === 'dark' - ? `rgba(${rgb}, 0.3)` - : `rgba(${rgb}, 0.15)` - return base - }, [mode, colors.colorPrimary]) - - const doFit = useCallback(() => { - if (!fitAddonRef.current || !termRef.current) return - try { - fitAddonRef.current.fit() - } catch { - // ignore - } - }, []) - - const connect = useCallback(() => { - closedRef.current = false - - if (!containerRef.current) return - - const token = localStorage.getItem('opsup_token') - if (!token) { - setErrorMsg('未登录,请重新登录') - setStatus('error') - return - } - - const wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:' - const wsUrl = `${wsProto}//${window.location.host}/api/terminal/${serverId}?token=${token}` - - // Dispose old terminal if exists - if (termRef.current) { - termRef.current.dispose() - termRef.current = null - } - - const term = new Terminal({ - cursorBlink: true, - fontSize: fontSize, - fontFamily: '"Cascadia Code", "Fira Code", "JetBrains Mono", Menlo, Monaco, "Courier New", monospace', - theme: termTheme, - allowProposedApi: true, - }) - - const fitAddon = new FitAddon() - const webLinksAddon = new WebLinksAddon() - - term.loadAddon(fitAddon) - term.loadAddon(webLinksAddon) - term.open(containerRef.current) - - termRef.current = term - fitAddonRef.current = fitAddon - - // Wait a tick for the DOM to layout, then fit - requestAnimationFrame(() => { - doFit() - }) - - const ws = new WebSocket(wsUrl) - ws.binaryType = 'arraybuffer' - wsRef.current = ws - - ws.onmessage = (event) => { - const data = event.data - if (typeof data === 'string') return - - const buf = new Uint8Array(data) - if (buf.length < 1) return - - const msgType = buf[0] - const payload = buf.slice(1) - - switch (msgType) { - case MSG_STDOUT: - term.write(payload) - break - case MSG_STDERR: - term.write(payload) - break - case MSG_ERROR: - setErrorMsg(new TextDecoder().decode(payload)) - setStatus('error') - break - case MSG_STATUS: { - try { - const s = JSON.parse(new TextDecoder().decode(payload)) - if (s.connected === false && !closedRef.current) { - setErrorMsg(s.message || '会话已结束') - setStatus('error') - } - } catch { /* */ } - break - } - case MSG_CONNECTED: { - setStatus('connected') - // Fit multiple times to ensure correct terminal size is sent to SSH - doFit() - setTimeout(doFit, 50) - setTimeout(doFit, 200) - break - } - } - } - - ws.onclose = () => { - if (closedRef.current) return - closedRef.current = true - setErrorMsg('SSH 连接已断开') - setStatus('error') - } - - ws.onerror = () => { - if (closedRef.current) return - closedRef.current = true - setErrorMsg('WebSocket 连接失败') - setStatus('error') - } - - term.onData((data) => { - if (ws.readyState === WebSocket.OPEN) { - const encoder = new TextEncoder() - const dataBytes = encoder.encode(data) - const msg = new Uint8Array(1 + dataBytes.length) - msg[0] = MSG_STDIN - msg.set(dataBytes, 1) - ws.send(msg) - } - }) - - let resizeTimer: ReturnType - term.onResize(({ cols, rows }) => { - clearTimeout(resizeTimer) - resizeTimer = setTimeout(() => { - if (ws.readyState === WebSocket.OPEN) { - const resizeMsg = new TextEncoder().encode(JSON.stringify({ cols, rows })) - const msg = new Uint8Array(1 + resizeMsg.length) - msg[0] = MSG_RESIZE - msg.set(resizeMsg, 1) - ws.send(msg) - } - }, 100) - }) - }, [serverId, doFit]) - - useEffect(() => { - connect() - return () => { - closedRef.current = true - wsRef.current?.close() - termRef.current?.dispose() - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) - - // Apply theme changes to live terminal - useEffect(() => { - if (termRef.current) { - termRef.current.options.theme = termTheme as any - } - }, [termTheme]) - - useEffect(() => { - if (isActive) { - setTimeout(doFit, 20) - } - }, [isActive, doFit]) - - // Apply font size changes to live terminal - useEffect(() => { - if (termRef.current) { - termRef.current.options.fontSize = fontSize - setTimeout(doFit, 20) - } - }, [fontSize, doFit]) - - useEffect(() => { - const handleResize = () => { - if (isActive) doFit() - } - window.addEventListener('resize', handleResize) - const vv = window.visualViewport - if (vv) { - vv.addEventListener('resize', handleResize) - return () => { - window.removeEventListener('resize', handleResize) - vv.removeEventListener('resize', handleResize) - } - } - return () => window.removeEventListener('resize', handleResize) - }, [isActive, doFit]) - - useEffect(() => { - if (isActive) { - setTimeout(doFit, 50) - setTimeout(doFit, 200) - } - }, [showBar, isActive, doFit]) + const termTheme = useMemo(() => ({ + ...TERM_THEMES[mode], + cursor: colors.colorPrimary, + selectionBackground: `rgba(${hexToRgb(colors.colorPrimary)}, ${mode === 'dark' ? 0.3 : 0.15})`, + }), [mode, colors.colorPrimary]) + const { containerRef, termRef, status, errorMsg, connect, sendShortcut } = useTerminalConnection(serverId, fontSize, termTheme, isActive, showBar) + useEffect(() => { onStatusChange?.(status) }, [status, onStatusChange]) return (
@@ -380,7 +158,7 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize } borderTop: '1px solid rgba(255,77,79,0.3)', zIndex: 10, }}> - + {errorMsg} @@ -389,8 +167,6 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize } type="primary" icon={} onClick={() => { - setStatus('connecting') - setErrorMsg('') connect() }} > @@ -409,7 +185,7 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize } background: colors.terminalBg, zIndex: 10, }}> -
+
{errorMsg} @@ -421,8 +197,6 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize } type="primary" icon={} onClick={() => { - setStatus('connecting') - setErrorMsg('') connect() }} > @@ -486,6 +260,7 @@ export default function TerminalTab({ serverId, serverName, isActive, fontSize } {status === 'connected' && ( +} })) +const tabs = [1, 2].map(id => ({ key: String(id), server: { id, name: `server-${id}` } })) as TabInfo[] + +it('supports arrow keys and close buttons without unmounting inactive terminals', async () => { + const select = vi.fn() + const close = vi.fn() + const view = render() + await waitFor(() => expect(lifecycle.mounted).toHaveBeenCalledTimes(2)) + const tab = screen.getByRole('tab', { name: /server-1/ }) + fireEvent.keyDown(tab, { key: 'ArrowRight' }) + expect(select).toHaveBeenLastCalledWith('2') + expect(screen.getByRole('tab', { name: /server-2/ })).toHaveFocus() + view.rerender() + expect(lifecycle.unmounted).not.toHaveBeenCalled() + expect(lifecycle.mounted).toHaveBeenCalledTimes(2) + fireEvent.click(screen.getByRole('button', { name: '关闭 server-2' })) + expect(close).toHaveBeenCalledWith('2') +}) + +it('does not present an unopened SSH session as connected', async () => { + render( {}} onClose={() => {}} />) + expect(screen.getAllByLabelText('正在连接')).toHaveLength(2) + expect(screen.queryByLabelText('已连接')).not.toBeInTheDocument() + fireEvent.click(await screen.findByText('Connect 1')) + expect(screen.getByLabelText('已连接')).toBeInTheDocument() +}) diff --git a/ui/src/components/TerminalTabs.tsx b/ui/src/components/TerminalTabs.tsx index 975a4c2..2ae6da4 100644 --- a/ui/src/components/TerminalTabs.tsx +++ b/ui/src/components/TerminalTabs.tsx @@ -1,23 +1,16 @@ -import { useState, useCallback } from 'react' -import { Empty } from 'antd' +import { useState, useCallback, lazy, Suspense, useEffect, useRef } from 'react' +import Empty from 'antd/es/empty' +import Spin from 'antd/es/spin' import { CloseOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons' -import TerminalTab from './TerminalTab' import { useTheme } from '../contexts/ThemeContext' import type { TabInfo } from '../pages/MainPage' +import type { ConnectionStatus } from '../hooks/useTerminalConnection' +const TerminalTab = lazy(() => import('./TerminalTab')) const FONT_KEY = 'opsup_font_size' -const DEFAULT_FONT_SIZE = 14 const MIN_SIZE = 10 const MAX_SIZE = 28 - -function loadFontSize(): number { - const saved = localStorage.getItem(FONT_KEY) - if (saved) { - const n = parseInt(saved, 10) - if (n >= MIN_SIZE && n <= MAX_SIZE) return n - } - return DEFAULT_FONT_SIZE -} +const labels = { connecting: '正在连接', connected: '已连接', error: '连接断开或失败' } interface Props { tabs: TabInfo[] @@ -28,207 +21,80 @@ interface Props { export default function TerminalTabs({ tabs, activeKey, onSelect, onClose }: Props) { const { colors } = useTheme() - const [fontSize, setFontSize] = useState(loadFontSize) - + const [fontSize, setFontSize] = useState(() => { + const saved = Number(localStorage.getItem(FONT_KEY)) + return saved >= MIN_SIZE && saved <= MAX_SIZE ? saved : 14 + }) + const [statuses, setStatuses] = useState>({}) + const callbacks = useRef(new Map void>()) + useEffect(() => { + const keys = new Set(tabs.map(tab => tab.key)) + for (const key of callbacks.current.keys()) if (!keys.has(key)) callbacks.current.delete(key) + setStatuses(previous => Object.fromEntries(Object.entries(previous).filter(([key]) => keys.has(key)))) + }, [tabs]) + const statusCallback = (key: string) => { + if (!callbacks.current.has(key)) callbacks.current.set(key, status => setStatuses(previous => previous[key] === status ? previous : { ...previous, [key]: status })) + return callbacks.current.get(key)! + } const changeFontSize = useCallback((delta: number) => { - setFontSize((prev) => { - const next = Math.min(MAX_SIZE, Math.max(MIN_SIZE, prev + delta)) + setFontSize(previous => { + const next = Math.min(MAX_SIZE, Math.max(MIN_SIZE, previous + delta)) localStorage.setItem(FONT_KEY, String(next)) return next }) }, []) - - if (tabs.length === 0) { - return ( -
- - 从左侧选择一个服务器开始连接 - - } - /> -
- ) + const focusTab = (key: string) => { + onSelect(key) + document.getElementById(`tab-${key}`)?.focus() } + const closeTab = (key: string) => { + const index = tabs.findIndex(tab => tab.key === key) + const next = tabs[index + 1] || tabs[index - 1] + onClose(key) + if (next) focusTab(next.key) + } + + if (!tabs.length) return
从服务器列表选择一个服务器开始连接} />
return ( -
- {/* Tab bar */} -
- {/* Tabs - scrollable */} -
- {tabs.map((tab) => ( -
onSelect(tab.key)} - style={{ - display: 'flex', - alignItems: 'center', - gap: 6, - padding: '6px 12px', - cursor: 'pointer', - fontSize: 13, - color: tab.key === activeKey ? colors.textPrimary : colors.textSecondary, - background: tab.key === activeKey ? colors.bgBase : 'transparent', - borderRadius: '6px 6px 0 0', - borderBottom: tab.key === activeKey ? `2px solid ${colors.colorPrimary}` : '2px solid transparent', - whiteSpace: 'nowrap', - transition: 'all 0.2s', - userSelect: 'none', - flexShrink: 0, - }} - > - • - {tab.server.name} - { - e.stopPropagation() - onClose(tab.key) - }} - style={{ - display: 'inline-flex', - alignItems: 'center', - justifyContent: 'center', - width: 16, - height: 16, - borderRadius: 3, - fontSize: 10, - color: colors.textTertiary, - }} - onMouseEnter={(e) => { - ;(e.currentTarget as HTMLSpanElement).style.background = colors.fillMedium - ;(e.currentTarget as HTMLSpanElement).style.color = colors.textPrimary +
+
+
+ {tabs.map((tab, index) => { + const status = statuses[tab.key] || 'connecting' + return
+ +
- ))} + })}
- - {/* Font size controls */} -
- - - {fontSize}px - - +
+ + {fontSize}px +
- - {/* Terminal area */} -
- {tabs.map((tab) => ( -
- +
+ {tabs.map(tab => ( + }> + +
))}
diff --git a/ui/src/contexts/ThemeContext.tsx b/ui/src/contexts/ThemeContext.tsx index eb76c93..64d6ae4 100644 --- a/ui/src/contexts/ThemeContext.tsx +++ b/ui/src/contexts/ThemeContext.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useState, useEffect, useMemo } from 'react' import type { ThemeConfig } from 'antd' -import { theme } from 'antd' +import theme from 'antd/es/theme' export type ThemeMode = 'dark' | 'light' export type AccentKey = 'blue' | 'green' | 'purple' | 'orange' | 'red' diff --git a/ui/src/hooks/useDirectory.test.tsx b/ui/src/hooks/useDirectory.test.tsx new file mode 100644 index 0000000..ce44a56 --- /dev/null +++ b/ui/src/hooks/useDirectory.test.tsx @@ -0,0 +1,93 @@ +import { act, renderHook, waitFor } from '@testing-library/react' +import { beforeEach, expect, it, vi } from 'vitest' +import { useDirectory } from './useDirectory' +import * as filesApi from '../api/files' + +vi.mock('../api/files', () => ({ listFiles: vi.fn() })) +const listFiles = vi.mocked(filesApi.listFiles) +function deferred() { + let resolve!: (value: any) => void + let reject!: (reason: unknown) => void + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} +const entry = (name: string) => ({ name, path: `/${name}`, isDir: true, mode: '', modTime: '', size: 0 }) +beforeEach(() => listFiles.mockReset()) + +it('aborts old requests and ignores out-of-order responses and finally blocks', async () => { + const first = deferred() + const second = deferred() + listFiles.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + const { result } = renderHook(() => useDirectory(true, 1)) + const signal = listFiles.mock.calls[0][2]! + act(() => { void result.current.loadFiles('/new') }) + expect(signal.aborted).toBe(true) + await act(async () => first.resolve({ data: [entry('old')] })) + expect(result.current.files).toEqual([]) + expect(result.current.loading).toBe(true) + await act(async () => second.resolve({ data: [entry('new')] })) + expect(result.current.files[0].name).toBe('new') + expect(result.current.currentPath).toBe('/new') + expect(result.current.ready).toBe(true) +}) + +it('invalidates callbacks when the modal closes or changes server', async () => { + const first = deferred() + const second = deferred() + listFiles.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + const { result, rerender, unmount } = renderHook(({ open, server }) => useDirectory(open, server), { initialProps: { open: true, server: 1 } }) + const firstSignal = listFiles.mock.calls[0][2]! + rerender({ open: true, server: 2 }) + expect(firstSignal.aborted).toBe(true) + await act(async () => first.resolve({ data: [entry('server-one')] })) + expect(result.current.files).toEqual([]) + const secondSignal = listFiles.mock.calls[1][2]! + rerender({ open: false, server: 2 }) + expect(secondSignal.aborted).toBe(true) + await act(async () => second.resolve({ data: [entry('server-two')] })) + expect(result.current.files).toEqual([]) + expect(result.current.ready).toBe(false) + unmount() +}) + +it('refreshes mutations only while their original server and directory are still visible', async () => { + listFiles.mockResolvedValue({ data: [] } as any) + const { result, rerender } = renderHook(({ server }) => useDirectory(true, server), { initialProps: { server: 1 } }) + await waitFor(() => expect(result.current.ready).toBe(true)) + const same = result.current.capture() + await act(async () => same.refresh()) + expect(listFiles).toHaveBeenCalledTimes(2) + const oldPath = result.current.capture() + await act(async () => { await result.current.loadFiles('/next') }) + act(() => oldPath.refresh()) + expect(listFiles).toHaveBeenCalledTimes(3) + const oldServer = result.current.capture() + rerender({ server: 2 }) + act(() => oldServer.refresh()) + expect(listFiles).toHaveBeenCalledTimes(4) + expect(oldServer.isCurrent()).toBe(false) +}) + +it('clears stale rows before a new request and never re-enables failed selections', async () => { + listFiles.mockResolvedValueOnce({ data: [entry('old')] } as any) + const pending = deferred() + listFiles.mockReturnValueOnce(pending.promise) + const { result } = renderHook(() => useDirectory(true, 1)) + await waitFor(() => expect(result.current.ready).toBe(true)) + act(() => { void result.current.loadFiles('/missing') }) + expect(result.current.files).toEqual([]) + expect(result.current.ready).toBe(false) + await act(async () => pending.reject(new Error('failure'))) + expect(result.current.ready).toBe(false) + expect(result.current.loading).toBe(false) +}) + +it('rejects a stale row confirmation even when the same path was refreshed', async () => { + listFiles.mockResolvedValue({ data: [entry('old')] } as any) + const { result } = renderHook(() => useDirectory(true, 1)) + await waitFor(() => expect(result.current.ready).toBe(true)) + const oldRowCapture = result.current.capture + await act(async () => { await result.current.loadFiles('/') }) + expect(oldRowCapture().isCurrent()).toBe(false) + expect(result.current.capture().isCurrent()).toBe(true) +}) diff --git a/ui/src/hooks/useDirectory.ts b/ui/src/hooks/useDirectory.ts new file mode 100644 index 0000000..124e747 --- /dev/null +++ b/ui/src/hooks/useDirectory.ts @@ -0,0 +1,55 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import message from 'antd/es/message' +import * as filesApi from '../api/files' +import type { FileEntry } from '../api/files' + +export function useDirectory(open: boolean, serverId: number) { + const [files, setFiles] = useState([]) + const [currentPath, setCurrentPath] = useState('/') + const [loading, setLoading] = useState(false) + const [ready, setReady] = useState(false) + const [renderedGeneration, setRenderedGeneration] = useState(0) + const generation = useRef(0) + const controller = useRef(null) + const visible = useRef({ open, serverId, path: '/' }) + visible.current.open = open + visible.current.serverId = serverId + + const loadFiles = useCallback(async (path: string) => { + controller.current?.abort() + const request = new AbortController() + controller.current = request + const id = ++generation.current + setRenderedGeneration(id) + visible.current.path = path + setCurrentPath(path) + setFiles([]) + setReady(false) + setLoading(true) + const current = () => !request.signal.aborted && generation.current === id && visible.current.open && visible.current.serverId === serverId + try { + const response = await filesApi.listFiles(serverId, path, request.signal) + if (current()) { setFiles(response.data || []); setReady(true) } + } catch (error: any) { + if (current()) message.error(error.response?.data?.error || '加载文件列表失败') + } finally { + if (current()) setLoading(false) + } + }, [serverId]) + + useEffect(() => { + if (open) void loadFiles('/') + return () => { + ++generation.current + controller.current?.abort() + } + }, [open, serverId, loadFiles]) + + const capture = () => { + const id = renderedGeneration + const path = currentPath + const isCurrent = () => generation.current === id && visible.current.open && visible.current.serverId === serverId && visible.current.path === path + return { serverId, path, isCurrent, refresh: () => { if (isCurrent()) void loadFiles(path) } } + } + return { files, currentPath, loading, ready: ready && open && visible.current.serverId === serverId, loadFiles, capture } +} diff --git a/ui/src/hooks/useTerminalConnection.test.tsx b/ui/src/hooks/useTerminalConnection.test.tsx new file mode 100644 index 0000000..30a1c18 --- /dev/null +++ b/ui/src/hooks/useTerminalConnection.test.tsx @@ -0,0 +1,155 @@ +import { StrictMode } from 'react' +import { act, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { inputFrames, useTerminalConnection } from './useTerminalConnection' + +const mocks = vi.hoisted(() => ({ terminals: [] as any[], observers: [] as any[] })) +vi.mock('@xterm/xterm', () => ({ Terminal: class { + cols = 80 + rows = 24 + options: any + data: (data: string) => void = () => {} + resize: () => void = () => {} + dispose = vi.fn() + write = vi.fn() + constructor(options: any) { this.options = options; mocks.terminals.push(this) } + loadAddon() {} + open() {} + onData(callback: (data: string) => void) { this.data = callback; return { dispose: vi.fn() } } + onResize(callback: () => void) { this.resize = callback; return { dispose: vi.fn() } } +} })) +vi.mock('@xterm/addon-fit', () => ({ FitAddon: class { fit = vi.fn() } })) +vi.mock('@xterm/addon-web-links', () => ({ WebLinksAddon: class {} })) + +class Socket { + static OPEN = 1 + static instances: Socket[] = [] + readyState = 1 + bufferedAmount = 0 + binaryType = '' + onmessage: ((event: { data: ArrayBuffer }) => void) | null = null + onclose: (() => void) | null = null + onerror: (() => void) | null = null + onopen: (() => void) | null = null + send = vi.fn() + close = vi.fn(() => { this.readyState = 3 }) + constructor() { Socket.instances.push(this) } + receive(type: number, text = '') { + const bytes = new TextEncoder().encode(text) + const frame = new Uint8Array(bytes.length + 1) + frame[0] = type + frame.set(bytes, 1) + this.onmessage?.({ data: frame.buffer }) + } +} +const dark = { background: '#000000' } +const light = { background: '#ffffff' } +function Harness({ server = 1, fontSize = 14, theme = dark }) { + const terminal = useTerminalConnection(server, fontSize, theme, true, true) + return <>
{terminal.status}{terminal.errorMsg} +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'requestAnimationFrame', 'cancelAnimationFrame'] }) + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => setTimeout(() => callback(0), 16)) + vi.stubGlobal('cancelAnimationFrame', (id: number) => clearTimeout(id)) + vi.stubGlobal('WebSocket', Socket) + vi.stubGlobal('ResizeObserver', class { + disconnect = vi.fn() + observe = vi.fn() + constructor(public callback: () => void) { mocks.observers.push(this) } + }) + Socket.instances = [] + mocks.terminals = [] + mocks.observers = [] + localStorage.setItem('opsup_token', 'test') +}) +afterEach(() => { vi.useRealTimers() }) + +describe('terminal connection ownership', () => { + it('reports connecting until SSH confirms, explicitly resizes and preserves the actual error', () => { + const view = render() + const socket = Socket.instances[0] + expect(screen.getByRole('status')).toHaveTextContent('connecting') + act(() => socket.receive(4)) + expect(screen.getByRole('status')).toHaveTextContent('connected') + expect(socket.send.mock.calls.some(([frame]) => frame[0] === 1)).toBe(true) + act(() => socket.receive(2, 'Host key missing: SHA256:observed')) + act(() => socket.onclose?.()) + expect(screen.getByText('Host key missing: SHA256:observed')).toBeInTheDocument() + expect(Socket.instances).toHaveLength(1) + view.unmount() + }) + + it('detaches old sockets, guards late callbacks and uses current theme/font on manual reconnect', () => { + const view = render() + const old = Socket.instances[0] + const lateMessage = old.onmessage! + act(() => old.receive(4)) + view.rerender() + fireEvent.click(screen.getByText('Reconnect')) + expect(old.close).toHaveBeenCalled() + expect(old.onmessage).toBeNull() + expect(old.onerror).toBeNull() + expect(old.onclose).toBeNull() + expect(mocks.terminals[0].dispose).toHaveBeenCalledOnce() + expect(mocks.observers[0].disconnect).toHaveBeenCalledOnce() + act(() => lateMessage({ data: new Uint8Array([4]).buffer })) + expect(screen.getByRole('status')).toHaveTextContent('connecting') + expect(mocks.terminals[1].options).toMatchObject({ fontSize: 20, theme: light }) + view.unmount() + expect(Socket.instances[1].close).toHaveBeenCalled() + expect(mocks.terminals[1].dispose).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + }) + + it('releases the prior session on server change and StrictMode remount', () => { + const view = render() + expect(Socket.instances).toHaveLength(2) + expect(Socket.instances[0].onmessage).toBeNull() + view.rerender() + expect(Socket.instances[1].close).toHaveBeenCalled() + expect(Socket.instances).toHaveLength(3) + view.unmount() + expect(vi.getTimerCount()).toBe(0) + }) + + it('drains a backpressured large Unicode paste without dropping or reordering bytes', () => { + const view = render() + const socket = Socket.instances[0] + act(() => socket.receive(4)) + socket.send.mockClear() + socket.bufferedAmount = 300 * 1024 + const text = '你好🙂'.repeat(20000) + act(() => mocks.terminals[0].data(text)) + expect(socket.send).not.toHaveBeenCalled() + socket.bufferedAmount = 0 + act(() => vi.advanceTimersByTime(16)) + const frames = socket.send.mock.calls.map(([frame]) => frame as Uint8Array).filter(frame => frame[0] === 0) + expect(frames.length).toBeGreaterThan(4) + expect(frames.every(frame => frame.length <= 16385)).toBe(true) + const received = new Uint8Array(frames.reduce((size, frame) => size + frame.length - 1, 0)) + let offset = 0 + frames.forEach(frame => { received.set(frame.subarray(1), offset); offset += frame.length - 1 }) + expect(new TextDecoder().decode(received)).toBe(text) + view.unmount() + }) + + it('warns about interrupted pending input instead of silently discarding it', () => { + const view = render() + const socket = Socket.instances[0] + act(() => socket.receive(4)) + socket.bufferedAmount = 300 * 1024 + act(() => mocks.terminals[0].data('pending')) + act(() => socket.onclose?.()) + expect(screen.getByText(/部分输入可能未送达/)).toBeInTheDocument() + view.unmount() + }) +}) + +it('prefixes every bounded stdin frame with protocol byte zero', () => { + const frames = [...inputFrames('a'.repeat(65536))] + expect(frames).toHaveLength(4) + expect(frames.every(frame => frame[0] === 0 && frame.length === 16385)).toBe(true) + expect([...inputFrames('')]).toEqual([]) +}) diff --git a/ui/src/hooks/useTerminalConnection.ts b/ui/src/hooks/useTerminalConnection.ts new file mode 100644 index 0000000..aadfb89 --- /dev/null +++ b/ui/src/hooks/useTerminalConnection.ts @@ -0,0 +1,188 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { Terminal, type ITheme } from '@xterm/xterm' +import { FitAddon } from '@xterm/addon-fit' +import { WebLinksAddon } from '@xterm/addon-web-links' + +export type ConnectionStatus = 'connecting' | 'connected' | 'error' +export const INPUT_CHUNK_BYTES = 16 * 1024 + +export function* inputFrames(data: string) { + const bytes = new TextEncoder().encode(data) + for (let offset = 0; offset < bytes.length; offset += INPUT_CHUNK_BYTES) { + const payload = bytes.subarray(offset, offset + INPUT_CHUNK_BYTES) + const frame = new Uint8Array(payload.length + 1) + frame.set(payload, 1) + yield frame + } +} + +export function useTerminalConnection(serverId: number, fontSize: number, theme: ITheme, isActive: boolean, showBar: boolean) { + const containerRef = useRef(null) + const termRef = useRef(null) + const wsRef = useRef(null) + const fitRef = useRef(null) + const generation = useRef(0) + const cleanupRef = useRef<() => void>(() => {}) + const sendRef = useRef<(data: string) => void>(() => {}) + const latest = useRef({ fontSize, theme, isActive }) + latest.current = { fontSize, theme, isActive } + const [status, setStatus] = useState('connecting') + const [errorMsg, setErrorMsg] = useState('') + + const doFit = useCallback(() => { + if (!latest.current.isActive || !containerRef.current?.clientWidth || !containerRef.current.clientHeight) return + try { fitRef.current?.fit() } catch { /* Container may be hidden during layout. */ } + }, []) + + const connect = useCallback(() => { + cleanupRef.current() + const id = ++generation.current + const current = () => generation.current === id + setStatus('connecting') + setErrorMsg('') + const token = localStorage.getItem('opsup_token') + if (!token || !containerRef.current) { + setStatus('error') + setErrorMsg('未登录,请重新登录') + return + } + let connected = false + let failed = false + let queue: Uint8Array[] = [] + let queueIndex = 0 + const timers = new Set>() + const rafs = new Set() + const later = (callback: () => void, delay: number) => { + const timer = setTimeout(() => { timers.delete(timer); if (current()) callback() }, delay) + timers.add(timer) + return timer + } + const term = new Terminal({ + cursorBlink: true, + fontSize: latest.current.fontSize, + theme: latest.current.theme, + fontFamily: '"Cascadia Code", "Fira Code", "JetBrains Mono", Menlo, Monaco, "Courier New", monospace', + }) + const fit = new FitAddon() + term.loadAddon(fit) + term.loadAddon(new WebLinksAddon()) + term.open(containerRef.current) + termRef.current = term + fitRef.current = fit + const proto = location.protocol === 'https:' ? 'wss:' : 'ws:' + const ws = new WebSocket(`${proto}//${location.host}/api/terminal/${serverId}?token=${encodeURIComponent(token)}`) + ws.binaryType = 'arraybuffer' + wsRef.current = ws + + const fail = (message: string) => { + if (!current() || failed) return + failed = true + connected = false + if (queueIndex < queue.length || ws.bufferedAmount > 0) message += ';连接中断,部分输入可能未送达,请检查后重试' + queue = [] + queueIndex = 0 + setErrorMsg(message) + setStatus('error') + ws.close() + } + let pumpTimer: ReturnType | undefined + const pump = () => { + pumpTimer = undefined + if (!current() || !connected || ws.readyState !== WebSocket.OPEN) return + try { + while (queueIndex < queue.length && ws.bufferedAmount < 256 * 1024) ws.send(queue[queueIndex++]) + } catch { fail('发送输入失败'); return } + if (queueIndex < queue.length) pumpTimer = later(pump, 16) + else { queue = []; queueIndex = 0 } + } + sendRef.current = (data) => { + if (!current() || !connected || ws.readyState !== WebSocket.OPEN) return + for (const frame of inputFrames(data)) queue.push(frame) + if (!pumpTimer) pump() + } + const sendResize = () => { + if (!current() || !connected || ws.readyState !== WebSocket.OPEN) return + const payload = new TextEncoder().encode(JSON.stringify({ cols: term.cols, rows: term.rows })) + const frame = new Uint8Array(payload.length + 1) + frame[0] = 0x01 + frame.set(payload, 1) + try { ws.send(frame) } catch { fail('发送终端尺寸失败') } + } + const fitAndResize = () => { doFit(); sendResize() } + const frame = requestAnimationFrame(() => { rafs.delete(frame); if (current()) doFit() }) + rafs.add(frame) + let resizeTimer: ReturnType | undefined + const dataSubscription = term.onData(data => { if (current()) sendRef.current(data) }) + const resizeSubscription = term.onResize(() => { + if (!current()) return + if (resizeTimer) { clearTimeout(resizeTimer); timers.delete(resizeTimer) } + resizeTimer = later(sendResize, 100) + }) + const observer = new ResizeObserver(() => { if (current()) fitAndResize() }) + observer.observe(containerRef.current) + ws.onmessage = event => { + if (!current() || failed || typeof event.data === 'string') return + const buffer = new Uint8Array(event.data) + if (!buffer.length) return + const payload = buffer.subarray(1) + switch (buffer[0]) { + case 0x00: + case 0x01: term.write(payload); break + case 0x02: fail(new TextDecoder().decode(payload)); break + case 0x03: + try { + const value = JSON.parse(new TextDecoder().decode(payload)) + if (value.connected === false) fail(value.message || '会话已结束') + } catch { /* Ignore malformed status frames. */ } + break + case 0x04: + connected = true + setStatus('connected') + fitAndResize() + later(fitAndResize, 50) + later(fitAndResize, 200) + break + } + } + ws.onclose = () => fail('SSH 连接已断开') + ws.onerror = () => fail('WebSocket 连接失败') + cleanupRef.current = () => { + ++generation.current + connected = false + ws.onmessage = null + ws.onclose = null + ws.onerror = null + ws.onopen = null + ws.close() + timers.forEach(clearTimeout) + rafs.forEach(cancelAnimationFrame) + observer.disconnect() + dataSubscription.dispose() + resizeSubscription.dispose() + term.dispose() + queue = [] + wsRef.current = null + termRef.current = null + fitRef.current = null + sendRef.current = () => {} + cleanupRef.current = () => {} + } + }, [serverId, doFit]) + + useEffect(() => { connect(); return () => cleanupRef.current() }, [connect]) + useEffect(() => { + if (termRef.current) { + termRef.current.options.theme = theme + termRef.current.options.fontSize = fontSize + } + const frame = requestAnimationFrame(doFit) + return () => cancelAnimationFrame(frame) + }, [theme, fontSize, isActive, showBar, doFit]) + useEffect(() => { + const viewport = window.visualViewport + viewport?.addEventListener('resize', doFit) + return () => viewport?.removeEventListener('resize', doFit) + }, [doFit]) + const sendShortcut = useCallback((data: string) => sendRef.current(data), []) + return { containerRef, termRef, status, errorMsg, connect, sendShortcut } +} diff --git a/ui/src/pages/LoginPage.tsx b/ui/src/pages/LoginPage.tsx index f1e3e8d..791fcf8 100644 --- a/ui/src/pages/LoginPage.tsx +++ b/ui/src/pages/LoginPage.tsx @@ -1,6 +1,11 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' -import { Form, Input, Button, Card, Typography, message } from 'antd' +import Form from 'antd/es/form' +import Input from 'antd/es/input' +import Button from 'antd/es/button' +import Card from 'antd/es/card' +import Typography from 'antd/es/typography' +import message from 'antd/es/message' import { UserOutlined, LockOutlined } from '@ant-design/icons' import { useAuth } from '../hooks/useAuth' import { getAuthStatus } from '../api/auth' diff --git a/ui/src/pages/MainPage.tsx b/ui/src/pages/MainPage.tsx index 8ec2400..eb44c03 100644 --- a/ui/src/pages/MainPage.tsx +++ b/ui/src/pages/MainPage.tsx @@ -1,6 +1,10 @@ import { useState, useCallback, useEffect } from 'react' -import { Layout, Button, Dropdown } from 'antd' -import { LogoutOutlined, SunOutlined, MoonOutlined, BgColorsOutlined, CheckOutlined } from '@ant-design/icons' +import Layout from 'antd/es/layout' +import Button from 'antd/es/button' +import Dropdown from 'antd/es/dropdown' +import Drawer from 'antd/es/drawer' +import Grid from 'antd/es/grid' +import { MenuOutlined, LogoutOutlined, SunOutlined, MoonOutlined, BgColorsOutlined, CheckOutlined } from '@ant-design/icons' import ServerSidebar from '../components/ServerSidebar' import TerminalTabs from '../components/TerminalTabs' import { useTheme, ACCENT_OPTIONS } from '../contexts/ThemeContext' @@ -15,6 +19,9 @@ export interface TabInfo { } export default function MainPage() { + const [drawerOpen, setDrawerOpen] = useState(false) + const screens = Grid.useBreakpoint() + const mobile = !screens.md const [tabs, setTabs] = useState([]) const [activeKey, setActiveKey] = useState('') const { mode, accent, colors, toggleMode, setAccent } = useTheme() @@ -39,6 +46,7 @@ export default function MainPage() { }, []) const openTerminal = useCallback((server: Server) => { + setDrawerOpen(false) const key = `${server.id}-${Date.now()}` setTabs((prev) => { const exists = prev.find((t) => t.server.id === server.id) @@ -69,18 +77,7 @@ export default function MainPage() { window.location.href = '/login' } - return ( - - -
- + + + return ( + + {mobile ? ( + setDrawerOpen(false)} + size={300} styles={{ body: { padding: 0, background: colors.bgSidebar, display: 'flex', flexDirection: 'column' } }}> + {sidebar} + + ) : ( + + {sidebar} + + )} + - - + {mobile &&
} +
+ />
diff --git a/ui/src/pages/SetupPage.test.tsx b/ui/src/pages/SetupPage.test.tsx new file mode 100644 index 0000000..4ddc630 --- /dev/null +++ b/ui/src/pages/SetupPage.test.tsx @@ -0,0 +1,27 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { MemoryRouter } from 'react-router-dom' +import { expect, it, vi } from 'vitest' +import SetupPage from './SetupPage' +import { ThemeProvider } from '../contexts/ThemeContext' + +const mocks = vi.hoisted(() => ({ doSetup: vi.fn() })) +vi.mock('../hooks/useAuth', () => ({ useAuth: () => ({ doSetup: mocks.doSetup }) })) +vi.mock('../api/auth', () => ({ getAuthStatus: () => Promise.resolve({ initialized: false }) })) + +it('enforces the backend administrator password minimum and bcrypt byte limit', async () => { + render() + fireEvent.change(screen.getByPlaceholderText('管理员用户名'), { target: { value: 'admin' } }) + const password = screen.getByPlaceholderText('密码') + const confirm = screen.getByPlaceholderText('确认密码') + fireEvent.change(password, { target: { value: 'short1' } }) + fireEvent.change(confirm, { target: { value: 'short1' } }) + fireEvent.click(screen.getByRole('button', { name: '创建管理员' })) + expect(await screen.findByText('密码至少12个字符')).toBeInTheDocument() + expect(mocks.doSetup).not.toHaveBeenCalled() + const oversized = '密'.repeat(25) + fireEvent.change(password, { target: { value: oversized } }) + fireEvent.change(confirm, { target: { value: oversized } }) + fireEvent.click(screen.getByRole('button', { name: '创建管理员' })) + expect(await screen.findByText('密码最多72个 UTF-8 字节')).toBeInTheDocument() + await waitFor(() => expect(mocks.doSetup).not.toHaveBeenCalled()) +}) diff --git a/ui/src/pages/SetupPage.tsx b/ui/src/pages/SetupPage.tsx index 007e271..9b1c7d4 100644 --- a/ui/src/pages/SetupPage.tsx +++ b/ui/src/pages/SetupPage.tsx @@ -1,6 +1,11 @@ import { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' -import { Form, Input, Button, Card, Typography, message } from 'antd' +import Form from 'antd/es/form' +import Input from 'antd/es/input' +import Button from 'antd/es/button' +import Card from 'antd/es/card' +import Typography from 'antd/es/typography' +import message from 'antd/es/message' import { UserOutlined, LockOutlined } from '@ant-design/icons' import { useAuth } from '../hooks/useAuth' import { getAuthStatus } from '../api/auth' @@ -65,7 +70,11 @@ export default function SetupPage() { } placeholder="管理员用户名" /> - + !value || new TextEncoder().encode(value).length <= 72 + ? Promise.resolve() : Promise.reject(new Error('密码最多72个 UTF-8 字节')) }, + ]}> } placeholder="密码" /> () +vi.stubGlobal('localStorage', { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, String(value)), + removeItem: (key: string) => storage.delete(key), + clear: () => storage.clear(), + key: (index: number) => [...storage.keys()][index] ?? null, + get length() { return storage.size }, +}) +Object.defineProperty(window, 'matchMedia', { writable: true, value: vi.fn().mockImplementation(query => ({ matches: false, media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn() })) }) +class ResizeObserverMock { + observe = vi.fn() + unobserve = vi.fn() + disconnect = vi.fn() +} +vi.stubGlobal('ResizeObserver', ResizeObserverMock) +const getComputedStyle = window.getComputedStyle +window.getComputedStyle = element => getComputedStyle(element) +afterEach(() => { cleanup(); localStorage.clear() }) diff --git a/ui/src/types/index.ts b/ui/src/types/index.ts index 38ff248..103e276 100644 --- a/ui/src/types/index.ts +++ b/ui/src/types/index.ts @@ -1,6 +1,7 @@ export interface Server { id: number name: string + host_key: string host: string port: number username: string @@ -14,6 +15,7 @@ export interface Server { export interface ServerForm { name: string + host_key: string host: string port: number username: string diff --git a/ui/src/utils/hostKey.ts b/ui/src/utils/hostKey.ts new file mode 100644 index 0000000..fa4bbe7 --- /dev/null +++ b/ui/src/utils/hostKey.ts @@ -0,0 +1 @@ +export const HOST_KEY_PATTERN = /^SHA256:[A-Za-z0-9+/]{43}$/ diff --git a/ui/vite.config.ts b/ui/vite.config.ts index 3fe91ab..45cb569 100644 --- a/ui/vite.config.ts +++ b/ui/vite.config.ts @@ -9,7 +9,7 @@ export default defineConfig({ }, server: { proxy: { - '/api': 'http://localhost:8080', + '/api': { target: 'http://localhost:8080', ws: true }, }, }, }) diff --git a/ui/vitest.config.ts b/ui/vitest.config.ts new file mode 100644 index 0000000..ac0b7cb --- /dev/null +++ b/ui/vitest.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], + test: { + environment: 'jsdom', + maxWorkers: 1, + setupFiles: ['./src/test/setup.ts'], + restoreMocks: true, + }, +}) From bdf33169a3b41737e58938b00dcfcbb7fdc26e5e Mon Sep 17 00:00:00 2001 From: Keegan Bozde <112920194+azzliang6@users.noreply.github.com> Date: Fri, 11 Sep 2026 07:37:59 +0000 Subject: [PATCH 3/3] Refine OpsUp appearance while preserving its terminal style --- ui/src/components/AuthFrame.tsx | 24 ++ ui/src/components/FileManager.tsx | 75 +---- ui/src/components/ServerFormModal.tsx | 8 +- ui/src/components/ServerSidebar.test.tsx | 25 ++ ui/src/components/ServerSidebar.tsx | 395 +++++------------------ ui/src/components/TerminalTab.tsx | 290 +++-------------- ui/src/components/TerminalTabs.tsx | 74 ++--- ui/src/contexts/ThemeContext.test.tsx | 23 ++ ui/src/contexts/ThemeContext.tsx | 167 ++++------ ui/src/pages/LoginPage.tsx | 88 +---- ui/src/pages/MainPage.tsx | 175 ++++------ ui/src/pages/SetupPage.tsx | 96 ++---- ui/src/styles/global.css | 211 ++++++++---- ui/src/styles/terminal.css | 59 ++-- 14 files changed, 575 insertions(+), 1135 deletions(-) create mode 100644 ui/src/components/AuthFrame.tsx create mode 100644 ui/src/components/ServerSidebar.test.tsx create mode 100644 ui/src/contexts/ThemeContext.test.tsx diff --git a/ui/src/components/AuthFrame.tsx b/ui/src/components/AuthFrame.tsx new file mode 100644 index 0000000..3e63ff2 --- /dev/null +++ b/ui/src/components/AuthFrame.tsx @@ -0,0 +1,24 @@ +import type { ReactNode } from 'react' +import Card from 'antd/es/card' + +interface Props { + title: string + description: string + children: ReactNode +} + +export default function AuthFrame({ title, description, children }: Props) { + return ( +
+ +
+ +

{title}

+

{description}

+
+ {children} +
OpsUp Web SSH Terminal
+
+
+ ) +} diff --git a/ui/src/components/FileManager.tsx b/ui/src/components/FileManager.tsx index 2be258a..b385a71 100644 --- a/ui/src/components/FileManager.tsx +++ b/ui/src/components/FileManager.tsx @@ -225,72 +225,31 @@ export default function FileManager({ open, serverId, serverName, onClose }: Pro ] return ( - - {/* Path bar */} -
- - + +
+
- - {/* Breadcrumb */} -
+
- - {/* Toolbar */} -
- - + +
+ +
- - {/* File table */} - `共 ${total} 项` }} - scroll={{ x: 560, y: '45vh' }} - style={{ maxHeight: '50vh', overflow: 'auto' }} - onRow={(record) => ({ - onDoubleClick: () => handleNavigate(record), - })} - /> + scroll={{ x: 560, y: 'min(42vh, 360px)' }} onRow={record => ({ onDoubleClick: () => handleNavigate(record) })} /> ) } diff --git a/ui/src/components/ServerFormModal.tsx b/ui/src/components/ServerFormModal.tsx index 542364e..9a6739d 100644 --- a/ui/src/components/ServerFormModal.tsx +++ b/ui/src/components/ServerFormModal.tsx @@ -147,16 +147,18 @@ export default function ServerFormModal({ open, server, onOk, onCancel }: Props) return ( -
+ diff --git a/ui/src/components/ServerSidebar.test.tsx b/ui/src/components/ServerSidebar.test.tsx new file mode 100644 index 0000000..da4b29f --- /dev/null +++ b/ui/src/components/ServerSidebar.test.tsx @@ -0,0 +1,25 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import { expect, it, vi } from 'vitest' +import ServerSidebar from './ServerSidebar' +import { ThemeProvider } from '../contexts/ThemeContext' + +vi.mock('../api/servers', () => ({ listServers: () => Promise.resolve([ + { id: 1, name: 'web-demo', host: '192.0.2.10', port: 22, username: 'demo', group: '演示环境' }, + { id: 2, name: 'api-demo', host: '192.0.2.20', port: 22, username: 'demo', group: '演示环境' }, +]) })) + +it('marks the active server without hiding file actions and preserves filtering and groups', async () => { + const onConnect = vi.fn() + render() + const active = await screen.findByRole('button', { name: '连接 api-demo' }) + expect(active).toHaveAttribute('aria-current', 'true') + expect(active.closest('.server-card')).toHaveAttribute('data-active', 'true') + expect(screen.getByRole('button', { name: '文件管理 api-demo' })).toBeVisible() + fireEvent.click(screen.getByRole('button', { name: '连接 web-demo' })) + expect(onConnect).toHaveBeenCalledWith(expect.objectContaining({ id: 1 })) + fireEvent.change(screen.getByRole('textbox', { name: '搜索服务器' }), { target: { value: 'api' } }) + expect(screen.queryByRole('button', { name: '连接 web-demo' })).not.toBeInTheDocument() + expect(screen.getByText('显示 1 / 2 台服务器')).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: /演示环境/ })) + expect(screen.queryByRole('button', { name: '连接 api-demo' })).not.toBeInTheDocument() +}) diff --git a/ui/src/components/ServerSidebar.tsx b/ui/src/components/ServerSidebar.tsx index f9c1df3..248977b 100644 --- a/ui/src/components/ServerSidebar.tsx +++ b/ui/src/components/ServerSidebar.tsx @@ -6,351 +6,108 @@ import message from 'antd/es/message' import Empty from 'antd/es/empty' import Spin from 'antd/es/spin' import Dropdown from 'antd/es/dropdown' -import { - PlusOutlined, - MoreOutlined, - SearchOutlined, - DesktopOutlined, - EditOutlined, - DeleteOutlined, - LinkOutlined, - CheckCircleOutlined, - FolderOutlined, - FolderOpenOutlined, - RightOutlined, - DownOutlined, -} from '@ant-design/icons' -import theme from 'antd/es/theme' +import { PlusOutlined, MoreOutlined, SearchOutlined, DesktopOutlined, EditOutlined, DeleteOutlined, LinkOutlined, CheckCircleOutlined, FolderOutlined, FolderOpenOutlined, RightOutlined, DownOutlined } from '@ant-design/icons' import * as serverApi from '../api/servers' -const ServerFormModal = lazy(() => import('./ServerFormModal')) -const FileManager = lazy(() => import('./FileManager')) -import { useTheme } from '../contexts/ThemeContext' import type { Server } from '../types' -interface Props { - onConnect: (server: Server) => void -} +const ServerFormModal = lazy(() => import('./ServerFormModal')) +const FileManager = lazy(() => import('./FileManager')) +interface Props { onConnect: (server: Server) => void; activeServerId?: number } -export default function ServerSidebar({ onConnect }: Props) { - const { colors } = useTheme() - const { token } = theme.useToken() +export default function ServerSidebar({ onConnect, activeServerId }: Props) { const [servers, setServers] = useState([]) const [loading, setLoading] = useState(true) const [search, setSearch] = useState('') const [modalOpen, setModalOpen] = useState(false) const [editing, setEditing] = useState(null) - const [contextMenu, setContextMenu] = useState<{ server: Server; x: number; y: number } | null>(null) const [collapsed, setCollapsed] = useState>({}) const [fileManagerServer, setFileManagerServer] = useState(null) const fetchServers = useCallback(async () => { - try { - const list = await serverApi.listServers() - setServers(list || []) - } catch { - // ignore - } finally { - setLoading(false) - } + try { setServers(await serverApi.listServers() || []) } + catch { /* Retain the last successfully loaded list. */ } + finally { setLoading(false) } }, []) + useEffect(() => { void fetchServers() }, [fetchServers]) - useEffect(() => { - fetchServers() - }, [fetchServers]) - - const handleAdd = () => { - setEditing(null) - setModalOpen(true) - } - - const handleEdit = (server: Server) => { - setEditing(server) - setModalOpen(true) - setContextMenu(null) - } - - const handleDelete = async (server: Server) => { - setContextMenu(null) + const handleEdit = (server: Server) => { setEditing(server); setModalOpen(true) } + const handleDelete = (server: Server) => { Modal.confirm({ - title: `确定删除 "${server.name}"?`, - content: '删除后连接信息将无法恢复', - okText: '删除', - okType: 'danger', - cancelText: '取消', - onOk: async () => { - await serverApi.deleteServer(server.id) - message.success('已删除') - fetchServers() - }, + title: `确定删除 "${server.name}"?`, content: '删除后连接信息将无法恢复', + okText: '删除', okType: 'danger', cancelText: '取消', + onOk: async () => { await serverApi.deleteServer(server.id); message.success('已删除'); await fetchServers() }, }) } - const handleTest = async (server: Server) => { - setContextMenu(null) try { - const res = await serverApi.testConnection(server.id) - if (res.success) { - message.success('连接成功') - } else { - message.error(`连接失败: ${res.error}`) - } - } catch (e: any) { - message.error(e.response?.data?.error || '测试失败') - } + const result = await serverApi.testConnection(server.id) + if (result.success) message.success('连接成功') + else message.error(`连接失败: ${result.error}`) + } catch (e: any) { message.error(e.response?.data?.error || '测试失败') } } - - const handleModalOk = async () => { - setModalOpen(false) - setEditing(null) - await fetchServers() - } - - const filtered = search - ? servers.filter( - (s) => - s.name.toLowerCase().includes(search.toLowerCase()) || - s.host.toLowerCase().includes(search.toLowerCase()) || - (s.group || '').toLowerCase().includes(search.toLowerCase()), - ) - : servers - - const handleContextMenu = (e: React.MouseEvent, server: Server) => { - e.preventDefault() - setContextMenu({ server, x: e.clientX, y: e.clientY }) - } - - useEffect(() => { - const close = () => setContextMenu(null) - if (contextMenu) { - document.addEventListener('click', close) - return () => document.removeEventListener('click', close) - } - }, [contextMenu]) - - // Group servers - const groups: { name: string; servers: Server[] }[] = [] + const handleModalOk = async () => { setModalOpen(false); setEditing(null); await fetchServers() } + const menuFor = (server: Server) => ({ items: [ + { key: 'connect', label: '连接', icon: , onClick: () => onConnect(server) }, + { key: 'files', label: '文件管理', icon: , onClick: () => setFileManagerServer(server) }, + { key: 'test', label: '测试连接', icon: , onClick: () => handleTest(server) }, + { key: 'edit', label: '编辑', icon: , onClick: () => handleEdit(server) }, + { key: 'delete', label: '删除', icon: , danger: true, onClick: () => handleDelete(server) }, + ] }) + + const query = search.toLowerCase() + const filtered = servers.filter(server => !query || [server.name, server.host, server.group || ''].some(value => value.toLowerCase().includes(query))) const groupMap = new Map() - for (const s of filtered) { - const g = s.group || '未分组' - if (!groupMap.has(g)) { - groupMap.set(g, []) - } - groupMap.get(g)!.push(s) - } - // Sort: "未分组" last - const sortedKeys = Array.from(groupMap.keys()).sort((a, b) => { - if (a === '未分组') return 1 - if (b === '未分组') return -1 - return a.localeCompare(b, 'zh') - }) - for (const key of sortedKeys) { - groups.push({ name: key, servers: groupMap.get(key)! }) - } - - const toggleGroup = (name: string) => { - setCollapsed((prev) => ({ ...prev, [name]: !prev[name] })) - } - - if (loading) { - return ( -
- -
- ) + for (const server of filtered) { + const name = server.group || '未分组' + if (!groupMap.has(name)) groupMap.set(name, []) + groupMap.get(name)!.push(server) } + const groups = Array.from(groupMap.keys()).sort((a, b) => a === '未分组' ? 1 : b === '未分组' ? -1 : a.localeCompare(b, 'zh')) + if (loading) return
加载服务器…
return ( -
- } - placeholder="搜索服务器..." - value={search} - onChange={(e) => setSearch(e.target.value)} - style={{ marginBottom: 12 }} - allowClear - /> - - - - {filtered.length === 0 ? ( - - {servers.length === 0 ? '暂无服务器' : '无匹配结果'} - - } - /> - ) : ( -
- {groups.map((group) => ( -
- {/* Group header */} - - - {/* Group servers */} - {!collapsed[group.name] && ( -
- {group.servers.map((server) => ( -
handleContextMenu(e, server)} - style={{ - padding: '8px 12px', - borderRadius: 6, - background: colors.fillSubtle, - border: `1px solid ${colors.borderLight}`, - cursor: 'pointer', - transition: 'all 0.15s', - marginLeft: 12, - }} - onMouseEnter={(e) => { - ;(e.currentTarget).style.background = colors.fillHover - }} - onMouseLeave={(e) => { - ;(e.currentTarget).style.background = colors.fillSubtle - }} - > - -
-
-
- ))} +
+
+ } placeholder="搜索服务器..." aria-label="搜索服务器" value={search} onChange={event => setSearch(event.target.value)} allowClear /> + +
+
+ {!filtered.length ?
+ +

{servers.length ? '试试名称、地址或分组关键词' : '添加第一台服务器,开始连接'}

+
: groups.map(name => ( +
+ + {!collapsed[name] &&
{groupMap.get(name)!.map(server => ( + +
+ +
+
- )} -
- ))} -
- )} - - {modalOpen && 加载服务器表单…
}> { - setModalOpen(false) - setEditing(null) - }} - />} - - {/* Context Menu */} - {contextMenu && ( -
e.stopPropagation()} - style={{ - position: 'fixed', - left: contextMenu.x, - top: contextMenu.y, - background: colors.bgContextMenu, - border: `1px solid ${colors.borderSubtle}`, - borderRadius: 8, - padding: '4px 0', - zIndex: 1000, - minWidth: 140, - boxShadow: colors.shadowContextMenu, - }} - > - } label="连接" colors={colors} onClick={() => onConnect(contextMenu.server)} /> - } label="文件管理" colors={colors} onClick={() => { setFileManagerServer(contextMenu.server); setContextMenu(null) }} /> - } label="测试连接" colors={colors} onClick={() => handleTest(contextMenu.server)} /> - } label="编辑" colors={colors} onClick={() => handleEdit(contextMenu.server)} /> -
- } label="删除" danger colors={colors} onClick={() => handleDelete(contextMenu.server)} /> -
- )} - - {/* File Manager Modal */} - {fileManagerServer && ( - 加载文件管理…
}> setFileManagerServer(null)} - /> - )} + + ))}
} + + ))} +
+
{search ? `显示 ${filtered.length} / ${servers.length} 台服务器` : `${servers.length} 台服务器`}
+ {modalOpen && 加载服务器表单…
}> + { setModalOpen(false); setEditing(null) }} /> + } + {fileManagerServer && 加载文件管理…
}> + setFileManagerServer(null)} /> + } ) } - -function CtxItem({ icon, label, danger, colors, onClick }: { icon: React.ReactNode; label: string; danger?: boolean; colors: any; onClick: () => void }) { - return ( - - ) -} diff --git a/ui/src/components/TerminalTab.tsx b/ui/src/components/TerminalTab.tsx index 551850c..6c59e78 100644 --- a/ui/src/components/TerminalTab.tsx +++ b/ui/src/components/TerminalTab.tsx @@ -2,7 +2,7 @@ import { useEffect, useState, useMemo } from 'react' import { useTerminalConnection, type ConnectionStatus } from '../hooks/useTerminalConnection' import Spin from 'antd/es/spin' import Button from 'antd/es/button' -import { ReloadOutlined, DisconnectOutlined } from '@ant-design/icons' +import { ReloadOutlined, DisconnectOutlined, CodeOutlined } from '@ant-design/icons' import '@xterm/xterm/css/xterm.css' import '../styles/terminal.css' import { useTheme } from '../contexts/ThemeContext' @@ -17,276 +17,66 @@ interface Props { const TERM_THEMES = { dark: { - background: '#1a1a2e', - foreground: '#e0e0e0', - cursor: '#1677ff', - selectionBackground: 'rgba(22, 119, 255, 0.3)', - black: '#1a1a2e', - red: '#ff6b6b', - green: '#51cf66', - yellow: '#ffd43b', - blue: '#339af0', - magenta: '#cc5de8', - cyan: '#22b8cf', - white: '#e0e0e0', - brightBlack: '#6b6b8d', - brightRed: '#ff8787', - brightGreen: '#69db7c', - brightYellow: '#ffe066', - brightBlue: '#4dabf7', - brightMagenta: '#da77f2', - brightCyan: '#3bc9db', - brightWhite: '#ffffff', + background: '#1a1a2e', foreground: '#e0e0e0', cursor: '#1677ff', selectionBackground: 'rgba(22, 119, 255, 0.3)', + black: '#1a1a2e', red: '#ff6b6b', green: '#51cf66', yellow: '#ffd43b', blue: '#339af0', magenta: '#cc5de8', cyan: '#22b8cf', white: '#e0e0e0', + brightBlack: '#6b6b8d', brightRed: '#ff8787', brightGreen: '#69db7c', brightYellow: '#ffe066', brightBlue: '#4dabf7', brightMagenta: '#da77f2', brightCyan: '#3bc9db', brightWhite: '#ffffff', }, light: { - background: '#ffffff', - foreground: '#1a1a1a', - cursor: '#1677ff', - selectionBackground: 'rgba(22, 119, 255, 0.15)', - black: '#ffffff', - red: '#c0392b', - green: '#27ae60', - yellow: '#f39c12', - blue: '#2980b9', - magenta: '#8e44ad', - cyan: '#16a085', - white: '#1a1a1a', - brightBlack: '#7f8c8d', - brightRed: '#e74c3c', - brightGreen: '#2ecc71', - brightYellow: '#f1c40f', - brightBlue: '#3498db', - brightMagenta: '#9b59b6', - brightCyan: '#1abc9c', - brightWhite: '#000000', + background: '#ffffff', foreground: '#1a1a1a', cursor: '#1677ff', selectionBackground: 'rgba(22, 119, 255, 0.15)', + black: '#ffffff', red: '#c0392b', green: '#27ae60', yellow: '#f39c12', blue: '#2980b9', magenta: '#8e44ad', cyan: '#16a085', white: '#1a1a1a', + brightBlack: '#7f8c8d', brightRed: '#e74c3c', brightGreen: '#2ecc71', brightYellow: '#f1c40f', brightBlue: '#3498db', brightMagenta: '#9b59b6', brightCyan: '#1abc9c', brightWhite: '#000000', }, } - function hexToRgb(hex: string): string { - const r = parseInt(hex.slice(1, 3), 16) - const g = parseInt(hex.slice(3, 5), 16) - const b = parseInt(hex.slice(5, 7), 16) - return `${r},${g},${b}` + return [1, 3, 5].map(offset => parseInt(hex.slice(offset, offset + 2), 16)).join(',') } - const SHORTCUTS = [ - // vim mode keys - { label: 'ESC', data: '\x1b' }, - { label: ':', data: ':' }, - { label: '/', data: '/' }, - { label: 'i', data: 'i' }, - { label: 'a', data: 'a' }, - { label: 'o', data: 'o' }, - { label: 'O', data: 'O' }, - { label: ':wq', data: ':wq\r' }, - { label: ':q!', data: ':q!\r' }, - { label: 'dd', data: 'dd' }, - { label: 'yy', data: 'yy' }, - { label: 'p', data: 'p' }, - { label: 'u', data: 'u' }, - { label: 'x', data: 'x' }, - { label: 'G', data: 'G' }, - { label: 'gg', data: 'gg' }, - { label: '$', data: '$' }, - { label: '0', data: '0' }, - { label: 'w', data: 'w' }, - { label: 'b', data: 'b' }, - // navigation - { label: 'Tab', data: '\t' }, - { label: '↑', data: '\x1b[A' }, - { label: '↓', data: '\x1b[B' }, - { label: '←', data: '\x1b[D' }, - { label: '→', data: '\x1b[C' }, - // ctrl shortcuts - { label: 'Ctrl+C', data: '\x03' }, - { label: 'Ctrl+Z', data: '\x1a' }, - { label: 'Ctrl+D', data: '\x04' }, - { label: 'Ctrl+L', data: '\x0c' }, - { label: 'Ctrl+U', data: '\x15' }, - { label: 'Ctrl+K', data: '\x0b' }, - { label: 'Ctrl+A', data: '\x01' }, - { label: 'Ctrl+E', data: '\x05' }, - { label: 'Ctrl+W', data: '\x17' }, - { label: 'Ctrl+R', data: '\x12' }, + { label: 'ESC', data: '\x1b' }, { label: ':', data: ':' }, { label: '/', data: '/' }, + { label: 'i', data: 'i' }, { label: 'a', data: 'a' }, { label: 'o', data: 'o' }, { label: 'O', data: 'O' }, + { label: ':wq', data: ':wq\r' }, { label: ':q!', data: ':q!\r' }, + { label: 'dd', data: 'dd' }, { label: 'yy', data: 'yy' }, { label: 'p', data: 'p' }, { label: 'u', data: 'u' }, + { label: 'x', data: 'x' }, { label: 'G', data: 'G' }, { label: 'gg', data: 'gg' }, { label: '$', data: '$' }, + { label: '0', data: '0' }, { label: 'w', data: 'w' }, { label: 'b', data: 'b' }, + { label: 'Tab', data: '\t' }, { label: '↑', data: '\x1b[A' }, { label: '↓', data: '\x1b[B' }, { label: '←', data: '\x1b[D' }, { label: '→', data: '\x1b[C' }, + { label: 'Ctrl+C', data: '\x03' }, { label: 'Ctrl+Z', data: '\x1a' }, { label: 'Ctrl+D', data: '\x04' }, + { label: 'Ctrl+L', data: '\x0c' }, { label: 'Ctrl+U', data: '\x15' }, { label: 'Ctrl+K', data: '\x0b' }, + { label: 'Ctrl+A', data: '\x01' }, { label: 'Ctrl+E', data: '\x05' }, { label: 'Ctrl+W', data: '\x17' }, { label: 'Ctrl+R', data: '\x12' }, ] export default function TerminalTab({ serverId, serverName, isActive, fontSize, onStatusChange }: Props) { const { mode, colors } = useTheme() const [showBar, setShowBar] = useState(true) const termTheme = useMemo(() => ({ - ...TERM_THEMES[mode], - cursor: colors.colorPrimary, + ...TERM_THEMES[mode], cursor: colors.colorPrimary, selectionBackground: `rgba(${hexToRgb(colors.colorPrimary)}, ${mode === 'dark' ? 0.3 : 0.15})`, }), [mode, colors.colorPrimary]) const { containerRef, termRef, status, errorMsg, connect, sendShortcut } = useTerminalConnection(serverId, fontSize, termTheme, isActive, showBar) useEffect(() => { onStatusChange?.(status) }, [status, onStatusChange]) return ( -
-
- {/* Terminal container: always visible so xterm can calculate dimensions */} -
- {/* Loading overlay */} - {status === 'connecting' && ( -
- - 正在连接 {serverName}... -
- )} - {/* Disconnected banner - keeps terminal history visible */} - {status === 'error' && termRef.current && ( -
- - - {errorMsg} - - -
- )} - {/* Initial error (no terminal yet) */} - {status === 'error' && !termRef.current && ( -
-
- -
- {errorMsg} -
-
- {serverName} -
- +
+
+
+ {status === 'connecting' &&
正在连接 {serverName}…
} + {status === 'error' && termRef.current &&
+ {errorMsg} + +
} + {status === 'error' && !termRef.current &&
+
+ +

{errorMsg}

{serverName} +
-
- )} +
}
- {/* Mobile shortcut bar */} - {showBar && status === 'connected' && ( -
- {SHORTCUTS.map((s) => ( - - ))} -
- )} - {/* Shortcut bar toggle */} - {status === 'connected' && ( - - )} + {showBar && status === 'connected' &&
+ {SHORTCUTS.map(shortcut => )} +
} + {status === 'connected' && }
) } diff --git a/ui/src/components/TerminalTabs.tsx b/ui/src/components/TerminalTabs.tsx index 2ae6da4..bd7c78a 100644 --- a/ui/src/components/TerminalTabs.tsx +++ b/ui/src/components/TerminalTabs.tsx @@ -1,8 +1,6 @@ import { useState, useCallback, lazy, Suspense, useEffect, useRef } from 'react' -import Empty from 'antd/es/empty' import Spin from 'antd/es/spin' import { CloseOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons' -import { useTheme } from '../contexts/ThemeContext' import type { TabInfo } from '../pages/MainPage' import type { ConnectionStatus } from '../hooks/useTerminalConnection' @@ -11,16 +9,9 @@ const FONT_KEY = 'opsup_font_size' const MIN_SIZE = 10 const MAX_SIZE = 28 const labels = { connecting: '正在连接', connected: '已连接', error: '连接断开或失败' } - -interface Props { - tabs: TabInfo[] - activeKey: string - onSelect: (key: string) => void - onClose: (key: string) => void -} +interface Props { tabs: TabInfo[]; activeKey: string; onSelect: (key: string) => void; onClose: (key: string) => void } export default function TerminalTabs({ tabs, activeKey, onSelect, onClose }: Props) { - const { colors } = useTheme() const [fontSize, setFontSize] = useState(() => { const saved = Number(localStorage.getItem(FONT_KEY)) return saved >= MIN_SIZE && saved <= MAX_SIZE ? saved : 14 @@ -43,10 +34,7 @@ export default function TerminalTabs({ tabs, activeKey, onSelect, onClose }: Pro return next }) }, []) - const focusTab = (key: string) => { - onSelect(key) - document.getElementById(`tab-${key}`)?.focus() - } + const focusTab = (key: string) => { onSelect(key); document.getElementById(`tab-${key}`)?.focus() } const closeTab = (key: string) => { const index = tabs.findIndex(tab => tab.key === key) const next = tabs[index + 1] || tabs[index - 1] @@ -54,18 +42,28 @@ export default function TerminalTabs({ tabs, activeKey, onSelect, onClose }: Pro if (next) focusTab(next.key) } - if (!tabs.length) return
从服务器列表选择一个服务器开始连接} />
+ if (!tabs.length) return ( +
+
终端工作区SSH / SFTP
+
+ +

开始一个终端会话

+

从服务器列表选择主机,在这里开始连接。
切换标签时,会话会保留在原处。

+
多标签终端文件管理快捷键支持
+
+
+ ) return ( -
-
-
+
+
+
{tabs.map((tab, index) => { const status = statuses[tab.key] || 'connecting' - return
- - +
})}
-
- - {fontSize}px - +
+ + {fontSize}px +
-
- {tabs.map(tab => ( - }> - - -
- ))} -
+
{tabs.map(tab => ( + }> + + +
+ ))}
) } diff --git a/ui/src/contexts/ThemeContext.test.tsx b/ui/src/contexts/ThemeContext.test.tsx new file mode 100644 index 0000000..63efbd4 --- /dev/null +++ b/ui/src/contexts/ThemeContext.test.tsx @@ -0,0 +1,23 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import { expect, it } from 'vitest' +import { ThemeProvider, useTheme } from './ThemeContext' + +function Controls() { + const { mode, accent, colors, toggleMode, setAccent } = useTheme() + return <>{mode}:{accent}:{colors.terminalBg} +} + +it('preserves the terminal palette and applies saved accent choices to CSS states', () => { + localStorage.setItem('opsup_theme_mode', 'invalid') + localStorage.setItem('opsup_theme_accent', 'invalid') + render() + expect(screen.getByRole('status')).toHaveTextContent('dark:blue:#1a1a2e') + fireEvent.click(screen.getByText('Accent')) + expect(document.documentElement.style.getPropertyValue('--color-primary')).toBe('#722ed1') + expect(document.documentElement.style.getPropertyValue('--accent-border')).toBe('#722ed140') + fireEvent.click(screen.getByText('Theme')) + expect(screen.getByRole('status')).toHaveTextContent('light:purple:#ffffff') + expect(document.documentElement.dataset.theme).toBe('light') + expect(localStorage.getItem('opsup_theme_mode')).toBe('light') + expect(localStorage.getItem('opsup_theme_accent')).toBe('purple') +}) diff --git a/ui/src/contexts/ThemeContext.tsx b/ui/src/contexts/ThemeContext.tsx index 64d6ae4..a5c2c03 100644 --- a/ui/src/contexts/ThemeContext.tsx +++ b/ui/src/contexts/ThemeContext.tsx @@ -6,13 +6,8 @@ export type ThemeMode = 'dark' | 'light' export type AccentKey = 'blue' | 'green' | 'purple' | 'orange' | 'red' const ACCENT_MAP: Record = { - blue: '#1677ff', - green: '#52c41a', - purple: '#722ed1', - orange: '#fa8c16', - red: '#f5222d', + blue: '#1677ff', green: '#52c41a', purple: '#722ed1', orange: '#fa8c16', red: '#f5222d', } - export const ACCENT_OPTIONS: { key: AccentKey; color: string; label: string }[] = [ { key: 'blue', color: '#1677ff', label: '蓝色' }, { key: 'green', color: '#52c41a', label: '绿色' }, @@ -47,69 +42,32 @@ export interface SemanticColors { function getSemanticColors(mode: ThemeMode, accent: AccentKey): SemanticColors { const primary = ACCENT_MAP[accent] - if (mode === 'dark') { - return { - bgBase: '#141414', - bgSidebar: '#1a1a2e', - bgTabBar: '#1a1a2e', - bgCardOverlay: 'rgba(30, 30, 50, 0.9)', - textPrimary: '#e0e0e0', - textSecondary: 'rgba(255,255,255,0.65)', - textTertiary: 'rgba(255,255,255,0.35)', - borderSubtle: 'rgba(255,255,255,0.06)', - borderLight: 'rgba(255,255,255,0.04)', - fillHover: 'rgba(255,255,255,0.07)', - fillSubtle: 'rgba(255,255,255,0.03)', - fillMedium: 'rgba(255,255,255,0.06)', - scrollbarThumb: 'rgba(255, 255, 255, 0.15)', - scrollbarHover: 'rgba(255, 255, 255, 0.3)', - bgContextMenu: '#2a2a2a', - shadowContextMenu: '0 6px 16px rgba(0,0,0,0.5)', - gradientPage: 'linear-gradient(135deg, #0c0c1d 0%, #1a1a2e 50%, #16213e 100%)', - gradientLogo: `linear-gradient(135deg, ${primary}, ${primary}cc)`, - colorPrimary: primary, - terminalBg: '#1a1a2e', - terminalFg: '#e0e0e0', - } - } - return { - bgBase: '#f0f2f5', - bgSidebar: '#ffffff', - bgTabBar: '#ffffff', - bgCardOverlay: 'rgba(255, 255, 255, 0.95)', - textPrimary: '#141414', - textSecondary: 'rgba(0,0,0,0.65)', - textTertiary: 'rgba(0,0,0,0.35)', - borderSubtle: 'rgba(0,0,0,0.06)', - borderLight: 'rgba(0,0,0,0.04)', - fillHover: 'rgba(0,0,0,0.04)', - fillSubtle: 'rgba(0,0,0,0.02)', - fillMedium: 'rgba(0,0,0,0.06)', - scrollbarThumb: 'rgba(0, 0, 0, 0.15)', - scrollbarHover: 'rgba(0, 0, 0, 0.3)', - bgContextMenu: '#ffffff', - shadowContextMenu: '0 6px 16px rgba(0,0,0,0.12)', - gradientPage: 'linear-gradient(135deg, #e8eaf6 0%, #c5cae9 50%, #bbdefb 100%)', - gradientLogo: `linear-gradient(135deg, ${primary}, ${primary}cc)`, - colorPrimary: primary, - terminalBg: '#ffffff', - terminalFg: '#1a1a1a', + const shared = { colorPrimary: primary, gradientLogo: `linear-gradient(145deg, ${primary}, ${primary}bb)` } + return mode === 'dark' ? { + ...shared, + bgBase: '#131320', bgSidebar: '#181827', bgTabBar: '#161625', + bgCardOverlay: 'rgba(26, 26, 46, 0.96)', + textPrimary: '#eeeef6', textSecondary: '#b4b4c9', textTertiary: '#9090aa', + borderSubtle: 'rgba(180,180,220,0.12)', borderLight: 'rgba(180,180,220,0.07)', + fillHover: 'rgba(180,180,220,0.09)', fillSubtle: 'rgba(180,180,220,0.035)', fillMedium: 'rgba(180,180,220,0.07)', + scrollbarThumb: 'rgba(180,180,220,0.2)', scrollbarHover: 'rgba(180,180,220,0.35)', + bgContextMenu: '#222238', shadowContextMenu: '0 12px 36px rgba(0,0,0,0.3)', + gradientPage: 'radial-gradient(ellipse at 50% 20%, #242444 0%, #171728 48%, #10101d 100%)', + terminalBg: '#1a1a2e', terminalFg: '#e0e0e0', + } : { + ...shared, + bgBase: '#f3f5f9', bgSidebar: '#fcfcfe', bgTabBar: '#f8f9fc', + bgCardOverlay: 'rgba(255,255,255,0.97)', + textPrimary: '#23243b', textSecondary: '#5d617a', textTertiary: '#70768c', + borderSubtle: 'rgba(56,65,99,0.12)', borderLight: 'rgba(56,65,99,0.07)', + fillHover: 'rgba(56,65,99,0.06)', fillSubtle: 'rgba(56,65,99,0.025)', fillMedium: 'rgba(56,65,99,0.05)', + scrollbarThumb: 'rgba(56,65,99,0.2)', scrollbarHover: 'rgba(56,65,99,0.35)', + bgContextMenu: '#ffffff', shadowContextMenu: '0 12px 36px rgba(36,44,80,0.12)', + gradientPage: 'radial-gradient(ellipse at 50% 20%, #e4e8fa 0%, #eef0f8 48%, #f6f7fb 100%)', + terminalBg: '#ffffff', terminalFg: '#1a1a1a', } } -const MODE_TOKENS: Record> = { - dark: { - colorBgContainer: '#1f1f1f', - colorBgElevated: '#2a2a2a', - colorBorder: '#3a3a3a', - }, - light: { - colorBgContainer: '#ffffff', - colorBgElevated: '#f5f5f5', - colorBorder: '#e8e8e8', - }, -} - interface ThemeContextValue { mode: ThemeMode accent: AccentKey @@ -119,7 +77,6 @@ interface ThemeContextValue { themeConfig: ThemeConfig colors: SemanticColors } - const ThemeContext = createContext(null) export function useTheme(): ThemeContextValue { @@ -129,59 +86,63 @@ export function useTheme(): ThemeContextValue { } function loadMode(): ThemeMode { - return (localStorage.getItem('opsup_theme_mode') as ThemeMode) || 'dark' + return localStorage.getItem('opsup_theme_mode') === 'light' ? 'light' : 'dark' } - function loadAccent(): AccentKey { - return (localStorage.getItem('opsup_theme_accent') as AccentKey) || 'blue' + const stored = localStorage.getItem('opsup_theme_accent') + return ACCENT_OPTIONS.find(option => option.key === stored)?.key || 'blue' } export function ThemeProvider({ children }: { children: React.ReactNode }) { const [mode, setModeState] = useState(loadMode) const [accent, setAccentState] = useState(loadAccent) - - const setMode = (m: ThemeMode) => { - setModeState(m) - localStorage.setItem('opsup_theme_mode', m) + const setMode = (value: ThemeMode) => { + setModeState(value) + localStorage.setItem('opsup_theme_mode', value) } - - const setAccent = (a: AccentKey) => { - setAccentState(a) - localStorage.setItem('opsup_theme_accent', a) + const setAccent = (value: AccentKey) => { + setAccentState(value) + localStorage.setItem('opsup_theme_accent', value) } - const toggleMode = () => setMode(mode === 'dark' ? 'light' : 'dark') - const colors = useMemo(() => getSemanticColors(mode, accent), [mode, accent]) - const themeConfig = useMemo(() => ({ algorithm: mode === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm, token: { - colorPrimary: ACCENT_MAP[accent], - borderRadius: 6, - ...MODE_TOKENS[mode], + colorPrimary: colors.colorPrimary, + colorBgContainer: mode === 'dark' ? '#1e1e32' : '#ffffff', + colorBgElevated: colors.bgContextMenu, + colorBgLayout: colors.bgBase, + colorBorder: mode === 'dark' ? '#38384f' : '#dfe3ed', + colorText: colors.textPrimary, + colorTextSecondary: colors.textSecondary, + colorTextPlaceholder: colors.textTertiary, + fontFamily: 'var(--font-ui)', + borderRadius: 8, + controlHeight: 34, + }, + components: { + Modal: { borderRadiusLG: 12 }, + Table: { headerBg: colors.fillSubtle, rowHoverBg: colors.fillHover }, + Button: { fontWeight: 500 }, }, - }), [mode, accent]) + }), [mode, colors]) - // Inject CSS custom properties useEffect(() => { const root = document.documentElement - root.style.setProperty('--bg-base', colors.bgBase) - root.style.setProperty('--bg-sidebar', colors.bgSidebar) - root.style.setProperty('--bg-terminal', colors.terminalBg) - root.style.setProperty('--text-primary', colors.textPrimary) - root.style.setProperty('--text-secondary', colors.textSecondary) - root.style.setProperty('--text-tertiary', colors.textTertiary) - root.style.setProperty('--scrollbar-thumb', colors.scrollbarThumb) - root.style.setProperty('--scrollbar-hover', colors.scrollbarHover) - root.style.setProperty('--fill-hover', colors.fillHover) - root.style.setProperty('--fill-subtle', colors.fillSubtle) - root.style.setProperty('--border-subtle', colors.borderSubtle) - }, [colors]) + root.dataset.theme = mode + const variables: Record = { + 'bg-base': colors.bgBase, 'bg-sidebar': colors.bgSidebar, 'bg-tab-bar': colors.bgTabBar, + 'bg-terminal': colors.terminalBg, 'bg-elevated': colors.bgContextMenu, + 'text-primary': colors.textPrimary, 'text-secondary': colors.textSecondary, 'text-tertiary': colors.textTertiary, + 'scrollbar-thumb': colors.scrollbarThumb, 'scrollbar-hover': colors.scrollbarHover, + 'fill-hover': colors.fillHover, 'fill-subtle': colors.fillSubtle, 'fill-medium': colors.fillMedium, + 'border-subtle': colors.borderSubtle, 'border-light': colors.borderLight, + 'color-primary': colors.colorPrimary, 'accent-soft': `${colors.colorPrimary}14`, 'accent-border': `${colors.colorPrimary}40`, + 'gradient-page': colors.gradientPage, 'gradient-logo': colors.gradientLogo, 'bg-card-overlay': colors.bgCardOverlay, + } + for (const [name, value] of Object.entries(variables)) root.style.setProperty(`--${name}`, value) + }, [mode, colors]) - return ( - - {children} - - ) + return {children} } diff --git a/ui/src/pages/LoginPage.tsx b/ui/src/pages/LoginPage.tsx index 791fcf8..d434a3c 100644 --- a/ui/src/pages/LoginPage.tsx +++ b/ui/src/pages/LoginPage.tsx @@ -3,33 +3,23 @@ import { useNavigate } from 'react-router-dom' import Form from 'antd/es/form' import Input from 'antd/es/input' import Button from 'antd/es/button' -import Card from 'antd/es/card' -import Typography from 'antd/es/typography' import message from 'antd/es/message' import { UserOutlined, LockOutlined } from '@ant-design/icons' import { useAuth } from '../hooks/useAuth' import { getAuthStatus } from '../api/auth' -import { useTheme } from '../contexts/ThemeContext' - -const { Title, Text } = Typography +import AuthFrame from '../components/AuthFrame' export default function LoginPage() { const [loading, setLoading] = useState(false) const [initialized, setInitialized] = useState(null) const navigate = useNavigate() const { doLogin } = useAuth() - const { colors } = useTheme() useEffect(() => { getAuthStatus().then((res) => { setInitialized(res.initialized) - if (!res.initialized) { - navigate('/setup', { replace: true }) - } - }).catch(() => { - // API error, assume initialized and show login - setInitialized(true) - }) + if (!res.initialized) navigate('/setup', { replace: true }) + }).catch(() => setInitialized(true)) }, [navigate]) const onFinish = async (values: { username: string; password: string }) => { @@ -46,65 +36,19 @@ export default function LoginPage() { } if (initialized === false) return null - return ( -
- -
-
- >_ -
- - OpsUp - - Web SSH Terminal -
- - - - } placeholder="用户名" /> - - - } placeholder="密码" /> - - - - - -
-
+ +
+ + } placeholder="用户名" autoComplete="username" /> + + + } placeholder="密码" autoComplete="current-password" /> + + + + + +
) } diff --git a/ui/src/pages/MainPage.tsx b/ui/src/pages/MainPage.tsx index eb44c03..1f103d8 100644 --- a/ui/src/pages/MainPage.tsx +++ b/ui/src/pages/MainPage.tsx @@ -12,62 +12,51 @@ import type { AccentKey } from '../contexts/ThemeContext' import type { Server } from '../types' const { Sider, Content } = Layout - -export interface TabInfo { - key: string - server: Server -} +export interface TabInfo { key: string; server: Server } export default function MainPage() { const [drawerOpen, setDrawerOpen] = useState(false) - const screens = Grid.useBreakpoint() - const mobile = !screens.md + const mobile = !Grid.useBreakpoint().md const [tabs, setTabs] = useState([]) - const [activeKey, setActiveKey] = useState('') - const { mode, accent, colors, toggleMode, setAccent } = useTheme() - + const [activeKey, setActiveKey] = useState('') + const { mode, accent, toggleMode, setAccent } = useTheme() const username = localStorage.getItem('opsup_username') || '' - - // Track visual viewport to keep shortcut bar above virtual keyboard - const [viewportHeight, setViewportHeight] = useState(() => - window.visualViewport ? window.visualViewport.height : window.innerHeight - ) + const [viewportHeight, setViewportHeight] = useState(() => window.visualViewport?.height || window.innerHeight) useEffect(() => { - const vv = window.visualViewport - if (!vv) return - const update = () => setViewportHeight(vv.height) - vv.addEventListener('resize', update) - vv.addEventListener('scroll', update) + const viewport = window.visualViewport + const update = () => setViewportHeight(viewport?.height || window.innerHeight) + update() + window.addEventListener('resize', update) + viewport?.addEventListener('resize', update) + viewport?.addEventListener('scroll', update) return () => { - vv.removeEventListener('resize', update) - vv.removeEventListener('scroll', update) + window.removeEventListener('resize', update) + viewport?.removeEventListener('resize', update) + viewport?.removeEventListener('scroll', update) } }, []) const openTerminal = useCallback((server: Server) => { setDrawerOpen(false) const key = `${server.id}-${Date.now()}` - setTabs((prev) => { - const exists = prev.find((t) => t.server.id === server.id) + setTabs(previous => { + const exists = previous.find(tab => tab.server.id === server.id) if (exists) { setActiveKey(exists.key) - return prev + return previous } setActiveKey(key) - return [...prev, { key, server }] + return [...previous, { key, server }] }) }, []) const closeTerminal = useCallback((targetKey: string) => { - setTabs((prev) => { - const newTabs = prev.filter((t) => t.key !== targetKey) - if (activeKey === targetKey && newTabs.length > 0) { - setActiveKey(newTabs[newTabs.length - 1].key) - } else if (newTabs.length === 0) { - setActiveKey('') - } - return newTabs + setTabs(previous => { + const next = previous.filter(tab => tab.key !== targetKey) + if (activeKey === targetKey && next.length) setActiveKey(next[next.length - 1].key) + else if (!next.length) setActiveKey('') + return next }) }, [activeKey]) @@ -77,96 +66,44 @@ export default function MainPage() { window.location.href = '/login' } - const sidebar = <>
- - OpsUp - -
- - -
-
-
- -
- + const sidebar = <> + {!mobile &&
+ +
OpsUpWeb SSH Terminal
+
} +
+ tab.key === activeKey)?.server.id} /> +
+
+ , label: '退出登录', onClick: logout }] }}> + + +
+ return ( - + {mobile ? ( - setDrawerOpen(false)} - size={300} styles={{ body: { padding: 0, background: colors.bgSidebar, display: 'flex', flexDirection: 'column' } }}> + setDrawerOpen(false)} size={320} + styles={{ wrapper: { maxWidth: 'calc(100vw - 24px)' }, body: { padding: 0, background: 'var(--bg-sidebar)', display: 'flex', flexDirection: 'column' } }}> {sidebar} - ) : ( - - {sidebar} - - )} - - - - {mobile &&
} -
+ ) : {sidebar}} + + + {mobile &&
OpsUp
} +
diff --git a/ui/src/pages/SetupPage.tsx b/ui/src/pages/SetupPage.tsx index 9b1c7d4..86ee61d 100644 --- a/ui/src/pages/SetupPage.tsx +++ b/ui/src/pages/SetupPage.tsx @@ -3,27 +3,20 @@ import { useNavigate } from 'react-router-dom' import Form from 'antd/es/form' import Input from 'antd/es/input' import Button from 'antd/es/button' -import Card from 'antd/es/card' -import Typography from 'antd/es/typography' import message from 'antd/es/message' import { UserOutlined, LockOutlined } from '@ant-design/icons' import { useAuth } from '../hooks/useAuth' import { getAuthStatus } from '../api/auth' -import { useTheme } from '../contexts/ThemeContext' - -const { Title, Text } = Typography +import AuthFrame from '../components/AuthFrame' export default function SetupPage() { const [loading, setLoading] = useState(false) const navigate = useNavigate() const { doSetup } = useAuth() - const { colors } = useTheme() useEffect(() => { getAuthStatus().then((res) => { - if (res.initialized) { - navigate('/login') - } + if (res.initialized) navigate('/login') }) }, [navigate]) @@ -41,64 +34,31 @@ export default function SetupPage() { } return ( -
- -
- - 初始化 OpsUp - - 创建管理员账户 -
- -
- - } placeholder="管理员用户名" /> - - !value || new TextEncoder().encode(value).length <= 72 - ? Promise.resolve() : Promise.reject(new Error('密码最多72个 UTF-8 字节')) }, - ]}> - } placeholder="密码" /> - - ({ - validator(_, value) { - if (!value || getFieldValue('password') === value) return Promise.resolve() - return Promise.reject(new Error('两次密码不一致')) - }, - }), - ]} - > - } placeholder="确认密码" /> - - - - - -
-
+ +
+ + } placeholder="管理员用户名" autoComplete="username" /> + + !value || new TextEncoder().encode(value).length <= 72 + ? Promise.resolve() : Promise.reject(new Error('密码最多72个 UTF-8 字节')) }, + ]}> + } placeholder="密码" autoComplete="new-password" /> + + ({ validator(_, value) { + return !value || getFieldValue('password') === value + ? Promise.resolve() : Promise.reject(new Error('两次密码不一致')) + } }), + ]}> + } placeholder="确认密码" autoComplete="new-password" /> + + + + + +
) } diff --git a/ui/src/styles/global.css b/ui/src/styles/global.css index 025fbbe..6d87e7a 100644 --- a/ui/src/styles/global.css +++ b/ui/src/styles/global.css @@ -1,81 +1,150 @@ - -* { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -html, body, #root { - height: 100%; - width: 100%; - overflow: hidden; -} - -body { - background: var(--bg-base, #141414); - color: var(--text-primary, rgba(255, 255, 255, 0.85)); - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; -} - -/* Scrollbar */ -::-webkit-scrollbar { - width: 6px; - height: 6px; -} - -::-webkit-scrollbar-track { - background: transparent; +:root { + --font-ui: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Noto Sans CJK SC', 'PingFang SC', 'Microsoft YaHei', sans-serif; + --font-mono: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; + --color-primary: #1677ff; + --bg-base: #131320; + --bg-sidebar: #181827; + --bg-terminal: #1a1a2e; + --text-primary: #eeeef6; } +* { margin: 0; padding: 0; box-sizing: border-box; } +html, body, #root { height: 100%; width: 100%; overflow: hidden; } +body { background: var(--bg-base); color: var(--text-primary); font-family: var(--font-ui); -webkit-font-smoothing: antialiased; } +::selection { background: var(--accent-border); } +::-webkit-scrollbar { width: 6px; height: 6px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: 6px; } +::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-hover); } +.plain-button { border: 0; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; } +button:focus-visible, [role='tab']:focus-visible { outline: 2px solid var(--color-primary); outline-offset: -2px; } +button:disabled { cursor: not-allowed; } +.plain-button:disabled { opacity: 0.35; } +.mono { font-family: var(--font-mono); } +.brand-mark { display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; width: 32px; height: 32px; border-radius: 9px; background: var(--gradient-logo); color: #fff; font: 600 17px var(--font-mono); box-shadow: inset 0 1px 0 #ffffff25; } -::-webkit-scrollbar-thumb { - background: var(--scrollbar-thumb, rgba(255, 255, 255, 0.15)); - border-radius: 3px; -} - -::-webkit-scrollbar-thumb:hover { - background: var(--scrollbar-hover, rgba(255, 255, 255, 0.3)); -} +.auth-page { height: 100%; display: flex; flex-direction: column; align-items: center; overflow-y: auto; padding: 32px 16px; background: var(--gradient-page); } +.auth-card.ant-card { width: 100%; max-width: 420px; margin: auto; flex-shrink: 0; border: 1px solid var(--border-subtle); border-radius: 16px; background: var(--bg-card-overlay); box-shadow: 0 24px 80px #00000026, 0 2px 8px #0000000a; } +.auth-card .ant-card-body { padding: 32px; } +.auth-heading { text-align: center; margin-bottom: 28px; } +.auth-heading .brand-mark { width: 52px; height: 52px; font-size: 26px; border-radius: 14px; margin-bottom: 18px; } +.auth-heading h1 { color: var(--text-primary); font-size: 24px; line-height: 1.4; font-weight: 600; letter-spacing: -0.6px; } +.auth-heading p { color: var(--text-tertiary); font-size: 13px; margin-top: 6px; } +.auth-card .ant-form-item { margin-bottom: 18px; } +.auth-card .ant-form-item-label > label { font-size: 12px; color: var(--text-secondary); } +.auth-card .ant-input-prefix { color: var(--text-tertiary); margin-right: 10px; } +.auth-card .auth-submit { margin-top: 6px; margin-bottom: 0; } +.auth-note { margin-top: 24px; padding-top: 18px; border-top: 1px solid var(--border-light); text-align: center; font-size: 12px; color: var(--text-tertiary); } -/* Force Ant Design Tabs to fill height */ -.ant-tabs { - height: 100%; - display: flex; - flex-direction: column; -} +.app-layout { background: var(--bg-base); } +.app-sidebar.ant-layout-sider { background: var(--bg-sidebar); border-right: 1px solid var(--border-subtle); } +.ant-layout-sider-children { display: flex; flex-direction: column; min-height: 0; } +.sidebar-header { height: 72px; display: flex; align-items: center; gap: 11px; padding: 16px; flex-shrink: 0; border-bottom: 1px solid var(--border-subtle); } +.sidebar-brand { min-width: 0; flex: 1; } +.sidebar-brand strong { display: block; font: 600 19px var(--font-mono); letter-spacing: -0.5px; color: var(--text-primary); } +.sidebar-brand small { display: block; margin-top: 3px; font-size: 10px; letter-spacing: 0.4px; color: var(--text-tertiary); } +.sidebar-content { flex: 1; min-height: 0; overflow: hidden; } +.sidebar-footer { padding: 10px 12px; display: flex; align-items: center; gap: 6px; border-top: 1px solid var(--border-subtle); } +.account-button.ant-btn { min-width: 0; flex: 1; justify-content: flex-start; padding-left: 4px; color: var(--text-secondary); font-size: 12px; } +.account-button > span:last-child { overflow: hidden; text-overflow: ellipsis; } +.account-avatar { width: 25px; height: 25px; display: inline-flex; justify-content: center; align-items: center; flex-shrink: 0; border-radius: 8px; background: var(--fill-medium); border: 1px solid var(--border-subtle); font-size: 11px; font-weight: 600; color: var(--text-secondary); } +.theme-action.ant-btn { color: var(--text-tertiary); } +.accent-option { display: flex; align-items: center; gap: 10px; min-width: 110px; } +.accent-swatch { width: 12px; height: 12px; border-radius: 50%; border: 1px solid #00000010; } -.ant-tabs-content-holder { - flex: 1; - overflow: hidden; -} +.server-sidebar { display: flex; flex-direction: column; height: 100%; min-height: 0; } +.sidebar-tools { padding: 16px 12px 12px; display: grid; gap: 10px; flex-shrink: 0; } +.sidebar-search.ant-input-affix-wrapper { background: var(--fill-subtle); border-color: var(--border-subtle); font-size: 12px; } +.sidebar-search .ant-input-prefix { color: var(--text-tertiary); } +.add-server-button.ant-btn { background: var(--accent-soft); border-color: var(--accent-border); color: var(--text-primary); font-size: 12px; } +.add-server-button.ant-btn:hover { background: var(--fill-hover); } +.server-list { flex: 1; min-height: 0; overflow-y: auto; padding: 0 12px 12px; } +.server-group + .server-group { margin-top: 12px; } +.server-group-toggle { display: flex; align-items: center; gap: 7px; width: 100%; padding: 8px 4px; border-radius: 6px; font-size: 11px; font-weight: 500; color: var(--text-tertiary); } +.server-group-toggle:hover { color: var(--text-secondary); } +.group-chevron { font-size: 8px; } +.group-count { margin-left: auto; min-width: 20px; padding: 1px 5px; border-radius: 5px; background: var(--fill-medium); color: var(--text-tertiary); font: 10px var(--font-mono); text-align: center; } +.server-group-items { display: grid; gap: 6px; } +.server-card { position: relative; display: flex; align-items: center; gap: 4px; padding: 10px 7px 10px 10px; border: 1px solid var(--border-light); border-radius: 8px; background: var(--fill-subtle); transition: background 140ms, border-color 140ms; } +.server-card:hover { background: var(--fill-hover); border-color: var(--border-subtle); } +.server-card[data-active='true'] { background: var(--accent-soft); border-color: var(--accent-border); box-shadow: inset 2px 0 var(--color-primary); } +.server-connect { display: flex; align-items: center; gap: 9px; flex: 1; min-width: 0; padding: 2px 0; } +.server-icon { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 30px; flex-shrink: 0; color: var(--color-primary); font-size: 15px; } +.server-copy { display: block; flex: 1; min-width: 0; } +.server-name { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-primary); font-size: 12px; font-weight: 550; line-height: 20px; } +.server-address { display: block; margin-top: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 10px/1.5 var(--font-mono); color: var(--text-tertiary); } +.server-actions { display: flex; align-items: center; flex-shrink: 0; gap: 0; } +.server-actions .ant-btn { color: var(--text-tertiary); width: 24px; min-width: 24px; height: 28px; } +.server-card:hover .server-actions .ant-btn, .server-card[data-active='true'] .server-actions .ant-btn { color: var(--text-secondary); } +.sidebar-summary { padding: 10px 16px; color: var(--text-tertiary); font-size: 10px; letter-spacing: 0.2px; border-top: 1px solid var(--border-light); } +.sidebar-empty { padding: 30px 4px; text-align: center; } +.sidebar-empty p { margin-top: 6px; color: var(--text-tertiary); font-size: 11px; } +.panel-loading { display: flex; justify-content: center; align-items: center; gap: 10px; padding: 32px 16px; color: var(--text-tertiary); font-size: 12px; } -.ant-tabs-content { - height: 100%; -} +.workspace-layout { background: var(--bg-terminal); flex: 1; min-width: 0; overflow: hidden; } +.workspace-content { height: 100%; min-width: 0; display: flex; flex-direction: column; } +.workspace-terminal { flex: 1; min-height: 0; } +.mobile-toolbar { display: flex; align-items: center; justify-content: space-between; padding: 7px 10px; border-bottom: 1px solid var(--border-subtle); background: var(--bg-sidebar); } +.mobile-toolbar > span { color: var(--text-tertiary); font: 12px var(--font-mono); } +.workspace-empty { height: 100%; display: flex; flex-direction: column; background: var(--bg-terminal); } +.empty-workspace-header { display: flex; justify-content: space-between; padding: 14px 20px; color: var(--text-tertiary); font-size: 11px; border-bottom: 1px solid var(--border-light); } +.empty-workspace-header span:last-child { font: 10px var(--font-mono); letter-spacing: 1px; } +.workspace-empty-content { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 32px 20px 72px; text-align: center; } +.empty-terminal-mark { width: 64px; height: 64px; display: flex; align-items: center; justify-content: center; border-radius: 16px; border: 1px solid var(--accent-border); background: var(--accent-soft); color: var(--color-primary); font: 500 28px var(--font-mono); margin-bottom: 22px; } +.workspace-empty h2 { font-size: 17px; font-weight: 500; color: var(--text-primary); margin-bottom: 10px; } +.workspace-empty p { font-size: 12px; line-height: 1.8; color: var(--text-tertiary); max-width: 300px; } +.empty-features { display: flex; gap: 8px; margin-top: 24px; } +.empty-features span { padding: 4px 9px; border: 1px solid var(--border-light); border-radius: 5px; color: var(--text-tertiary); font-size: 10px; } +.terminal-workspace { display: flex; flex-direction: column; height: 100%; width: 100%; overflow: hidden; } +.terminal-tab-bar { display: flex; align-items: center; background: var(--bg-tab-bar); border-bottom: 1px solid var(--border-subtle); padding: 6px 10px 0; min-height: 44px; flex-shrink: 0; } +.terminal-tab-list { display: flex; gap: 3px; flex: 1; min-width: 0; overflow-x: auto; scrollbar-width: thin; } +.terminal-tab-item { display: flex; align-items: center; flex-shrink: 0; max-width: 240px; border: 1px solid transparent; border-bottom: 2px solid transparent; border-radius: 7px 7px 0 0; transition: background 140ms; } +.terminal-tab-item:hover { background: var(--fill-subtle); } +.terminal-tab-item[data-active='true'] { background: var(--bg-terminal); border-color: var(--border-subtle); border-bottom-color: var(--color-primary); } +.terminal-tab-label { display: flex; align-items: center; gap: 8px; padding: 9px 8px 9px 11px; color: var(--text-tertiary); min-width: 0; font-size: 12px; white-space: nowrap; } +.terminal-tab-item[data-active='true'] .terminal-tab-label { color: var(--text-primary); } +.tab-name { overflow: hidden; text-overflow: ellipsis; } +.connection-dot { flex-shrink: 0; width: 6px; height: 6px; border-radius: 50%; background: #c38d38; } +.connection-dot[data-status='connected'] { background: #52c41a; } +.connection-dot[data-status='error'] { background: #f07070; } +.tab-close { display: flex; align-items: center; justify-content: center; width: 23px; height: 23px; flex-shrink: 0; margin-right: 5px; border-radius: 4px; font-size: 9px; color: var(--text-tertiary); } +.tab-close:hover { color: var(--text-primary); background: var(--fill-hover); } +.font-controls { display: flex; align-items: center; gap: 2px; margin: 0 0 5px 12px; padding: 2px; border: 1px solid var(--border-light); border-radius: 6px; color: var(--text-tertiary); flex-shrink: 0; } +.font-controls button { display: flex; align-items: center; justify-content: center; width: 25px; height: 24px; border-radius: 4px; font-size: 10px; } +.font-controls button:hover:not(:disabled) { background: var(--fill-hover); color: var(--text-primary); } +.font-controls span { min-width: 34px; text-align: center; font: 10px var(--font-mono); } +.terminal-panels { flex: 1; min-height: 0; position: relative; overflow: hidden; } +.terminal-panel { position: absolute; inset: 0; } -.ant-tabs-tabpane { - height: 100%; -} +.ant-modal.opsup-modal { top: clamp(16px, 8vh, 64px); } +.file-manager .plain-button:disabled { opacity: 1; cursor: default; } +.opsup-modal .ant-modal-title { font-size: 15px; font-weight: 600; } +.opsup-modal .ant-modal-header { margin-bottom: 22px; padding-bottom: 16px; border-bottom: 1px solid var(--border-subtle); } +.opsup-modal .ant-modal-footer { margin-top: 22px; padding-top: 16px; border-top: 1px solid var(--border-subtle); } +.opsup-modal .ant-form-item-label > label { font-size: 12px; color: var(--text-secondary); } +.opsup-modal .ant-form-item-extra { font-size: 11px; line-height: 1.7; margin-top: 7px; color: var(--text-tertiary); } +.opsup-modal code { font-family: var(--font-mono); overflow-wrap: anywhere; } +.file-toolbar { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; } +.file-breadcrumbs { margin-bottom: 14px; overflow-wrap: anywhere; font-size: 12px; } +.file-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; } +.file-manager .ant-table-wrapper { border: 1px solid var(--border-subtle); border-radius: 8px; overflow: hidden; } +.file-manager .ant-pagination { padding-right: 12px; } -.ant-tabs-tabpane-active { - height: 100%; -} - -.plain-button { - border: 0; - background: transparent; - color: inherit; - font: inherit; - text-align: left; - cursor: pointer; -} -button:focus-visible, [role="tab"]:focus-visible { - outline: 2px solid var(--color-primary, #1677ff); - outline-offset: -2px; -} -.server-connect { width: 100%; overflow-wrap: anywhere; } -.server-actions { display: flex; justify-content: flex-end; gap: 4px; margin-top: 4px; } -.ant-layout-sider-children { display: flex; flex-direction: column; min-height: 0; } @media (max-width: 767px) { button { touch-action: manipulation; } - .server-actions .ant-btn { min-width: 36px; min-height: 36px; } + .auth-page { padding: 24px 16px; } + .auth-card .ant-card-body { padding: 26px 24px; } + .sidebar-header { height: 64px; } + .server-actions .ant-btn { min-width: 32px; height: 36px; } + .terminal-tab-bar { padding: 4px 6px 0; min-height: 44px; } + .terminal-tab-item { max-width: 205px; } + .terminal-tab-label { padding: 10px 8px; } + .font-controls { margin-left: 6px; border: 0; gap: 0; } + .font-controls button { width: 25px; } + .font-controls span { min-width: 30px; } + .workspace-empty-content { padding-bottom: 48px; } + .empty-workspace-header { padding: 12px; } + .opsup-modal .ant-modal-header { margin-bottom: 16px; } +} +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } } diff --git a/ui/src/styles/terminal.css b/ui/src/styles/terminal.css index 04cb22c..9b8a819 100644 --- a/ui/src/styles/terminal.css +++ b/ui/src/styles/terminal.css @@ -1,34 +1,27 @@ -.terminal-container { - width: 100%; - height: 100%; - padding: 4px; - background: var(--bg-terminal, #1a1a2e); -} - -.terminal-container .xterm { - height: 100%; -} - -.terminal-loading { - display: flex; - align-items: center; - justify-content: center; - height: 100%; - color: var(--text-tertiary, rgba(255, 255, 255, 0.45)); - font-size: 14px; -} - -.terminal-error { - display: flex; - align-items: center; - justify-content: center; - height: 100%; - color: #ff4d4f; - font-size: 14px; - padding: 20px; - text-align: center; -} - -.mobile-shortcut-bar::-webkit-scrollbar { - display: none; +.terminal-session { height: 100%; width: 100%; display: flex; flex-direction: column; position: relative; } +.terminal-body { flex: 1; min-height: 0; position: relative; } +.terminal-container { width: 100%; height: 100%; padding: 10px 12px; background: var(--bg-terminal, #1a1a2e); } +.terminal-container .xterm { height: 100%; } +.terminal-overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 24px; background: var(--bg-terminal); color: var(--text-tertiary); font-size: 12px; z-index: 10; } +.terminal-disconnected { position: absolute; bottom: 0; left: 0; right: 0; display: flex; align-items: center; gap: 16px; padding: 12px 16px; max-height: 45%; overflow-y: auto; background: var(--bg-elevated); border-top: 1px solid #ff787540; box-shadow: 0 -4px 20px #0000000a; z-index: 10; } +.terminal-disconnected > span { flex: 1; min-width: 0; color: #f07070; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; } +.terminal-disconnected .ant-btn { flex-shrink: 0; } +.terminal-error-card { text-align: center; max-width: 400px; overflow-wrap: anywhere; } +.terminal-error-icon { font-size: 30px; color: #f07070; margin-bottom: 20px; } +.terminal-error-card p { color: var(--text-secondary); font-size: 13px; line-height: 1.8; } +.terminal-error-card small { display: block; color: var(--text-tertiary); margin: 8px 0 20px; } +.mobile-shortcut-bar { position: absolute; bottom: 0; left: 0; right: 0; display: flex; align-items: center; gap: 5px; padding: 6px 10px; height: 44px; overflow-x: auto; background: var(--bg-tab-bar); border-top: 1px solid var(--border-subtle); scrollbar-width: none; z-index: 15; } +.mobile-shortcut-bar::-webkit-scrollbar { display: none; } +.terminal-shortcut { flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; padding: 4px 10px; min-width: 34px; height: 29px; border: 1px solid var(--border-subtle); border-radius: 5px; background: var(--fill-subtle); color: var(--text-secondary); font: 11px var(--font-mono); cursor: pointer; user-select: none; -webkit-tap-highlight-color: transparent; transition: background 120ms, border-color 120ms; box-shadow: 0 1px 0 #00000018; } +.terminal-shortcut:hover { background: var(--fill-hover); border-color: var(--accent-border); } +.terminal-shortcut:active { background: var(--accent-soft); color: var(--color-primary); } +.shortcut-toggle { position: absolute; right: 12px; display: flex; align-items: center; justify-content: center; width: 30px; height: 28px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-tab-bar); color: var(--text-tertiary); font-size: 15px; z-index: 20; cursor: pointer; box-shadow: 0 2px 8px #00000015; } +.shortcut-toggle[aria-pressed='true'] { color: var(--color-primary); } +.shortcut-toggle:hover { border-color: var(--accent-border); } +[data-theme='light'] .terminal-disconnected > span { color: #b73442; } +@media (max-width: 767px) { + .terminal-container { padding: 8px; } + .terminal-disconnected { flex-wrap: wrap; gap: 8px; padding: 10px 12px; max-height: 50%; } + .terminal-disconnected > span { flex-basis: 100%; } + .mobile-shortcut-bar { padding-left: 8px; padding-right: 8px; } }