iaun 7 mesiacov pred
commit
6fea387450
99 zmenil súbory, kde vykonal 21832 pridanie a 0 odobranie
  1. 4 0
      .env.example
  2. 35 0
      .gitignore
  3. 1 0
      .kiro/specs/ec2-management-platform/.config.kiro
  4. 506 0
      .kiro/specs/ec2-management-platform/design.md
  5. 144 0
      .kiro/specs/ec2-management-platform/requirements.md
  6. 251 0
      .kiro/specs/ec2-management-platform/tasks.md
  7. 1 0
      .kiro/specs/web-rdp-connect/.config.kiro
  8. 303 0
      .kiro/specs/web-rdp-connect/design.md
  9. 115 0
      .kiro/specs/web-rdp-connect/requirements.md
  10. 60 0
      .kiro/specs/web-rdp-connect/tasks.md
  11. 40 0
      Dockerfile
  12. 89 0
      README.md
  13. 24 0
      client/.gitignore
  14. 19 0
      client/index.html
  15. 2293 0
      client/package-lock.json
  16. 26 0
      client/package.json
  17. 0 0
      client/public/favicon.svg
  18. 24 0
      client/public/icons.svg
  19. 20 0
      client/src/App.tsx
  20. 32 0
      client/src/api/axios.ts
  21. BIN
      client/src/assets/hero.png
  22. 1 0
      client/src/assets/typescript.svg
  23. 0 0
      client/src/assets/vite.svg
  24. 177 0
      client/src/components/AwsConfigForm.tsx
  25. 117 0
      client/src/components/GuacamoleConfig.tsx
  26. 97 0
      client/src/components/InstanceLogs.tsx
  27. 206 0
      client/src/components/InstanceMonitor.tsx
  28. 189 0
      client/src/components/InvitationManager.tsx
  29. 134 0
      client/src/components/RdpSessionMonitor.tsx
  30. 38 0
      client/src/components/RdpStatusBar.tsx
  31. 27 0
      client/src/components/RouteGuards.tsx
  32. 68 0
      client/src/components/SystemSettings.tsx
  33. 201 0
      client/src/components/UserManager.tsx
  34. 9 0
      client/src/main.tsx
  35. 58 0
      client/src/pages/AdminPage.tsx
  36. 561 0
      client/src/pages/DashboardPage.tsx
  37. 72 0
      client/src/pages/LoginPage.tsx
  38. 332 0
      client/src/pages/RdpPage.tsx
  39. 106 0
      client/src/pages/RegisterPage.tsx
  40. 46 0
      client/src/router.tsx
  41. 119 0
      client/src/types/guacamole-common-js.d.ts
  42. 53 0
      client/src/utils/auth.ts
  43. 29 0
      client/tsconfig.json
  44. 18 0
      client/vite.config.ts
  45. 5824 0
      server/package-lock.json
  46. 40 0
      server/package.json
  47. 40 0
      server/src/app.test.ts
  48. 89 0
      server/src/app.ts
  49. 181 0
      server/src/db.test.ts
  50. 157 0
      server/src/db.ts
  51. 402 0
      server/src/integration.test.ts
  52. 85 0
      server/src/middleware/auth.property.test.ts
  53. 162 0
      server/src/middleware/auth.test.ts
  54. 68 0
      server/src/middleware/auth.ts
  55. 95 0
      server/src/routes/admin-instances.property.test.ts
  56. 253 0
      server/src/routes/admin-instances.test.ts
  57. 108 0
      server/src/routes/admin-instances.ts
  58. 20 0
      server/src/routes/admin-logs.ts
  59. 117 0
      server/src/routes/admin-users.ts
  60. 175 0
      server/src/routes/auth.property.test.ts
  61. 187 0
      server/src/routes/auth.test.ts
  62. 217 0
      server/src/routes/auth.ts
  63. 151 0
      server/src/routes/aws-config.property.test.ts
  64. 218 0
      server/src/routes/aws-config.test.ts
  65. 202 0
      server/src/routes/aws-config.ts
  66. 183 0
      server/src/routes/instances-time.property.test.ts
  67. 186 0
      server/src/routes/instances.property.test.ts
  68. 368 0
      server/src/routes/instances.test.ts
  69. 221 0
      server/src/routes/instances.ts
  70. 113 0
      server/src/routes/invitations.property.test.ts
  71. 197 0
      server/src/routes/invitations.test.ts
  72. 131 0
      server/src/routes/invitations.ts
  73. 313 0
      server/src/routes/rdp-sessions.property.test.ts
  74. 299 0
      server/src/routes/rdp-sessions.test.ts
  75. 127 0
      server/src/routes/rdp-sessions.ts
  76. 313 0
      server/src/routes/settings.test.ts
  77. 173 0
      server/src/routes/settings.ts
  78. 492 0
      server/src/services/connection-manager.property.test.ts
  79. 454 0
      server/src/services/connection-manager.test.ts
  80. 408 0
      server/src/services/connection-manager.ts
  81. 101 0
      server/src/services/guacamole-proxy.ts
  82. 183 0
      server/src/services/instance-lifecycle-rdp.test.ts
  83. 286 0
      server/src/services/instance-manager.property.test.ts
  84. 387 0
      server/src/services/instance-manager.test.ts
  85. 433 0
      server/src/services/instance-manager.ts
  86. 164 0
      server/src/services/lifetime-timer.property.test.ts
  87. 243 0
      server/src/services/lifetime-timer.test.ts
  88. 71 0
      server/src/services/lifetime-timer.ts
  89. 77 0
      server/src/services/userdata.property.test.ts
  90. 47 0
      server/src/services/userdata.test.ts
  91. 52 0
      server/src/services/userdata.ts
  92. 37 0
      server/src/utils/crypto.property.test.ts
  93. 112 0
      server/src/utils/crypto.test.ts
  94. 40 0
      server/src/utils/crypto.ts
  95. 69 0
      server/src/utils/validation.property.test.ts
  96. 73 0
      server/src/utils/validation.test.ts
  97. 9 0
      server/src/utils/validation.ts
  98. 20 0
      server/tsconfig.json
  99. 14 0
      server/vitest.config.ts

+ 4 - 0
.env.example

@@ -0,0 +1,4 @@
+PORT=3000
+JWT_SECRET=your-jwt-secret-here
+
+# AWS credentials are configured via the admin UI, not environment variables.

+ 35 - 0
.gitignore

@@ -0,0 +1,35 @@
+# Dependencies
+node_modules/
+
+# Build output
+client/dist/
+server/dist/
+
+# Environment
+.env
+.env.*
+!.env.example
+
+# Database
+server/data/
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Logs
+*.log
+npm-debug.log*
+
+# Credentials
+*.csv
+*.pem
+*.key
+
+scripts/

+ 1 - 0
.kiro/specs/ec2-management-platform/.config.kiro

@@ -0,0 +1 @@
+{"specId": "b165b760-91d2-42c7-a14e-7dc17537df74", "workflowType": "requirements-first", "specType": "feature"}

+ 506 - 0
.kiro/specs/ec2-management-platform/design.md

@@ -0,0 +1,506 @@
+# EC2 管理平台 - 设计文档
+
+## 概述
+
+EC2 管理平台是一个全栈 Web 应用,允许管理员配置 AWS 资源参数,用户通过邀请码注册后自助启动 Windows EC2 实例。系统自动完成实例初始化(包括注册表写入 MachineGuid),并提供 RDP 登录信息。实例具有生命周期时间限制,到期后自动销毁。
+
+### 技术栈选择
+
+**前端:**
+- React 18 + TypeScript
+- Ant Design 5(UI 组件库)
+- React Router(路由管理)
+- Axios(HTTP 请求)
+- Vite(构建工具)
+
+**后端:**
+- Node.js + Express + TypeScript
+- 选择理由:
+  1. 与前端共享 TypeScript 语言,降低全栈开发的上下文切换成本
+  2. Express 生态成熟,中间件丰富,适合快速构建 REST API
+  3. AWS SDK for JavaScript v3 原生支持,与 EC2 API 集成顺畅
+  4. 异步 I/O 模型适合处理 EC2 实例状态轮询和生命周期管理等 I/O 密集型任务
+  5. 部署简单,单一运行时即可服务前后端
+
+**数据库:**
+- SQLite(通过 better-sqlite3)
+- 选择理由:本系统为内部管理工具,用户量有限,SQLite 零配置、单文件部署,简化运维复杂度。如未来需要扩展,可迁移至 PostgreSQL。
+
+**其他依赖:**
+- AWS SDK v3(@aws-sdk/client-ec2):EC2 实例管理
+- bcrypt:密码哈希
+- jsonwebtoken:JWT 认证
+- node-cron:定时任务(实例生命周期检查)
+- crypto(Node.js 内置):AWS Secret Key 加密存储
+
+## 架构
+
+### 系统架构图
+
+```mermaid
+graph TB
+    subgraph 前端 - React + Ant Design
+        A[登录/注册页面] --> B[用户面板 User_Dashboard]
+        A --> C[管理员面板 Admin_Panel]
+        B --> D[实例列表]
+        B --> E[启动实例表单]
+        C --> F[邀请码管理]
+        C --> G[AWS 配置]
+        C --> H[实例监控]
+        C --> I[系统设置]
+    end
+
+    subgraph 后端 - Node.js + Express
+        J[API 路由层]
+        K[认证中间件 - JWT]
+        L[Registration_Service]
+        M[Instance_Manager]
+        N[Lifetime_Timer - node-cron]
+        O[AWS 配置服务]
+    end
+
+    subgraph 外部服务
+        P[(SQLite 数据库)]
+        Q[AWS EC2 API]
+    end
+
+    B & C --> J
+    J --> K
+    K --> L & M & O
+    M --> Q
+    N --> M
+    L & M & O --> P
+```
+
+### 分层架构
+
+系统采用经典三层架构:
+
+1. **表现层(前端)**:React SPA,通过 REST API 与后端通信
+2. **业务逻辑层(后端)**:Express 路由 → 中间件 → Service 层 → 数据访问层
+3. **数据层**:SQLite 数据库 + AWS EC2 API
+
+### 认证与授权
+
+- 使用 JWT(JSON Web Token)进行无状态认证
+- 用户角色分为 `admin` 和 `user`,管理员同时拥有两种角色权限
+- API 路由通过中间件进行角色校验
+
+## 组件与接口
+
+### 前端组件
+
+| 组件 | 职责 |
+|------|------|
+| `LoginPage` | 用户登录 |
+| `RegisterPage` | 邀请码注册 |
+| `UserDashboard` | 用户实例列表、启动实例、查看 RDP 信息 |
+| `AdminPanel` | 管理员功能入口 |
+| `InvitationManager` | 邀请码 CRUD |
+| `AwsConfigForm` | AWS 参数配置 |
+| `InstanceMonitor` | 全局实例监控 |
+| `SystemSettings` | 实例最大使用时长等系统配置 |
+
+### 后端 API 接口
+
+#### 认证相关
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| POST | `/api/auth/register` | 用户注册(需邀请码) |
+| POST | `/api/auth/login` | 用户登录 |
+| GET | `/api/auth/me` | 获取当前用户信息 |
+
+#### 邀请码管理(Admin)
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| POST | `/api/admin/invitations` | 创建邀请码 |
+| GET | `/api/admin/invitations` | 获取邀请码列表 |
+| PATCH | `/api/admin/invitations/:id/disable` | 禁用邀请码 |
+| DELETE | `/api/admin/invitations/:id` | 删除邀请码 |
+
+#### AWS 配置(Admin)
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| GET | `/api/admin/aws-config` | 获取当前 AWS 配置(Secret Key 脱敏) |
+| PUT | `/api/admin/aws-config` | 更新 AWS 配置(含凭证验证) |
+
+#### 系统设置(Admin)
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| GET | `/api/admin/settings` | 获取系统设置 |
+| PUT | `/api/admin/settings` | 更新系统设置(如最大使用时长) |
+
+#### 实例管理(User)
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| POST | `/api/instances` | 启动新实例(需提供 MachineGuid) |
+| GET | `/api/instances` | 获取当前用户的实例列表 |
+| POST | `/api/instances/:id/stop` | 关机 |
+| POST | `/api/instances/:id/start` | 启动已停止的实例 |
+| POST | `/api/instances/:id/reboot` | 重启 |
+| DELETE | `/api/instances/:id` | 销毁实例 |
+| GET | `/api/instances/:id/rdp` | 获取 RDP 连接信息 |
+
+#### 实例监控(Admin)
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| GET | `/api/admin/instances` | 获取所有用户的实例列表 |
+| DELETE | `/api/admin/instances/:id` | 管理员销毁任意实例 |
+| GET | `/api/admin/instances/stats` | 获取运行中实例统计 |
+
+
+## 数据模型
+
+### 数据库表结构
+
+```mermaid
+erDiagram
+    users {
+        integer id PK
+        string username UK
+        string password_hash
+        string role "admin | user"
+        integer created_at
+    }
+
+    invitation_codes {
+        integer id PK
+        string code UK
+        boolean is_active
+        integer usage_count
+        integer created_at
+    }
+
+    aws_config {
+        integer id PK
+        string access_key
+        string secret_key_encrypted
+        string region
+        string ami_id
+        string instance_type
+        string key_pair_name
+        string security_group_id
+        integer updated_at
+    }
+
+    system_settings {
+        integer id PK
+        string key UK
+        string value
+        integer updated_at
+    }
+
+    instances {
+        integer id PK
+        integer user_id FK
+        string ec2_instance_id UK
+        string machine_guid
+        string status "pending | running | stopped | terminated"
+        string public_ip
+        string rdp_username
+        string rdp_password_encrypted
+        integer started_at
+        integer expires_at
+        integer created_at
+    }
+
+    users ||--o{ instances : "拥有"
+```
+
+### 数据模型说明
+
+**users 表**
+- `role` 字段取值为 `admin` 或 `user`,管理员角色拥有全部权限
+- `password_hash` 使用 bcrypt 加密存储
+- 系统首次启动时自动创建默认管理员账户
+
+**invitation_codes 表**
+- `is_active` 控制邀请码是否可用,禁用后不可用于注册
+- `usage_count` 记录该邀请码被使用的次数,同一邀请码可被多次使用
+
+**aws_config 表**
+- 全局唯一配置,仅存储一条记录
+- `secret_key_encrypted` 使用 AES-256 加密存储
+- 管理员更新配置后,后续新建实例使用新配置
+
+**system_settings 表**
+- 键值对存储,当前主要存储 `max_instance_lifetime_hours`(实例最大使用时长,单位:小时)
+
+**instances 表**
+- `machine_guid` 存储用户指定的 UUID,用于写入 EC2 实例注册表
+- `status` 与 AWS EC2 实例状态同步
+- `expires_at` = `started_at` + 管理员配置的最大使用时长
+- `rdp_password_encrypted` 使用 AES-256 加密存储
+
+### 关键流程
+
+#### 用户注册流程
+
+```mermaid
+sequenceDiagram
+    participant U as 用户
+    participant FE as 前端
+    participant API as 后端 API
+    participant DB as 数据库
+
+    U->>FE: 填写注册表单(用户名、密码、邀请码)
+    FE->>API: POST /api/auth/register
+    API->>DB: 查询邀请码是否存在且有效
+    alt 邀请码无效
+        API-->>FE: 400 "邀请码无效"
+        FE-->>U: 显示错误提示
+    else 邀请码有效
+        API->>DB: 创建用户记录
+        API->>DB: 邀请码 usage_count + 1
+        API-->>FE: 201 注册成功 + JWT
+        FE-->>U: 重定向至 User_Dashboard
+    end
+```
+
+#### EC2 实例启动流程
+
+```mermaid
+sequenceDiagram
+    participant U as 用户
+    participant FE as 前端
+    participant API as 后端 API
+    participant DB as 数据库
+    participant AWS as AWS EC2
+
+    U->>FE: 输入 MachineGuid,点击启动
+    FE->>FE: UUID 格式校验
+    FE->>API: POST /api/instances {machineGuid}
+    API->>DB: 读取 AWS 配置
+    API->>AWS: RunInstances(含 UserData 脚本)
+    Note over AWS: UserData 脚本写入<br/>MachineGuid 到注册表
+    AWS-->>API: 返回 instance_id
+    API->>AWS: 等待实例进入 running 状态
+    AWS-->>API: 返回公网 IP
+    API->>AWS: GetPasswordData 获取 Windows 密码
+    API->>DB: 保存实例记录(含 RDP 信息、过期时间)
+    API-->>FE: 返回实例信息 + RDP 凭证
+    FE-->>U: 显示 RDP 连接信息
+```
+
+#### 实例生命周期自动销毁流程
+
+```mermaid
+sequenceDiagram
+    participant Cron as Lifetime_Timer (node-cron)
+    participant DB as 数据库
+    participant AWS as AWS EC2
+
+    loop 每分钟执行
+        Cron->>DB: 查询已过期且未终止的实例
+        alt 存在过期实例
+            Cron->>AWS: TerminateInstances
+            Cron->>DB: 更新实例状态为 terminated
+        end
+    end
+```
+
+#### 实例状态同步流程
+
+```mermaid
+sequenceDiagram
+    participant FE as 前端
+    participant API as 后端 API
+    participant DB as 数据库
+    participant AWS as AWS EC2
+
+    loop 每 30 秒轮询
+        FE->>API: GET /api/instances
+        API->>AWS: DescribeInstances
+        API->>DB: 同步更新实例状态
+        API-->>FE: 返回最新实例列表
+    end
+```
+
+
+## 正确性属性
+
+*属性(Property)是指在系统所有有效执行中都应保持为真的特征或行为——本质上是对系统应做什么的形式化陈述。属性是人类可读规范与机器可验证正确性保证之间的桥梁。*
+
+### 属性 1:邀请码注册有效性
+
+*对于任意* 注册请求,注册成功当且仅当提供的邀请码存在于系统中且处于启用状态(is_active = true)。使用无效、不存在或已禁用的邀请码的注册请求应被拒绝,且不创建用户账户。
+
+**验证需求:1.1, 1.2, 2.3**
+
+### 属性 2:邀请码可重复使用
+
+*对于任意* 有效邀请码和任意数量 N(N ≥ 1)的不同用户,使用同一邀请码连续注册 N 个用户应全部成功,且邀请码的 usage_count 应等于 N。
+
+**验证需求:1.3**
+
+### 属性 3:邀请码删除即移除
+
+*对于任意* 邀请码列表,删除其中一个邀请码后,重新查询列表应不包含该邀请码,且列表长度减少 1。
+
+**验证需求:2.4**
+
+### 属性 4:管理员拥有双重权限
+
+*对于任意* 角色为 admin 的用户,该用户应能同时访问所有管理员 API 端点和所有普通用户 API 端点。
+
+**验证需求:3.2**
+
+### 属性 5:AWS Secret Key 加密存储往返
+
+*对于任意* AWS Secret Key 字符串,加密后存储再解密应得到与原始值完全相同的字符串,且加密后的值不等于原始明文。
+
+**验证需求:4.4**
+
+### 属性 6:AWS 配置传播
+
+*对于任意* AWS 配置更新,更新后创建的新实例应使用更新后的配置参数(Region、AMI ID 等),而非更新前的旧配置。
+
+**验证需求:4.5**
+
+### 属性 7:MachineGuid UUID 格式校验
+
+*对于任意* 字符串输入,MachineGuid 校验函数应接受该输入当且仅当它严格匹配 UUID 格式(`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,其中 x 为十六进制字符)。对于任意纯空白字符串或格式不符的字符串,校验应拒绝。
+
+**验证需求:5.2, 5.3**
+
+### 属性 8:MachineGuid 持久化往返
+
+*对于任意* 有效的 MachineGuid,提交启动请求后,查询该实例记录应返回与提交时完全相同的 MachineGuid 值。
+
+**验证需求:5.4**
+
+### 属性 9:UserData 脚本包含 MachineGuid
+
+*对于任意* 有效的 MachineGuid,生成的 EC2 UserData 脚本应包含该 MachineGuid 值,且目标注册表路径为 `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography` 的 `MachineGuid` 键。
+
+**验证需求:6.2**
+
+### 属性 10:实例创建返回完整 RDP 凭证
+
+*对于任意* 成功创建的 EC2 实例,返回的响应应包含非空的公网 IP 地址、RDP 用户名和 RDP 密码。
+
+**验证需求:6.4**
+
+### 属性 11:实例生命周期状态转换
+
+*对于任意* EC2 实例,执行有效的生命周期操作应产生正确的状态转换:对 running 实例执行 stop → stopped;对 stopped 实例执行 start → running;对 running 实例执行 reboot → running;对任意非 terminated 实例执行 destroy → terminated。
+
+**验证需求:7.2, 7.3, 7.4, 7.5**
+
+### 属性 12:实例列表数据完整性
+
+*对于任意* 实例集合,查询返回的列表应包含所有属于该查询范围的实例,且每条记录包含实例状态、公网 IP 和剩余使用时间字段。管理员查询还应额外包含所属用户和启动时间字段。
+
+**验证需求:7.1, 9.1**
+
+### 属性 13:实例过期时间正确计算
+
+*对于任意* 新创建的实例和任意管理员配置的最大使用时长 H(小时),该实例的 expires_at 应等于 started_at + H × 3600 秒。
+
+**验证需求:8.2**
+
+### 属性 14:过期实例自动终止
+
+*对于任意* expires_at 已过的非 terminated 实例,生命周期检查器应将其标记为 terminated 并调用 AWS 终止 API。
+
+**验证需求:8.3**
+
+### 属性 15:剩余时间计算正确性
+
+*对于任意* 运行中的实例和任意当前时间 T(T < expires_at),显示的剩余使用时间应等于 expires_at - T。当 T ≥ expires_at 时,剩余时间应为 0。
+
+**验证需求:8.4**
+
+### 属性 16:到期提醒触发
+
+*对于任意* 运行中的实例,当剩余使用时间从 ≥ 30 分钟变为 < 30 分钟时,系统应生成一条到期提醒通知。
+
+**验证需求:8.5**
+
+### 属性 17:运行中实例计数
+
+*对于任意* 实例集合,管理员面板显示的运行中实例总数应等于该集合中 status 为 "running" 的实例数量。
+
+**验证需求:9.3**
+
+## 错误处理
+
+### 错误分类与处理策略
+
+| 错误类型 | 场景 | 处理方式 |
+|----------|------|----------|
+| 认证错误 | JWT 过期/无效 | 返回 401,前端重定向至登录页 |
+| 权限错误 | 非管理员访问管理接口 | 返回 403,前端显示无权限提示 |
+| 输入校验错误 | 邀请码无效、UUID 格式错误 | 返回 400,前端显示具体错误信息 |
+| AWS 凭证错误 | Access Key/Secret Key 无效 | 返回 400,提示"AWS 凭证无效" |
+| AWS API 错误 | EC2 启动失败、API 调用超时 | 返回 502,记录日志,向用户显示失败原因 |
+| 资源冲突 | 用户名已存在 | 返回 409,提示"用户名已被使用" |
+| 配置缺失 | AWS 配置未设置即尝试启动实例 | 返回 400,提示"请先配置 AWS 参数" |
+
+### 全局错误处理
+
+- 后端使用 Express 全局错误处理中间件,统一错误响应格式:
+  ```json
+  {
+    "error": {
+      "code": "INVALID_INVITATION_CODE",
+      "message": "邀请码无效"
+    }
+  }
+  ```
+- 前端使用 Axios 拦截器统一处理 HTTP 错误,401 自动跳转登录页
+- 所有 AWS API 调用使用 try-catch 包裹,失败时记录详细日志
+
+### 生命周期管理容错
+
+- Lifetime_Timer 每分钟执行一次,即使某次执行失败,下次仍会重试
+- 实例终止操作失败时,记录日志并在下次检查时重试
+- AWS API 调用设置合理超时(30 秒),避免长时间阻塞
+
+## 测试策略
+
+### 双重测试方法
+
+本项目采用单元测试与属性测试相结合的策略,确保全面覆盖。
+
+#### 属性测试(Property-Based Testing)
+
+- **测试库**:fast-check(TypeScript 生态中最成熟的属性测试库)
+- **配置**:每个属性测试至少运行 100 次迭代
+- **标注格式**:每个测试用注释标注对应的设计属性
+  ```typescript
+  // Feature: ec2-management-platform, Property 7: MachineGuid UUID 格式校验
+  ```
+- 每个正确性属性由一个单独的属性测试实现
+- 属性测试覆盖所有在正确性属性章节中定义的 17 个属性
+
+#### 单元测试
+
+- **测试框架**:Vitest
+- 单元测试聚焦于:
+  - 具体示例和边界情况(如空字符串、极端值)
+  - 组件间集成点(如 API 路由 → Service → 数据库)
+  - 错误条件和异常路径
+  - AWS API 调用的 Mock 测试
+- 避免编写过多单元测试,属性测试已覆盖大量输入场景
+
+#### 测试覆盖重点
+
+| 模块 | 属性测试 | 单元测试 |
+|------|----------|----------|
+| 邀请码注册逻辑 | 属性 1, 2 | 注册流程集成测试 |
+| 邀请码管理 | 属性 3 | CRUD 操作示例 |
+| 权限校验 | 属性 4 | 角色中间件测试 |
+| 加密存储 | 属性 5 | 加密/解密边界值 |
+| UUID 校验 | 属性 7 | 特殊字符、空值 |
+| UserData 脚本生成 | 属性 9 | 脚本格式验证 |
+| 实例状态转换 | 属性 11 | 无效状态转换拒绝 |
+| 过期时间计算 | 属性 13, 15 | 时区边界、零值 |
+| 生命周期检查 | 属性 14 | 定时任务触发验证 |
+

+ 144 - 0
.kiro/specs/ec2-management-platform/requirements.md

@@ -0,0 +1,144 @@
+# 需求文档
+
+## 简介
+
+EC2 管理平台是一个 Web 系统,允许管理员配置 AWS 资源参数,用户通过邀请码注册后,可自助启动 Windows EC2 实例。系统自动完成实例初始化(包括注册表写入),并提供 Windows 远程桌面登录信息。实例具有生命周期时间限制,到期后自动销毁。
+
+## 术语表
+
+- **Platform**:EC2 管理平台 Web 系统
+- **Admin_Panel**:管理员后台界面,用于系统配置和用户管理
+- **User_Dashboard**:用户操作界面,用于管理个人 EC2 实例
+- **Instance_Manager**:EC2 实例生命周期管理模块,负责启动、关机、重启、销毁操作
+- **Registration_Service**:用户注册服务,处理邀请码验证和账户创建
+- **Invitation_Code**:邀请码,管理员创建的可复用注册凭证
+- **MachineGuid**:机器 ID,用户设置的 UUID 格式标识符,写入 EC2 实例注册表
+- **Lifetime_Timer**:实例生存计时器,控制实例自动销毁的倒计时模块
+- **RDP_Credentials**:Windows 远程桌面连接信息,包含 IP 地址、用户名和密码
+
+## 需求
+
+### 需求 1:用户注册与邀请码
+
+**用户故事:** 作为一名新用户,我希望通过邀请码注册账户,以便获得使用平台的权限。
+
+#### 验收标准
+
+1. WHEN 用户提交包含有效邀请码的注册表单, THE Registration_Service SHALL 创建用户账户并返回注册成功信息
+2. WHEN 用户提交包含无效或不存在的邀请码的注册表单, THE Registration_Service SHALL 拒绝注册并返回"邀请码无效"的错误提示
+3. THE Registration_Service SHALL 允许同一个 Invitation_Code 被多个用户重复使用
+4. WHEN 用户注册成功, THE Platform SHALL 将用户重定向至 User_Dashboard
+
+### 需求 2:邀请码管理
+
+**用户故事:** 作为管理员,我希望在后台创建和管理邀请码,以便控制用户注册。
+
+#### 验收标准
+
+1. THE Admin_Panel SHALL 提供创建新 Invitation_Code 的功能
+2. THE Admin_Panel SHALL 展示所有 Invitation_Code 的列表,包含创建时间和使用次数
+3. WHEN 管理员禁用某个 Invitation_Code, THE Registration_Service SHALL 拒绝使用该邀请码的后续注册请求
+4. WHEN 管理员删除某个 Invitation_Code, THE Admin_Panel SHALL 从列表中移除该邀请码
+
+### 需求 3:管理员与系统初始化
+
+**用户故事:** 作为系统部署者,我希望系统初始化时自动创建默认管理员账户,以便立即开始配置系统。
+
+#### 验收标准
+
+1. WHEN Platform 首次启动, THE Platform SHALL 创建一个默认管理员账户
+2. THE Platform SHALL 赋予管理员账户同时拥有管理员权限和普通用户权限
+3. WHEN 管理员登录, THE Platform SHALL 同时显示 Admin_Panel 入口和 User_Dashboard 入口
+
+### 需求 4:AWS 配置管理
+
+**用户故事:** 作为管理员,我希望在后台配置 AWS 参数,以便系统能正确创建 EC2 实例。
+
+#### 验收标准
+
+1. THE Admin_Panel SHALL 提供配置 AWS Access Key、Secret Key、Region 和 AMI ID 的表单
+2. WHEN 管理员提交 AWS 配置, THE Platform SHALL 验证 Access Key 和 Secret Key 的有效性
+3. IF AWS 凭证验证失败, THEN THE Admin_Panel SHALL 显示"AWS 凭证无效"的错误提示并拒绝保存
+4. THE Platform SHALL 以加密形式存储 AWS Secret Key
+5. WHEN 管理员更新 AWS 配置, THE Platform SHALL 对后续新建的实例使用更新后的配置
+
+### 需求 5:MachineGuid 设置
+
+**用户故事:** 作为用户,我希望在启动实例前设置 MachineGuid(机器 ID),以便实例使用我指定的标识符。
+
+#### 验收标准
+
+1. WHEN 用户请求启动实例, THE User_Dashboard SHALL 要求用户输入 MachineGuid
+2. THE User_Dashboard SHALL 仅接受严格符合 UUID 格式(00000000-0000-0000-0000-000000000000,其中每位为十六进制字符)的 MachineGuid
+3. WHEN 用户输入不符合 UUID 格式的 MachineGuid, THE User_Dashboard SHALL 显示格式错误提示并阻止提交
+4. WHEN 用户提交有效的 MachineGuid, THE Platform SHALL 将该值与实例启动请求关联存储
+
+### 需求 6:EC2 实例启动与初始化
+
+**用户故事:** 作为用户,我希望一键启动 Windows EC2 实例并自动完成初始化配置,以便快速获得可用的远程桌面环境。
+
+#### 验收标准
+
+1. WHEN 用户提交启动请求, THE Instance_Manager SHALL 使用管理员配置的 AWS 参数创建一个新的 Windows EC2 实例
+2. WHEN EC2 实例启动完成, THE Instance_Manager SHALL 通过 EC2 User Data 脚本将用户指定的 MachineGuid 写入 Windows 注册表路径 `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography` 的 `MachineGuid` 键值
+3. WHEN EC2 实例进入 running 状态, THE Instance_Manager SHALL 获取实例的公网 IP 地址
+4. WHEN EC2 实例初始化完成, THE Platform SHALL 向用户展示 RDP_Credentials,包含公网 IP 地址、用户名和密码
+5. IF EC2 实例启动失败, THEN THE Platform SHALL 向用户显示包含失败原因的错误信息
+
+### 需求 7:EC2 实例生命周期管理
+
+**用户故事:** 作为用户,我希望能对自己的 EC2 实例执行关机、重启和销毁操作,以便灵活管理实例状态。
+
+#### 验收标准
+
+1. THE User_Dashboard SHALL 展示用户所有 EC2 实例的列表,包含实例状态、公网 IP 和剩余使用时间
+2. WHEN 用户对运行中的实例执行关机操作, THE Instance_Manager SHALL 停止该 EC2 实例
+3. WHEN 用户对已停止的实例执行启动操作, THE Instance_Manager SHALL 重新启动该 EC2 实例
+4. WHEN 用户对运行中的实例执行重启操作, THE Instance_Manager SHALL 重启该 EC2 实例
+5. WHEN 用户对实例执行销毁操作, THE Instance_Manager SHALL 终止并释放该 EC2 实例及其关联资源
+6. WHEN 实例状态发生变化, THE User_Dashboard SHALL 在 30 秒内更新显示最新状态
+
+### 需求 8:实例使用时间限制
+
+**用户故事:** 作为管理员,我希望限制每个实例的最大使用时间,以便控制 AWS 资源成本。
+
+#### 验收标准
+
+1. THE Admin_Panel SHALL 提供设置实例最大使用时长(单位:小时)的配置项
+2. WHEN EC2 实例启动成功, THE Lifetime_Timer SHALL 开始计时
+3. WHEN 实例使用时间达到管理员设置的最大时长, THE Instance_Manager SHALL 自动终止并释放该实例
+4. WHILE 实例处于运行状态, THE User_Dashboard SHALL 显示该实例的剩余使用时间
+5. WHEN 实例剩余使用时间不足 30 分钟, THE Platform SHALL 向用户发送即将到期的提醒通知
+
+### 需求 9:管理员实例监控
+
+**用户故事:** 作为管理员,我希望查看所有用户的实例状态,以便监控系统资源使用情况。
+
+#### 验收标准
+
+1. THE Admin_Panel SHALL 展示所有用户的 EC2 实例列表,包含所属用户、实例状态、公网 IP、启动时间和剩余使用时间
+2. WHEN 管理员对任意实例执行销毁操作, THE Instance_Manager SHALL 终止并释放该实例
+3. THE Admin_Panel SHALL 展示当前运行中的实例总数
+
+### 需求 10:Web 端远程桌面评估(可选功能)
+
+**用户故事:** 作为用户,我希望在浏览器中直接操作 EC2 实例,以便无需安装 RDP 客户端。
+
+#### 验收标准
+
+1. WHERE 系统启用了 Web 远程桌面功能, THE Platform SHALL 通过 Apache Guacamole 或类似方案提供基于浏览器的 RDP 连接
+2. WHERE 系统未启用 Web 远程桌面功能, THE Platform SHALL 仅提供 RDP_Credentials 供用户使用本地 RDP 客户端连接
+3. WHERE 系统启用了 Web 远程桌面功能, WHEN 用户点击"在线连接"按钮, THE Platform SHALL 在新浏览器标签页中打开远程桌面会话
+
+---
+
+## 补充说明
+
+### 关于 Web 端远程桌面的可行性评估
+
+在浏览器中直接控制 EC2 实例在技术上是可行的,主要方案如下:
+
+- **Apache Guacamole**:开源的无客户端远程桌面网关,支持 RDP/VNC/SSH 协议,通过 HTML5 在浏览器中渲染远程桌面。这是最成熟的方案,但需要额外部署 Guacamole 服务器作为中间代理。
+- **AWS DCV (NICE DCV)**:AWS 提供的高性能远程桌面协议,支持 Web 浏览器访问,但需要在 EC2 实例上安装 DCV 服务端。
+
+建议初期以提供 RDP 登录信息为主,将 Web 远程桌面作为可选增强功能在后续迭代中实现。

+ 251 - 0
.kiro/specs/ec2-management-platform/tasks.md

@@ -0,0 +1,251 @@
+# 实现计划:EC2 管理平台
+
+## 概述
+
+基于 React + TypeScript 前端和 Node.js + Express + TypeScript 后端的全栈实现,使用 SQLite 数据库,集成 AWS SDK v3 管理 EC2 实例。采用增量构建方式,从项目骨架和数据层开始,逐步实现认证、邀请码、AWS 配置、实例管理和生命周期控制等功能模块。
+
+## 任务
+
+- [x] 1. 项目初始化与基础架构搭建
+  - [x] 1.1 初始化后端项目结构
+    - 创建 `server/` 目录,初始化 `package.json`,安装依赖:express, better-sqlite3, bcrypt, jsonwebtoken, node-cron, @aws-sdk/client-ec2, cors, dotenv
+    - 配置 TypeScript(tsconfig.json),设置 Vitest 测试框架和 fast-check
+    - 创建 Express 应用入口 `server/src/app.ts`,配置中间件(cors, json 解析, 全局错误处理)
+    - _需求:3.1, 4.1_
+
+  - [x] 1.2 初始化前端项目结构
+    - 使用 Vite 创建 React + TypeScript 项目于 `client/` 目录
+    - 安装依赖:antd, react-router-dom, axios
+    - 配置 Axios 拦截器(401 自动跳转登录页)和基础路由结构
+    - _需求:1.4, 3.3_
+
+  - [x] 1.3 创建数据库初始化模块与数据模型
+    - 创建 `server/src/db.ts`,使用 better-sqlite3 初始化数据库
+    - 创建 users、invitation_codes、aws_config、system_settings、instances 五张表
+    - 实现系统首次启动时自动创建默认管理员账户逻辑(用户名 admin,默认密码,role=admin)
+    - _需求:3.1, 3.2_
+
+- [x] 2. 认证与用户注册模块
+  - [x] 2.1 实现 JWT 认证中间件与角色校验
+    - 创建 `server/src/middleware/auth.ts`,实现 JWT 验证中间件
+    - 实现角色校验中间件:`requireAuth`(登录校验)和 `requireAdmin`(管理员校验)
+    - 管理员角色同时拥有 admin 和 user 权限
+    - _需求:3.2, 3.3_
+
+  - [x] 2.2 编写属性测试:管理员双重权限
+    - **属性 4:管理员拥有双重权限**
+    - **验证需求:3.2**
+
+  - [x] 2.3 实现用户注册 API(含邀请码验证)
+    - 创建 `server/src/routes/auth.ts`,实现 POST `/api/auth/register`
+    - 验证邀请码存在且 is_active=true,无效则返回 400 "邀请码无效"
+    - 注册成功后创建用户、邀请码 usage_count+1、返回 JWT
+    - 实现 POST `/api/auth/login` 和 GET `/api/auth/me`
+    - _需求:1.1, 1.2, 1.3, 1.4_
+
+  - [x] 2.4 编写属性测试:邀请码注册有效性
+    - **属性 1:邀请码注册有效性**
+    - **验证需求:1.1, 1.2, 2.3**
+
+  - [x] 2.5 编写属性测试:邀请码可重复使用
+    - **属性 2:邀请码可重复使用**
+    - **验证需求:1.3**
+
+  - [x] 2.6 实现前端登录与注册页面
+    - 创建 `LoginPage` 和 `RegisterPage` 组件
+    - 注册表单包含用户名、密码、邀请码字段
+    - 注册成功后重定向至 User_Dashboard,显示错误提示
+    - _需求:1.1, 1.2, 1.4_
+
+- [x] 3. 检查点 - 确保认证模块测试通过
+  - 确保所有测试通过,如有问题请询问用户。
+
+- [x] 4. 邀请码管理模块
+  - [x] 4.1 实现邀请码 CRUD API
+    - 创建 `server/src/routes/invitations.ts`
+    - 实现 POST `/api/admin/invitations`(创建邀请码)
+    - 实现 GET `/api/admin/invitations`(获取列表,含创建时间和使用次数)
+    - 实现 PATCH `/api/admin/invitations/:id/disable`(禁用邀请码)
+    - 实现 DELETE `/api/admin/invitations/:id`(删除邀请码)
+    - 所有接口需 requireAdmin 中间件保护
+    - _需求:2.1, 2.2, 2.3, 2.4_
+
+  - [x] 4.2 编写属性测试:邀请码删除即移除
+    - **属性 3:邀请码删除即移除**
+    - **验证需求:2.4**
+
+  - [x] 4.3 实现前端邀请码管理页面
+    - 创建 `InvitationManager` 组件,展示邀请码列表(Ant Design Table)
+    - 实现创建、禁用、删除邀请码的交互
+    - _需求:2.1, 2.2, 2.3, 2.4_
+
+- [x] 5. AWS 配置与系统设置模块
+  - [x] 5.1 实现加密工具模块
+    - 创建 `server/src/utils/crypto.ts`,实现 AES-256 加密/解密函数
+    - 用于 AWS Secret Key 和 RDP 密码的加密存储
+    - _需求:4.4_
+
+  - [x] 5.2 编写属性测试:AWS Secret Key 加密存储往返
+    - **属性 5:AWS Secret Key 加密存储往返**
+    - **验证需求:4.4**
+
+  - [x] 5.3 实现 AWS 配置 API
+    - 创建 `server/src/routes/aws-config.ts`
+    - 实现 GET `/api/admin/aws-config`(Secret Key 脱敏返回)
+    - 实现 PUT `/api/admin/aws-config`(含 AWS 凭证有效性验证,失败返回"AWS 凭证无效")
+    - Secret Key 使用加密工具加密后存储
+    - _需求:4.1, 4.2, 4.3, 4.4, 4.5_
+
+  - [x] 5.4 编写属性测试:AWS 配置传播
+    - **属性 6:AWS 配置传播**
+    - **验证需求:4.5**
+
+  - [x] 5.5 实现系统设置 API
+    - 创建 `server/src/routes/settings.ts`
+    - 实现 GET/PUT `/api/admin/settings`,支持 max_instance_lifetime_hours 配置
+    - _需求:8.1_
+
+  - [x] 5.6 实现前端 AWS 配置与系统设置页面
+    - 创建 `AwsConfigForm` 组件(Access Key、Secret Key、Region、AMI ID 表单)
+    - 创建 `SystemSettings` 组件(实例最大使用时长配置)
+    - 凭证验证失败时显示错误提示
+    - _需求:4.1, 4.2, 4.3, 8.1_
+
+- [x] 6. 检查点 - 确保配置模块测试通过
+  - 确保所有测试通过,如有问题请询问用户。
+
+- [x] 7. EC2 实例启动与管理模块
+  - [x] 7.1 实现 MachineGuid UUID 校验工具
+    - 创建 `server/src/utils/validation.ts`,实现 UUID 格式校验函数
+    - 严格匹配 `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` 格式(x 为十六进制字符)
+    - _需求:5.2, 5.3_
+
+  - [x] 7.2 编写属性测试:MachineGuid UUID 格式校验
+    - **属性 7:MachineGuid UUID 格式校验**
+    - **验证需求:5.2, 5.3**
+
+  - [x] 7.3 实现 UserData 脚本生成器
+    - 创建 `server/src/services/userdata.ts`,生成 PowerShell 脚本
+    - 脚本将 MachineGuid 写入 `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography` 的 `MachineGuid` 键值
+    - _需求:6.2_
+
+  - [x] 7.4 编写属性测试:UserData 脚本包含 MachineGuid
+    - **属性 9:UserData 脚本包含 MachineGuid**
+    - **验证需求:6.2**
+
+  - [x] 7.5 实现 Instance_Manager 核心服务
+    - 创建 `server/src/services/instance-manager.ts`
+    - 实现 EC2 实例启动(RunInstances + UserData)、获取公网 IP、获取 Windows 密码(GetPasswordData)
+    - 实现关机(StopInstances)、启动(StartInstances)、重启(RebootInstances)、销毁(TerminateInstances)
+    - 启动成功后计算 expires_at = started_at + max_lifetime_hours * 3600
+    - 启动失败时返回包含失败原因的错误信息
+    - _需求:6.1, 6.2, 6.3, 6.4, 6.5, 7.2, 7.3, 7.4, 7.5_
+
+  - [x] 7.6 编写属性测试:MachineGuid 持久化往返
+    - **属性 8:MachineGuid 持久化往返**
+    - **验证需求:5.4**
+
+  - [x] 7.7 编写属性测试:实例创建返回完整 RDP 凭证
+    - **属性 10:实例创建返回完整 RDP 凭证**
+    - **验证需求:6.4**
+
+  - [x] 7.8 编写属性测试:实例生命周期状态转换
+    - **属性 11:实例生命周期状态转换**
+    - **验证需求:7.2, 7.3, 7.4, 7.5**
+
+  - [x] 7.9 实现实例管理 API 路由
+    - 创建 `server/src/routes/instances.ts`
+    - 实现 POST `/api/instances`(启动,需 MachineGuid)
+    - 实现 GET `/api/instances`(当前用户实例列表,含状态、IP、剩余时间)
+    - 实现 POST `/api/instances/:id/stop`、`/start`、`/reboot`
+    - 实现 DELETE `/api/instances/:id`(销毁)
+    - 实现 GET `/api/instances/:id/rdp`(获取 RDP 信息)
+    - _需求:5.4, 6.1, 6.4, 7.1, 7.2, 7.3, 7.4, 7.5_
+
+  - [x] 7.10 编写属性测试:实例列表数据完整性
+    - **属性 12:实例列表数据完整性**
+    - **验证需求:7.1, 9.1**
+
+- [x] 8. 检查点 - 确保实例管理模块测试通过
+  - 确保所有测试通过,如有问题请询问用户。
+
+- [x] 9. 实例生命周期与定时任务模块
+  - [x] 9.1 实现 Lifetime_Timer 定时任务
+    - 创建 `server/src/services/lifetime-timer.ts`,使用 node-cron 每分钟执行
+    - 查询 expires_at 已过且 status 非 terminated 的实例
+    - 调用 AWS TerminateInstances 并更新数据库状态为 terminated
+    - 失败时记录日志,下次检查重试
+    - _需求:8.2, 8.3_
+
+  - [x] 9.2 编写属性测试:实例过期时间正确计算
+    - **属性 13:实例过期时间正确计算**
+    - **验证需求:8.2**
+
+  - [x] 9.3 编写属性测试:过期实例自动终止
+    - **属性 14:过期实例自动终止**
+    - **验证需求:8.3**
+
+  - [x] 9.4 实现剩余时间计算与到期提醒
+    - 在实例查询接口中计算并返回剩余使用时间(expires_at - 当前时间)
+    - 实现到期提醒逻辑:剩余时间 < 30 分钟时,在实例数据中标记 `expiring_soon: true`
+    - _需求:8.4, 8.5_
+
+  - [x] 9.5 编写属性测试:剩余时间计算正确性
+    - **属性 15:剩余时间计算正确性**
+    - **验证需求:8.4**
+
+  - [x] 9.6 编写属性测试:到期提醒触发
+    - **属性 16:到期提醒触发**
+    - **验证需求:8.5**
+
+- [x] 10. 管理员监控与实例管理模块
+  - [x] 10.1 实现管理员实例监控 API
+    - 创建 `server/src/routes/admin-instances.ts`
+    - 实现 GET `/api/admin/instances`(所有用户实例列表,含所属用户、状态、IP、启动时间、剩余时间)
+    - 实现 DELETE `/api/admin/instances/:id`(管理员销毁任意实例)
+    - 实现 GET `/api/admin/instances/stats`(运行中实例总数统计)
+    - _需求:9.1, 9.2, 9.3_
+
+  - [x] 10.2 编写属性测试:运行中实例计数
+    - **属性 17:运行中实例计数**
+    - **验证需求:9.3**
+
+- [x] 11. 前端用户面板与管理员面板
+  - [x] 11.1 实现用户面板 User_Dashboard
+    - 创建实例列表组件,展示实例状态、公网 IP、剩余使用时间
+    - 实现启动实例表单(含 MachineGuid 输入和 UUID 格式前端校验)
+    - 实现关机、启动、重启、销毁操作按钮
+    - 实现 RDP 连接信息展示(IP、用户名、密码)
+    - 实现 30 秒轮询刷新实例状态
+    - 实现到期提醒通知(Ant Design Notification)
+    - _需求:5.1, 5.2, 5.3, 6.4, 7.1, 7.6, 8.4, 8.5_
+
+  - [x] 11.2 实现管理员面板 Admin_Panel
+    - 创建管理员入口页面,包含邀请码管理、AWS 配置、系统设置、实例监控的导航
+    - 创建 `InstanceMonitor` 组件,展示所有用户实例列表和运行中实例总数
+    - 实现管理员销毁任意实例功能
+    - 管理员登录后同时显示 Admin_Panel 入口和 User_Dashboard 入口
+    - _需求:3.3, 9.1, 9.2, 9.3_
+
+- [x] 12. 集成与收尾
+  - [x] 12.1 前后端联调与路由整合
+    - 在 `server/src/app.ts` 中注册所有 API 路由
+    - 配置前端代理(Vite proxy)指向后端 API
+    - 实现前端路由守卫(未登录重定向至登录页,非管理员无法访问管理页面)
+    - _需求:1.4, 3.3_
+
+  - [x] 12.2 编写集成测试
+    - 测试完整注册→登录→启动实例→查看 RDP 信息流程
+    - 测试管理员配置 AWS→用户启动实例流程
+    - _需求:1.1, 1.4, 6.1, 6.4_
+
+- [x] 13. 最终检查点 - 确保所有测试通过
+  - 确保所有测试通过,如有问题请询问用户。
+
+## 说明
+
+- 标记 `*` 的任务为可选任务,可跳过以加速 MVP 交付
+- 每个任务引用了对应的需求编号,确保可追溯性
+- 检查点任务用于阶段性验证,确保增量开发的正确性
+- 属性测试验证系统的通用正确性属性,单元测试覆盖具体示例和边界情况
+- 需求 10(Web 端远程桌面)为可选功能,不包含在当前实现计划中,建议后续迭代实现

+ 1 - 0
.kiro/specs/web-rdp-connect/.config.kiro

@@ -0,0 +1 @@
+{"specId": "b165b760-91d2-42c7-a14e-7dc17537df74", "workflowType": "requirements-first", "specType": "feature"}

+ 303 - 0
.kiro/specs/web-rdp-connect/design.md

@@ -0,0 +1,303 @@
+# 技术设计文档:Web RDP 连接
+
+## 概述
+
+本功能为现有 EC2 管理平台新增基于浏览器的远程桌面连接能力。通过集成 Apache Guacamole 生态(guacd + guacamole-lite + guacamole-common-js),用户无需安装本地 RDP 客户端即可在 Web 页面中直接操作 Windows EC2 实例。
+
+核心技术路线:
+- **guacd**:Apache Guacamole 的 C 语言守护进程,负责 RDP 协议处理(独立部署,推荐 Docker)
+- **guacamole-lite**:轻量级 Node.js WebSocket 代理,替代完整的 Java Guacamole Web 应用,将浏览器 Guacamole 协议指令转发给 guacd
+- **@nicedoc/guacamole-common-js**:前端 JavaScript 客户端库,在浏览器中渲染远程桌面画面
+
+数据流:`浏览器(guacamole-common-js) ↔ WebSocket ↔ guacamole-lite(Node.js) ↔ TCP ↔ guacd ↔ RDP ↔ EC2 实例`
+
+## 架构
+
+```mermaid
+graph TB
+    subgraph 浏览器
+        A[React 前端] --> B[guacamole-common-js]
+    end
+
+    subgraph Node.js 后端
+        C[Express API Server]
+        D[guacamole-lite WebSocket Server]
+        E[Connection Manager Service]
+        C --> E
+        E --> D
+    end
+
+    subgraph 外部服务
+        F[guacd 守护进程 :4822]
+        G[EC2 实例 RDP :3389]
+    end
+
+    B <-->|WSS| D
+    D <-->|TCP Guacamole 协议| F
+    F <-->|RDP| G
+    C <-->|HTTP REST| A
+```
+
+### 关键设计决策
+
+1. **guacamole-lite 集成方式**:将 guacamole-lite 的 WebSocket 服务器附加到现有 Express HTTP 服务器上,共享同一端口,通过路径 `/ws/rdp` 区分。避免额外端口管理。
+
+2. **会话令牌机制**:使用 JWT 签名的一次性令牌(包含连接参数的加密 token),由后端 API 生成,前端通过 WebSocket URL 查询参数传递给 guacamole-lite。guacamole-lite 验证并解密 token 获取 RDP 连接参数。
+
+3. **前端路由**:新增 `/rdp/:instanceId` 路由页面,在新标签页中打开。该页面独立于 Dashboard,全屏展示远程桌面画面。
+
+4. **Guacamole 配置存储**:复用现有 `system_settings` 表存储 guacd 地址和端口配置,管理员通过 Admin Panel 配置。
+
+## 组件与接口
+
+### 后端新增组件
+
+#### 1. Connection Manager Service (`server/src/services/connection-manager.ts`)
+
+负责 RDP 会话的创建、查询和销毁。
+
+```typescript
+interface RdpSession {
+  id: string;           // UUID
+  userId: number;
+  instanceId: number;
+  ec2InstanceId: string;
+  token: string;        // JWT 签名的一次性令牌
+  status: 'connecting' | 'connected' | 'disconnected';
+  createdAt: number;
+  expiresAt: number;
+}
+
+// 创建 RDP 会话,返回连接令牌
+function createRdpSession(userId: number, instanceId: number): RdpSession;
+
+// 获取活跃会话列表(管理员用)
+function getActiveSessions(): RdpSession[];
+
+// 终止指定会话
+function terminateSession(sessionId: string): void;
+
+// 终止某实例的所有会话
+function terminateSessionsByInstance(ec2InstanceId: string): void;
+
+// 清理过期会话
+function cleanupExpiredSessions(): void;
+```
+
+#### 2. Guacamole WebSocket 代理 (`server/src/services/guacamole-proxy.ts`)
+
+封装 guacamole-lite 的初始化和配置。
+
+```typescript
+// 初始化 guacamole-lite WebSocket 服务器,附加到 HTTP server
+function initGuacamoleProxy(httpServer: HttpServer, encryptionKey: string): void;
+```
+
+#### 3. RDP 会话 API 路由 (`server/src/routes/rdp-sessions.ts`)
+
+```
+POST   /api/instances/:id/rdp-session   — 创建 RDP 会话(用户)
+GET    /api/admin/rdp-sessions           — 获取所有活跃会话(管理员)
+DELETE /api/admin/rdp-sessions/:id       — 强制断开会话(管理员)
+```
+
+#### 4. Guacamole 配置 API(扩展现有 settings 路由)
+
+```
+GET    /api/admin/settings               — 获取设置(含 guacamole 配置)
+PUT    /api/admin/settings               — 更新设置(含 guacamole 配置)
+POST   /api/admin/guacamole/test         — 测试 guacd 连通性
+```
+
+### 前端新增组件
+
+#### 1. RDP 连接页面 (`client/src/pages/RdpPage.tsx`)
+
+独立的远程桌面页面,通过 `/rdp/:instanceId` 路由访问。
+
+- 初始化 guacamole-common-js 客户端
+- 连接 WebSocket 并渲染远程桌面画面
+- 提供工具栏:全屏切换、剪贴板、连接状态指示器、断开连接按钮
+
+#### 2. 连接状态指示器 (`client/src/components/RdpStatusBar.tsx`)
+
+显示在远程桌面页面顶部,展示连接状态(连接中/已连接/已断开)和重连按钮。
+
+#### 3. Guacamole 配置表单 (`client/src/components/GuacamoleConfig.tsx`)
+
+管理员面板中的 Guacamole 服务配置表单,包含地址、端口和连通性测试按钮。
+
+#### 4. RDP 会话监控 (`client/src/components/RdpSessionMonitor.tsx`)
+
+管理员面板中展示活跃 RDP 会话列表,支持强制断开操作。
+
+### Dashboard 修改
+
+在 `DashboardPage.tsx` 的实例操作列中,为 running 状态且有公网 IP 的实例添加"在线连接"按钮。当 Guacamole 未配置时隐藏该按钮。
+
+## 数据模型
+
+### 新增数据库表:`rdp_sessions`
+
+```sql
+CREATE TABLE IF NOT EXISTS rdp_sessions (
+  id TEXT PRIMARY KEY,                -- UUID
+  user_id INTEGER NOT NULL,
+  instance_id INTEGER NOT NULL,
+  ec2_instance_id TEXT NOT NULL,
+  token_hash TEXT NOT NULL,           -- 令牌哈希(用于验证一次性使用)
+  status TEXT NOT NULL DEFAULT 'connecting'
+    CHECK(status IN ('connecting', 'connected', 'disconnected')),
+  created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
+  expires_at INTEGER NOT NULL,
+  used_at INTEGER,                    -- 令牌首次使用时间
+  FOREIGN KEY (user_id) REFERENCES users(id),
+  FOREIGN KEY (instance_id) REFERENCES instances(id)
+);
+```
+
+### system_settings 新增键值
+
+| key | value 示例 | 说明 |
+|-----|-----------|------|
+| `guacamole_host` | `127.0.0.1` | guacd 服务地址 |
+| `guacamole_port` | `4822` | guacd 服务端口 |
+
+### guacamole-lite 连接令牌结构
+
+guacamole-lite 使用加密的 JSON token 传递连接参数:
+
+```json
+{
+  "connection": {
+    "type": "rdp",
+    "settings": {
+      "hostname": "EC2公网IP",
+      "port": "3389",
+      "username": "Administrator",
+      "password": "RDP密码",
+      "security": "nla",
+      "ignore-cert": "true",
+      "width": 1920,
+      "height": 1080
+    }
+  }
+}
+```
+
+该 JSON 由后端使用 AES-256-CBC 加密后作为 token 传递给前端,前端通过 WebSocket URL 参数发送给 guacamole-lite,guacamole-lite 使用相同密钥解密获取连接参数。
+
+
+## 正确性属性
+
+*属性是一种在系统所有有效执行中都应成立的特征或行为——本质上是关于系统应该做什么的形式化陈述。属性是人类可读规范与机器可验证正确性保证之间的桥梁。*
+
+### 属性 1:在线连接按钮可见性
+
+*对于任意* EC2 实例,"在线连接"按钮应当可见当且仅当该实例 status 为 "running" 且 public_ip 非空且 Guacamole 服务已配置。其他任何情况下按钮应当隐藏。
+
+**验证需求: 1.1, 1.2, 5.4**
+
+### 属性 2:RDP 会话创建包含正确连接参数
+
+*对于任意* 拥有有效 RDP 凭证的 running 状态实例,当实例所有者请求创建 RDP 会话时,系统应返回一个包含唯一会话令牌的 RDP_Session,且该令牌解密后包含正确的主机 IP、用户名和密码。
+
+**验证需求: 2.1, 2.2**
+
+### 属性 3:实例所有权强制检查
+
+*对于任意* 用户和任意实例,若该用户不是实例所有者,则创建 RDP 会话的请求应返回 403 状态码,且不应创建任何会话记录。
+
+**验证需求: 3.1, 3.2**
+
+### 属性 4:会话令牌有效性约束
+
+*对于任意* RDP 会话令牌,该令牌应具有有限有效期;当令牌过期或已被使用后,系统应拒绝基于该令牌的连接请求。
+
+**验证需求: 3.3, 3.4**
+
+### 属性 5:实例终止级联清理会话
+
+*对于任意* 拥有活跃 RDP 会话的 EC2 实例,当该实例被停止或销毁时,与该实例关联的所有活跃会话应被终止(状态变为 disconnected)。
+
+**验证需求: 4.2**
+
+### 属性 6:管理员活跃会话列表完整性
+
+*对于任意* 系统中存在的活跃 RDP 会话集合,管理员查询接口应返回所有活跃会话,且每条记录包含所属用户、目标实例、连接时长和连接状态字段。
+
+**验证需求: 7.1, 7.3**
+
+### 属性 7:管理员强制断开会话
+
+*对于任意* 活跃 RDP 会话,当管理员执行强制断开操作后,该会话状态应变为 disconnected 且不再出现在活跃会话列表中。
+
+**验证需求: 7.2**
+
+## 错误处理
+
+| 场景 | 错误码 | 错误消息 | HTTP 状态码 |
+|------|--------|---------|------------|
+| 实例不存在 | NOT_FOUND | 实例不存在 | 404 |
+| 非实例所有者 | FORBIDDEN | 无权操作此实例 | 403 |
+| 实例非 running 状态 | INVALID_STATE | 实例未处于运行状态,无法建立远程连接 | 400 |
+| RDP 凭证缺失 | RDP_CREDENTIALS_MISSING | 该实例缺少 RDP 连接信息 | 400 |
+| Guacamole 未配置 | GUACAMOLE_NOT_CONFIGURED | Guacamole 服务未配置 | 503 |
+| Guacamole 不可达 | GUACAMOLE_UNREACHABLE | Guacamole 服务不可达 | 502 |
+| 会话令牌过期 | TOKEN_EXPIRED | 会话已过期,请重新连接 | 401 |
+| 会话令牌已使用 | TOKEN_USED | 会话令牌已被使用 | 401 |
+| RDP 连接失败 | RDP_CONNECTION_FAILED | 连接失败:目标实例不可达,请确认实例已完成初始化 | 502 |
+| 会话不存在 | SESSION_NOT_FOUND | 会话不存在 | 404 |
+
+### 前端错误处理策略
+
+- 连接失败时显示错误提示卡片,包含错误原因和重试按钮
+- WebSocket 断开时显示"连接已断开"状态栏,提供重新连接按钮
+- API 请求失败时使用 antd message 组件显示错误消息
+
+## 测试策略
+
+### 双重测试方法
+
+本功能采用单元测试与属性测试相结合的方式确保正确性:
+
+- **单元测试**:验证具体示例、边界情况和错误条件
+- **属性测试**:验证跨所有输入的通用属性
+
+两者互补,单元测试捕获具体 bug,属性测试验证通用正确性。
+
+### 属性测试配置
+
+- 使用 **fast-check** 库(项目已有依赖)
+- 每个属性测试最少运行 **100 次迭代**
+- 每个属性测试必须通过注释引用设计文档中的属性
+- 标签格式:**Feature: web-rdp-connect, Property {number}: {property_text}**
+- 每个正确性属性由**单个**属性测试实现
+
+### 单元测试范围
+
+- Connection Manager Service:会话 CRUD、所有权验证、令牌生成与验证、过期清理
+- RDP Session API 路由:请求验证、权限检查、错误响应
+- Guacamole 配置 API:配置保存、连通性测试
+- 前端组件:按钮可见性逻辑、状态指示器渲染
+
+### 属性测试范围
+
+对应设计文档中的 7 个正确性属性:
+
+1. **Property 1** - 按钮可见性:生成随机实例状态和配置组合,验证按钮可见性逻辑
+2. **Property 2** - 会话创建:生成随机实例和凭证,验证会话创建结果
+3. **Property 3** - 所有权检查:生成随机用户-实例组合,验证权限拒绝
+4. **Property 4** - 令牌有效性:生成随机令牌状态(过期/已用/有效),验证接受/拒绝
+5. **Property 5** - 级联清理:生成随机实例和关联会话,验证终止级联
+6. **Property 6** - 会话列表完整性:生成随机会话集合,验证 API 返回完整性
+7. **Property 7** - 强制断开:生成随机活跃会话,验证断开后状态变更
+
+### 测试文件组织
+
+```
+server/src/services/connection-manager.test.ts          — 单元测试
+server/src/services/connection-manager.property.test.ts — 属性测试
+server/src/routes/rdp-sessions.test.ts                  — API 路由单元测试
+server/src/routes/rdp-sessions.property.test.ts         — API 路由属性测试
+```

+ 115 - 0
.kiro/specs/web-rdp-connect/requirements.md

@@ -0,0 +1,115 @@
+# 需求文档
+
+## 简介
+
+Web RDP 连接功能为现有 EC2 管理平台新增基于浏览器的远程桌面能力。用户无需安装本地 RDP 客户端,即可在 Web 页面中直接连接并操作 Windows EC2 实例的图形界面。系统通过 Apache Guacamole 作为无客户端远程桌面网关,将 RDP 协议转换为 HTML5 渲染,在浏览器中提供完整的远程桌面体验。
+
+## 术语表
+
+- **Platform**:EC2 管理平台 Web 系统
+- **User_Dashboard**:用户操作界面,用于管理个人 EC2 实例
+- **Admin_Panel**:管理员后台界面,用于系统配置和用户管理
+- **Web_RDP_Gateway**:基于 Apache Guacamole 的 Web 远程桌面网关服务,负责将 RDP 协议转换为 HTML5 WebSocket 流
+- **Guacamole_Server**:Apache Guacamole 的 guacd 守护进程,处理实际的 RDP 协议连接
+- **Connection_Manager**:连接管理模块,负责创建、维护和销毁 Web RDP 会话
+- **RDP_Session**:一次 Web 远程桌面会话,包含连接参数、认证令牌和会话状态
+- **Instance_Manager**:EC2 实例生命周期管理模块(已有)
+- **RDP_Credentials**:Windows 远程桌面连接信息,包含 IP 地址、用户名和密码(已有)
+
+## 需求
+
+### 需求 1:Web RDP 连接入口
+
+**用户故事:** 作为用户,我希望在实例列表中看到"在线连接"按钮,以便直接在浏览器中打开远程桌面。
+
+#### 验收标准
+
+1. WHILE EC2 实例处于 running 状态且拥有公网 IP, THE User_Dashboard SHALL 在该实例的操作列中显示"在线连接"按钮
+2. WHILE EC2 实例处于非 running 状态, THE User_Dashboard SHALL 隐藏该实例的"在线连接"按钮
+3. WHEN 用户点击"在线连接"按钮, THE Platform SHALL 在新浏览器标签页中打开远程桌面会话页面
+
+### 需求 2:Web RDP 会话建立
+
+**用户故事:** 作为用户,我希望点击连接后系统自动使用已有的 RDP 凭证建立远程桌面会话,以便无需手动输入连接信息。
+
+#### 验收标准
+
+1. WHEN 用户发起 Web RDP 连接请求, THE Connection_Manager SHALL 从数据库读取该实例的 RDP_Credentials(公网 IP、用户名、密码)
+2. WHEN Connection_Manager 获取到有效的 RDP_Credentials, THE Connection_Manager SHALL 创建一个包含连接参数的 RDP_Session 并生成唯一的会话令牌
+3. WHEN RDP_Session 创建成功, THE Web_RDP_Gateway SHALL 通过 Guacamole_Server 与目标 EC2 实例建立 RDP 协议连接
+4. WHEN RDP 协议连接建立成功, THE Platform SHALL 在浏览器中渲染远程桌面画面并支持键盘和鼠标输入
+5. IF 目标 EC2 实例的 RDP 服务不可达, THEN THE Platform SHALL 向用户显示"连接失败:目标实例不可达,请确认实例已完成初始化"的错误提示
+
+### 需求 3:Web RDP 会话认证与安全
+
+**用户故事:** 作为用户,我希望 Web RDP 连接受到认证保护,以便只有实例所有者能访问远程桌面。
+
+#### 验收标准
+
+1. THE Connection_Manager SHALL 仅允许实例所有者创建该实例的 RDP_Session
+2. WHEN 非实例所有者尝试创建 RDP_Session, THE Connection_Manager SHALL 返回 403 权限拒绝错误
+3. THE Connection_Manager SHALL 为每个 RDP_Session 生成一个具有有限有效期的一次性会话令牌
+4. WHEN 会话令牌过期或已被使用, THE Web_RDP_Gateway SHALL 拒绝连接请求并返回"会话已过期"的错误提示
+5. THE Platform SHALL 通过 WebSocket 安全连接(WSS)传输远程桌面数据流
+
+### 需求 4:Web RDP 会话生命周期管理
+
+**用户故事:** 作为用户,我希望远程桌面会话能自动管理生命周期,以便在实例关闭或销毁时自动断开连接。
+
+#### 验收标准
+
+1. WHEN 用户主动关闭远程桌面标签页, THE Connection_Manager SHALL 释放该 RDP_Session 占用的资源
+2. WHEN EC2 实例被停止或销毁, THE Connection_Manager SHALL 自动终止与该实例关联的所有活跃 RDP_Session
+3. WHEN RDP 连接意外断开, THE Platform SHALL 向用户显示"连接已断开"的提示并提供重新连接按钮
+4. WHILE RDP_Session 处于活跃状态, THE Platform SHALL 在远程桌面页面顶部显示连接状态指示器(已连接/连接中/已断开)
+
+### 需求 5:Guacamole 服务集成配置
+
+**用户故事:** 作为管理员,我希望在后台配置 Guacamole 服务的连接参数,以便系统能正确连接到远程桌面网关。
+
+#### 验收标准
+
+1. THE Admin_Panel SHALL 提供配置 Guacamole_Server 地址和端口的表单
+2. WHEN 管理员提交 Guacamole 配置, THE Platform SHALL 验证与 Guacamole_Server 的连通性
+3. IF Guacamole_Server 连通性验证失败, THEN THE Admin_Panel SHALL 显示"Guacamole 服务不可达"的错误提示并拒绝保存
+4. WHEN Guacamole 配置未设置, THE User_Dashboard SHALL 隐藏所有实例的"在线连接"按钮并仅提供 RDP_Credentials 查看功能
+
+### 需求 6:远程桌面交互体验
+
+**用户故事:** 作为用户,我希望在浏览器中获得流畅的远程桌面操作体验,以便高效完成工作。
+
+#### 验收标准
+
+1. THE Platform SHALL 支持在远程桌面会话中传递标准键盘输入,包括组合键(Ctrl+C、Ctrl+V、Alt+Tab)
+2. THE Platform SHALL 支持在远程桌面会话中传递鼠标操作,包括单击、双击、右键和滚轮
+3. THE Platform SHALL 提供远程桌面画面的自适应缩放功能,适配不同浏览器窗口尺寸
+4. THE Platform SHALL 在远程桌面页面提供全屏切换按钮
+5. THE Platform SHALL 在远程桌面页面提供剪贴板同步功能,支持本地与远程之间的文本复制粘贴
+
+### 需求 7:连接状态监控(管理员)
+
+**用户故事:** 作为管理员,我希望查看当前所有活跃的 Web RDP 会话,以便监控系统资源使用情况。
+
+#### 验收标准
+
+1. THE Admin_Panel SHALL 展示所有活跃 RDP_Session 的列表,包含所属用户、目标实例、连接时长和连接状态
+2. WHEN 管理员对某个 RDP_Session 执行强制断开操作, THE Connection_Manager SHALL 立即终止该会话并释放资源
+3. THE Admin_Panel SHALL 显示当前活跃 Web RDP 会话的总数
+
+---
+
+## 补充说明
+
+### 技术方案概述
+
+本功能基于 Apache Guacamole 实现,架构如下:
+
+- **guacd(Guacamole Server)**:C 语言编写的守护进程,负责实际的 RDP/VNC/SSH 协议处理。需要独立部署(推荐 Docker 方式)。
+- **guacamole-lite 或自定义 WebSocket 代理**:Node.js 端集成方案,作为 WebSocket 服务端,将浏览器的 Guacamole 协议指令转发给 guacd。避免部署完整的 Java Guacamole Web 应用。
+- **@nicedoc/guacamole-common-js(前端)**:Guacamole 官方 JavaScript 客户端库,在浏览器中渲染远程桌面画面并处理用户输入。
+
+### 部署依赖
+
+- 需要额外部署 guacd 服务(推荐使用 `guacamole/guacd` Docker 镜像)
+- guacd 需要能够通过网络访问 EC2 实例的 RDP 端口(3389)
+- 后端服务器需要能够连接 guacd 的监听端口(默认 4822)

+ 60 - 0
.kiro/specs/web-rdp-connect/tasks.md

@@ -0,0 +1,60 @@
+# 任务列表:Web RDP 连接
+
+## 1. 数据库与基础设施
+- [x] 1.1 在 `server/src/db.ts` 的 `createTables` 中添加 `rdp_sessions` 表定义
+- [x] 1.2 在 `system_settings` 表中添加 `guacamole_host` 和 `guacamole_port` 默认值种子数据
+
+## 2. Connection Manager 服务
+- [x] 2.1 创建 `server/src/services/connection-manager.ts`,实现 `createRdpSession` 函数:验证实例所有权、读取 RDP 凭证、生成加密令牌、创建会话记录
+- [x] 2.2 实现 `getActiveSessions` 函数:查询所有状态为 connecting/connected 的会话,包含用户名、实例 ID、连接时长
+- [x] 2.3 实现 `terminateSession` 函数:将指定会话状态更新为 disconnected
+- [x] 2.4 实现 `terminateSessionsByInstance` 函数:终止某 EC2 实例关联的所有活跃会话
+- [x] 2.5 实现 `cleanupExpiredSessions` 函数:清理过期会话记录
+- [x] 2.6 实现令牌验证逻辑:检查令牌是否过期或已使用
+- [x] 2.7 编写 `connection-manager.test.ts` 单元测试
+- [x] 2.8 编写 `connection-manager.property.test.ts` 属性测试(覆盖属性 2-7)
+
+## 3. Guacamole 代理集成
+- [x] 3.1 安装 `guacamole-lite` 依赖包
+- [x] 3.2 创建 `server/src/services/guacamole-proxy.ts`,封装 guacamole-lite WebSocket 服务器初始化
+- [x] 3.3 在 `server/src/app.ts` 中集成 guacamole-lite,将 WebSocket 服务器附加到 HTTP server 的 `/ws/rdp` 路径
+- [x] 3.4 实现 guacd 连通性测试函数(TCP 连接检测)
+
+## 4. RDP 会话 API 路由
+- [x] 4.1 创建 `server/src/routes/rdp-sessions.ts`,实现 `POST /api/instances/:id/rdp-session` 接口
+- [x] 4.2 实现 `GET /api/admin/rdp-sessions` 接口(管理员获取活跃会话列表)
+- [x] 4.3 实现 `DELETE /api/admin/rdp-sessions/:id` 接口(管理员强制断开会话)
+- [x] 4.4 实现 `POST /api/admin/guacamole/test` 接口(测试 guacd 连通性)
+- [x] 4.5 在 `server/src/app.ts` 中注册新路由
+- [x] 4.6 编写 `rdp-sessions.test.ts` 单元测试
+- [x] 4.7 编写 `rdp-sessions.property.test.ts` 属性测试(覆盖属性 3、6、7)
+
+## 5. 扩展现有设置 API
+- [x] 5.1 扩展 `GET /api/admin/settings` 返回 guacamole_host 和 guacamole_port
+- [x] 5.2 扩展 `PUT /api/admin/settings` 支持保存 guacamole_host 和 guacamole_port
+- [x] 5.3 添加 `GET /api/settings/guacamole-status` 公开接口,返回 Guacamole 是否已配置(供前端判断按钮可见性)
+
+## 6. 实例生命周期联动
+- [x] 6.1 在 `instance-manager.ts` 的 `stopInstance` 和 `terminateInstance` 中调用 `terminateSessionsByInstance` 清理关联会话
+- [x] 6.2 编写联动逻辑的单元测试
+
+## 7. 前端 - RDP 连接页面
+- [x] 7.1 安装 `@nicedoc/guacamole-common-js` 前端依赖
+- [x] 7.2 创建 `client/src/pages/RdpPage.tsx`:初始化 Guacamole 客户端、连接 WebSocket、渲染远程桌面画面
+- [x] 7.3 实现连接状态指示器组件 `client/src/components/RdpStatusBar.tsx`(连接中/已连接/已断开 + 重连按钮)
+- [x] 7.4 实现工具栏功能:全屏切换按钮、剪贴板同步面板、断开连接按钮
+- [x] 7.5 实现远程桌面画面自适应缩放逻辑
+- [x] 7.6 在 `client/src/router.tsx` 中添加 `/rdp/:instanceId` 路由
+
+## 8. 前端 - Dashboard 修改
+- [x] 8.1 在 `DashboardPage.tsx` 中添加获取 Guacamole 配置状态的 API 调用
+- [x] 8.2 在实例操作列中为 running 且有公网 IP 的实例添加"在线连接"按钮(仅当 Guacamole 已配置时显示)
+- [x] 8.3 实现点击"在线连接"按钮时调用创建 RDP 会话 API 并在新标签页打开 `/rdp/:instanceId?token=xxx`
+
+## 9. 前端 - 管理员面板
+- [x] 9.1 创建 `client/src/components/GuacamoleConfig.tsx`:Guacamole 服务地址和端口配置表单,含连通性测试按钮
+- [x] 9.2 创建 `client/src/components/RdpSessionMonitor.tsx`:活跃 RDP 会话列表,含强制断开按钮和会话总数显示
+- [x] 9.3 在 `AdminPage.tsx` 中集成 GuacamoleConfig 和 RdpSessionMonitor 组件
+
+## 10. Vite 代理配置
+- [x] 10.1 在 `client/vite.config.ts` 中添加 `/ws/rdp` 的 WebSocket 代理配置

+ 40 - 0
Dockerfile

@@ -0,0 +1,40 @@
+# Bifrost Anywhere
+# Stage 1: Build client
+FROM node:22-alpine AS client-build
+WORKDIR /app/client
+COPY client/package.json client/package-lock.json ./
+RUN npm ci
+COPY client/ ./
+RUN npm run build
+
+# Stage 2: Build server
+FROM node:22-alpine AS server-build
+WORKDIR /app/server
+COPY server/package.json server/package-lock.json ./
+RUN npm ci
+COPY server/ ./
+RUN npm run build
+
+# Stage 3: Production
+FROM node:22-alpine
+WORKDIR /app
+
+# better-sqlite3 needs native build deps
+RUN apk add --no-cache python3 make g++
+
+COPY server/package.json server/package-lock.json ./server/
+RUN cd server && npm ci --omit=dev
+
+COPY --from=server-build /app/server/dist ./server/dist
+COPY --from=client-build /app/client/dist ./server/public
+
+# Data volume for SQLite
+RUN mkdir -p /app/server/data
+VOLUME ["/app/server/data"]
+
+ENV NODE_ENV=production
+ENV PORT=3000
+EXPOSE 3000
+
+WORKDIR /app/server
+CMD ["node", "dist/app.js"]

+ 89 - 0
README.md

@@ -0,0 +1,89 @@
+# Bifrost Anywhere
+
+基于 Web 的 AWS EC2 实例管理平台,支持通过 Apache Guacamole 进行浏览器内 RDP 远程桌面连接。
+
+## 技术栈
+
+- 前端:React 19 + TypeScript + Vite + Ant Design
+- 后端:Express + TypeScript + better-sqlite3
+- 远程桌面:guacamole-lite + guacamole-common-js
+- AWS SDK v3
+
+## 项目结构
+
+```
+├── client/          # React 前端
+│   └── src/
+│       ├── components/  # UI 组件
+│       ├── pages/       # 页面
+│       ├── api/         # Axios 配置
+│       └── utils/       # 工具函数
+├── server/          # Express 后端
+│   └── src/
+│       ├── routes/      # API 路由
+│       ├── services/    # 业务逻辑
+│       ├── middleware/  # 中间件
+│       └── utils/       # 工具函数
+└── Dockerfile
+```
+
+## 快速开始
+
+### 环境要求
+
+- Node.js >= 18
+- npm
+
+### 本地开发
+
+```bash
+# 安装依赖
+cd server && npm install
+cd ../client && npm install
+
+# 配置环境变量
+cp .env.example .env
+# 编辑 .env 填入 AWS 凭证等配置
+
+# 启动后端 (端口 3000)
+cd server && npm run dev
+
+# 启动前端 (端口 5173,自动代理 API 到后端)
+cd client && npm run dev
+```
+
+### Docker 部署
+
+```bash
+# 1. 启动 guacd(Guacamole 代理守护进程,用于 RDP 连接)
+docker run -d --name guacd guacamole/guacd
+
+# 2. 构建应用镜像
+docker build -t bifrost-anywhere .
+
+# 3. 运行应用容器(链接 guacd)
+docker run -d \
+  -p 3000:3000 \
+  -v bifrost-anywhere-data:/app/server/data \
+  --link guacd:guacd \
+  --env-file .env \
+  --name bifrost-anywhere \
+  bifrost-anywhere
+```
+
+## 环境变量
+
+| 变量 | 说明 | 默认值 |
+|------|------|--------|
+| `PORT` | 服务端口 | `3000` |
+| `JWT_SECRET` | JWT 签名密钥 | - |
+
+> AWS 凭证(Access Key、Secret Key、Region 等)通过管理员页面配置,加密后存储在数据库中,无需设置环境变量。
+
+## API
+
+- `GET /api/health` — 健康检查
+- `/api/auth` — 认证相关
+- `/api/instances` — 实例管理
+- `/api/admin/*` — 管理员接口
+- `ws://host/ws/rdp` — RDP WebSocket 连接

+ 24 - 0
client/.gitignore

@@ -0,0 +1,24 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+lerna-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
+
+# Editor directories and files
+.vscode/*
+!.vscode/extensions.json
+.idea
+.DS_Store
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?

+ 19 - 0
client/index.html

@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Bifrost Anywhere</title>
+    <style>
+      body {
+        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
+        margin: 0;
+      }
+    </style>
+  </head>
+  <body>
+    <div id="root"></div>
+    <script type="module" src="/src/main.tsx"></script>
+  </body>
+</html>

+ 2293 - 0
client/package-lock.json

@@ -0,0 +1,2293 @@
+{
+  "name": "client",
+  "version": "0.0.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "client",
+      "version": "0.0.0",
+      "dependencies": {
+        "antd": "^6.3.5",
+        "axios": "^1.14.0",
+        "guacamole-common-js": "^1.5.0",
+        "react": "^19.2.4",
+        "react-dom": "^19.2.4",
+        "react-router-dom": "^7.13.2"
+      },
+      "devDependencies": {
+        "@types/react": "^19.2.14",
+        "@types/react-dom": "^19.2.3",
+        "@vitejs/plugin-react": "^6.0.1",
+        "typescript": "~5.9.3",
+        "vite": "^8.0.1"
+      }
+    },
+    "node_modules/@ant-design/colors": {
+      "version": "8.0.1",
+      "resolved": "https://registry.npmjs.org/@ant-design/colors/-/colors-8.0.1.tgz",
+      "integrity": "sha512-foPVl0+SWIslGUtD/xBr1p9U4AKzPhNYEseXYRRo5QSzGACYZrQbe11AYJbYfAWnWSpGBx6JjBmSeugUsD9vqQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@ant-design/fast-color": "^3.0.0"
+      }
+    },
+    "node_modules/@ant-design/cssinjs": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/@ant-design/cssinjs/-/cssinjs-2.1.2.tgz",
+      "integrity": "sha512-2Hy8BnCEH31xPeSLbhhB2ctCPXE2ZnASdi+KbSeS79BNbUhL9hAEe20SkUk+BR8aKTmqb6+FKFruk7w8z0VoRQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.11.1",
+        "@emotion/hash": "^0.8.0",
+        "@emotion/unitless": "^0.7.5",
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1",
+        "csstype": "^3.1.3",
+        "stylis": "^4.3.4"
+      },
+      "peerDependencies": {
+        "react": ">=16.0.0",
+        "react-dom": ">=16.0.0"
+      }
+    },
+    "node_modules/@ant-design/cssinjs-utils": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/@ant-design/cssinjs-utils/-/cssinjs-utils-2.1.2.tgz",
+      "integrity": "sha512-5fTHQ158jJJ5dC/ECeyIdZUzKxE/mpEMRZxthyG1sw/AKRHKgJBg00Yi6ACVXgycdje7KahRNvNET/uBccwCnA==",
+      "license": "MIT",
+      "dependencies": {
+        "@ant-design/cssinjs": "^2.1.2",
+        "@babel/runtime": "^7.23.2",
+        "@rc-component/util": "^1.4.0"
+      },
+      "peerDependencies": {
+        "react": ">=18",
+        "react-dom": ">=18"
+      }
+    },
+    "node_modules/@ant-design/fast-color": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/@ant-design/fast-color/-/fast-color-3.0.1.tgz",
+      "integrity": "sha512-esKJegpW4nckh0o6kV3Tkb7NPIZYbPnnFxmQDUmL08ukXZAvV85TZBr70eGuke/CIArLaP6aw8lt9KILjnWuOw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=8.x"
+      }
+    },
+    "node_modules/@ant-design/icons": {
+      "version": "6.1.1",
+      "resolved": "https://registry.npmjs.org/@ant-design/icons/-/icons-6.1.1.tgz",
+      "integrity": "sha512-AMT4N2y++TZETNHiM77fs4a0uPVCJGuL5MTonk13Pvv7UN7sID1cNEZOc1qNqx6zLKAOilTEFAdAoAFKa0U//Q==",
+      "license": "MIT",
+      "dependencies": {
+        "@ant-design/colors": "^8.0.0",
+        "@ant-design/icons-svg": "^4.4.0",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8"
+      },
+      "peerDependencies": {
+        "react": ">=16.0.0",
+        "react-dom": ">=16.0.0"
+      }
+    },
+    "node_modules/@ant-design/icons-svg": {
+      "version": "4.4.2",
+      "resolved": "https://registry.npmjs.org/@ant-design/icons-svg/-/icons-svg-4.4.2.tgz",
+      "integrity": "sha512-vHbT+zJEVzllwP+CM+ul7reTEfBR0vgxFe7+lREAsAA7YGsYpboiq2sQNeQeRvh09GfQgs/GyFEvZpJ9cLXpXA==",
+      "license": "MIT"
+    },
+    "node_modules/@ant-design/react-slick": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/@ant-design/react-slick/-/react-slick-2.0.0.tgz",
+      "integrity": "sha512-HMS9sRoEmZey8LsE/Yo6+klhlzU12PisjrVcydW3So7RdklyEd2qehyU6a7Yp+OYN72mgsYs3NFCyP2lCPFVqg==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.28.4",
+        "clsx": "^2.1.1",
+        "json2mq": "^0.2.0",
+        "throttle-debounce": "^5.0.0"
+      },
+      "peerDependencies": {
+        "react": "^0.14.0 || ^15.0.1 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+        "react-dom": "^0.14.0 || ^15.0.1 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+      }
+    },
+    "node_modules/@babel/runtime": {
+      "version": "7.29.2",
+      "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
+      "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
+    "node_modules/@emnapi/core": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz",
+      "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==",
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "peer": true,
+      "dependencies": {
+        "@emnapi/wasi-threads": "1.2.0",
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@emnapi/runtime": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz",
+      "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==",
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "peer": true,
+      "dependencies": {
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@emnapi/wasi-threads": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz",
+      "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==",
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "peer": true,
+      "dependencies": {
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@emotion/hash": {
+      "version": "0.8.0",
+      "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz",
+      "integrity": "sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==",
+      "license": "MIT"
+    },
+    "node_modules/@emotion/unitless": {
+      "version": "0.7.5",
+      "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.7.5.tgz",
+      "integrity": "sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==",
+      "license": "MIT"
+    },
+    "node_modules/@napi-rs/wasm-runtime": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.2.tgz",
+      "integrity": "sha512-sNXv5oLJ7ob93xkZ1XnxisYhGYXfaG9f65/ZgYuAu3qt7b3NadcOEhLvx28hv31PgX8SZJRYrAIPQilQmFpLVw==",
+      "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"
+      }
+    },
+    "node_modules/@oxc-project/types": {
+      "version": "0.122.0",
+      "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.122.0.tgz",
+      "integrity": "sha512-oLAl5kBpV4w69UtFZ9xqcmTi+GENWOcPF7FCrczTiBbmC0ibXxCwyvZGbO39rCVEuLGAZM84DH0pUIyyv/YJzA==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/Boshen"
+      }
+    },
+    "node_modules/@rc-component/async-validator": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/async-validator/-/async-validator-5.1.0.tgz",
+      "integrity": "sha512-n4HcR5siNUXRX23nDizbZBQPO0ZM/5oTtmKZ6/eqL0L2bo747cklFdZGRN2f+c9qWGICwDzrhW0H7tE9PptdcA==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.24.4"
+      },
+      "engines": {
+        "node": ">=14.x"
+      }
+    },
+    "node_modules/@rc-component/cascader": {
+      "version": "1.14.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/cascader/-/cascader-1.14.0.tgz",
+      "integrity": "sha512-Ip9356xwZUR2nbW5PRVGif4B/bDve4pLa/N+PGbvBaTnjbvmN4PFMBGQSmlDlzKP1ovxaYMvwF/dI9lXNLT4iQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/select": "~1.6.0",
+        "@rc-component/tree": "~1.2.0",
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/checkbox": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/checkbox/-/checkbox-2.0.0.tgz",
+      "integrity": "sha512-3CXGPpAR9gsPKeO2N78HAPOzU30UdemD6HGJoWVJOpa6WleaGB5kzZj3v6bdTZab31YuWgY/RxV3VKPctn0DwQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/collapse": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/collapse/-/collapse-1.2.0.tgz",
+      "integrity": "sha512-ZRYSKSS39qsFx93p26bde7JUZJshsUBEQRlRXPuJYlAiNX0vyYlF5TsAm8JZN3LcF8XvKikdzPbgAtXSbkLUkw==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.10.1",
+        "@rc-component/motion": "^1.1.4",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/color-picker": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/color-picker/-/color-picker-3.1.1.tgz",
+      "integrity": "sha512-OHaCHLHszCegdXmIq2ZRIZBN/EtpT6Wm8SG/gpzLATHbVKc/avvuKi+zlOuk05FTWvgaMmpxAko44uRJ3M+2pg==",
+      "license": "MIT",
+      "dependencies": {
+        "@ant-design/fast-color": "^3.0.1",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/context": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/context/-/context-2.0.1.tgz",
+      "integrity": "sha512-HyZbYm47s/YqtP6pKXNMjPEMaukyg7P0qVfgMLzr7YiFNMHbK2fKTAGzms9ykfGHSfyf75nBbgWw+hHkp+VImw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/dialog": {
+      "version": "1.8.4",
+      "resolved": "https://registry.npmjs.org/@rc-component/dialog/-/dialog-1.8.4.tgz",
+      "integrity": "sha512-Ay6PM7phkTkquplG8fWfUGFZ2GTLx9diTl4f0d8Eqxd7W1u1KjE9AQooFQHOHnhZf0Ya3z51+5EKCWHmt/dNEw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.1.3",
+        "@rc-component/portal": "^2.1.0",
+        "@rc-component/util": "^1.9.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/drawer": {
+      "version": "1.4.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/drawer/-/drawer-1.4.2.tgz",
+      "integrity": "sha512-1ib+fZEp6FBu+YvcIktm+nCQ+Q+qIpwpoaJH6opGr4ofh2QMq+qdr5DLC4oCf5qf3pcWX9lUWPYX652k4ini8Q==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.1.4",
+        "@rc-component/portal": "^2.1.3",
+        "@rc-component/util": "^1.9.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/dropdown": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/dropdown/-/dropdown-1.0.2.tgz",
+      "integrity": "sha512-6PY2ecUSYhDPhkNHHb4wfeAya04WhpmUSKzdR60G+kMNVUCX2vjT/AgTS0Lz0I/K6xrPMJ3enQbwVpeN3sHCgg==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/trigger": "^3.0.0",
+        "@rc-component/util": "^1.2.1",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.11.0",
+        "react-dom": ">=16.11.0"
+      }
+    },
+    "node_modules/@rc-component/form": {
+      "version": "1.8.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/form/-/form-1.8.0.tgz",
+      "integrity": "sha512-eUD5KKYnIZWmJwRA0vnyO/ovYUfHGU1svydY1OrqU5fw8Oz9Tdqvxvrlh0wl6xI/EW69dT7II49xpgOWzK3T5A==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/async-validator": "^5.1.0",
+        "@rc-component/util": "^1.6.2",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/image": {
+      "version": "1.8.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/image/-/image-1.8.0.tgz",
+      "integrity": "sha512-Dr41bFevLB5NgVaJhEUmNvbEf+ynAhim6W98ZW2xvCsdFISc2TYP4ZvCVdie3eaZdum2kieVcvpNHu+UrzAAHA==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.0.0",
+        "@rc-component/portal": "^2.1.2",
+        "@rc-component/util": "^1.10.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/input": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/input/-/input-1.1.2.tgz",
+      "integrity": "sha512-Q61IMR47piUBudgixJ30CciKIy9b1H95qe7GgEKOmSJVJXvFRWJllJfQry9tif+MX2cWFXWJf/RXz4kaCeq/Fg==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.0.0",
+        "react-dom": ">=16.0.0"
+      }
+    },
+    "node_modules/@rc-component/input-number": {
+      "version": "1.6.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/input-number/-/input-number-1.6.2.tgz",
+      "integrity": "sha512-Gjcq7meZlCOiWN1t1xCC+7/s85humHVokTBI7PJgTfoyw5OWF74y3e6P8PHX104g9+b54jsodFIzyaj6p8LI9w==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/mini-decimal": "^1.0.1",
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/mentions": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/mentions/-/mentions-1.6.0.tgz",
+      "integrity": "sha512-KIkQNP6habNuTsLhUv0UGEOwG67tlmE7KNIJoQZZNggEZl5lQJTytFDb69sl5CK3TDdISCTjKP3nGEBKgT61CQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/input": "~1.1.0",
+        "@rc-component/menu": "~1.2.0",
+        "@rc-component/textarea": "~1.1.0",
+        "@rc-component/trigger": "^3.0.0",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/menu": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/menu/-/menu-1.2.0.tgz",
+      "integrity": "sha512-VWwDuhvYHSnTGj4n6bV3ISrLACcPAzdPOq3d0BzkeiM5cve8BEYfvkEhNoM0PLzv51jpcejeyrLXeMVIJ+QJlg==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.1.4",
+        "@rc-component/overflow": "^1.0.0",
+        "@rc-component/trigger": "^3.0.0",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/mini-decimal": {
+      "version": "1.1.3",
+      "resolved": "https://registry.npmjs.org/@rc-component/mini-decimal/-/mini-decimal-1.1.3.tgz",
+      "integrity": "sha512-bk/FJ09fLf+NLODMAFll6CfYrHPBioTedhW6lxDBuuWucJEqFUd4l/D/5JgIi3dina6sYahB8iuPAZTNz2pMxw==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.18.0"
+      },
+      "engines": {
+        "node": ">=8.x"
+      }
+    },
+    "node_modules/@rc-component/motion": {
+      "version": "1.3.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/motion/-/motion-1.3.2.tgz",
+      "integrity": "sha512-itfd+GztzJYAb04Z4RkEub1TbJAfZc2Iuy8p44U44xD1F5+fNYFKI3897ijlbIyfvXkTmMm+KGcjkQQGMHywEQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.2.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/mutate-observer": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/mutate-observer/-/mutate-observer-2.0.1.tgz",
+      "integrity": "sha512-AyarjoLU5YlxuValRi+w8JRH2Z84TBbFO2RoGWz9d8bSu0FqT8DtugH3xC3BV7mUwlmROFauyWuXFuq4IFbH+w==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.2.0"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/notification": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/notification/-/notification-1.2.0.tgz",
+      "integrity": "sha512-OX3J+zVU7rvoJCikjrfW7qOUp7zlDeFBK2eA3SFbGSkDqo63Sl4Ss8A04kFP+fxHSxMDIS9jYVEZtU1FNCFuBA==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.1.4",
+        "@rc-component/util": "^1.2.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/overflow": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/overflow/-/overflow-1.0.0.tgz",
+      "integrity": "sha512-GSlBeoE0XTBi5cf3zl8Qh7Uqhn7v8RrlJ8ajeVpEkNe94HWy5l5BQ0Mwn2TVUq9gdgbfEMUmTX7tJFAg7mz0Rw==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.11.1",
+        "@rc-component/resize-observer": "^1.0.1",
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/pagination": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/pagination/-/pagination-1.2.0.tgz",
+      "integrity": "sha512-YcpUFE8dMLfSo6OARJlK6DbHHvrxz7pMGPGmC/caZSJJz6HRKHC1RPP001PRHCvG9Z/veD039uOQmazVuLJzlw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/picker": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/picker/-/picker-1.9.1.tgz",
+      "integrity": "sha512-9FBYYsvH3HMLICaPDA/1Th5FLaDkFa7qAtangIdlhKb3ZALaR745e9PsOhheJb6asS4QXc12ffiAcjdkZ4C5/g==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/overflow": "^1.0.0",
+        "@rc-component/resize-observer": "^1.0.0",
+        "@rc-component/trigger": "^3.6.15",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=12.x"
+      },
+      "peerDependencies": {
+        "date-fns": ">= 2.x",
+        "dayjs": ">= 1.x",
+        "luxon": ">= 3.x",
+        "moment": ">= 2.x",
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      },
+      "peerDependenciesMeta": {
+        "date-fns": {
+          "optional": true
+        },
+        "dayjs": {
+          "optional": true
+        },
+        "luxon": {
+          "optional": true
+        },
+        "moment": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@rc-component/portal": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/portal/-/portal-2.2.0.tgz",
+      "integrity": "sha512-oc6FlA+uXCMiwArHsJyHcIkX4q6uKyndrPol2eWX8YPkAnztHOPsFIRtmWG4BMlGE5h7YIRE3NiaJ5VS8Lb1QQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.2.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=12.x"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/progress": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/progress/-/progress-1.0.2.tgz",
+      "integrity": "sha512-WZUnH9eGxH1+xodZKqdrHke59uyGZSWgj5HBM5Kwk5BrTMuAORO7VJ2IP5Qbm9aH3n9x3IcesqHHR0NWPBC7fQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.2.1",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/qrcode": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/qrcode/-/qrcode-1.1.1.tgz",
+      "integrity": "sha512-LfLGNymzKdUPjXUbRP+xOhIWY4jQ+YMj5MmWAcgcAq1Ij8XP7tRmAXqyuv96XvLUBE/5cA8hLFl9eO1JQMujrA==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.24.7"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/rate": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/rate/-/rate-1.0.1.tgz",
+      "integrity": "sha512-bkXxeBqDpl5IOC7yL7GcSYjQx9G8H+6kLYQnNZWeBYq2OYIv1MONd6mqKTjnnJYpV0cQIU2z3atdW0j1kttpTw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/resize-observer": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/resize-observer/-/resize-observer-1.1.2.tgz",
+      "integrity": "sha512-t/Bb0W8uvL4PYKAB3YcChC+DlHh0Wt5kM7q/J+0qpVEUMLe7Hk5zuvc9km0hMnTFPSx5Z7Wu/fzCLN6erVLE8Q==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.2.0"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/segmented": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/segmented/-/segmented-1.3.0.tgz",
+      "integrity": "sha512-5J/bJ01mbDnoA6P/FW8SxUvKn+OgUSTZJPzCNnTBntG50tzoP7DydGhqxp7ggZXZls7me3mc2EQDXakU3iTVFg==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.11.1",
+        "@rc-component/motion": "^1.1.4",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.0.0",
+        "react-dom": ">=16.0.0"
+      }
+    },
+    "node_modules/@rc-component/select": {
+      "version": "1.6.15",
+      "resolved": "https://registry.npmjs.org/@rc-component/select/-/select-1.6.15.tgz",
+      "integrity": "sha512-SyVCWnqxCQZZcQvQJ/CxSjx2bGma6ds/HtnpkIfZVnt6RoEgbqUmHgD6vrzNarNXwbLXerwVzWwq8F3d1sst7g==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/overflow": "^1.0.0",
+        "@rc-component/trigger": "^3.0.0",
+        "@rc-component/util": "^1.3.0",
+        "@rc-component/virtual-list": "^1.0.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": "*",
+        "react-dom": "*"
+      }
+    },
+    "node_modules/@rc-component/slider": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/slider/-/slider-1.0.1.tgz",
+      "integrity": "sha512-uDhEPU1z3WDfCJhaL9jfd2ha/Eqpdfxsn0Zb0Xcq1NGQAman0TWaR37OWp2vVXEOdV2y0njSILTMpTfPV1454g==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/steps": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/steps/-/steps-1.2.2.tgz",
+      "integrity": "sha512-/yVIZ00gDYYPHSY0JP+M+s3ZvuXLu2f9rEjQqiUDs7EcYsUYrpJ/1bLj9aI9R7MBR3fu/NGh6RM9u2qGfqp+Nw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.2.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/switch": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/@rc-component/switch/-/switch-1.0.3.tgz",
+      "integrity": "sha512-Jgi+EbOBquje/XNdofr7xbJQZPYJP+BlPfR0h+WN4zFkdtB2EWqEfvkXJWeipflwjWip0/17rNbxEAqs8hVHfw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/table": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/@rc-component/table/-/table-1.9.1.tgz",
+      "integrity": "sha512-FVI5ZS/GdB3BcgexfCYKi3iHhZS3Fr59EtsxORszYGrfpH1eWr33eDNSYkVfLI6tfJ7vftJDd9D5apfFWqkdJg==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/context": "^2.0.1",
+        "@rc-component/resize-observer": "^1.0.0",
+        "@rc-component/util": "^1.1.0",
+        "@rc-component/virtual-list": "^1.0.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/tabs": {
+      "version": "1.7.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/tabs/-/tabs-1.7.0.tgz",
+      "integrity": "sha512-J48cs2iBi7Ho3nptBxxIqizEliUC+ExE23faspUQKGQ550vaBlv3aGF8Epv/UB1vFWeoJDTW/dNzgIU0Qj5i/w==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/dropdown": "~1.0.0",
+        "@rc-component/menu": "~1.2.0",
+        "@rc-component/motion": "^1.1.3",
+        "@rc-component/resize-observer": "^1.0.0",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/textarea": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/textarea/-/textarea-1.1.2.tgz",
+      "integrity": "sha512-9rMUEODWZDMovfScIEHXWlVZuPljZ2pd1LKNjslJVitn4SldEzq5vO1CL3yy3Dnib6zZal2r2DPtjy84VVpF6A==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/input": "~1.1.0",
+        "@rc-component/resize-observer": "^1.0.0",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/tooltip": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/tooltip/-/tooltip-1.4.0.tgz",
+      "integrity": "sha512-8Rx5DCctIlLI4raR0I0xHjVTf1aF48+gKCNeAAo5bmF5VoR5YED+A/XEqzXv9KKqrJDRcd3Wndpxh2hyzrTtSg==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/trigger": "^3.7.1",
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/tour": {
+      "version": "2.3.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/tour/-/tour-2.3.0.tgz",
+      "integrity": "sha512-K04K9r32kUC+auBSQfr+Fss4SpSIS9JGe56oq/ALAX0p+i2ylYOI1MgR83yBY7v96eO6ZFXcM/igCQmubps0Ow==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/portal": "^2.2.0",
+        "@rc-component/trigger": "^3.0.0",
+        "@rc-component/util": "^1.7.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/tree": {
+      "version": "1.2.4",
+      "resolved": "https://registry.npmjs.org/@rc-component/tree/-/tree-1.2.4.tgz",
+      "integrity": "sha512-5Gli43+m4R7NhpYYz3Z61I6LOw9yI6CNChxgVtvrO6xB1qML7iE6QMLVMB3+FTjo2yF6uFdAHtqWPECz/zbX5w==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.0.0",
+        "@rc-component/util": "^1.8.1",
+        "@rc-component/virtual-list": "^1.0.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=10.x"
+      },
+      "peerDependencies": {
+        "react": "*",
+        "react-dom": "*"
+      }
+    },
+    "node_modules/@rc-component/tree-select": {
+      "version": "1.8.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/tree-select/-/tree-select-1.8.0.tgz",
+      "integrity": "sha512-iYsPq3nuLYvGqdvFAW+l+I9ASRIOVbMXyA8FGZg2lGym/GwkaWeJGzI4eJ7c9IOEhRj0oyfIN4S92Fl3J05mjQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/select": "~1.6.0",
+        "@rc-component/tree": "~1.2.0",
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": "*",
+        "react-dom": "*"
+      }
+    },
+    "node_modules/@rc-component/trigger": {
+      "version": "3.9.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/trigger/-/trigger-3.9.0.tgz",
+      "integrity": "sha512-X8btpwfrT27AgrZVOz4swclhEHTZcqaHeQMXXBgveagOiakTa36uObXbdwerXffgV8G9dH1fAAE0DHtVQs8EHg==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/motion": "^1.1.4",
+        "@rc-component/portal": "^2.2.0",
+        "@rc-component/resize-observer": "^1.1.1",
+        "@rc-component/util": "^1.2.1",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/upload": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/upload/-/upload-1.1.0.tgz",
+      "integrity": "sha512-LIBV90mAnUE6VK5N4QvForoxZc4XqEYZimcp7fk+lkE4XwHHyJWxpIXQQwMU8hJM+YwBbsoZkGksL1sISWHQxw==",
+      "license": "MIT",
+      "dependencies": {
+        "@rc-component/util": "^1.3.0",
+        "clsx": "^2.1.1"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rc-component/util": {
+      "version": "1.10.0",
+      "resolved": "https://registry.npmjs.org/@rc-component/util/-/util-1.10.0.tgz",
+      "integrity": "sha512-aY9GLBuiUdpyfIUpAWSYer4Tu3mVaZCo5A0q9NtXcazT3MRiI3/WNHCR+DUn5VAtR6iRRf0ynCqQUcHli5UdYw==",
+      "license": "MIT",
+      "dependencies": {
+        "is-mobile": "^5.0.0",
+        "react-is": "^18.2.0"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "react-dom": ">=18.0.0"
+      }
+    },
+    "node_modules/@rc-component/virtual-list": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/@rc-component/virtual-list/-/virtual-list-1.0.2.tgz",
+      "integrity": "sha512-uvTol/mH74FYsn5loDGJxo+7kjkO4i+y4j87Re1pxJBs0FaeuMuLRzQRGaXwnMcV1CxpZLi2Z56Rerj2M00fjQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@babel/runtime": "^7.20.0",
+        "@rc-component/resize-observer": "^1.0.1",
+        "@rc-component/util": "^1.4.0",
+        "clsx": "^2.1.1"
+      },
+      "engines": {
+        "node": ">=8.x"
+      },
+      "peerDependencies": {
+        "react": ">=16.9.0",
+        "react-dom": ">=16.9.0"
+      }
+    },
+    "node_modules/@rolldown/binding-android-arm64": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.12.tgz",
+      "integrity": "sha512-pv1y2Fv0JybcykuiiD3qBOBdz6RteYojRFY1d+b95WVuzx211CRh+ytI/+9iVyWQ6koTh5dawe4S/yRfOFjgaA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-darwin-arm64": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.12.tgz",
+      "integrity": "sha512-cFYr6zTG/3PXXF3pUO+umXxt1wkRK/0AYT8lDwuqvRC+LuKYWSAQAQZjCWDQpAH172ZV6ieYrNnFzVVcnSflAg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-darwin-x64": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.12.tgz",
+      "integrity": "sha512-ZCsYknnHzeXYps0lGBz8JrF37GpE9bFVefrlmDrAQhOEi4IOIlcoU1+FwHEtyXGx2VkYAvhu7dyBf75EJQffBw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-freebsd-x64": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.12.tgz",
+      "integrity": "sha512-dMLeprcVsyJsKolRXyoTH3NL6qtsT0Y2xeuEA8WQJquWFXkEC4bcu1rLZZSnZRMtAqwtrF/Ib9Ddtpa/Gkge9Q==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.12.tgz",
+      "integrity": "sha512-YqWjAgGC/9M1lz3GR1r1rP79nMgo3mQiiA+Hfo+pvKFK1fAJ1bCi0ZQVh8noOqNacuY1qIcfyVfP6HoyBRZ85Q==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-arm64-gnu": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.12.tgz",
+      "integrity": "sha512-/I5AS4cIroLpslsmzXfwbe5OmWvSsrFuEw3mwvbQ1kDxJ822hFHIx+vsN/TAzNVyepI/j/GSzrtCIwQPeKCLIg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-arm64-musl": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.12.tgz",
+      "integrity": "sha512-V6/wZztnBqlx5hJQqNWwFdxIKN0m38p8Jas+VoSfgH54HSj9tKTt1dZvG6JRHcjh6D7TvrJPWFGaY9UBVOaWPw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.12.tgz",
+      "integrity": "sha512-AP3E9BpcUYliZCxa3w5Kwj9OtEVDYK6sVoUzy4vTOJsjPOgdaJZKFmN4oOlX0Wp0RPV2ETfmIra9x1xuayFB7g==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-s390x-gnu": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.12.tgz",
+      "integrity": "sha512-nWwpvUSPkoFmZo0kQazZYOrT7J5DGOJ/+QHHzjvNlooDZED8oH82Yg67HvehPPLAg5fUff7TfWFHQS8IV1n3og==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-x64-gnu": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.12.tgz",
+      "integrity": "sha512-RNrafz5bcwRy+O9e6P8Z/OCAJW/A+qtBczIqVYwTs14pf4iV1/+eKEjdOUta93q2TsT/FI0XYDP3TCky38LMAg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-linux-x64-musl": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.12.tgz",
+      "integrity": "sha512-Jpw/0iwoKWx3LJ2rc1yjFrj+T7iHZn2JDg1Yny1ma0luviFS4mhAIcd1LFNxK3EYu3DHWCps0ydXQ5i/rrJ2ig==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-openharmony-arm64": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.12.tgz",
+      "integrity": "sha512-vRugONE4yMfVn0+7lUKdKvN4D5YusEiPilaoO2sgUWpCvrncvWgPMzK00ZFFJuiPgLwgFNP5eSiUlv2tfc+lpA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-wasm32-wasi": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.12.tgz",
+      "integrity": "sha512-ykGiLr/6kkiHc0XnBfmFJuCjr5ZYKKofkx+chJWDjitX+KsJuAmrzWhwyOMSHzPhzOHOy7u9HlFoa5MoAOJ/Zg==",
+      "cpu": [
+        "wasm32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "@napi-rs/wasm-runtime": "^1.1.1"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@rolldown/binding-win32-arm64-msvc": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.12.tgz",
+      "integrity": "sha512-5eOND4duWkwx1AzCxadcOrNeighiLwMInEADT0YM7xeEOOFcovWZCq8dadXgcRHSf3Ulh1kFo/qvzoFiCLOL1Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/binding-win32-x64-msvc": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.12.tgz",
+      "integrity": "sha512-PyqoipaswDLAZtot351MLhrlrh6lcZPo2LSYE+VDxbVk24LVKAGOuE4hb8xZQmrPAuEtTZW8E6D2zc5EUZX4Lw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      }
+    },
+    "node_modules/@rolldown/pluginutils": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.12.tgz",
+      "integrity": "sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw==",
+      "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==",
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "dependencies": {
+        "tslib": "^2.4.0"
+      }
+    },
+    "node_modules/@types/react": {
+      "version": "19.2.14",
+      "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
+      "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "csstype": "^3.2.2"
+      }
+    },
+    "node_modules/@types/react-dom": {
+      "version": "19.2.3",
+      "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
+      "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
+      "dev": true,
+      "license": "MIT",
+      "peerDependencies": {
+        "@types/react": "^19.2.0"
+      }
+    },
+    "node_modules/@vitejs/plugin-react": {
+      "version": "6.0.1",
+      "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.1.tgz",
+      "integrity": "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@rolldown/pluginutils": "1.0.0-rc.7"
+      },
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      },
+      "peerDependencies": {
+        "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
+        "babel-plugin-react-compiler": "^1.0.0",
+        "vite": "^8.0.0"
+      },
+      "peerDependenciesMeta": {
+        "@rolldown/plugin-babel": {
+          "optional": true
+        },
+        "babel-plugin-react-compiler": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@vitejs/plugin-react/node_modules/@rolldown/pluginutils": {
+      "version": "1.0.0-rc.7",
+      "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.7.tgz",
+      "integrity": "sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/antd": {
+      "version": "6.3.5",
+      "resolved": "https://registry.npmjs.org/antd/-/antd-6.3.5.tgz",
+      "integrity": "sha512-8BPz9lpZWQm42PTx7yL4KxWAotVuqINiKcoYRcLtdd5BFmAcAZicVyFTnBJyRDlzGZFZeRW3foGu6jXYFnej6Q==",
+      "license": "MIT",
+      "dependencies": {
+        "@ant-design/colors": "^8.0.1",
+        "@ant-design/cssinjs": "^2.1.2",
+        "@ant-design/cssinjs-utils": "^2.1.2",
+        "@ant-design/fast-color": "^3.0.1",
+        "@ant-design/icons": "^6.1.1",
+        "@ant-design/react-slick": "~2.0.0",
+        "@babel/runtime": "^7.28.4",
+        "@rc-component/cascader": "~1.14.0",
+        "@rc-component/checkbox": "~2.0.0",
+        "@rc-component/collapse": "~1.2.0",
+        "@rc-component/color-picker": "~3.1.1",
+        "@rc-component/dialog": "~1.8.4",
+        "@rc-component/drawer": "~1.4.2",
+        "@rc-component/dropdown": "~1.0.2",
+        "@rc-component/form": "~1.8.0",
+        "@rc-component/image": "~1.8.0",
+        "@rc-component/input": "~1.1.2",
+        "@rc-component/input-number": "~1.6.2",
+        "@rc-component/mentions": "~1.6.0",
+        "@rc-component/menu": "~1.2.0",
+        "@rc-component/motion": "^1.3.2",
+        "@rc-component/mutate-observer": "^2.0.1",
+        "@rc-component/notification": "~1.2.0",
+        "@rc-component/pagination": "~1.2.0",
+        "@rc-component/picker": "~1.9.1",
+        "@rc-component/progress": "~1.0.2",
+        "@rc-component/qrcode": "~1.1.1",
+        "@rc-component/rate": "~1.0.1",
+        "@rc-component/resize-observer": "^1.1.2",
+        "@rc-component/segmented": "~1.3.0",
+        "@rc-component/select": "~1.6.15",
+        "@rc-component/slider": "~1.0.1",
+        "@rc-component/steps": "~1.2.2",
+        "@rc-component/switch": "~1.0.3",
+        "@rc-component/table": "~1.9.1",
+        "@rc-component/tabs": "~1.7.0",
+        "@rc-component/textarea": "~1.1.2",
+        "@rc-component/tooltip": "~1.4.0",
+        "@rc-component/tour": "~2.3.0",
+        "@rc-component/tree": "~1.2.4",
+        "@rc-component/tree-select": "~1.8.0",
+        "@rc-component/trigger": "^3.9.0",
+        "@rc-component/upload": "~1.1.0",
+        "@rc-component/util": "^1.10.0",
+        "clsx": "^2.1.1",
+        "dayjs": "^1.11.11",
+        "scroll-into-view-if-needed": "^3.1.0",
+        "throttle-debounce": "^5.0.2"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/ant-design"
+      },
+      "peerDependencies": {
+        "react": ">=18.0.0",
+        "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==",
+      "license": "MIT"
+    },
+    "node_modules/axios": {
+      "version": "1.14.0",
+      "resolved": "https://registry.npmjs.org/axios/-/axios-1.14.0.tgz",
+      "integrity": "sha512-3Y8yrqLSwjuzpXuZ0oIYZ/XGgLwUIBU3uLvbcpb0pidD9ctpShJd43KSlEEkVQg6DS0G9NKyzOvBfUtDKEyHvQ==",
+      "license": "MIT",
+      "dependencies": {
+        "follow-redirects": "^1.15.11",
+        "form-data": "^4.0.5",
+        "proxy-from-env": "^2.1.0"
+      }
+    },
+    "node_modules/call-bind-apply-helpers": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+      "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/clsx": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
+      "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/combined-stream": {
+      "version": "1.0.8",
+      "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+      "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+      "license": "MIT",
+      "dependencies": {
+        "delayed-stream": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/compute-scroll-into-view": {
+      "version": "3.1.1",
+      "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.1.tgz",
+      "integrity": "sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==",
+      "license": "MIT"
+    },
+    "node_modules/cookie": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
+      "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "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/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/delayed-stream": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+      "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
+    "node_modules/detect-libc": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+      "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/dunder-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+      "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "gopd": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-define-property": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+      "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-errors": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+      "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "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==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-set-tostringtag": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+      "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.6",
+        "has-tostringtag": "^1.0.2",
+        "hasown": "^2.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/fdir": {
+      "version": "6.5.0",
+      "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+      "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12.0.0"
+      },
+      "peerDependencies": {
+        "picomatch": "^3 || ^4"
+      },
+      "peerDependenciesMeta": {
+        "picomatch": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/follow-redirects": {
+      "version": "1.15.11",
+      "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
+      "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
+      "funding": [
+        {
+          "type": "individual",
+          "url": "https://github.com/sponsors/RubenVerborgh"
+        }
+      ],
+      "license": "MIT",
+      "engines": {
+        "node": ">=4.0"
+      },
+      "peerDependenciesMeta": {
+        "debug": {
+          "optional": true
+        }
+      }
+    },
+    "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==",
+      "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"
+      },
+      "engines": {
+        "node": ">= 6"
+      }
+    },
+    "node_modules/fsevents": {
+      "version": "2.3.3",
+      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+      "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+      }
+    },
+    "node_modules/function-bind": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+      "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-intrinsic": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+      "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "es-define-property": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "es-object-atoms": "^1.1.1",
+        "function-bind": "^1.1.2",
+        "get-proto": "^1.0.1",
+        "gopd": "^1.2.0",
+        "has-symbols": "^1.1.0",
+        "hasown": "^2.0.2",
+        "math-intrinsics": "^1.1.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+      "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+      "license": "MIT",
+      "dependencies": {
+        "dunder-proto": "^1.0.1",
+        "es-object-atoms": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/gopd": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+      "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/guacamole-common-js": {
+      "version": "1.5.0",
+      "resolved": "https://registry.npmjs.org/guacamole-common-js/-/guacamole-common-js-1.5.0.tgz",
+      "integrity": "sha512-zxztif3GGhKbg1RgOqwmqot8kXgv2HmHFg1EvWwd4q7UfEKvBcYZ0f+7G8HzvU+FUxF0Psqm9Kl5vCbgfrRgJg==",
+      "license": "Apache 2.0"
+    },
+    "node_modules/has-symbols": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+      "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/has-tostringtag": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+      "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+      "license": "MIT",
+      "dependencies": {
+        "has-symbols": "^1.0.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/hasown": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+      "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "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/json2mq": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/json2mq/-/json2mq-0.2.0.tgz",
+      "integrity": "sha512-SzoRg7ux5DWTII9J2qkrZrqV1gt+rTaoufMxEzXbS26Uid0NwaJd123HcoB80TgubEppxxIGdNxCx50fEoEWQA==",
+      "license": "MIT",
+      "dependencies": {
+        "string-convert": "^0.2.0"
+      }
+    },
+    "node_modules/lightningcss": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
+      "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
+      "dev": true,
+      "license": "MPL-2.0",
+      "dependencies": {
+        "detect-libc": "^2.0.3"
+      },
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      },
+      "optionalDependencies": {
+        "lightningcss-android-arm64": "1.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"
+      }
+    },
+    "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==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-darwin-arm64": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
+      "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-darwin-x64": {
+      "version": "1.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==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-freebsd-x64": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
+      "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-arm-gnueabihf": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
+      "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-arm64-gnu": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
+      "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-arm64-musl": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
+      "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-x64-gnu": {
+      "version": "1.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==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-linux-x64-musl": {
+      "version": "1.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==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-win32-arm64-msvc": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
+      "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/lightningcss-win32-x64-msvc": {
+      "version": "1.32.0",
+      "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
+      "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MPL-2.0",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">= 12.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/parcel"
+      }
+    },
+    "node_modules/math-intrinsics": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+      "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/mime-db": {
+      "version": "1.52.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+      "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mime-types": {
+      "version": "2.1.35",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+      "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "1.52.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/nanoid": {
+      "version": "3.3.11",
+      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+      "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "bin": {
+        "nanoid": "bin/nanoid.cjs"
+      },
+      "engines": {
+        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+      }
+    },
+    "node_modules/picocolors": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+      "dev": true,
+      "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==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/jonschlinkert"
+      }
+    },
+    "node_modules/postcss": {
+      "version": "8.5.8",
+      "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
+      "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/postcss/"
+        },
+        {
+          "type": "tidelift",
+          "url": "https://tidelift.com/funding/github/npm/postcss"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "nanoid": "^3.3.11",
+        "picocolors": "^1.1.1",
+        "source-map-js": "^1.2.1"
+      },
+      "engines": {
+        "node": "^10 || ^12 || >=14"
+      }
+    },
+    "node_modules/proxy-from-env": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
+      "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/react": {
+      "version": "19.2.4",
+      "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
+      "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/react-dom": {
+      "version": "19.2.4",
+      "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",
+      "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",
+      "license": "MIT",
+      "dependencies": {
+        "scheduler": "^0.27.0"
+      },
+      "peerDependencies": {
+        "react": "^19.2.4"
+      }
+    },
+    "node_modules/react-is": {
+      "version": "18.3.1",
+      "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
+      "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
+      "license": "MIT"
+    },
+    "node_modules/react-router": {
+      "version": "7.13.2",
+      "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.13.2.tgz",
+      "integrity": "sha512-tX1Aee+ArlKQP+NIUd7SE6Li+CiGKwQtbS+FfRxPX6Pe4vHOo6nr9d++u5cwg+Z8K/x8tP+7qLmujDtfrAoUJA==",
+      "license": "MIT",
+      "dependencies": {
+        "cookie": "^1.0.1",
+        "set-cookie-parser": "^2.6.0"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      },
+      "peerDependencies": {
+        "react": ">=18",
+        "react-dom": ">=18"
+      },
+      "peerDependenciesMeta": {
+        "react-dom": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/react-router-dom": {
+      "version": "7.13.2",
+      "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.13.2.tgz",
+      "integrity": "sha512-aR7SUORwTqAW0JDeiWF07e9SBE9qGpByR9I8kJT5h/FrBKxPMS6TiC7rmVO+gC0q52Bx7JnjWe8Z1sR9faN4YA==",
+      "license": "MIT",
+      "dependencies": {
+        "react-router": "7.13.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      },
+      "peerDependencies": {
+        "react": ">=18",
+        "react-dom": ">=18"
+      }
+    },
+    "node_modules/rolldown": {
+      "version": "1.0.0-rc.12",
+      "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.12.tgz",
+      "integrity": "sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@oxc-project/types": "=0.122.0",
+        "@rolldown/pluginutils": "1.0.0-rc.12"
+      },
+      "bin": {
+        "rolldown": "bin/cli.mjs"
+      },
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      },
+      "optionalDependencies": {
+        "@rolldown/binding-android-arm64": "1.0.0-rc.12",
+        "@rolldown/binding-darwin-arm64": "1.0.0-rc.12",
+        "@rolldown/binding-darwin-x64": "1.0.0-rc.12",
+        "@rolldown/binding-freebsd-x64": "1.0.0-rc.12",
+        "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.12",
+        "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.12",
+        "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.12",
+        "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.12",
+        "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.12",
+        "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.12",
+        "@rolldown/binding-linux-x64-musl": "1.0.0-rc.12",
+        "@rolldown/binding-openharmony-arm64": "1.0.0-rc.12",
+        "@rolldown/binding-wasm32-wasi": "1.0.0-rc.12",
+        "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.12",
+        "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.12"
+      }
+    },
+    "node_modules/scheduler": {
+      "version": "0.27.0",
+      "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
+      "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
+      "license": "MIT"
+    },
+    "node_modules/scroll-into-view-if-needed": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.1.0.tgz",
+      "integrity": "sha512-49oNpRjWRvnU8NyGVmUaYG4jtTkNonFZI86MmGRDqBphEK2EXT9gdEUoQPZhuBM8yWHxCWbobltqYO5M4XrUvQ==",
+      "license": "MIT",
+      "dependencies": {
+        "compute-scroll-into-view": "^3.0.2"
+      }
+    },
+    "node_modules/set-cookie-parser": {
+      "version": "2.7.2",
+      "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
+      "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
+      "license": "MIT"
+    },
+    "node_modules/source-map-js": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+      "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "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/stylis": {
+      "version": "4.3.6",
+      "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz",
+      "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==",
+      "license": "MIT"
+    },
+    "node_modules/throttle-debounce": {
+      "version": "5.0.2",
+      "resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-5.0.2.tgz",
+      "integrity": "sha512-B71/4oyj61iNH0KeCamLuE2rmKuTO5byTOSVwECM5FA7TiAiAW+UqTKZ9ERueC4qvgSttUhdmq1mXC3kJqGX7A==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=12.22"
+      }
+    },
+    "node_modules/tinyglobby": {
+      "version": "0.2.15",
+      "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
+      "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "fdir": "^6.5.0",
+        "picomatch": "^4.0.3"
+      },
+      "engines": {
+        "node": ">=12.0.0"
+      },
+      "funding": {
+        "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==",
+      "dev": true,
+      "license": "0BSD",
+      "optional": true
+    },
+    "node_modules/typescript": {
+      "version": "5.9.3",
+      "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "tsc": "bin/tsc",
+        "tsserver": "bin/tsserver"
+      },
+      "engines": {
+        "node": ">=14.17"
+      }
+    },
+    "node_modules/vite": {
+      "version": "8.0.3",
+      "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.3.tgz",
+      "integrity": "sha512-B9ifbFudT1TFhfltfaIPgjo9Z3mDynBTJSUYxTjOQruf/zHH+ezCQKcoqO+h7a9Pw9Nm/OtlXAiGT1axBgwqrQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "lightningcss": "^1.32.0",
+        "picomatch": "^4.0.4",
+        "postcss": "^8.5.8",
+        "rolldown": "1.0.0-rc.12",
+        "tinyglobby": "^0.2.15"
+      },
+      "bin": {
+        "vite": "bin/vite.js"
+      },
+      "engines": {
+        "node": "^20.19.0 || >=22.12.0"
+      },
+      "funding": {
+        "url": "https://github.com/vitejs/vite?sponsor=1"
+      },
+      "optionalDependencies": {
+        "fsevents": "~2.3.3"
+      },
+      "peerDependencies": {
+        "@types/node": "^20.19.0 || >=22.12.0",
+        "@vitejs/devtools": "^0.1.0",
+        "esbuild": "^0.27.0",
+        "jiti": ">=1.21.0",
+        "less": "^4.0.0",
+        "sass": "^1.70.0",
+        "sass-embedded": "^1.70.0",
+        "stylus": ">=0.54.8",
+        "sugarss": "^5.0.0",
+        "terser": "^5.16.0",
+        "tsx": "^4.8.1",
+        "yaml": "^2.4.2"
+      },
+      "peerDependenciesMeta": {
+        "@types/node": {
+          "optional": true
+        },
+        "@vitejs/devtools": {
+          "optional": true
+        },
+        "esbuild": {
+          "optional": true
+        },
+        "jiti": {
+          "optional": true
+        },
+        "less": {
+          "optional": true
+        },
+        "sass": {
+          "optional": true
+        },
+        "sass-embedded": {
+          "optional": true
+        },
+        "stylus": {
+          "optional": true
+        },
+        "sugarss": {
+          "optional": true
+        },
+        "terser": {
+          "optional": true
+        },
+        "tsx": {
+          "optional": true
+        },
+        "yaml": {
+          "optional": true
+        }
+      }
+    }
+  }
+}

+ 26 - 0
client/package.json

@@ -0,0 +1,26 @@
+{
+  "name": "bifrost-anywhere-client",
+  "private": true,
+  "version": "0.0.0",
+  "type": "module",
+  "scripts": {
+    "dev": "vite",
+    "build": "tsc && vite build",
+    "preview": "vite preview"
+  },
+  "devDependencies": {
+    "@types/react": "^19.2.14",
+    "@types/react-dom": "^19.2.3",
+    "@vitejs/plugin-react": "^6.0.1",
+    "typescript": "~5.9.3",
+    "vite": "^8.0.1"
+  },
+  "dependencies": {
+    "antd": "^6.3.5",
+    "axios": "^1.14.0",
+    "guacamole-common-js": "^1.5.0",
+    "react": "^19.2.4",
+    "react-dom": "^19.2.4",
+    "react-router-dom": "^7.13.2"
+  }
+}

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
client/public/favicon.svg


+ 24 - 0
client/public/icons.svg

@@ -0,0 +1,24 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+  <symbol id="bluesky-icon" viewBox="0 0 16 17">
+    <g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
+    <defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
+  </symbol>
+  <symbol id="discord-icon" viewBox="0 0 20 19">
+    <path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
+  </symbol>
+  <symbol id="documentation-icon" viewBox="0 0 21 20">
+    <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
+    <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
+    <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
+  </symbol>
+  <symbol id="github-icon" viewBox="0 0 19 19">
+    <path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
+  </symbol>
+  <symbol id="social-icon" viewBox="0 0 20 20">
+    <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
+    <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
+  </symbol>
+  <symbol id="x-icon" viewBox="0 0 19 19">
+    <path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
+  </symbol>
+</svg>

+ 20 - 0
client/src/App.tsx

@@ -0,0 +1,20 @@
+import React from 'react';
+import { ConfigProvider } from 'antd';
+import AppRouter from './router';
+
+const App: React.FC = () => {
+  return (
+    <ConfigProvider
+      theme={{
+        token: {
+          fontFamily:
+            '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif',
+        },
+      }}
+    >
+      <AppRouter />
+    </ConfigProvider>
+  );
+};
+
+export default App;

+ 32 - 0
client/src/api/axios.ts

@@ -0,0 +1,32 @@
+import axios from 'axios';
+
+const api = axios.create({
+  baseURL: '/api',
+  timeout: 30000,
+});
+
+// Request interceptor: attach JWT token
+api.interceptors.request.use((config) => {
+  const token = localStorage.getItem('token');
+  if (token) {
+    config.headers.Authorization = `Bearer ${token}`;
+  }
+  return config;
+});
+
+// Response interceptor: 401 → redirect to login
+api.interceptors.response.use(
+  (response) => response,
+  (error) => {
+    if (error.response?.status === 401) {
+      localStorage.removeItem('token');
+      // Avoid redirect loop if already on login page
+      if (window.location.pathname !== '/login') {
+        window.location.href = '/login';
+      }
+    }
+    return Promise.reject(error);
+  },
+);
+
+export default api;

BIN
client/src/assets/hero.png


+ 1 - 0
client/src/assets/typescript.svg

@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="32" height="32" viewBox="0 0 256 256"><path fill="#007ACC" d="M0 128v128h256V0H0z"/><path fill="#FFF" d="m56.612 128.85l-.081 10.483h33.32v94.68h23.568v-94.68h33.321v-10.28c0-5.69-.122-10.444-.284-10.566c-.122-.162-20.4-.244-44.983-.203l-44.74.122l-.121 10.443Zm149.955-10.742c6.501 1.625 11.459 4.51 16.01 9.224c2.357 2.52 5.851 7.111 6.136 8.208c.08.325-11.053 7.802-17.798 11.988c-.244.162-1.22-.894-2.317-2.52c-3.291-4.795-6.745-6.867-12.028-7.233c-7.76-.528-12.759 3.535-12.718 10.321c0 1.992.284 3.17 1.097 4.795c1.707 3.536 4.876 5.649 14.832 9.956c18.326 7.883 26.168 13.084 31.045 20.48c5.445 8.249 6.664 21.415 2.966 31.208c-4.063 10.646-14.14 17.879-28.323 20.276c-4.388.772-14.79.65-19.504-.203c-10.28-1.828-20.033-6.908-26.047-13.572c-2.357-2.6-6.949-9.387-6.664-9.874c.122-.163 1.178-.813 2.356-1.504c1.138-.65 5.446-3.129 9.509-5.485l7.355-4.267l1.544 2.276c2.154 3.29 6.867 7.801 9.712 9.305c8.167 4.307 19.383 3.698 24.909-1.26c2.357-2.153 3.332-4.388 3.332-7.68c0-2.966-.366-4.266-1.91-6.501c-1.99-2.845-6.054-5.242-17.595-10.24c-13.206-5.69-18.895-9.224-24.096-14.832c-3.007-3.25-5.852-8.452-7.03-12.8c-.975-3.617-1.22-12.678-.447-16.335c2.723-12.76 12.353-21.659 26.25-24.3c4.51-.853 14.994-.528 19.424.569Z"/></svg>

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
client/src/assets/vite.svg


+ 177 - 0
client/src/components/AwsConfigForm.tsx

@@ -0,0 +1,177 @@
+import React, { useEffect, useState } from 'react';
+import { Form, Input, Select, Button, message, Spin } from 'antd';
+import api from '../api/axios';
+
+const AWS_REGIONS = [
+  'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2',
+  'ap-east-1', 'ap-south-1', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ap-southeast-1', 'ap-southeast-2',
+  'ca-central-1',
+  'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1',
+  'sa-east-1',
+  'me-south-1',
+  'af-south-1',
+];
+
+interface AwsConfig {
+  accessKey: string;
+  secretKey: string;
+  region: string;
+  amiId: string;
+  instanceType: string;
+  keyPairName: string;
+  securityGroupId: string;
+  subnetId: string;
+}
+
+const AwsConfigForm: React.FC = () => {
+  const [form] = Form.useForm();
+  const [loading, setLoading] = useState(false);
+  const [saving, setSaving] = useState(false);
+  const [verifying, setVerifying] = useState(false);
+
+  useEffect(() => {
+    const fetchConfig = async () => {
+      setLoading(true);
+      try {
+        const { data } = await api.get('/admin/aws-config');
+        if (data) {
+          form.setFieldsValue({
+            accessKey: data.accessKey || '',
+            secretKey: '',
+            region: data.region || undefined,
+            amiId: data.amiId || '',
+            instanceType: data.instanceType || '',
+            keyPairName: data.keyPairName || '',
+            securityGroupId: data.securityGroupId || '',
+            subnetId: data.subnetId || '',
+          });
+        }
+      } catch {
+        message.error('获取 AWS 配置失败');
+      } finally {
+        setLoading(false);
+      }
+    };
+    fetchConfig();
+  }, [form]);
+
+  const handleSubmit = async (values: AwsConfig) => {
+    setSaving(true);
+    try {
+      await api.put('/admin/aws-config', {
+        accessKey: values.accessKey,
+        secretKey: values.secretKey || undefined,
+        region: values.region,
+        amiId: values.amiId,
+        instanceType: values.instanceType,
+        keyPairName: values.keyPairName,
+        securityGroupId: values.securityGroupId,
+        subnetId: values.subnetId,
+      });
+      message.success('AWS 配置保存成功');
+      // Clear secret key field after successful save
+      form.setFieldValue('secretKey', '');
+    } catch (err: any) {
+      const errMsg = err?.response?.data?.error?.message;
+      if (errMsg === 'AWS 凭证无效') {
+        message.error('AWS 凭证无效,请检查 Access Key 和 Secret Key');
+      } else {
+        message.error(errMsg || '保存 AWS 配置失败');
+      }
+    } finally {
+      setSaving(false);
+    }
+  };
+
+  const handleVerify = async () => {
+    setVerifying(true);
+    try {
+      const { data } = await api.post('/admin/aws-config/verify');
+      if (data.valid) {
+        message.success(`凭证有效,Account: ${data.account}, ARN: ${data.arn}`);
+      } else {
+        message.error(`凭证无效: ${data.message}`);
+      }
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '验证失败');
+    } finally {
+      setVerifying(false);
+    }
+  };
+
+  return (
+    <Spin spinning={loading}>
+      <Form
+        form={form}
+        layout="vertical"
+        onFinish={handleSubmit}
+        style={{ maxWidth: 600 }}
+      >
+        <Form.Item
+          label="Access Key"
+          name="accessKey"
+          rules={[{ required: true, message: '请输入 Access Key' }]}
+        >
+          <Input placeholder="AKIAIOSFODNN7EXAMPLE" />
+        </Form.Item>
+
+        <Form.Item
+          label="Secret Access Key"
+          name="secretKey"
+          extra="留空则保留原有 Secret Access Key"
+        >
+          <Input.Password placeholder="输入新的 Secret Access Key" />
+        </Form.Item>
+
+        <Form.Item
+          label="Region"
+          name="region"
+          rules={[{ required: true, message: '请选择 Region' }]}
+        >
+          <Select placeholder="选择 AWS 区域">
+            {AWS_REGIONS.map((r) => (
+              <Select.Option key={r} value={r}>{r}</Select.Option>
+            ))}
+          </Select>
+        </Form.Item>
+
+        <Form.Item
+          label="AMI ID"
+          name="amiId"
+          rules={[{ required: true, message: '请输入 AMI ID' }]}
+        >
+          <Input placeholder="ami-0abcdef1234567890" />
+        </Form.Item>
+
+        <Form.Item label="Instance Type" name="instanceType" rules={[{ required: true, message: '请输入 Instance Type' }]}>
+          <Input placeholder="t3.medium" />
+        </Form.Item>
+
+        <Form.Item label="Key Pair Name" name="keyPairName" rules={[{ required: true, message: '请输入 Key Pair Name' }]}>
+          <Input placeholder="my-key-pair" />
+        </Form.Item>
+
+        <Form.Item label="Security Group ID" name="securityGroupId" rules={[{ required: true, message: '请输入 Security Group ID' }]}>
+          <Input placeholder="sg-0123456789abcdef0" />
+        </Form.Item>
+
+        <Form.Item label="Subnet ID" name="subnetId" rules={[{ required: true, message: '请输入 Subnet ID' }]}>
+          <Input placeholder="subnet-0123456789abcdef0" />
+        </Form.Item>
+
+        <Form.Item>
+          <div style={{ display: 'flex', gap: 8 }}>
+            <Button type="primary" htmlType="submit" loading={saving}>
+              保存配置
+            </Button>
+            <Button onClick={handleVerify} loading={verifying}>
+              验证 Access Key
+            </Button>
+          </div>
+        </Form.Item>
+      </Form>
+    </Spin>
+  );
+};
+
+export default AwsConfigForm;

+ 117 - 0
client/src/components/GuacamoleConfig.tsx

@@ -0,0 +1,117 @@
+import React, { useEffect, useState } from 'react';
+import { Form, Input, InputNumber, Button, Space, message, Spin, Alert } from 'antd';
+import api from '../api/axios';
+
+const GuacamoleConfig: React.FC = () => {
+  const [form] = Form.useForm();
+  const [loading, setLoading] = useState(false);
+  const [saving, setSaving] = useState(false);
+  const [testing, setTesting] = useState(false);
+  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
+
+  useEffect(() => {
+    const fetchSettings = async () => {
+      setLoading(true);
+      try {
+        const { data } = await api.get('/admin/settings');
+        form.setFieldsValue({
+          guacamole_host: data.guacamole_host || '',
+          guacamole_port: data.guacamole_port ?? 4822,
+        });
+      } catch {
+        message.error('获取 Guacamole 配置失败');
+      } finally {
+        setLoading(false);
+      }
+    };
+    fetchSettings();
+  }, [form]);
+
+  const handleSubmit = async (values: { guacamole_host: string; guacamole_port: number }) => {
+    setSaving(true);
+    try {
+      await api.put('/admin/settings', {
+        guacamole_host: values.guacamole_host,
+        guacamole_port: values.guacamole_port,
+      });
+      message.success('Guacamole 配置保存成功');
+    } catch (err: any) {
+      const errMsg = err?.response?.data?.error?.message;
+      message.error(errMsg || '保存 Guacamole 配置失败');
+    } finally {
+      setSaving(false);
+    }
+  };
+
+  const handleTest = async () => {
+    const host = form.getFieldValue('guacamole_host');
+    const port = form.getFieldValue('guacamole_port');
+    if (!host) {
+      message.warning('请先填写 Guacamole 服务地址');
+      return;
+    }
+    setTesting(true);
+    setTestResult(null);
+    try {
+      const { data } = await api.post('/admin/guacamole/test', { host, port });
+      setTestResult({ success: data.success, message: data.message || '连接成功' });
+    } catch (err: any) {
+      const errMsg = err?.response?.data?.error?.message || '连通性测试失败';
+      setTestResult({ success: false, message: errMsg });
+    } finally {
+      setTesting(false);
+    }
+  };
+
+  return (
+    <Spin spinning={loading}>
+      <Form
+        form={form}
+        layout="vertical"
+        onFinish={handleSubmit}
+        style={{ maxWidth: 400 }}
+      >
+        <Form.Item
+          label="Guacamole 服务地址"
+          name="guacamole_host"
+          rules={[{ required: true, message: '请输入 Guacamole 服务地址' }]}
+        >
+          <Input placeholder="127.0.0.1" />
+        </Form.Item>
+
+        <Form.Item
+          label="Guacamole 服务端口"
+          name="guacamole_port"
+          rules={[{ required: true, message: '请输入 Guacamole 服务端口' }]}
+        >
+          <InputNumber min={1} max={65535} style={{ width: '100%' }} placeholder="4822" />
+        </Form.Item>
+
+        <Form.Item>
+          <Space>
+            <Button type="primary" htmlType="submit" loading={saving}>
+              保存配置
+            </Button>
+            <Button onClick={handleTest} loading={testing}>
+              测试连通性
+            </Button>
+          </Space>
+        </Form.Item>
+      </Form>
+
+      {testResult && (
+        <Alert
+          type={testResult.success ? 'success' : 'error'}
+          message={testResult.success ? '连接成功' : '连接失败'}
+          description={testResult.message}
+          showIcon
+          closable
+          onClose={() => setTestResult(null)}
+          style={{ marginTop: 16, maxWidth: 400 }}
+        />
+      )}
+    </Spin>
+  );
+};
+
+export default GuacamoleConfig;

+ 97 - 0
client/src/components/InstanceLogs.tsx

@@ -0,0 +1,97 @@
+import React, { useEffect, useState, useCallback } from 'react';
+import { Table, Button, Tag, message } from 'antd';
+import { ReloadOutlined } from '@ant-design/icons';
+import type { ColumnsType } from 'antd/es/table';
+import api from '../api/axios';
+
+interface LogEntry {
+  id: number;
+  user_id: number;
+  username: string;
+  ec2_instance_id: string | null;
+  action: string;
+  duration_seconds: number | null;
+  created_at: number;
+}
+
+const ACTION_LABEL: Record<string, { text: string; color: string }> = {
+  launch: { text: '启动', color: 'green' },
+  stop: { text: '关机', color: 'orange' },
+  start: { text: '开机', color: 'blue' },
+  terminate: { text: '销毁', color: 'red' },
+};
+
+function formatDuration(seconds: number | null): string {
+  if (seconds == null) return '-';
+  const h = Math.floor(seconds / 3600);
+  const m = Math.floor((seconds % 3600) / 60);
+  if (h > 0) return `${h}时${m}分`;
+  return `${m}分`;
+}
+
+const InstanceLogs: React.FC = () => {
+  const [logs, setLogs] = useState<LogEntry[]>([]);
+  const [loading, setLoading] = useState(false);
+
+  const fetchLogs = useCallback(async () => {
+    setLoading(true);
+    try {
+      const { data } = await api.get<LogEntry[]>('/admin/logs?limit=200');
+      setLogs(Array.isArray(data) ? data : []);
+    } catch {
+      message.error('获取日志失败');
+    } finally {
+      setLoading(false);
+    }
+  }, []);
+
+  useEffect(() => { fetchLogs(); }, [fetchLogs]);
+
+  const columns: ColumnsType<LogEntry> = [
+    { title: '用户', dataIndex: 'username', key: 'username', width: 120 },
+    {
+      title: '操作',
+      dataIndex: 'action',
+      key: 'action',
+      width: 100,
+      render: (action: string) => {
+        const info = ACTION_LABEL[action] || { text: action, color: 'default' };
+        return <Tag color={info.color}>{info.text}</Tag>;
+      },
+    },
+    { title: '实例 ID', dataIndex: 'ec2_instance_id', key: 'ec2_instance_id', ellipsis: true, width: 200 },
+    {
+      title: '运行时长',
+      dataIndex: 'duration_seconds',
+      key: 'duration_seconds',
+      width: 120,
+      render: (val: number | null) => formatDuration(val),
+    },
+    {
+      title: '时间',
+      dataIndex: 'created_at',
+      key: 'created_at',
+      width: 180,
+      render: (val: number) => val ? new Date(val * 1000).toLocaleString() : '-',
+    },
+  ];
+
+  return (
+    <div>
+      <div style={{ marginBottom: 16 }}>
+        <Button icon={<ReloadOutlined />} onClick={fetchLogs} loading={loading}>刷新</Button>
+      </div>
+      <Table<LogEntry>
+        columns={columns}
+        dataSource={logs}
+        rowKey="id"
+        loading={loading}
+        pagination={{ pageSize: 15 }}
+        scroll={{ x: 700 }}
+        size="small"
+      />
+    </div>
+  );
+};
+
+export default InstanceLogs;

+ 206 - 0
client/src/components/InstanceMonitor.tsx

@@ -0,0 +1,206 @@
+import React, { useEffect, useState, useCallback } from 'react';
+import {
+  Table,
+  Button,
+  Tag,
+  Popconfirm,
+  Statistic,
+  Card,
+  message,
+  Row,
+  Col,
+} from 'antd';
+import { ReloadOutlined, DeleteOutlined } from '@ant-design/icons';
+import type { ColumnsType } from 'antd/es/table';
+import api from '../api/axios';
+
+interface AdminInstance {
+  id: number;
+  ec2_instance_id: string;
+  machine_guid: string;
+  status: string;
+  public_ip: string | null;
+  started_at: number | null;
+  expires_at: number | null;
+  remaining_time: number;
+  expiring_soon: boolean;
+  username: string;
+  created_at: number;
+}
+
+const STATUS_COLOR: Record<string, string> = {
+  pending: 'orange',
+  running: 'green',
+  stopped: 'red',
+  terminated: 'default',
+};
+
+const STATUS_LABEL: Record<string, string> = {
+  pending: '启动中',
+  running: '运行中',
+  stopped: '已停止',
+  terminated: '已销毁',
+};
+
+function formatRemainingTime(seconds: number): string {
+  if (seconds <= 0) return '已到期';
+  const h = Math.floor(seconds / 3600);
+  const m = Math.floor((seconds % 3600) / 60);
+  if (h > 0) return `${h}时${m}分`;
+  return `${m}分`;
+}
+
+function formatTimestamp(ts: number | null): string {
+  if (!ts) return '-';
+  return new Date(ts * 1000).toLocaleString();
+}
+
+const InstanceMonitor: React.FC = () => {
+  const [instances, setInstances] = useState<AdminInstance[]>([]);
+  const [loading, setLoading] = useState(false);
+  const [runningCount, setRunningCount] = useState(0);
+  const [actionLoading, setActionLoading] = useState<Record<number, boolean>>({});
+
+  const fetchInstances = useCallback(async () => {
+    setLoading(true);
+    try {
+      const [instancesRes, statsRes] = await Promise.all([
+        api.get<AdminInstance[]>('/admin/instances'),
+        api.get<{ running_count: number }>('/admin/instances/stats'),
+      ]);
+      setInstances(Array.isArray(instancesRes.data) ? instancesRes.data : []);
+      setRunningCount(statsRes.data.running_count ?? 0);
+    } catch {
+      message.error('获取实例数据失败');
+    } finally {
+      setLoading(false);
+    }
+  }, []);
+
+  useEffect(() => {
+    fetchInstances();
+  }, [fetchInstances]);
+
+  const handleTerminate = async (id: number) => {
+    setActionLoading((prev) => ({ ...prev, [id]: true }));
+    try {
+      await api.delete(`/admin/instances/${id}`);
+      message.success('实例已销毁');
+      fetchInstances();
+    } catch (err: any) {
+      const errMsg = err?.response?.data?.error?.message || '销毁失败';
+      message.error(errMsg);
+    } finally {
+      setActionLoading((prev) => ({ ...prev, [id]: false }));
+    }
+  };
+
+  const columns: ColumnsType<AdminInstance> = [
+    {
+      title: '用户',
+      dataIndex: 'username',
+      key: 'username',
+      width: 100,
+    },
+    {
+      title: '实例ID',
+      dataIndex: 'ec2_instance_id',
+      key: 'ec2_instance_id',
+      ellipsis: true,
+      width: 180,
+    },
+    {
+      title: '状态',
+      dataIndex: 'status',
+      key: 'status',
+      width: 100,
+      render: (status: string) => (
+        <Tag color={STATUS_COLOR[status] || 'default'}>
+          {STATUS_LABEL[status] || status}
+        </Tag>
+      ),
+    },
+    {
+      title: '公网IP',
+      dataIndex: 'public_ip',
+      key: 'public_ip',
+      width: 140,
+      render: (ip: string | null) => ip || '-',
+    },
+    {
+      title: '启动时间',
+      dataIndex: 'started_at',
+      key: 'started_at',
+      width: 180,
+      render: (ts: number | null) => formatTimestamp(ts),
+    },
+    {
+      title: '剩余时间',
+      dataIndex: 'remaining_time',
+      key: 'remaining_time',
+      width: 120,
+      render: (time: number, record: AdminInstance) => {
+        if (record.status === 'terminated') return '-';
+        return (
+          <span style={record.expiring_soon ? { color: '#ff4d4f', fontWeight: 'bold' } : undefined}>
+            {formatRemainingTime(time)}
+          </span>
+        );
+      },
+    },
+    {
+      title: '操作',
+      key: 'actions',
+      width: 100,
+      render: (_: unknown, record: AdminInstance) => {
+        if (record.status === 'terminated') return null;
+        return (
+          <Popconfirm
+            title="确定销毁此实例?此操作不可恢复。"
+            onConfirm={() => handleTerminate(record.id)}
+            okText="确定"
+            cancelText="取消"
+          >
+            <Button
+              size="small"
+              danger
+              icon={<DeleteOutlined />}
+              loading={actionLoading[record.id] || false}
+            >
+              销毁
+            </Button>
+          </Popconfirm>
+        );
+      },
+    },
+  ];
+
+  return (
+    <div>
+      <Row gutter={16} style={{ marginBottom: 16 }}>
+        <Col>
+          <Card>
+            <Statistic title="运行中实例" value={runningCount} />
+          </Card>
+        </Col>
+      </Row>
+
+      <div style={{ marginBottom: 16 }}>
+        <Button icon={<ReloadOutlined />} onClick={fetchInstances} loading={loading}>
+          刷新
+        </Button>
+      </div>
+
+      <Table<AdminInstance>
+        columns={columns}
+        dataSource={instances}
+        rowKey="id"
+        loading={loading}
+        pagination={{ pageSize: 10 }}
+        scroll={{ x: 900 }}
+      />
+    </div>
+  );
+};
+
+export default InstanceMonitor;

+ 189 - 0
client/src/components/InvitationManager.tsx

@@ -0,0 +1,189 @@
+import React, { useEffect, useState, useCallback } from 'react';
+import { Table, Button, Modal, Input, message, Tag, Popconfirm, Space } from 'antd';
+import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';
+import type { ColumnsType } from 'antd/es/table';
+import api from '../api/axios';
+
+interface Invitation {
+  id: number;
+  code: string;
+  is_active: boolean | number;
+  usage_count: number;
+  created_at: string | number;
+}
+
+const InvitationManager: React.FC = () => {
+  const [invitations, setInvitations] = useState<Invitation[]>([]);
+  const [loading, setLoading] = useState(false);
+  const [modalOpen, setModalOpen] = useState(false);
+  const [newCode, setNewCode] = useState('');
+  const [creating, setCreating] = useState(false);
+
+  const fetchInvitations = useCallback(async () => {
+    setLoading(true);
+    try {
+      const { data } = await api.get<Invitation[]>('/admin/invitations');
+      setInvitations(Array.isArray(data) ? data : []);
+    } catch {
+      message.error('获取邀请码列表失败');
+    } finally {
+      setLoading(false);
+    }
+  }, []);
+
+  useEffect(() => {
+    fetchInvitations();
+  }, [fetchInvitations]);
+
+  const handleCreate = async () => {
+    setCreating(true);
+    try {
+      const body: { code?: string } = {};
+      if (newCode.trim()) {
+        body.code = newCode.trim();
+      }
+      await api.post('/admin/invitations', body);
+      message.success('邀请码创建成功');
+      setModalOpen(false);
+      setNewCode('');
+      fetchInvitations();
+    } catch {
+      message.error('创建邀请码失败');
+    } finally {
+      setCreating(false);
+    }
+  };
+
+  const handleDisable = async (id: number) => {
+    try {
+      await api.patch(`/admin/invitations/${id}/disable`);
+      message.success('邀请码已禁用');
+      fetchInvitations();
+    } catch {
+      message.error('禁用邀请码失败');
+    }
+  };
+
+  const handleEnable = async (id: number) => {
+    try {
+      await api.patch(`/admin/invitations/${id}/enable`);
+      message.success('邀请码已启用');
+      fetchInvitations();
+    } catch {
+      message.error('启用邀请码失败');
+    }
+  };
+
+  const handleDelete = async (id: number) => {
+    try {
+      await api.delete(`/admin/invitations/${id}`);
+      message.success('邀请码已删除');
+      fetchInvitations();
+    } catch {
+      message.error('删除邀请码失败');
+    }
+  };
+
+  const formatTime = (value: string | number) => {
+    if (!value) return '-';
+    const ts = typeof value === 'number' ? value * 1000 : new Date(value).getTime();
+    return new Date(ts).toLocaleString();
+  };
+
+  const columns: ColumnsType<Invitation> = [
+    {
+      title: '邀请码',
+      dataIndex: 'code',
+      key: 'code',
+      ellipsis: true,
+    },
+    {
+      title: '状态',
+      dataIndex: 'is_active',
+      key: 'is_active',
+      width: 100,
+      render: (active: boolean | number) => {
+        const isActive = active === true || active === 1;
+        return isActive ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>;
+      },
+    },
+    {
+      title: '使用次数',
+      dataIndex: 'usage_count',
+      key: 'usage_count',
+      width: 100,
+    },
+    {
+      title: '创建时间',
+      dataIndex: 'created_at',
+      key: 'created_at',
+      width: 200,
+      render: (val: string | number) => formatTime(val),
+    },
+    {
+      title: '操作',
+      key: 'actions',
+      width: 180,
+      render: (_: unknown, record: Invitation) => {
+        const isActive = record.is_active === true || record.is_active === 1;
+        return (
+          <Space>
+            {isActive ? (
+              <Popconfirm title="确定禁用此邀请码?" onConfirm={() => handleDisable(record.id)} okText="确定" cancelText="取消">
+                <Button size="small">禁用</Button>
+              </Popconfirm>
+            ) : (
+              <Popconfirm title="确定启用此邀请码?" onConfirm={() => handleEnable(record.id)} okText="确定" cancelText="取消">
+                <Button size="small" type="primary">启用</Button>
+              </Popconfirm>
+            )}
+            <Popconfirm title="确定删除此邀请码?" onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
+              <Button size="small" danger>删除</Button>
+            </Popconfirm>
+          </Space>
+        );
+      },
+    },
+  ];
+
+  return (
+    <div>
+      <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
+        <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalOpen(true)}>
+          创建邀请码
+        </Button>
+        <Button icon={<ReloadOutlined />} onClick={fetchInvitations} loading={loading}>
+          刷新
+        </Button>
+      </div>
+
+      <Table<Invitation>
+        columns={columns}
+        dataSource={invitations}
+        rowKey="id"
+        loading={loading}
+        pagination={{ pageSize: 10 }}
+        scroll={{ x: 700 }}
+      />
+
+      <Modal
+        title="创建邀请码"
+        open={modalOpen}
+        onOk={handleCreate}
+        onCancel={() => { setModalOpen(false); setNewCode(''); }}
+        confirmLoading={creating}
+        okText="创建"
+        cancelText="取消"
+      >
+        <Input
+          placeholder="输入自定义邀请码(留空则自动生成)"
+          value={newCode}
+          onChange={(e) => setNewCode(e.target.value)}
+          onPressEnter={handleCreate}
+        />
+      </Modal>
+    </div>
+  );
+};
+
+export default InvitationManager;

+ 134 - 0
client/src/components/RdpSessionMonitor.tsx

@@ -0,0 +1,134 @@
+import React, { useEffect, useState, useCallback, useRef } from 'react';
+import { Table, Button, Tag, Space, message, Popconfirm, Typography } from 'antd';
+import type { ColumnsType } from 'antd/es/table';
+import api from '../api/axios';
+
+const { Text } = Typography;
+
+interface RdpSession {
+  id: string;
+  username: string;
+  ec2InstanceId: string;
+  status: 'connecting' | 'connected' | 'disconnected';
+  durationSeconds: number;
+}
+
+function formatDuration(seconds: number): string {
+  const h = Math.floor(seconds / 3600);
+  const m = Math.floor((seconds % 3600) / 60);
+  const s = seconds % 60;
+  if (h > 0) return `${h}时${m}分${s}秒`;
+  if (m > 0) return `${m}分${s}秒`;
+  return `${s}秒`;
+}
+
+const statusColorMap: Record<string, string> = {
+  connecting: 'orange',
+  connected: 'green',
+  disconnected: 'default',
+};
+
+const RdpSessionMonitor: React.FC = () => {
+  const [sessions, setSessions] = useState<RdpSession[]>([]);
+  const [loading, setLoading] = useState(false);
+  const [disconnecting, setDisconnecting] = useState<string | null>(null);
+  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
+
+  const fetchSessions = useCallback(async () => {
+    setLoading(true);
+    try {
+      const { data } = await api.get('/admin/rdp-sessions');
+      setSessions(data.sessions ?? data ?? []);
+    } catch {
+      message.error('获取 RDP 会话列表失败');
+    } finally {
+      setLoading(false);
+    }
+  }, []);
+
+  useEffect(() => {
+    fetchSessions();
+    timerRef.current = setInterval(fetchSessions, 30000);
+    return () => {
+      if (timerRef.current) clearInterval(timerRef.current);
+    };
+  }, [fetchSessions]);
+
+  const handleDisconnect = async (sessionId: string) => {
+    setDisconnecting(sessionId);
+    try {
+      await api.delete(`/admin/rdp-sessions/${sessionId}`);
+      message.success('会话已断开');
+      fetchSessions();
+    } catch (err: any) {
+      const errMsg = err?.response?.data?.error?.message;
+      message.error(errMsg || '断开会话失败');
+    } finally {
+      setDisconnecting(null);
+    }
+  };
+
+  const columns: ColumnsType<RdpSession> = [
+    { title: '用户', dataIndex: 'username', key: 'username' },
+    { title: 'EC2 实例 ID', dataIndex: 'ec2InstanceId', key: 'ec2InstanceId' },
+    {
+      title: '状态',
+      dataIndex: 'status',
+      key: 'status',
+      render: (status: string) => (
+        <Tag color={statusColorMap[status] || 'default'}>{status}</Tag>
+      ),
+    },
+    {
+      title: '连接时长',
+      dataIndex: 'durationSeconds',
+      key: 'durationSeconds',
+      render: (val: number) => formatDuration(val),
+    },
+    {
+      title: '操作',
+      key: 'actions',
+      render: (_, record) => (
+        <Popconfirm
+          title="确定要强制断开此会话吗?"
+          onConfirm={() => handleDisconnect(record.id)}
+          okText="确定"
+          cancelText="取消"
+        >
+          <Button
+            danger
+            size="small"
+            loading={disconnecting === record.id}
+          >
+            强制断开
+          </Button>
+        </Popconfirm>
+      ),
+    },
+  ];
+
+  const activeCount = sessions.filter(
+    (s) => s.status === 'connecting' || s.status === 'connected',
+  ).length;
+
+  return (
+    <div>
+      <Space style={{ marginBottom: 16 }}>
+        <Text strong>当前活跃会话数:{activeCount}</Text>
+        <Button size="small" onClick={fetchSessions} loading={loading}>
+          刷新
+        </Button>
+      </Space>
+      <Table
+        columns={columns}
+        dataSource={sessions}
+        rowKey="id"
+        loading={loading}
+        pagination={false}
+        size="small"
+      />
+    </div>
+  );
+};
+
+export default RdpSessionMonitor;

+ 38 - 0
client/src/components/RdpStatusBar.tsx

@@ -0,0 +1,38 @@
+import type React from 'react';
+import { Tag, Button, Space } from 'antd';
+import { ReloadOutlined } from '@ant-design/icons';
+
+export type RdpConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
+
+interface RdpStatusBarProps {
+  status: RdpConnectionStatus;
+  onReconnect?: () => void;
+}
+
+const STATUS_CONFIG: Record<RdpConnectionStatus, { label: string; color: string }> = {
+  connecting: { label: '连接中', color: 'orange' },
+  connected: { label: '已连接', color: 'green' },
+  disconnected: { label: '已断开', color: 'red' },
+  error: { label: '连接错误', color: 'red' },
+};
+
+const RdpStatusBar: React.FC<RdpStatusBarProps> = ({ status, onReconnect }) => {
+  const config = STATUS_CONFIG[status];
+
+  return (
+    <Space size="small">
+      <Tag color={config.color}>{config.label}</Tag>
+      {(status === 'disconnected' || status === 'error') && onReconnect && (
+        <Button
+          size="small"
+          icon={<ReloadOutlined />}
+          onClick={onReconnect}
+        >
+          重新连接
+        </Button>
+      )}
+    </Space>
+  );
+};
+
+export default RdpStatusBar;

+ 27 - 0
client/src/components/RouteGuards.tsx

@@ -0,0 +1,27 @@
+import React from 'react';
+import { Navigate } from 'react-router-dom';
+import { isLoggedIn, getUserRole } from '../utils/auth';
+
+/**
+ * ProtectedRoute: redirects to /login if user is not authenticated.
+ */
+export const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+  if (!isLoggedIn()) {
+    return <Navigate to="/login" replace />;
+  }
+  return <>{children}</>;
+};
+
+/**
+ * AdminRoute: redirects to /dashboard if user is not an admin.
+ * Also includes authentication check (redirects to /login if not logged in).
+ */
+export const AdminRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+  if (!isLoggedIn()) {
+    return <Navigate to="/login" replace />;
+  }
+  if (getUserRole() !== 'admin') {
+    return <Navigate to="/dashboard" replace />;
+  }
+  return <>{children}</>;
+};

+ 68 - 0
client/src/components/SystemSettings.tsx

@@ -0,0 +1,68 @@
+import React, { useEffect, useState } from 'react';
+import { Form, InputNumber, Button, message, Spin } from 'antd';
+import api from '../api/axios';
+
+const SystemSettings: React.FC = () => {
+  const [form] = Form.useForm();
+  const [loading, setLoading] = useState(false);
+  const [saving, setSaving] = useState(false);
+
+  useEffect(() => {
+    const fetchSettings = async () => {
+      setLoading(true);
+      try {
+        const { data } = await api.get('/admin/settings');
+        form.setFieldsValue({
+          max_instance_lifetime_minutes: data.max_instance_lifetime_minutes ?? 1440,
+        });
+      } catch {
+        message.error('获取系统设置失败');
+      } finally {
+        setLoading(false);
+      }
+    };
+    fetchSettings();
+  }, [form]);
+
+  const handleSubmit = async (values: { max_instance_lifetime_minutes: number }) => {
+    setSaving(true);
+    try {
+      await api.put('/admin/settings', {
+        max_instance_lifetime_minutes: values.max_instance_lifetime_minutes,
+      });
+      message.success('系统设置保存成功');
+    } catch (err: any) {
+      const errMsg = err?.response?.data?.error?.message;
+      message.error(errMsg || '保存系统设置失败');
+    } finally {
+      setSaving(false);
+    }
+  };
+
+  return (
+    <Spin spinning={loading}>
+      <Form
+        form={form}
+        layout="vertical"
+        onFinish={handleSubmit}
+        style={{ maxWidth: 400 }}
+      >
+        <Form.Item
+          label="实例最大使用时长(分钟)"
+          name="max_instance_lifetime_minutes"
+          rules={[{ required: true, message: '请输入最大使用时长' }]}
+        >
+          <InputNumber min={1} max={43200} style={{ width: '100%' }} placeholder="1440" />
+        </Form.Item>
+
+        <Form.Item>
+          <Button type="primary" htmlType="submit" loading={saving}>
+            保存设置
+          </Button>
+        </Form.Item>
+      </Form>
+    </Spin>
+  );
+};
+
+export default SystemSettings;

+ 201 - 0
client/src/components/UserManager.tsx

@@ -0,0 +1,201 @@
+import React, { useEffect, useState, useCallback } from 'react';
+import { Table, Button, Tag, message, Popconfirm, Modal, Form, Input, Select, Space } from 'antd';
+import { ReloadOutlined, EditOutlined, DeleteOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
+import type { ColumnsType } from 'antd/es/table';
+import api from '../api/axios';
+
+interface MachineGuid {
+  id: number;
+  label: string;
+  machine_guid: string;
+}
+
+interface User {
+  id: number;
+  username: string;
+  role: string;
+  invitation_code: string | null;
+  created_at: number;
+  machine_guids: MachineGuid[];
+}
+
+function maskGuid(guid: string): string {
+  if (guid.length < 16) return guid;
+  return guid.slice(0, 8) + '-****-****-****-' + guid.slice(-12);
+}
+
+const MaskedGuid: React.FC<{ guid: string }> = ({ guid }) => {
+  const [visible, setVisible] = useState(false);
+  return (
+    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
+      <span>{visible ? guid : maskGuid(guid)}</span>
+      <Button type="text" size="small" icon={visible ? <EyeInvisibleOutlined /> : <EyeOutlined />} onClick={() => setVisible(!visible)} />
+    </span>
+  );
+};
+
+const UserManager: React.FC = () => {
+  const [users, setUsers] = useState<User[]>([]);
+  const [loading, setLoading] = useState(false);
+  const [editModalOpen, setEditModalOpen] = useState(false);
+  const [editingUser, setEditingUser] = useState<User | null>(null);
+  const [editForm] = Form.useForm();
+  const [saving, setSaving] = useState(false);
+
+  const fetchUsers = useCallback(async () => {
+    setLoading(true);
+    try {
+      const { data } = await api.get<User[]>('/admin/users');
+      setUsers(Array.isArray(data) ? data : []);
+    } catch {
+      message.error('获取用户列表失败');
+    } finally {
+      setLoading(false);
+    }
+  }, []);
+
+  useEffect(() => { fetchUsers(); }, [fetchUsers]);
+
+  const formatTime = (value: number) => {
+    if (!value) return '-';
+    return new Date(value * 1000).toLocaleString();
+  };
+
+  const handleEdit = (user: User) => {
+    setEditingUser(user);
+    editForm.setFieldsValue({ username: user.username, role: user.role, password: '' });
+    setEditModalOpen(true);
+  };
+
+  const handleEditSubmit = async (values: { username: string; role: string; password: string }) => {
+    if (!editingUser) return;
+    setSaving(true);
+    try {
+      const body: Record<string, string> = { username: values.username, role: values.role };
+      if (values.password) body.password = values.password;
+      await api.put(`/admin/users/${editingUser.id}`, body);
+      message.success('用户信息已更新');
+      setEditModalOpen(false);
+      fetchUsers();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '更新失败');
+    } finally {
+      setSaving(false);
+    }
+  };
+
+  const handleDelete = async (id: number) => {
+    try {
+      await api.delete(`/admin/users/${id}`);
+      message.success('用户已删除');
+      fetchUsers();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '删除失败');
+    }
+  };
+
+  const columns: ColumnsType<User> = [
+    { title: '用户名', dataIndex: 'username', key: 'username', width: 140 },
+    {
+      title: '角色',
+      dataIndex: 'role',
+      key: 'role',
+      width: 100,
+      render: (role: string) => <Tag color={role === 'admin' ? 'blue' : 'default'}>{role === 'admin' ? '管理员' : '用户'}</Tag>,
+    },
+    {
+      title: '邀请码',
+      dataIndex: 'invitation_code',
+      key: 'invitation_code',
+      width: 160,
+      render: (code: string | null) => code || <span style={{ color: '#999' }}>-</span>,
+    },
+    {
+      title: 'MachineGuid 数量',
+      key: 'guid_count',
+      width: 140,
+      render: (_: unknown, record: User) => record.machine_guids.length,
+    },
+    {
+      title: '注册时间',
+      dataIndex: 'created_at',
+      key: 'created_at',
+      width: 180,
+      render: (val: number) => formatTime(val),
+    },
+    {
+      title: '操作',
+      key: 'actions',
+      width: 140,
+      render: (_: unknown, record: User) => (
+        <Space>
+          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
+          <Popconfirm title="确定删除此用户?关联数据将一并删除。" onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
+            <Button size="small" danger icon={<DeleteOutlined />}>删除</Button>
+          </Popconfirm>
+        </Space>
+      ),
+    },
+  ];
+
+  const guidColumns: ColumnsType<MachineGuid> = [
+    { title: '备注', dataIndex: 'label', key: 'label', width: 120, render: (v: string) => v || '-' },
+    { title: 'MachineGuid', dataIndex: 'machine_guid', key: 'machine_guid', render: (guid: string) => <MaskedGuid guid={guid} /> },
+  ];
+
+  return (
+    <div>
+      <div style={{ marginBottom: 16 }}>
+        <Button icon={<ReloadOutlined />} onClick={fetchUsers} loading={loading}>刷新</Button>
+      </div>
+      <Table<User>
+        columns={columns}
+        dataSource={users}
+        rowKey="id"
+        loading={loading}
+        pagination={{ pageSize: 10 }}
+        scroll={{ x: 900 }}
+        expandable={{
+          expandedRowRender: (record) =>
+            record.machine_guids.length > 0 ? (
+              <Table<MachineGuid>
+                columns={guidColumns}
+                dataSource={record.machine_guids}
+                rowKey="id"
+                size="small"
+                pagination={false}
+              />
+            ) : (
+              <span style={{ color: '#999' }}>暂无 MachineGuid</span>
+            ),
+          rowExpandable: () => true,
+        }}
+      />
+
+      <Modal
+        title="编辑用户"
+        open={editModalOpen}
+        onCancel={() => setEditModalOpen(false)}
+        footer={null}
+        destroyOnHidden
+      >
+        <Form form={editForm} onFinish={handleEditSubmit} layout="vertical">
+          <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
+            <Input />
+          </Form.Item>
+          <Form.Item label="角色" name="role" rules={[{ required: true }]}>
+            <Select options={[{ value: 'admin', label: '管理员' }, { value: 'user', label: '用户' }]} />
+          </Form.Item>
+          <Form.Item label="新密码" name="password" extra="留空则不修改密码">
+            <Input.Password placeholder="留空不修改" />
+          </Form.Item>
+          <Form.Item>
+            <Button type="primary" htmlType="submit" loading={saving} block>保存</Button>
+          </Form.Item>
+        </Form>
+      </Modal>
+    </div>
+  );
+};
+
+export default UserManager;

+ 9 - 0
client/src/main.tsx

@@ -0,0 +1,9 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import App from './App';
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>,
+);

+ 58 - 0
client/src/pages/AdminPage.tsx

@@ -0,0 +1,58 @@
+import React from 'react';
+import { Typography, Card, Button, Space } from 'antd';
+import { DashboardOutlined, LogoutOutlined } from '@ant-design/icons';
+import { Link } from 'react-router-dom';
+import InvitationManager from '../components/InvitationManager';
+import UserManager from '../components/UserManager';
+import AwsConfigForm from '../components/AwsConfigForm';
+import SystemSettings from '../components/SystemSettings';
+import InstanceMonitor from '../components/InstanceMonitor';
+import InstanceLogs from '../components/InstanceLogs';
+import GuacamoleConfig from '../components/GuacamoleConfig';
+import RdpSessionMonitor from '../components/RdpSessionMonitor';
+
+const { Title } = Typography;
+
+const AdminPage: React.FC = () => {
+  return (
+    <div style={{ padding: 24, maxWidth: 1400, margin: '0 auto' }}>
+      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
+        <Title level={2} style={{ margin: 0 }}>管理员面板</Title>
+        <Space>
+          <Link to="/dashboard">
+            <Button icon={<DashboardOutlined />}>用户面板</Button>
+          </Link>
+          <Button icon={<LogoutOutlined />} onClick={() => { localStorage.removeItem('token'); window.location.href = '/login'; }}>
+            登出
+          </Button>
+        </Space>
+      </div>
+      <Card title="实例监控" style={{ marginBottom: 24 }}>
+        <InstanceMonitor />
+      </Card>
+      <Card title="用户管理" style={{ marginBottom: 24 }}>
+        <UserManager />
+      </Card>
+      <Card title="邀请码管理" style={{ marginBottom: 24 }}>
+        <InvitationManager />
+      </Card>
+      <Card title="AWS 配置" style={{ marginBottom: 24 }}>
+        <AwsConfigForm />
+      </Card>
+      <Card title="Guacamole 配置" style={{ marginBottom: 24 }}>
+        <GuacamoleConfig />
+      </Card>
+      <Card title="RDP 会话监控" style={{ marginBottom: 24 }}>
+        <RdpSessionMonitor />
+      </Card>
+      <Card title="系统设置" style={{ marginBottom: 24 }}>
+        <SystemSettings />
+      </Card>
+      <Card title="实例操作日志" style={{ marginBottom: 24 }}>
+        <InstanceLogs />
+      </Card>
+    </div>
+  );
+};
+
+export default AdminPage;

+ 561 - 0
client/src/pages/DashboardPage.tsx

@@ -0,0 +1,561 @@
+import React, { useEffect, useState, useCallback, useRef } from 'react';
+import {
+  Typography,
+  Table,
+  Button,
+  Form,
+  Input,
+  Tag,
+  Popconfirm,
+  Modal,
+  Space,
+  Card,
+  Select,
+  message,
+  notification,
+  Descriptions,
+} from 'antd';
+import {
+  PlusOutlined,
+  ReloadOutlined,
+  PoweroffOutlined,
+  PlayCircleOutlined,
+  RedoOutlined,
+  DeleteOutlined,
+  DesktopOutlined,
+  SettingOutlined,
+  EyeOutlined,
+  EyeInvisibleOutlined,
+  LogoutOutlined,
+  LinkOutlined,
+  DownloadOutlined,
+  CopyOutlined,
+} from '@ant-design/icons';
+import type { ColumnsType } from 'antd/es/table';
+import { Link } from 'react-router-dom';
+import api from '../api/axios';
+
+const { Title } = Typography;
+
+const UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+
+interface Instance {
+  id: number;
+  ec2_instance_id: string;
+  machine_guid: string;
+  status: string;
+  public_ip: string | null;
+  started_at: number | null;
+  expires_at: number | null;
+  remaining_time: number;
+  expiring_soon: boolean;
+  created_at: number;
+}
+
+interface SavedGuid {
+  id: number;
+  label: string;
+  machine_guid: string;
+}
+
+interface RdpInfo {
+  publicIp: string;
+  rdpUsername: string;
+  rdpPassword: string;
+}
+
+const STATUS_COLOR: Record<string, string> = {
+  pending: 'orange',
+  running: 'green',
+  stopped: 'red',
+  terminated: 'default',
+};
+
+const STATUS_LABEL: Record<string, string> = {
+  pending: '启动中',
+  running: '运行中',
+  stopped: '已停止',
+  terminated: '已销毁',
+};
+
+/** Mask a UUID: show first 8 and last 4 chars, mask the rest */
+function maskGuid(guid: string): string {
+  if (guid.length < 16) return guid;
+  return guid.slice(0, 8) + '-****-****-****-' + guid.slice(-12);
+}
+
+function formatRemainingTime(seconds: number): string {
+  if (seconds <= 0) return '已到期';
+  const h = Math.floor(seconds / 3600);
+  const m = Math.floor((seconds % 3600) / 60);
+  const s = seconds % 60;
+  if (h > 0) return `${h}时${m}分`;
+  if (m > 0) return `${m}分${s}秒`;
+  return `${s}秒`;
+}
+
+/** Inline component to show/hide a MachineGuid */
+const MaskedGuid: React.FC<{ guid: string }> = ({ guid }) => {
+  const [visible, setVisible] = useState(false);
+  return (
+    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
+      <span>{visible ? guid : maskGuid(guid)}</span>
+      <Button
+        type="text"
+        size="small"
+        icon={visible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
+        onClick={() => setVisible(!visible)}
+      />
+    </span>
+  );
+};
+
+const DashboardPage: React.FC = () => {
+  const [instances, setInstances] = useState<Instance[]>([]);
+  const [loading, setLoading] = useState(false);
+  const [launchModalOpen, setLaunchModalOpen] = useState(false);
+  const [launching, setLaunching] = useState(false);
+  const [rdpModalOpen, setRdpModalOpen] = useState(false);
+  const [rdpInfo, setRdpInfo] = useState<RdpInfo | null>(null);
+  const [rdpLoading, setRdpLoading] = useState(false);
+  const [actionLoading, setActionLoading] = useState<Record<number, boolean>>({});
+  const [webRdpLoading, setWebRdpLoading] = useState<Record<number, boolean>>({});
+  const [guacamoleConfigured, setGuacamoleConfigured] = useState(false);
+  const [userRole, setUserRole] = useState<string>('user');
+  const [savedGuids, setSavedGuids] = useState<SavedGuid[]>([]);
+  const [newGuidInput, setNewGuidInput] = useState('');
+  const [newLabelInput, setNewLabelInput] = useState('');
+  const [guidSaving, setGuidSaving] = useState(false);
+  const [launchForm] = Form.useForm();
+  const notifiedIdsRef = useRef<Set<number>>(new Set());
+
+  const fetchInstances = useCallback(async () => {
+    setLoading(true);
+    try {
+      const { data } = await api.get<Instance[]>('/instances');
+      setInstances(Array.isArray(data) ? data : []);
+    } catch {
+      message.error('获取实例列表失败');
+    } finally {
+      setLoading(false);
+    }
+  }, []);
+
+  const fetchUserRole = useCallback(async () => {
+    try {
+      const { data } = await api.get<{ user: { role: string } }>('/auth/me');
+      setUserRole(data.user.role);
+    } catch { /* ignore */ }
+  }, []);
+
+  const fetchGuids = useCallback(async () => {
+    try {
+      const { data } = await api.get<SavedGuid[]>('/auth/machine-guids');
+      setSavedGuids(Array.isArray(data) ? data : []);
+    } catch { /* ignore */ }
+  }, []);
+
+  const fetchGuacamoleStatus = useCallback(async () => {
+    try {
+      const { data } = await api.get<{ configured: boolean }>('/settings/guacamole-status');
+      setGuacamoleConfigured(data.configured);
+    } catch {
+      setGuacamoleConfigured(false);
+    }
+  }, []);
+
+  const handleAddGuid = async () => {
+    if (!UUID_REGEX.test(newGuidInput)) {
+      message.error('MachineGuid 格式无效,需为 UUID 格式');
+      return;
+    }
+    setGuidSaving(true);
+    try {
+      await api.post('/auth/machine-guids', { machine_guid: newGuidInput, label: newLabelInput });
+      message.success('MachineGuid 已添加');
+      setNewGuidInput('');
+      setNewLabelInput('');
+      fetchGuids();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '添加失败');
+    } finally {
+      setGuidSaving(false);
+    }
+  };
+
+  const handleDeleteGuid = async (id: number) => {
+    try {
+      await api.delete(`/auth/machine-guids/${id}`);
+      message.success('已删除');
+      fetchGuids();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '删除失败');
+    }
+  };
+
+  useEffect(() => {
+    instances.forEach((inst) => {
+      if (inst.expiring_soon && !notifiedIdsRef.current.has(inst.id)) {
+        notifiedIdsRef.current.add(inst.id);
+        notification.warning({
+          message: '实例即将到期',
+          description: `实例 ${inst.ec2_instance_id || inst.id} 剩余时间不足 5 分钟,请及时保存数据。`,
+          duration: 10,
+        });
+      }
+    });
+  }, [instances]);
+
+  useEffect(() => {
+    fetchInstances();
+    fetchUserRole();
+    fetchGuids();
+    fetchGuacamoleStatus();
+    const timer = setInterval(fetchInstances, 30000);
+    return () => clearInterval(timer);
+  }, [fetchInstances, fetchUserRole, fetchGuids, fetchGuacamoleStatus]);
+
+  const handleLaunch = async (values: { machineGuid: string }) => {
+    setLaunching(true);
+    try {
+      await api.post('/instances', { machineGuid: values.machineGuid });
+      message.success('实例启动请求已提交');
+      setLaunchModalOpen(false);
+      launchForm.resetFields();
+      fetchInstances();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '启动实例失败');
+    } finally {
+      setLaunching(false);
+    }
+  };
+
+  const handleAction = async (id: number, action: 'stop' | 'start' | 'reboot') => {
+    setActionLoading((prev) => ({ ...prev, [id]: true }));
+    try {
+      await api.post(`/instances/${id}/${action}`);
+      const labels = { stop: '关机', start: '启动', reboot: '重启' };
+      message.success(`${labels[action]}操作已执行`);
+      fetchInstances();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '操作失败');
+    } finally {
+      setActionLoading((prev) => ({ ...prev, [id]: false }));
+    }
+  };
+
+  const handleTerminate = async (id: number) => {
+    setActionLoading((prev) => ({ ...prev, [id]: true }));
+    try {
+      await api.delete(`/instances/${id}`);
+      message.success('实例已销毁');
+      fetchInstances();
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '销毁失败');
+    } finally {
+      setActionLoading((prev) => ({ ...prev, [id]: false }));
+    }
+  };
+
+  const handleShowRdp = async (id: number) => {
+    setRdpLoading(true);
+    setRdpModalOpen(true);
+    setRdpInfo(null);
+    try {
+      const { data } = await api.get<RdpInfo>(`/instances/${id}/rdp`);
+      setRdpInfo(data);
+    } catch (err: any) {
+      message.error(err?.response?.data?.error?.message || '获取 RDP 信息失败');
+      setRdpModalOpen(false);
+    } finally {
+      setRdpLoading(false);
+    }
+  };
+
+  const handleWebRdp = (id: number) => {
+    Modal.confirm({
+      title: '在线连接',
+      content: '实例启动时可能尚未完成初始化,连接/认证可能会失败。如遇失败请多次尝试重新连接。',
+      okText: '连接',
+      cancelText: '取消',
+      onOk: async () => {
+        setWebRdpLoading((prev) => ({ ...prev, [id]: true }));
+        try {
+          const { data } = await api.post<{ id: string; token: string }>(`/instances/${id}/rdp-session`);
+          window.open(`/rdp/${id}?token=${encodeURIComponent(data.token)}`, '_blank');
+        } catch (err: any) {
+          message.error(err?.response?.data?.error?.message || '创建远程桌面会话失败');
+        } finally {
+          setWebRdpLoading((prev) => ({ ...prev, [id]: false }));
+        }
+      },
+    });
+  };
+
+  const columns: ColumnsType<Instance> = [
+    {
+      title: '实例ID',
+      dataIndex: 'ec2_instance_id',
+      key: 'ec2_instance_id',
+      ellipsis: true,
+      width: 180,
+    },
+    {
+      title: '状态',
+      dataIndex: 'status',
+      key: 'status',
+      width: 100,
+      render: (status: string) => (
+        <Tag color={STATUS_COLOR[status] || 'default'}>
+          {STATUS_LABEL[status] || status}
+        </Tag>
+      ),
+    },
+    {
+      title: '公网IP',
+      dataIndex: 'public_ip',
+      key: 'public_ip',
+      width: 140,
+      render: (ip: string | null) => ip || '-',
+    },
+    {
+      title: '剩余时间',
+      dataIndex: 'remaining_time',
+      key: 'remaining_time',
+      width: 120,
+      render: (time: number, record: Instance) => {
+        if (record.status === 'terminated') return '-';
+        if (record.status === 'pending') return <Tag color="processing">启动中</Tag>;
+        return (
+          <span style={record.expiring_soon ? { color: '#ff4d4f', fontWeight: 'bold' } : undefined}>
+            {formatRemainingTime(time)}
+          </span>
+        );
+      },
+    },
+    {
+      title: 'MachineGuid',
+      dataIndex: 'machine_guid',
+      key: 'machine_guid',
+      width: 320,
+      render: (guid: string) => guid ? <MaskedGuid guid={guid} /> : '-',
+    },
+    {
+      title: '操作',
+      key: 'actions',
+      width: 320,
+      render: (_: unknown, record: Instance) => {
+        const isLoading = actionLoading[record.id] || false;
+        const isTerminated = record.status === 'terminated';
+        return (
+          <Space wrap>
+            {record.status === 'running' && (
+              <>
+                <Button size="small" icon={<PoweroffOutlined />} loading={isLoading} onClick={() => handleAction(record.id, 'stop')}>关机</Button>
+                <Button size="small" icon={<RedoOutlined />} loading={isLoading} onClick={() => handleAction(record.id, 'reboot')}>重启</Button>
+                <Button size="small" icon={<DesktopOutlined />} disabled={!record.public_ip} title={!record.public_ip ? '等待分配公网 IP...' : ''} onClick={() => handleShowRdp(record.id)}>RDP信息</Button>
+                {guacamoleConfigured && (
+                  <Button size="small" icon={<LinkOutlined />} loading={webRdpLoading[record.id] || false} disabled={!record.public_ip} title={!record.public_ip ? '等待分配公网 IP...' : ''} onClick={() => handleWebRdp(record.id)}>在线连接</Button>
+                )}
+              </>
+            )}
+            {record.status === 'stopped' && (
+              <Button size="small" icon={<PlayCircleOutlined />} loading={isLoading} onClick={() => handleAction(record.id, 'start')}>启动</Button>
+            )}
+            {!isTerminated && (
+              <Popconfirm title="确定销毁此实例?此操作不可恢复。" onConfirm={() => handleTerminate(record.id)} okText="确定" cancelText="取消">
+                <Button size="small" danger icon={<DeleteOutlined />} loading={isLoading}>销毁</Button>
+              </Popconfirm>
+            )}
+          </Space>
+        );
+      },
+    },
+  ];
+
+  return (
+    <div style={{ padding: 24, maxWidth: 1400, margin: '0 auto' }}>
+      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
+        <Title level={2} style={{ margin: 0 }}>用户面板</Title>
+        <Space>
+          {userRole === 'admin' && (
+            <Link to="/admin">
+              <Button icon={<SettingOutlined />}>管理员面板</Button>
+            </Link>
+          )}
+          <Button icon={<LogoutOutlined />} onClick={() => { localStorage.removeItem('token'); window.location.href = '/login'; }}>
+            登出
+          </Button>
+        </Space>
+      </div>
+
+      <Card title="我的 MachineGuid" style={{ marginBottom: 24 }}>
+        <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
+          <div style={{ flex: 1, minWidth: 300 }}>
+            <div style={{ marginBottom: 8, fontWeight: 500 }}>添加新 MachineGuid</div>
+            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+              <Input
+                value={newLabelInput}
+                onChange={(e) => setNewLabelInput(e.target.value)}
+                placeholder="备注(可选)"
+              />
+              <div>
+                <Input
+                  value={newGuidInput}
+                  onChange={(e) => setNewGuidInput(e.target.value)}
+                  placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
+                  status={newGuidInput && !UUID_REGEX.test(newGuidInput) ? 'error' : undefined}
+                />
+                {newGuidInput && !UUID_REGEX.test(newGuidInput) && (
+                  <div style={{ color: '#ff4d4f', fontSize: 12, marginTop: 4 }}>
+                    格式无效,需为 UUID 格式
+                  </div>
+                )}
+              </div>
+              <Button type="primary" loading={guidSaving} onClick={handleAddGuid} icon={<PlusOutlined />} disabled={!newGuidInput || !UUID_REGEX.test(newGuidInput)}>
+                添加
+              </Button>
+            </div>
+            <div style={{ fontSize: 14, color: '#555', marginTop: 12 }}>
+              在<b>可以</b>通过 VPN 联网的 Windows 电脑运行 regedit,导航到 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography,复制 MachineGuid 的值,或通过如下方式取得:
+            </div>
+            <div style={{ fontSize: 14, color: '#555', marginTop: 12 }}>
+              <b>cmd: </b>
+            </div>
+            <div style={{ fontSize: 14, color: '#555', marginTop: 12 }}>
+              reg query "HKLM\SOFTWARE\Microsoft\Cryptography" /v MachineGuid
+            </div>
+            <div style={{ fontSize: 14, color: '#555', marginTop: 12 }}>
+              <b>powershell: </b>
+            </div>
+            <div style={{ fontSize: 14, color: '#555', marginTop: 12 }}>
+              (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Cryptography").MachineGuid
+            </div>
+          </div>
+          <div style={{ flex: 1, minWidth: 300 }}>
+            <Table<SavedGuid>
+              dataSource={savedGuids}
+              rowKey="id"
+              size="small"
+              pagination={{ pageSize: 5, size: 'small' }}
+              locale={{ emptyText: '暂无保存的 MachineGuid' }}
+              columns={[
+                {
+                  title: '备注',
+                  dataIndex: 'label',
+                  key: 'label',
+                  width: 120,
+                  render: (label: string) => label || '-',
+                },
+                {
+                  title: 'MachineGuid',
+                  dataIndex: 'machine_guid',
+                  key: 'machine_guid',
+                  render: (guid: string) => <MaskedGuid guid={guid} />,
+                },
+                {
+                  title: '操作',
+                  key: 'action',
+                  width: 80,
+                  render: (_: unknown, record: SavedGuid) => (
+                    <Popconfirm title="确定删除此 MachineGuid?" onConfirm={() => handleDeleteGuid(record.id)} okText="确定" cancelText="取消">
+                      <Button type="text" size="small" danger icon={<DeleteOutlined />} />
+                    </Popconfirm>
+                  ),
+                },
+              ]}
+            />
+          </div>
+        </div>
+      </Card>
+
+      <Card style={{ marginBottom: 24 }}>
+        <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
+          <Button type="primary" icon={<PlusOutlined />} onClick={() => setLaunchModalOpen(true)}>
+            启动新实例
+          </Button>
+          <Button icon={<ReloadOutlined />} onClick={fetchInstances} loading={loading}>
+            刷新
+          </Button>
+        </div>
+        <Table<Instance> columns={columns} dataSource={instances} rowKey="id" loading={loading} pagination={{ pageSize: 10 }} scroll={{ x: 1100 }} />
+      </Card>
+
+      <Modal title="启动新实例" open={launchModalOpen} onCancel={() => { setLaunchModalOpen(false); launchForm.resetFields(); }} footer={null} destroyOnHidden>
+        <Form form={launchForm} onFinish={handleLaunch} layout="vertical">
+          <Form.Item
+            label="MachineGuid"
+            name="machineGuid"
+            rules={[
+              { required: true, message: '请选择或输入 MachineGuid' },
+              { pattern: UUID_REGEX, message: 'MachineGuid 格式无效,需为 UUID 格式' },
+            ]}
+          >
+            {savedGuids.length > 0 ? (
+              <Select
+                showSearch
+                placeholder="选择已保存的 MachineGuid"
+                optionFilterProp="label"
+                options={savedGuids.map((g) => ({
+                  value: g.machine_guid,
+                  label: g.label ? `${g.label} (${maskGuid(g.machine_guid)})` : maskGuid(g.machine_guid),
+                }))}
+              />
+            ) : (
+              <Input placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
+            )}
+          </Form.Item>
+          <Form.Item>
+            <Button type="primary" htmlType="submit" loading={launching} block>启动实例</Button>
+          </Form.Item>
+        </Form>
+      </Modal>
+
+      <Modal title="RDP 连接信息" open={rdpModalOpen} onCancel={() => setRdpModalOpen(false)} footer={<Button onClick={() => setRdpModalOpen(false)}>关闭</Button>}>
+        {rdpLoading ? (
+          <div style={{ textAlign: 'center', padding: 24 }}>加载中...</div>
+        ) : rdpInfo ? (
+          <>
+            <Descriptions column={1} bordered>
+              <Descriptions.Item label="公网 IP">{rdpInfo.publicIp} <CopyOutlined style={{ cursor: 'pointer', color: '#1677ff' }} onClick={() => { navigator.clipboard.writeText(rdpInfo.publicIp); message.success('已复制'); }} /></Descriptions.Item>
+              <Descriptions.Item label="用户名">{rdpInfo.rdpUsername} <CopyOutlined style={{ cursor: 'pointer', color: '#1677ff' }} onClick={() => { navigator.clipboard.writeText(rdpInfo.rdpUsername); message.success('已复制'); }} /></Descriptions.Item>
+              <Descriptions.Item label="密码">{rdpInfo.rdpPassword} <CopyOutlined style={{ cursor: 'pointer', color: '#1677ff' }} onClick={() => { navigator.clipboard.writeText(rdpInfo.rdpPassword); message.success('已复制'); }} /></Descriptions.Item>
+            </Descriptions>
+            <div style={{ marginTop: 12 }}>
+              <Button
+                icon={<DownloadOutlined />}
+                onClick={() => {
+                  const rdpContent = [
+                    'full address:s:' + rdpInfo.publicIp,
+                    'username:s:' + rdpInfo.rdpUsername,
+                    'prompt for credentials:i:0',
+                    'screen mode id:i:2',
+                    'desktopwidth:i:1920',
+                    'desktopheight:i:1080',
+                    'session bpp:i:32',
+                    'authentication level:i:0',
+                    'enablecredsspsupport:i:1',
+                  ].join('\r\n');
+                  const blob = new Blob([rdpContent], { type: 'application/x-rdp' });
+                  const url = URL.createObjectURL(blob);
+                  const a = document.createElement('a');
+                  a.href = url;
+                  a.download = `${rdpInfo.publicIp}.rdp`;
+                  a.click();
+                  URL.revokeObjectURL(url);
+                }}
+              >
+                下载 RDP 文件
+              </Button>
+            </div>
+            <div style={{ marginTop: 12, color: '#888', fontSize: 13 }}>
+              实例可能需要至少 4 分钟的初始化时间,如无法访问或认证失败请稍等片刻。
+            </div>
+          </>
+        ) : null}
+      </Modal>
+    </div>
+  );
+};
+
+export default DashboardPage;

+ 72 - 0
client/src/pages/LoginPage.tsx

@@ -0,0 +1,72 @@
+import React, { useState } from 'react';
+import { Form, Input, Button, Card, Typography, message } from 'antd';
+import { UserOutlined, LockOutlined } from '@ant-design/icons';
+import { Link, useNavigate } from 'react-router-dom';
+import api from '../api/axios';
+
+const { Title } = Typography;
+
+interface LoginFormValues {
+  username: string;
+  password: string;
+}
+
+interface LoginResponse {
+  token: string;
+  user: { id: number; username: string; role: string };
+}
+
+const LoginPage: React.FC = () => {
+  const navigate = useNavigate();
+  const [loading, setLoading] = useState(false);
+
+  const onFinish = async (values: LoginFormValues) => {
+    setLoading(true);
+    try {
+      const { data } = await api.post<LoginResponse>('/auth/login', values);
+      localStorage.setItem('token', data.token);
+      if (data.user.role === 'admin') {
+        navigate('/admin', { replace: true });
+      } else {
+        navigate('/dashboard', { replace: true });
+      }
+    } catch (err: unknown) {
+      const error = err as { response?: { data?: { error?: { message?: string }; message?: string } } };
+      const msg =
+        error.response?.data?.error?.message ??
+        error.response?.data?.message ??
+        '登录失败,请重试';
+      message.error(msg);
+    } finally {
+      setLoading(false);
+    }
+  };
+
+  return (
+    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh', background: '#f0f2f5' }}>
+      <Card style={{ width: 400 }}>
+        <Title level={3} style={{ textAlign: 'center', marginBottom: 24 }}>
+          Bifrost Anywhere
+        </Title>
+        <Form<LoginFormValues> name="login" onFinish={onFinish} autoComplete="off">
+          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
+            <Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
+          </Form.Item>
+          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
+            <Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
+          </Form.Item>
+          <Form.Item>
+            <Button type="primary" htmlType="submit" loading={loading} block size="large">
+              登录
+            </Button>
+          </Form.Item>
+          <Form.Item style={{ marginBottom: 0, textAlign: 'center' }}>
+            还没有账户? <Link to="/register">立即注册</Link>
+          </Form.Item>
+        </Form>
+      </Card>
+    </div>
+  );
+};
+
+export default LoginPage;

+ 332 - 0
client/src/pages/RdpPage.tsx

@@ -0,0 +1,332 @@
+import React, { useEffect, useRef, useState, useCallback } from 'react';
+import { useParams, useSearchParams, useNavigate } from 'react-router-dom';
+import { Button, Space, Drawer, Input, message } from 'antd';
+import {
+  FullscreenOutlined,
+  FullscreenExitOutlined,
+  CopyOutlined,
+  DisconnectOutlined,
+} from '@ant-design/icons';
+import Guacamole from 'guacamole-common-js';
+import RdpStatusBar from '../components/RdpStatusBar';
+import type { RdpConnectionStatus } from '../components/RdpStatusBar';
+
+const { TextArea } = Input;
+
+const RdpPage: React.FC = () => {
+  const { instanceId } = useParams<{ instanceId: string }>();
+  const [searchParams] = useSearchParams();
+  const navigate = useNavigate();
+  const token = searchParams.get('token');
+
+  const displayRef = useRef<HTMLDivElement>(null);
+  const clientRef = useRef<Guacamole.Client | null>(null);
+  const keyboardRef = useRef<Guacamole.Keyboard | null>(null);
+
+  const [status, setStatus] = useState<RdpConnectionStatus>('connecting');
+  const [isFullscreen, setIsFullscreen] = useState(false);
+  const [clipboardOpen, setClipboardOpen] = useState(false);
+  const [clipboardText, setClipboardText] = useState('');
+  const clipboardOpenRef = useRef(false);
+
+  // Build WebSocket URL based on current page location
+  const buildWsUrl = useCallback(() => {
+    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
+    return `${protocol}//${window.location.host}/ws/rdp?token=${encodeURIComponent(token || '')}`;
+  }, [token]);
+
+  // Scale display to fit the container
+  const scaleDisplay = useCallback(() => {
+    const client = clientRef.current;
+    if (!client || !displayRef.current) return;
+
+    const display = client.getDisplay();
+    const displayWidth = display.getWidth();
+    const displayHeight = display.getHeight();
+    if (displayWidth === 0 || displayHeight === 0) return;
+
+    const container = displayRef.current;
+    // Reserve space for the toolbar (48px top bar)
+    const containerWidth = container.clientWidth;
+    const containerHeight = container.clientHeight;
+    if (containerWidth === 0 || containerHeight === 0) return;
+
+    const scaleX = containerWidth / displayWidth;
+    const scaleY = containerHeight / displayHeight;
+    const scale = Math.min(scaleX, scaleY);
+
+    display.scale(scale);
+  }, []);
+
+  // Connect to the Guacamole server
+  const connectGuacamole = useCallback(() => {
+    if (!token || !displayRef.current) return;
+
+    // Clean up any existing connection
+    if (clientRef.current) {
+      clientRef.current.disconnect();
+    }
+
+    setStatus('connecting');
+
+    const wsUrl = buildWsUrl();
+    const tunnel = new Guacamole.WebSocketTunnel(wsUrl);
+    const client = new Guacamole.Client(tunnel);
+    clientRef.current = client;
+
+    // Handle client state changes
+    client.onstatechange = (state: number) => {
+      switch (state) {
+        case 1: // CONNECTING
+        case 2: // WAITING
+          setStatus('connecting');
+          break;
+        case 3: // CONNECTED
+          setStatus('connected');
+          // Scale once connected
+          setTimeout(scaleDisplay, 100);
+          break;
+        case 4: // DISCONNECTING
+        case 5: // DISCONNECTED
+          setStatus('disconnected');
+          break;
+      }
+    };
+
+    // Handle errors
+    client.onerror = (error: Guacamole.Status) => {
+      console.error('Guacamole client error:', error);
+      setStatus('error');
+      message.error(`连接错误: ${error.message || '未知错误'}`);
+    };
+
+    // Handle remote clipboard
+    client.onclipboard = (stream: Guacamole.InputStream, mimetype: string) => {
+      if (mimetype !== 'text/plain') return;
+      const reader = new Guacamole.StringReader(stream);
+      let data = '';
+      reader.ontext = (text: string) => { data += text; };
+      reader.onend = () => { setClipboardText(data); };
+    };
+
+    // Add display element to container
+    const displayElement = client.getDisplay().getElement();
+    displayRef.current.innerHTML = '';
+    displayRef.current.appendChild(displayElement);
+
+    // Set up mouse handling
+    const mouse = new Guacamole.Mouse(displayElement);
+    const sendMouseState = (state: Guacamole.Mouse.State) => {
+      const display = client.getDisplay();
+      const scale = display.getScale();
+      const scaledState = new Guacamole.Mouse.State();
+      scaledState.x = state.x / scale;
+      scaledState.y = state.y / scale;
+      scaledState.left = state.left;
+      scaledState.middle = state.middle;
+      scaledState.right = state.right;
+      scaledState.up = state.up;
+      scaledState.down = state.down;
+      client.sendMouseState(scaledState);
+    };
+    mouse.onmousedown = mouse.onmouseup = mouse.onmousemove = sendMouseState;
+
+    // Set up keyboard handling — attach to document for reliable capture.
+    // Keyboard forwarding is suppressed when the clipboard drawer is open.
+    const keyboard = new Guacamole.Keyboard(document);
+    keyboardRef.current = keyboard;
+    keyboard.onkeydown = (keysym: number) => {
+      if (clipboardOpenRef.current) return true; // let browser handle it
+      client.sendKeyEvent(1 as unknown as boolean, keysym);
+      return false; // prevent default browser behavior
+    };
+    keyboard.onkeyup = (keysym: number) => {
+      if (clipboardOpenRef.current) return;
+      client.sendKeyEvent(0 as unknown as boolean, keysym);
+    };
+
+    // Listen for display resize from server
+    client.getDisplay().onresize = () => {
+      scaleDisplay();
+    };
+
+    // Connect
+    client.connect('');
+  }, [token, buildWsUrl, scaleDisplay]);
+
+  // Initialize connection on mount
+  useEffect(() => {
+    connectGuacamole();
+    return () => {
+      if (keyboardRef.current) {
+        keyboardRef.current.onkeydown = null;
+        keyboardRef.current.onkeyup = null;
+      }
+      if (clientRef.current) {
+        clientRef.current.disconnect();
+        clientRef.current = null;
+      }
+    };
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, []);
+
+  // Window resize handler for adaptive scaling
+  useEffect(() => {
+    const handleResize = () => scaleDisplay();
+    window.addEventListener('resize', handleResize);
+    return () => window.removeEventListener('resize', handleResize);
+  }, [scaleDisplay]);
+
+  // Fullscreen change listener
+  useEffect(() => {
+    const handleFullscreenChange = () => {
+      setIsFullscreen(!!document.fullscreenElement);
+    };
+    document.addEventListener('fullscreenchange', handleFullscreenChange);
+    return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);
+  }, []);
+
+  // Keep clipboardOpenRef in sync with state so the keyboard handler can read it
+  useEffect(() => {
+    clipboardOpenRef.current = clipboardOpen;
+  }, [clipboardOpen]);
+
+  // Fullscreen toggle
+  const toggleFullscreen = async () => {
+    try {
+      if (document.fullscreenElement) {
+        await document.exitFullscreen();
+      } else {
+        await document.documentElement.requestFullscreen();
+      }
+    } catch {
+      message.error('全屏切换失败');
+    }
+  };
+
+  // Send clipboard text to remote
+  const sendClipboard = () => {
+    const client = clientRef.current;
+    if (!client || !clipboardText) return;
+    const stream = client.createClipboardStream('text/plain');
+    const writer = new Guacamole.StringWriter(stream);
+    writer.sendText(clipboardText);
+    writer.sendEnd();
+    message.success('剪贴板已同步到远程');
+  };
+
+  // Disconnect and close tab
+  const handleDisconnect = () => {
+    if (clientRef.current) {
+      clientRef.current.disconnect();
+      clientRef.current = null;
+    }
+    window.close();
+  };
+
+  // Reconnect handler
+  const handleReconnect = () => {
+    connectGuacamole();
+  };
+
+  if (!token) {
+    return (
+      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
+        <div style={{ textAlign: 'center' }}>
+          <h2>缺少连接令牌</h2>
+          <p>无法建立远程桌面连接,请从实例列表重新发起连接。</p>
+          <Button type="primary" onClick={() => navigate('/dashboard')}>返回面板</Button>
+        </div>
+      </div>
+    );
+  }
+
+  return (
+    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden', background: '#000' }}>
+      {/* Toolbar */}
+      <div
+        style={{
+          display: 'flex',
+          justifyContent: 'space-between',
+          alignItems: 'center',
+          padding: '0 16px',
+          height: 48,
+          background: '#1f1f1f',
+          borderBottom: '1px solid #333',
+          flexShrink: 0,
+        }}
+      >
+        <Space>
+          <span style={{ color: '#fff', fontSize: 14 }}>
+            远程桌面 - 实例 {instanceId}
+          </span>
+          <RdpStatusBar status={status} onReconnect={handleReconnect} />
+        </Space>
+        <Space>
+          <Button
+            size="small"
+            icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
+            onClick={toggleFullscreen}
+          >
+            {isFullscreen ? '退出全屏' : '全屏'}
+          </Button>
+          <Button
+            size="small"
+            icon={<CopyOutlined />}
+            onClick={() => setClipboardOpen(true)}
+          >
+            剪贴板
+          </Button>
+          <Button
+            size="small"
+            danger
+            icon={<DisconnectOutlined />}
+            onClick={handleDisconnect}
+          >
+            断开连接
+          </Button>
+        </Space>
+      </div>
+
+      {/* Remote desktop display container */}
+      <div
+        ref={displayRef}
+        style={{
+          flex: 1,
+          overflow: 'hidden',
+          display: 'flex',
+          justifyContent: 'center',
+          alignItems: 'center',
+          cursor: 'none',
+        }}
+      />
+
+      {/* Clipboard sync drawer */}
+      <Drawer
+        title="剪贴板同步"
+        open={clipboardOpen}
+        onClose={() => setClipboardOpen(false)}
+        width={400}
+      >
+        <p style={{ marginBottom: 8, color: '#666' }}>
+          在此处粘贴文本,然后点击"发送到远程"将内容同步到远程桌面剪贴板。
+          远程桌面复制的内容也会自动显示在此处。
+        </p>
+        <TextArea
+          rows={10}
+          value={clipboardText}
+          onChange={(e) => setClipboardText(e.target.value)}
+          placeholder="在此输入或粘贴文本..."
+        />
+        <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
+          <Button type="primary" onClick={sendClipboard} disabled={!clipboardText}>
+            发送到远程
+          </Button>
+          <Button onClick={() => setClipboardText('')}>清空</Button>
+        </div>
+      </Drawer>
+    </div>
+  );
+};
+
+export default RdpPage;

+ 106 - 0
client/src/pages/RegisterPage.tsx

@@ -0,0 +1,106 @@
+import React, { useState } from 'react';
+import { Form, Input, Button, Card, Typography, message } from 'antd';
+import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons';
+import { Link, useNavigate } from 'react-router-dom';
+import api from '../api/axios';
+
+const { Title } = Typography;
+
+interface RegisterFormValues {
+  username: string;
+  password: string;
+  invitationCode: string;
+}
+
+interface RegisterResponse {
+  token: string;
+  user: { id: number; username: string; role: string };
+}
+
+const RegisterPage: React.FC = () => {
+  const navigate = useNavigate();
+  const [loading, setLoading] = useState(false);
+
+  const onFinish = async (values: RegisterFormValues) => {
+    setLoading(true);
+    try {
+      const { data } = await api.post<RegisterResponse>('/auth/register', values);
+      localStorage.setItem('token', data.token);
+      message.success('注册成功');
+      if (data.user.role === 'admin') {
+        navigate('/admin', { replace: true });
+      } else {
+        navigate('/dashboard', { replace: true });
+      }
+    } catch (err: unknown) {
+      const error = err as { response?: { data?: { error?: { message?: string }; message?: string } } };
+      const msg =
+        error.response?.data?.error?.message ??
+        error.response?.data?.message ??
+        '注册失败,请重试';
+      message.error(msg);
+    } finally {
+      setLoading(false);
+    }
+  };
+
+  return (
+    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh', background: '#f0f2f5' }}>
+      <Card style={{ width: 400 }}>
+        <Title level={3} style={{ textAlign: 'center', marginBottom: 24 }}>
+          注册账户
+        </Title>
+        <Form<RegisterFormValues> name="register" onFinish={onFinish} autoComplete="off">
+          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
+            <Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
+          </Form.Item>
+          <Form.Item
+            name="password"
+            rules={[
+              { required: true, message: '请输入密码' },
+              { min: 12, message: '密码长度至少 12 位' },
+              {
+                validator: (_, value) => {
+                  if (!value) return Promise.resolve();
+                  const cats = [/[A-Z]/, /[a-z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((r) => r.test(value)).length;
+                  if (cats < 2) return Promise.reject('密码需包含大写字母、小写字母、数字、特殊字符中的至少两种');
+                  return Promise.resolve();
+                },
+              },
+            ]}
+          >
+            <Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
+          </Form.Item>
+          <Form.Item
+            name="confirmPassword"
+            dependencies={['password']}
+            rules={[
+              { required: true, message: '请确认密码' },
+              ({ getFieldValue }) => ({
+                validator(_, value) {
+                  if (!value || getFieldValue('password') === value) return Promise.resolve();
+                  return Promise.reject('两次输入的密码不一致');
+                },
+              }),
+            ]}
+          >
+            <Input.Password prefix={<LockOutlined />} placeholder="确认密码" size="large" />
+          </Form.Item>
+          <Form.Item name="invitationCode" rules={[{ required: true, message: '请输入邀请码' }]}>
+            <Input prefix={<KeyOutlined />} placeholder="邀请码" size="large" />
+          </Form.Item>
+          <Form.Item>
+            <Button type="primary" htmlType="submit" loading={loading} block size="large">
+              注册
+            </Button>
+          </Form.Item>
+          <Form.Item style={{ marginBottom: 0, textAlign: 'center' }}>
+            已有账户? <Link to="/login">返回登录</Link>
+          </Form.Item>
+        </Form>
+      </Card>
+    </div>
+  );
+};
+
+export default RegisterPage;

+ 46 - 0
client/src/router.tsx

@@ -0,0 +1,46 @@
+import React from 'react';
+import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
+import LoginPage from './pages/LoginPage';
+import RegisterPage from './pages/RegisterPage';
+import DashboardPage from './pages/DashboardPage';
+import AdminPage from './pages/AdminPage';
+import RdpPage from './pages/RdpPage';
+import { ProtectedRoute, AdminRoute } from './components/RouteGuards';
+
+const AppRouter: React.FC = () => {
+  return (
+    <BrowserRouter>
+      <Routes>
+        <Route path="/login" element={<LoginPage />} />
+        <Route path="/register" element={<RegisterPage />} />
+        <Route
+          path="/dashboard"
+          element={
+            <ProtectedRoute>
+              <DashboardPage />
+            </ProtectedRoute>
+          }
+        />
+        <Route
+          path="/rdp/:instanceId"
+          element={
+            <ProtectedRoute>
+              <RdpPage />
+            </ProtectedRoute>
+          }
+        />
+        <Route
+          path="/admin"
+          element={
+            <AdminRoute>
+              <AdminPage />
+            </AdminRoute>
+          }
+        />
+        <Route path="/" element={<Navigate to="/login" replace />} />
+      </Routes>
+    </BrowserRouter>
+  );
+};
+
+export default AppRouter;

+ 119 - 0
client/src/types/guacamole-common-js.d.ts

@@ -0,0 +1,119 @@
+declare module 'guacamole-common-js' {
+  namespace Guacamole {
+    class Client {
+      constructor(tunnel: Tunnel);
+      connect(data?: string): void;
+      disconnect(): void;
+      getDisplay(): Display;
+      sendKeyEvent(pressed: number | boolean, keysym: number): void;
+      sendMouseState(state: Mouse.State): void;
+      createClipboardStream(mimetype: string): OutputStream;
+      onclipboard: ((stream: InputStream, mimetype: string) => void) | null;
+      onstatechange: ((state: number) => void) | null;
+      onerror: ((status: Status) => void) | null;
+      static State: {
+        IDLE: 0;
+        CONNECTING: 1;
+        WAITING: 2;
+        CONNECTED: 3;
+        DISCONNECTING: 4;
+        DISCONNECTED: 5;
+      };
+    }
+
+    class Display {
+      getElement(): HTMLElement;
+      getWidth(): number;
+      getHeight(): number;
+      scale(s: number): void;
+      getScale(): number;
+      onresize: ((width: number, height: number) => void) | null;
+    }
+
+    class Tunnel {
+      onerror: ((status: Status) => void) | null;
+      onstatechange: ((state: number) => void) | null;
+      state: number;
+      static State: {
+        CONNECTING: 0;
+        OPEN: 1;
+        CLOSED: 2;
+        UNSTABLE: 3;
+      };
+    }
+
+    class WebSocketTunnel extends Tunnel {
+      constructor(url: string);
+    }
+
+    class Mouse {
+      constructor(element: HTMLElement);
+      onmousedown: ((state: Mouse.State) => void) | null;
+      onmouseup: ((state: Mouse.State) => void) | null;
+      onmousemove: ((state: Mouse.State) => void) | null;
+    }
+
+    namespace Mouse {
+      class State {
+        x: number;
+        y: number;
+        left: boolean;
+        middle: boolean;
+        right: boolean;
+        up: boolean;
+        down: boolean;
+      }
+
+      class Touchpad {
+        constructor(element: HTMLElement);
+        onmousedown: ((state: Mouse.State) => void) | null;
+        onmouseup: ((state: Mouse.State) => void) | null;
+        onmousemove: ((state: Mouse.State) => void) | null;
+      }
+
+      class Touchscreen {
+        constructor(element: HTMLElement);
+        onmousedown: ((state: Mouse.State) => void) | null;
+        onmouseup: ((state: Mouse.State) => void) | null;
+        onmousemove: ((state: Mouse.State) => void) | null;
+      }
+    }
+
+    class Keyboard {
+      constructor(element: HTMLElement | Document);
+      onkeydown: ((keysym: number) => boolean | void) | null;
+      onkeyup: ((keysym: number) => void) | null;
+    }
+
+    class InputStream {
+      onblob: ((data: string) => void) | null;
+      onend: (() => void) | null;
+    }
+
+    class OutputStream {
+      sendBlob(data: string): void;
+      sendEnd(): void;
+    }
+
+    class StringReader {
+      constructor(stream: InputStream);
+      ontext: ((text: string) => void) | null;
+      onend: (() => void) | null;
+    }
+
+    class StringWriter {
+      constructor(stream: OutputStream);
+      sendText(text: string): void;
+      sendEnd(): void;
+    }
+
+    class Status {
+      code: number;
+      message?: string;
+      isError(): boolean;
+      static Code: Record<string, number>;
+    }
+  }
+
+  export default Guacamole;
+}

+ 53 - 0
client/src/utils/auth.ts

@@ -0,0 +1,53 @@
+/**
+ * Auth utilities for JWT token parsing and role checking.
+ * Decodes the JWT payload without verification (verification is done server-side).
+ */
+
+interface JwtPayload {
+  id: number;
+  username: string;
+  role: string;
+  iat?: number;
+  exp?: number;
+}
+
+export function getToken(): string | null {
+  return localStorage.getItem('token');
+}
+
+export function isLoggedIn(): boolean {
+  const token = getToken();
+  if (!token) return false;
+  const payload = parseJwt(token);
+  if (!payload) return false;
+  // Check expiration
+  if (payload.exp && payload.exp * 1000 < Date.now()) {
+    localStorage.removeItem('token');
+    return false;
+  }
+  return true;
+}
+
+export function getUserRole(): string | null {
+  const token = getToken();
+  if (!token) return null;
+  const payload = parseJwt(token);
+  return payload?.role ?? null;
+}
+
+function parseJwt(token: string): JwtPayload | null {
+  try {
+    const base64Url = token.split('.')[1];
+    if (!base64Url) return null;
+    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
+    const jsonPayload = decodeURIComponent(
+      atob(base64)
+        .split('')
+        .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
+        .join(''),
+    );
+    return JSON.parse(jsonPayload);
+  } catch {
+    return null;
+  }
+}

+ 29 - 0
client/tsconfig.json

@@ -0,0 +1,29 @@
+{
+  "compilerOptions": {
+    "target": "ES2023",
+    "useDefineForClassFields": true,
+    "module": "ESNext",
+    "lib": ["ES2023", "DOM", "DOM.Iterable"],
+    "types": ["vite/client"],
+    "skipLibCheck": true,
+
+    /* Bundler mode */
+    "moduleResolution": "bundler",
+    "allowImportingTsExtensions": true,
+    "verbatimModuleSyntax": true,
+    "moduleDetection": "force",
+    "noEmit": true,
+
+    /* JSX */
+    "jsx": "react-jsx",
+
+    /* Linting */
+    "strict": true,
+    "noUnusedLocals": true,
+    "noUnusedParameters": true,
+    "erasableSyntaxOnly": true,
+    "noFallthroughCasesInSwitch": true,
+    "noUncheckedSideEffectImports": true
+  },
+  "include": ["src"]
+}

+ 18 - 0
client/vite.config.ts

@@ -0,0 +1,18 @@
+import { defineConfig } from 'vite';
+import react from '@vitejs/plugin-react';
+
+export default defineConfig({
+  plugins: [react()],
+  server: {
+    proxy: {
+      '/api': {
+        target: 'http://localhost:3000',
+        changeOrigin: true,
+      },
+      '/ws/rdp': {
+        target: 'ws://localhost:3000',
+        ws: true,
+      },
+    },
+  },
+});

+ 5824 - 0
server/package-lock.json

@@ -0,0 +1,5824 @@
+{
+  "name": "ec2-management-server",
+  "version": "1.0.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "ec2-management-server",
+      "version": "1.0.0",
+      "dependencies": {
+        "@aws-sdk/client-ec2": "^3.700.0",
+        "@aws-sdk/client-sts": "^3.1020.0",
+        "bcrypt": "^5.1.1",
+        "better-sqlite3": "^11.7.0",
+        "cors": "^2.8.5",
+        "dotenv": "^16.4.7",
+        "express": "^4.21.1",
+        "guacamole-lite": "^1.2.0",
+        "jsonwebtoken": "^9.0.2",
+        "node-cron": "^3.0.3"
+      },
+      "devDependencies": {
+        "@types/bcrypt": "^5.0.2",
+        "@types/better-sqlite3": "^7.6.12",
+        "@types/cors": "^2.8.17",
+        "@types/express": "^5.0.0",
+        "@types/jsonwebtoken": "^9.0.7",
+        "@types/node": "^22.10.0",
+        "@types/node-cron": "^3.0.11",
+        "@types/supertest": "^7.2.0",
+        "fast-check": "^3.23.1",
+        "supertest": "^7.2.2",
+        "tsx": "^4.21.0",
+        "typescript": "^5.7.2",
+        "vitest": "^2.1.8"
+      }
+    },
+    "node_modules/@aws-crypto/sha256-browser": {
+      "version": "5.2.0",
+      "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz",
+      "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-crypto/sha256-js": "^5.2.0",
+        "@aws-crypto/supports-web-crypto": "^5.2.0",
+        "@aws-crypto/util": "^5.2.0",
+        "@aws-sdk/types": "^3.222.0",
+        "@aws-sdk/util-locate-window": "^3.0.0",
+        "@smithy/util-utf8": "^2.0.0",
+        "tslib": "^2.6.2"
+      }
+    },
+    "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz",
+      "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz",
+      "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/is-array-buffer": "^2.2.0",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": {
+      "version": "2.3.0",
+      "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",
+      "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/util-buffer-from": "^2.2.0",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@aws-crypto/sha256-js": {
+      "version": "5.2.0",
+      "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz",
+      "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-crypto/util": "^5.2.0",
+        "@aws-sdk/types": "^3.222.0",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=16.0.0"
+      }
+    },
+    "node_modules/@aws-crypto/supports-web-crypto": {
+      "version": "5.2.0",
+      "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz",
+      "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      }
+    },
+    "node_modules/@aws-crypto/util": {
+      "version": "5.2.0",
+      "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz",
+      "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.222.0",
+        "@smithy/util-utf8": "^2.0.0",
+        "tslib": "^2.6.2"
+      }
+    },
+    "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz",
+      "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz",
+      "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/is-array-buffer": "^2.2.0",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": {
+      "version": "2.3.0",
+      "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",
+      "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/util-buffer-from": "^2.2.0",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/client-ec2": {
+      "version": "3.1020.0",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/client-ec2/-/client-ec2-3.1020.0.tgz",
+      "integrity": "sha512-lAqyx2RtaYv/jVhYhwjr0GH3UjtkjVzqe+GT3o/DEX+QtYpUEbB2wq4TJPpBSfOD93P5OgpXlQ4YQtqphcOyrw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-crypto/sha256-browser": "5.2.0",
+        "@aws-crypto/sha256-js": "5.2.0",
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/credential-provider-node": "^3.972.28",
+        "@aws-sdk/middleware-host-header": "^3.972.8",
+        "@aws-sdk/middleware-logger": "^3.972.8",
+        "@aws-sdk/middleware-recursion-detection": "^3.972.9",
+        "@aws-sdk/middleware-sdk-ec2": "^3.972.18",
+        "@aws-sdk/middleware-user-agent": "^3.972.27",
+        "@aws-sdk/region-config-resolver": "^3.972.10",
+        "@aws-sdk/types": "^3.973.6",
+        "@aws-sdk/util-endpoints": "^3.996.5",
+        "@aws-sdk/util-user-agent-browser": "^3.972.8",
+        "@aws-sdk/util-user-agent-node": "^3.973.13",
+        "@smithy/config-resolver": "^4.4.13",
+        "@smithy/core": "^3.23.13",
+        "@smithy/fetch-http-handler": "^5.3.15",
+        "@smithy/hash-node": "^4.2.12",
+        "@smithy/invalid-dependency": "^4.2.12",
+        "@smithy/middleware-content-length": "^4.2.12",
+        "@smithy/middleware-endpoint": "^4.4.28",
+        "@smithy/middleware-retry": "^4.4.45",
+        "@smithy/middleware-serde": "^4.2.16",
+        "@smithy/middleware-stack": "^4.2.12",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/node-http-handler": "^4.5.1",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "@smithy/util-base64": "^4.3.2",
+        "@smithy/util-body-length-browser": "^4.2.2",
+        "@smithy/util-body-length-node": "^4.2.3",
+        "@smithy/util-defaults-mode-browser": "^4.3.44",
+        "@smithy/util-defaults-mode-node": "^4.2.48",
+        "@smithy/util-endpoints": "^3.3.3",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-retry": "^4.2.12",
+        "@smithy/util-utf8": "^4.2.2",
+        "@smithy/util-waiter": "^4.2.14",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/client-sts": {
+      "version": "3.1020.0",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.1020.0.tgz",
+      "integrity": "sha512-dTl2jo7iufOoRCw/8qpiS85bbBFv7Avj6hIYBawT/LGn+61KydUDWhQpD9c3ChVB2arrnrWWOUiA1J7hRk/VwQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-crypto/sha256-browser": "5.2.0",
+        "@aws-crypto/sha256-js": "5.2.0",
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/credential-provider-node": "^3.972.28",
+        "@aws-sdk/middleware-host-header": "^3.972.8",
+        "@aws-sdk/middleware-logger": "^3.972.8",
+        "@aws-sdk/middleware-recursion-detection": "^3.972.9",
+        "@aws-sdk/middleware-user-agent": "^3.972.27",
+        "@aws-sdk/region-config-resolver": "^3.972.10",
+        "@aws-sdk/types": "^3.973.6",
+        "@aws-sdk/util-endpoints": "^3.996.5",
+        "@aws-sdk/util-user-agent-browser": "^3.972.8",
+        "@aws-sdk/util-user-agent-node": "^3.973.13",
+        "@smithy/config-resolver": "^4.4.13",
+        "@smithy/core": "^3.23.13",
+        "@smithy/fetch-http-handler": "^5.3.15",
+        "@smithy/hash-node": "^4.2.12",
+        "@smithy/invalid-dependency": "^4.2.12",
+        "@smithy/middleware-content-length": "^4.2.12",
+        "@smithy/middleware-endpoint": "^4.4.28",
+        "@smithy/middleware-retry": "^4.4.45",
+        "@smithy/middleware-serde": "^4.2.16",
+        "@smithy/middleware-stack": "^4.2.12",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/node-http-handler": "^4.5.1",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "@smithy/util-base64": "^4.3.2",
+        "@smithy/util-body-length-browser": "^4.2.2",
+        "@smithy/util-body-length-node": "^4.2.3",
+        "@smithy/util-defaults-mode-browser": "^4.3.44",
+        "@smithy/util-defaults-mode-node": "^4.2.48",
+        "@smithy/util-endpoints": "^3.3.3",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-retry": "^4.2.12",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/core": {
+      "version": "3.973.26",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.973.26.tgz",
+      "integrity": "sha512-A/E6n2W42ruU+sfWk+mMUOyVXbsSgGrY3MJ9/0Az5qUdG67y8I6HYzzoAa+e/lzxxl1uCYmEL6BTMi9ZiZnplQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@aws-sdk/xml-builder": "^3.972.16",
+        "@smithy/core": "^3.23.13",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/signature-v4": "^5.3.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-base64": "^4.3.2",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-env": {
+      "version": "3.972.24",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.24.tgz",
+      "integrity": "sha512-FWg8uFmT6vQM7VuzELzwVo5bzExGaKHdubn0StjgrcU5FvuLExUe+k06kn/40uKv59rYzhez8eFNM4yYE/Yb/w==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-http": {
+      "version": "3.972.26",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.26.tgz",
+      "integrity": "sha512-CY4ppZ+qHYqcXqBVi//sdHST1QK3KzOEiLtpLsc9W2k2vfZPKExGaQIsOwcyvjpjUEolotitmd3mUNY56IwDEA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/fetch-http-handler": "^5.3.15",
+        "@smithy/node-http-handler": "^4.5.1",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-stream": "^4.5.21",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-ini": {
+      "version": "3.972.27",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.27.tgz",
+      "integrity": "sha512-Um26EsNSUfVUX0wUXnUA1W3wzKhVy6nviEElsh5lLZUYj9bk6DXOPnpte0gt+WHubcVfVsRk40bbm4KaroTEag==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/credential-provider-env": "^3.972.24",
+        "@aws-sdk/credential-provider-http": "^3.972.26",
+        "@aws-sdk/credential-provider-login": "^3.972.27",
+        "@aws-sdk/credential-provider-process": "^3.972.24",
+        "@aws-sdk/credential-provider-sso": "^3.972.27",
+        "@aws-sdk/credential-provider-web-identity": "^3.972.27",
+        "@aws-sdk/nested-clients": "^3.996.17",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/credential-provider-imds": "^4.2.12",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-login": {
+      "version": "3.972.27",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.27.tgz",
+      "integrity": "sha512-t3ehEtHomGZwg5Gixw4fYbYtG9JBnjfAjSDabxhPEu/KLLUp0BB37/APX7MSKXQhX6ZH7pseuACFJ19NrAkNdg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/nested-clients": "^3.996.17",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-node": {
+      "version": "3.972.28",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.28.tgz",
+      "integrity": "sha512-rren+P6k5rShG5PX61iVi40kKdueyuMLBRTctQbyR5LooO9Ygr5L6R7ilG7RF1957NSH3KC3TU206fZuKwjSpQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/credential-provider-env": "^3.972.24",
+        "@aws-sdk/credential-provider-http": "^3.972.26",
+        "@aws-sdk/credential-provider-ini": "^3.972.27",
+        "@aws-sdk/credential-provider-process": "^3.972.24",
+        "@aws-sdk/credential-provider-sso": "^3.972.27",
+        "@aws-sdk/credential-provider-web-identity": "^3.972.27",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/credential-provider-imds": "^4.2.12",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-process": {
+      "version": "3.972.24",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.24.tgz",
+      "integrity": "sha512-Q2k/XLrFXhEztPHqj4SLCNID3hEPdlhh1CDLBpNnM+1L8fq7P+yON9/9M1IGN/dA5W45v44ylERfXtDAlmMNmw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-sso": {
+      "version": "3.972.27",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.27.tgz",
+      "integrity": "sha512-CWXeGjlbBuHcm9appZUgXKP2zHDyTti0/+gXpSFJ2J3CnSwf1KWjicjN0qG2ozkMH6blrrzMrimeIOEYNl238Q==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/nested-clients": "^3.996.17",
+        "@aws-sdk/token-providers": "3.1020.0",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/credential-provider-web-identity": {
+      "version": "3.972.27",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.27.tgz",
+      "integrity": "sha512-CUY4hQIFswdQNEsRGEzGBUKGMK5KpqmNDdu2ROMgI+45PLFS8H0y3Tm7kvM16uvvw3n1pVxk85tnRVUTgtaa1w==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/nested-clients": "^3.996.17",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/middleware-host-header": {
+      "version": "3.972.8",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.972.8.tgz",
+      "integrity": "sha512-wAr2REfKsqoKQ+OkNqvOShnBoh+nkPurDKW7uAeVSu6kUECnWlSJiPvnoqxGlfousEY/v9LfS9sNc46hjSYDIQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/middleware-logger": {
+      "version": "3.972.8",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.972.8.tgz",
+      "integrity": "sha512-CWl5UCM57WUFaFi5kB7IBY1UmOeLvNZAZ2/OZ5l20ldiJ3TiIz1pC65gYj8X0BCPWkeR1E32mpsCk1L1I4n+lA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/middleware-recursion-detection": {
+      "version": "3.972.9",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.972.9.tgz",
+      "integrity": "sha512-/Wt5+CT8dpTFQxEJ9iGy/UGrXr7p2wlIOEHvIr/YcHYByzoLjrqkYqXdJjd9UIgWjv7eqV2HnFJen93UTuwfTQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@aws/lambda-invoke-store": "^0.2.2",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/middleware-sdk-ec2": {
+      "version": "3.972.18",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-ec2/-/middleware-sdk-ec2-3.972.18.tgz",
+      "integrity": "sha512-ZbZlOxCRHm9mQSWcQuaZZ3KoV5+XiyHmq6m4sKDfVsD8SQ1XblacJPyNJzNkDB9Do4pO+J5FPj/nvSj+zVn7Mw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@aws-sdk/util-format-url": "^3.972.8",
+        "@smithy/middleware-endpoint": "^4.4.28",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/signature-v4": "^5.3.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/middleware-user-agent": {
+      "version": "3.972.27",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.972.27.tgz",
+      "integrity": "sha512-TIRLO5UR2+FVUGmhYoAwVkKhcVzywEDX/5LzR9tjy1h8FQAXOtFg2IqgmwvxU7y933rkTn9rl6AdgcAUgQ1/Kg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/types": "^3.973.6",
+        "@aws-sdk/util-endpoints": "^3.996.5",
+        "@smithy/core": "^3.23.13",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-retry": "^4.2.12",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/nested-clients": {
+      "version": "3.996.17",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.996.17.tgz",
+      "integrity": "sha512-7B0HIX0tEFmOSJuWzdHZj1WhMXSryM+h66h96ZkqSncoY7J6wq61KOu4Kr57b/YnJP3J/EeQYVFulgR281h+7A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-crypto/sha256-browser": "5.2.0",
+        "@aws-crypto/sha256-js": "5.2.0",
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/middleware-host-header": "^3.972.8",
+        "@aws-sdk/middleware-logger": "^3.972.8",
+        "@aws-sdk/middleware-recursion-detection": "^3.972.9",
+        "@aws-sdk/middleware-user-agent": "^3.972.27",
+        "@aws-sdk/region-config-resolver": "^3.972.10",
+        "@aws-sdk/types": "^3.973.6",
+        "@aws-sdk/util-endpoints": "^3.996.5",
+        "@aws-sdk/util-user-agent-browser": "^3.972.8",
+        "@aws-sdk/util-user-agent-node": "^3.973.13",
+        "@smithy/config-resolver": "^4.4.13",
+        "@smithy/core": "^3.23.13",
+        "@smithy/fetch-http-handler": "^5.3.15",
+        "@smithy/hash-node": "^4.2.12",
+        "@smithy/invalid-dependency": "^4.2.12",
+        "@smithy/middleware-content-length": "^4.2.12",
+        "@smithy/middleware-endpoint": "^4.4.28",
+        "@smithy/middleware-retry": "^4.4.45",
+        "@smithy/middleware-serde": "^4.2.16",
+        "@smithy/middleware-stack": "^4.2.12",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/node-http-handler": "^4.5.1",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "@smithy/util-base64": "^4.3.2",
+        "@smithy/util-body-length-browser": "^4.2.2",
+        "@smithy/util-body-length-node": "^4.2.3",
+        "@smithy/util-defaults-mode-browser": "^4.3.44",
+        "@smithy/util-defaults-mode-node": "^4.2.48",
+        "@smithy/util-endpoints": "^3.3.3",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-retry": "^4.2.12",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/region-config-resolver": {
+      "version": "3.972.10",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.972.10.tgz",
+      "integrity": "sha512-1dq9ToC6e070QvnVhhbAs3bb5r6cQ10gTVc6cyRV5uvQe7P138TV2uG2i6+Yok4bAkVAcx5AqkTEBUvWEtBlsQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/config-resolver": "^4.4.13",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/token-providers": {
+      "version": "3.1020.0",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1020.0.tgz",
+      "integrity": "sha512-T61KA/VKl0zVUubdxigr1ut7SEpwE1/4CIKb14JDLyTAOne2yWKtQE1dDCSHl0UqrZNwW/bTt+EBHfQbslZJdw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/core": "^3.973.26",
+        "@aws-sdk/nested-clients": "^3.996.17",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/types": {
+      "version": "3.973.6",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.6.tgz",
+      "integrity": "sha512-Atfcy4E++beKtwJHiDln2Nby8W/mam64opFPTiHEqgsthqeydFS1pY+OUlN1ouNOmf8ArPU/6cDS65anOP3KQw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/util-endpoints": {
+      "version": "3.996.5",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.996.5.tgz",
+      "integrity": "sha512-Uh93L5sXFNbyR5sEPMzUU8tJ++Ku97EY4udmC01nB8Zu+xfBPwpIwJ6F7snqQeq8h2pf+8SGN5/NoytfKgYPIw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "@smithy/util-endpoints": "^3.3.3",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/util-format-url": {
+      "version": "3.972.8",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/util-format-url/-/util-format-url-3.972.8.tgz",
+      "integrity": "sha512-J6DS9oocrgxM8xlUTTmQOuwRF6rnAGEujAN9SAzllcrQmwn5iJ58ogxy3SEhD0Q7JZvlA5jvIXBkpQRqEqlE9A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/querystring-builder": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/util-locate-window": {
+      "version": "3.965.5",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.5.tgz",
+      "integrity": "sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws-sdk/util-user-agent-browser": {
+      "version": "3.972.8",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.972.8.tgz",
+      "integrity": "sha512-B3KGXJviV2u6Cdw2SDY2aDhoJkVfY/Q/Trwk2CMSkikE1Oi6gRzxhvhIfiRpHfmIsAhV4EA54TVEX8K6CbHbkA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/types": "^4.13.1",
+        "bowser": "^2.11.0",
+        "tslib": "^2.6.2"
+      }
+    },
+    "node_modules/@aws-sdk/util-user-agent-node": {
+      "version": "3.973.13",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.973.13.tgz",
+      "integrity": "sha512-s1dCJ0J9WU9UPkT3FFqhKTSquYTkqWXGRaapHFyWwwJH86ZussewhNST5R5TwXVL1VSHq4aJVl9fWK+svaRVCQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@aws-sdk/middleware-user-agent": "^3.972.27",
+        "@aws-sdk/types": "^3.973.6",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-config-provider": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      },
+      "peerDependencies": {
+        "aws-crt": ">=1.0.0"
+      },
+      "peerDependenciesMeta": {
+        "aws-crt": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@aws-sdk/xml-builder": {
+      "version": "3.972.16",
+      "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.16.tgz",
+      "integrity": "sha512-iu2pyvaqmeatIJLURLqx9D+4jKAdTH20ntzB6BFwjyN7V960r4jK32mx0Zf7YbtOYAbmbtQfDNuL60ONinyw7A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "fast-xml-parser": "5.5.8",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=20.0.0"
+      }
+    },
+    "node_modules/@aws/lambda-invoke-store": {
+      "version": "0.2.4",
+      "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.4.tgz",
+      "integrity": "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==",
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@esbuild/aix-ppc64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+      "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/android-arm": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+      "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/android-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+      "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/android-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+      "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/darwin-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+      "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/darwin-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+      "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/freebsd-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+      "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/freebsd-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+      "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-arm": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+      "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+      "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-ia32": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+      "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-loong64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+      "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-mips64el": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+      "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-ppc64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+      "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-riscv64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+      "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-s390x": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+      "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/linux-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+      "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/netbsd-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz",
+      "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/netbsd-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+      "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/openbsd-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz",
+      "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/openbsd-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+      "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/openharmony-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz",
+      "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@esbuild/sunos-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+      "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/win32-arm64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+      "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/win32-ia32": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+      "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@esbuild/win32-x64": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+      "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/@jridgewell/sourcemap-codec": {
+      "version": "1.5.5",
+      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+      "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@mapbox/node-pre-gyp": {
+      "version": "1.0.11",
+      "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
+      "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "detect-libc": "^2.0.0",
+        "https-proxy-agent": "^5.0.0",
+        "make-dir": "^3.1.0",
+        "node-fetch": "^2.6.7",
+        "nopt": "^5.0.0",
+        "npmlog": "^5.0.1",
+        "rimraf": "^3.0.2",
+        "semver": "^7.3.5",
+        "tar": "^6.1.11"
+      },
+      "bin": {
+        "node-pre-gyp": "bin/node-pre-gyp"
+      }
+    },
+    "node_modules/@noble/hashes": {
+      "version": "1.8.0",
+      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
+      "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^14.21.3 || >=16"
+      },
+      "funding": {
+        "url": "https://paulmillr.com/funding/"
+      }
+    },
+    "node_modules/@paralleldrive/cuid2": {
+      "version": "2.3.1",
+      "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz",
+      "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@noble/hashes": "^1.1.5"
+      }
+    },
+    "node_modules/@rollup/rollup-android-arm-eabi": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz",
+      "integrity": "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ]
+    },
+    "node_modules/@rollup/rollup-android-arm64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz",
+      "integrity": "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ]
+    },
+    "node_modules/@rollup/rollup-darwin-arm64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz",
+      "integrity": "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ]
+    },
+    "node_modules/@rollup/rollup-darwin-x64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz",
+      "integrity": "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ]
+    },
+    "node_modules/@rollup/rollup-freebsd-arm64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz",
+      "integrity": "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ]
+    },
+    "node_modules/@rollup/rollup-freebsd-x64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz",
+      "integrity": "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz",
+      "integrity": "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz",
+      "integrity": "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm64-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz",
+      "integrity": "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-arm64-musl": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz",
+      "integrity": "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-loong64-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz",
+      "integrity": "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-loong64-musl": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz",
+      "integrity": "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz",
+      "integrity": "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-ppc64-musl": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz",
+      "integrity": "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz",
+      "integrity": "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-riscv64-musl": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz",
+      "integrity": "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-s390x-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz",
+      "integrity": "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-x64-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz",
+      "integrity": "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-linux-x64-musl": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz",
+      "integrity": "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ]
+    },
+    "node_modules/@rollup/rollup-openbsd-x64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz",
+      "integrity": "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ]
+    },
+    "node_modules/@rollup/rollup-openharmony-arm64": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz",
+      "integrity": "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openharmony"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-arm64-msvc": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz",
+      "integrity": "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-ia32-msvc": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz",
+      "integrity": "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-x64-gnu": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz",
+      "integrity": "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@rollup/rollup-win32-x64-msvc": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz",
+      "integrity": "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ]
+    },
+    "node_modules/@smithy/config-resolver": {
+      "version": "4.4.13",
+      "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.4.13.tgz",
+      "integrity": "sha512-iIzMC5NmOUP6WL6o8iPBjFhUhBZ9pPjpUpQYWMUFQqKyXXzOftbfK8zcQCz/jFV1Psmf05BK5ypx4K2r4Tnwdg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-config-provider": "^4.2.2",
+        "@smithy/util-endpoints": "^3.3.3",
+        "@smithy/util-middleware": "^4.2.12",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/core": {
+      "version": "3.23.13",
+      "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.23.13.tgz",
+      "integrity": "sha512-J+2TT9D6oGsUVXVEMvz8h2EmdVnkBiy2auCie4aSJMvKlzUtO5hqjEzXhoCUkIMo7gAYjbQcN0g/MMSXEhDs1Q==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "@smithy/util-base64": "^4.3.2",
+        "@smithy/util-body-length-browser": "^4.2.2",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-stream": "^4.5.21",
+        "@smithy/util-utf8": "^4.2.2",
+        "@smithy/uuid": "^1.1.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/credential-provider-imds": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.2.12.tgz",
+      "integrity": "sha512-cr2lR792vNZcYMriSIj+Um3x9KWrjcu98kn234xA6reOAFMmbRpQMOv8KPgEmLLtx3eldU6c5wALKFqNOhugmg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/fetch-http-handler": {
+      "version": "5.3.15",
+      "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.3.15.tgz",
+      "integrity": "sha512-T4jFU5N/yiIfrtrsb9uOQn7RdELdM/7HbyLNr6uO/mpkj1ctiVs7CihVr51w4LyQlXWDpXFn4BElf1WmQvZu/A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/querystring-builder": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-base64": "^4.3.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/hash-node": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.2.12.tgz",
+      "integrity": "sha512-QhBYbGrbxTkZ43QoTPrK72DoYviDeg6YKDrHTMJbbC+A0sml3kSjzFtXP7BtbyJnXojLfTQldGdUR0RGD8dA3w==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-buffer-from": "^4.2.2",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/invalid-dependency": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.2.12.tgz",
+      "integrity": "sha512-/4F1zb7Z8LOu1PalTdESFHR0RbPwHd3FcaG1sI3UEIriQTWakysgJr65lc1jj6QY5ye7aFsisajotH6UhWfm/g==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/is-array-buffer": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.2.tgz",
+      "integrity": "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/middleware-content-length": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.2.12.tgz",
+      "integrity": "sha512-YE58Yz+cvFInWI/wOTrB+DbvUVz/pLn5mC5MvOV4fdRUc6qGwygyngcucRQjAhiCEbmfLOXX0gntSIcgMvAjmA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/middleware-endpoint": {
+      "version": "4.4.28",
+      "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.4.28.tgz",
+      "integrity": "sha512-p1gfYpi91CHcs5cBq982UlGlDrxoYUX6XdHSo91cQ2KFuz6QloHosO7Jc60pJiVmkWrKOV8kFYlGFFbQ2WUKKQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/core": "^3.23.13",
+        "@smithy/middleware-serde": "^4.2.16",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "@smithy/url-parser": "^4.2.12",
+        "@smithy/util-middleware": "^4.2.12",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/middleware-retry": {
+      "version": "4.4.45",
+      "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.4.45.tgz",
+      "integrity": "sha512-td1PxpwDIaw5/oP/xIRxBGxJKoF1L4DBAwbZ8wjMuXBYOP/r2ZE/Ocou+mBHx/yk9knFEtDBwhSrYVn+Mz4pHw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/service-error-classification": "^4.2.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-retry": "^4.2.12",
+        "@smithy/uuid": "^1.1.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/middleware-serde": {
+      "version": "4.2.16",
+      "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.2.16.tgz",
+      "integrity": "sha512-beqfV+RZ9RSv+sQqor3xroUUYgRFCGRw6niGstPG8zO9LgTl0B0MCucxjmrH/2WwksQN7UUgI7KNANoZv+KALA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/core": "^3.23.13",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/middleware-stack": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.2.12.tgz",
+      "integrity": "sha512-kruC5gRHwsCOuyCd4ouQxYjgRAym2uDlCvQ5acuMtRrcdfg7mFBg6blaxcJ09STpt3ziEkis6bhg1uwrWU7txw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/node-config-provider": {
+      "version": "4.3.12",
+      "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.12.tgz",
+      "integrity": "sha512-tr2oKX2xMcO+rBOjobSwVAkV05SIfUKz8iI53rzxEmgW3GOOPOv0UioSDk+J8OpRQnpnhsO3Af6IEBabQBVmiw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/shared-ini-file-loader": "^4.4.7",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/node-http-handler": {
+      "version": "4.5.1",
+      "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.5.1.tgz",
+      "integrity": "sha512-ejjxdAXjkPIs9lyYyVutOGNOraqUE9v/NjGMKwwFrfOM354wfSD8lmlj8hVwUzQmlLLF4+udhfCX9Exnbmvfzw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/querystring-builder": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/property-provider": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.12.tgz",
+      "integrity": "sha512-jqve46eYU1v7pZ5BM+fmkbq3DerkSluPr5EhvOcHxygxzD05ByDRppRwRPPpFrsFo5yDtCYLKu+kreHKVrvc7A==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/protocol-http": {
+      "version": "5.3.12",
+      "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.12.tgz",
+      "integrity": "sha512-fit0GZK9I1xoRlR4jXmbLhoN0OdEpa96ul8M65XdmXnxXkuMxM0Y8HDT0Fh0Xb4I85MBvBClOzgSrV1X2s1Hxw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/querystring-builder": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.2.12.tgz",
+      "integrity": "sha512-6wTZjGABQufekycfDGMEB84BgtdOE/rCVTov+EDXQ8NHKTUNIp/j27IliwP7tjIU9LR+sSzyGBOXjeEtVgzCHg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-uri-escape": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/querystring-parser": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.2.12.tgz",
+      "integrity": "sha512-P2OdvrgiAKpkPNKlKUtWbNZKB1XjPxM086NeVhK+W+wI46pIKdWBe5QyXvhUm3MEcyS/rkLvY8rZzyUdmyDZBw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/service-error-classification": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.2.12.tgz",
+      "integrity": "sha512-LlP29oSQN0Tw0b6D0Xo6BIikBswuIiGYbRACy5ujw/JgWSzTdYj46U83ssf6Ux0GyNJVivs2uReU8pt7Eu9okQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/shared-ini-file-loader": {
+      "version": "4.4.7",
+      "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.4.7.tgz",
+      "integrity": "sha512-HrOKWsUb+otTeo1HxVWeEb99t5ER1XrBi/xka2Wv6NVmTbuCUC1dvlrksdvxFtODLBjsC+PHK+fuy2x/7Ynyiw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/signature-v4": {
+      "version": "5.3.12",
+      "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.3.12.tgz",
+      "integrity": "sha512-B/FBwO3MVOL00DaRSXfXfa/TRXRheagt/q5A2NM13u7q+sHS59EOVGQNfG7DkmVtdQm5m3vOosoKAXSqn/OEgw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/is-array-buffer": "^4.2.2",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-hex-encoding": "^4.2.2",
+        "@smithy/util-middleware": "^4.2.12",
+        "@smithy/util-uri-escape": "^4.2.2",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/smithy-client": {
+      "version": "4.12.8",
+      "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.12.8.tgz",
+      "integrity": "sha512-aJaAX7vHe5i66smoSSID7t4rKY08PbD8EBU7DOloixvhOozfYWdcSYE4l6/tjkZ0vBZhGjheWzB2mh31sLgCMA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/core": "^3.23.13",
+        "@smithy/middleware-endpoint": "^4.4.28",
+        "@smithy/middleware-stack": "^4.2.12",
+        "@smithy/protocol-http": "^5.3.12",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-stream": "^4.5.21",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/types": {
+      "version": "4.13.1",
+      "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.13.1.tgz",
+      "integrity": "sha512-787F3yzE2UiJIQ+wYW1CVg2odHjmaWLGksnKQHUrK/lYZSEcy1msuLVvxaR/sI2/aDe9U+TBuLsXnr3vod1g0g==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/url-parser": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.2.12.tgz",
+      "integrity": "sha512-wOPKPEpso+doCZGIlr+e1lVI6+9VAKfL4kZWFgzVgGWY2hZxshNKod4l2LXS3PRC9otH/JRSjtEHqQ/7eLciRA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/querystring-parser": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-base64": {
+      "version": "4.3.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.2.tgz",
+      "integrity": "sha512-XRH6b0H/5A3SgblmMa5ErXQ2XKhfbQB+Fm/oyLZ2O2kCUrwgg55bU0RekmzAhuwOjA9qdN5VU2BprOvGGUkOOQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/util-buffer-from": "^4.2.2",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-body-length-browser": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.2.2.tgz",
+      "integrity": "sha512-JKCrLNOup3OOgmzeaKQwi4ZCTWlYR5H4Gm1r2uTMVBXoemo1UEghk5vtMi1xSu2ymgKVGW631e2fp9/R610ZjQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-body-length-node": {
+      "version": "4.2.3",
+      "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.2.3.tgz",
+      "integrity": "sha512-ZkJGvqBzMHVHE7r/hcuCxlTY8pQr1kMtdsVPs7ex4mMU+EAbcXppfo5NmyxMYi2XU49eqaz56j2gsk4dHHPG/g==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-buffer-from": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.2.tgz",
+      "integrity": "sha512-FDXD7cvUoFWwN6vtQfEta540Y/YBe5JneK3SoZg9bThSoOAC/eGeYEua6RkBgKjGa/sz6Y+DuBZj3+YEY21y4Q==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/is-array-buffer": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-config-provider": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.2.2.tgz",
+      "integrity": "sha512-dWU03V3XUprJwaUIFVv4iOnS1FC9HnMHDfUrlNDSh4315v0cWyaIErP8KiqGVbf5z+JupoVpNM7ZB3jFiTejvQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-defaults-mode-browser": {
+      "version": "4.3.44",
+      "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.3.44.tgz",
+      "integrity": "sha512-eZg6XzaCbVr2S5cAErU5eGBDaOVTuTo1I65i4tQcHENRcZ8rMWhQy1DaIYUSLyZjsfXvmCqZrstSMYyGFocvHA==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-defaults-mode-node": {
+      "version": "4.2.48",
+      "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.2.48.tgz",
+      "integrity": "sha512-FqOKTlqSaoV3nzO55pMs5NBnZX8EhoI0DGmn9kbYeXWppgHD6dchyuj2HLqp4INJDJbSrj6OFYJkAh/WhSzZPg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/config-resolver": "^4.4.13",
+        "@smithy/credential-provider-imds": "^4.2.12",
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/property-provider": "^4.2.12",
+        "@smithy/smithy-client": "^4.12.8",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-endpoints": {
+      "version": "3.3.3",
+      "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.3.3.tgz",
+      "integrity": "sha512-VACQVe50j0HZPjpwWcjyT51KUQ4AnsvEaQ2lKHOSL4mNLD0G9BjEniQ+yCt1qqfKfiAHRAts26ud7hBjamrwig==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/node-config-provider": "^4.3.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-hex-encoding": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.2.tgz",
+      "integrity": "sha512-Qcz3W5vuHK4sLQdyT93k/rfrUwdJ8/HZ+nMUOyGdpeGA1Wxt65zYwi3oEl9kOM+RswvYq90fzkNDahPS8K0OIg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-middleware": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.12.tgz",
+      "integrity": "sha512-Er805uFUOvgc0l8nv0e0su0VFISoxhJ/AwOn3gL2NWNY2LUEldP5WtVcRYSQBcjg0y9NfG8JYrCJaYDpupBHJQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-retry": {
+      "version": "4.2.12",
+      "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.2.12.tgz",
+      "integrity": "sha512-1zopLDUEOwumjcHdJ1mwBHddubYF8GMQvstVCLC54Y46rqoHwlIU+8ZzUeaBcD+WCJHyDGSeZ2ml9YSe9aqcoQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/service-error-classification": "^4.2.12",
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-stream": {
+      "version": "4.5.21",
+      "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.5.21.tgz",
+      "integrity": "sha512-KzSg+7KKywLnkoKejRtIBXDmwBfjGvg1U1i/etkC7XSWUyFCoLno1IohV2c74IzQqdhX5y3uE44r/8/wuK+A7Q==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/fetch-http-handler": "^5.3.15",
+        "@smithy/node-http-handler": "^4.5.1",
+        "@smithy/types": "^4.13.1",
+        "@smithy/util-base64": "^4.3.2",
+        "@smithy/util-buffer-from": "^4.2.2",
+        "@smithy/util-hex-encoding": "^4.2.2",
+        "@smithy/util-utf8": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-uri-escape": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.2.2.tgz",
+      "integrity": "sha512-2kAStBlvq+lTXHyAZYfJRb/DfS3rsinLiwb+69SstC9Vb0s9vNWkRwpnj918Pfi85mzi42sOqdV72OLxWAISnw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-utf8": {
+      "version": "4.2.2",
+      "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.2.tgz",
+      "integrity": "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/util-buffer-from": "^4.2.2",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/util-waiter": {
+      "version": "4.2.14",
+      "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.2.14.tgz",
+      "integrity": "sha512-2zqq5o/oizvMaFUlNiTyZ7dbgYv1a893aGut2uaxtbzTx/VYYnRxWzDHuD/ftgcw94ffenua+ZNLrbqwUYE+Bg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@smithy/types": "^4.13.1",
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@smithy/uuid": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/@smithy/uuid/-/uuid-1.1.2.tgz",
+      "integrity": "sha512-O/IEdcCUKkubz60tFbGA7ceITTAJsty+lBjNoorP4Z6XRqaFb/OjQjZODophEcuq68nKm6/0r+6/lLQ+XVpk8g==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "tslib": "^2.6.2"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/@types/bcrypt": {
+      "version": "5.0.2",
+      "resolved": "https://registry.npmjs.org/@types/bcrypt/-/bcrypt-5.0.2.tgz",
+      "integrity": "sha512-6atioO8Y75fNcbmj0G7UjI9lXN2pQ/IGJ2FWT4a/btd0Lk9lQalHLKhkgKVZ3r+spnmWUKfbMi1GEe9wyHQfNQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/better-sqlite3": {
+      "version": "7.6.13",
+      "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",
+      "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/body-parser": {
+      "version": "1.19.6",
+      "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
+      "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/connect": "*",
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/connect": {
+      "version": "3.4.38",
+      "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
+      "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/cookiejar": {
+      "version": "2.1.5",
+      "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz",
+      "integrity": "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/cors": {
+      "version": "2.8.19",
+      "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
+      "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/estree": {
+      "version": "1.0.8",
+      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+      "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/express": {
+      "version": "5.0.6",
+      "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
+      "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/body-parser": "*",
+        "@types/express-serve-static-core": "^5.0.0",
+        "@types/serve-static": "^2"
+      }
+    },
+    "node_modules/@types/express-serve-static-core": {
+      "version": "5.1.1",
+      "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",
+      "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*",
+        "@types/qs": "*",
+        "@types/range-parser": "*",
+        "@types/send": "*"
+      }
+    },
+    "node_modules/@types/http-errors": {
+      "version": "2.0.5",
+      "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
+      "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/jsonwebtoken": {
+      "version": "9.0.10",
+      "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
+      "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/ms": "*",
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/methods": {
+      "version": "1.1.4",
+      "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
+      "integrity": "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/ms": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+      "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/node": {
+      "version": "22.19.15",
+      "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
+      "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "undici-types": "~6.21.0"
+      }
+    },
+    "node_modules/@types/node-cron": {
+      "version": "3.0.11",
+      "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz",
+      "integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/qs": {
+      "version": "6.15.0",
+      "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.0.tgz",
+      "integrity": "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/range-parser": {
+      "version": "1.2.7",
+      "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
+      "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/@types/send": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
+      "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/serve-static": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
+      "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/http-errors": "*",
+        "@types/node": "*"
+      }
+    },
+    "node_modules/@types/superagent": {
+      "version": "8.1.9",
+      "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.9.tgz",
+      "integrity": "sha512-pTVjI73witn+9ILmoJdajHGW2jkSaOzhiFYF1Rd3EQ94kymLqB9PjD9ISg7WaALC7+dCHT0FGe9T2LktLq/3GQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/cookiejar": "^2.1.5",
+        "@types/methods": "^1.1.4",
+        "@types/node": "*",
+        "form-data": "^4.0.0"
+      }
+    },
+    "node_modules/@types/supertest": {
+      "version": "7.2.0",
+      "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-7.2.0.tgz",
+      "integrity": "sha512-uh2Lv57xvggst6lCqNdFAmDSvoMG7M/HDtX4iUCquxQ5EGPtaPM5PL5Hmi7LCvOG8db7YaCPNJEeoI8s/WzIQw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/methods": "^1.1.4",
+        "@types/superagent": "^8.1.0"
+      }
+    },
+    "node_modules/@vitest/expect": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
+      "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@vitest/spy": "2.1.9",
+        "@vitest/utils": "2.1.9",
+        "chai": "^5.1.2",
+        "tinyrainbow": "^1.2.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/@vitest/mocker": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",
+      "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@vitest/spy": "2.1.9",
+        "estree-walker": "^3.0.3",
+        "magic-string": "^0.30.12"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      },
+      "peerDependencies": {
+        "msw": "^2.4.9",
+        "vite": "^5.0.0"
+      },
+      "peerDependenciesMeta": {
+        "msw": {
+          "optional": true
+        },
+        "vite": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@vitest/pretty-format": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
+      "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "tinyrainbow": "^1.2.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/@vitest/runner": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
+      "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@vitest/utils": "2.1.9",
+        "pathe": "^1.1.2"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/@vitest/snapshot": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
+      "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@vitest/pretty-format": "2.1.9",
+        "magic-string": "^0.30.12",
+        "pathe": "^1.1.2"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/@vitest/spy": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
+      "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "tinyspy": "^3.0.2"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/@vitest/utils": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
+      "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@vitest/pretty-format": "2.1.9",
+        "loupe": "^3.1.2",
+        "tinyrainbow": "^1.2.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/abbrev": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
+      "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
+      "license": "ISC"
+    },
+    "node_modules/accepts": {
+      "version": "1.3.8",
+      "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
+      "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-types": "~2.1.34",
+        "negotiator": "0.6.3"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "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/agent-base/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/agent-base/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/ansi-regex": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+      "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/aproba": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.1.0.tgz",
+      "integrity": "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==",
+      "license": "ISC"
+    },
+    "node_modules/are-we-there-yet": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
+      "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
+      "deprecated": "This package is no longer supported.",
+      "license": "ISC",
+      "dependencies": {
+        "delegates": "^1.0.0",
+        "readable-stream": "^3.6.0"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/array-flatten": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
+      "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
+      "license": "MIT"
+    },
+    "node_modules/asap": {
+      "version": "2.0.6",
+      "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
+      "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "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==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/balanced-match": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+      "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+      "license": "MIT"
+    },
+    "node_modules/base64-js": {
+      "version": "1.5.1",
+      "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+      "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/bcrypt": {
+      "version": "5.1.1",
+      "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz",
+      "integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==",
+      "hasInstallScript": true,
+      "license": "MIT",
+      "dependencies": {
+        "@mapbox/node-pre-gyp": "^1.0.11",
+        "node-addon-api": "^5.0.0"
+      },
+      "engines": {
+        "node": ">= 10.0.0"
+      }
+    },
+    "node_modules/better-sqlite3": {
+      "version": "11.10.0",
+      "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
+      "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
+      "hasInstallScript": true,
+      "license": "MIT",
+      "dependencies": {
+        "bindings": "^1.5.0",
+        "prebuild-install": "^7.1.1"
+      }
+    },
+    "node_modules/bindings": {
+      "version": "1.5.0",
+      "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
+      "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
+      "license": "MIT",
+      "dependencies": {
+        "file-uri-to-path": "1.0.0"
+      }
+    },
+    "node_modules/bl": {
+      "version": "4.1.0",
+      "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+      "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+      "license": "MIT",
+      "dependencies": {
+        "buffer": "^5.5.0",
+        "inherits": "^2.0.4",
+        "readable-stream": "^3.4.0"
+      }
+    },
+    "node_modules/body-parser": {
+      "version": "1.20.4",
+      "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz",
+      "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==",
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "~3.1.2",
+        "content-type": "~1.0.5",
+        "debug": "2.6.9",
+        "depd": "2.0.0",
+        "destroy": "~1.2.0",
+        "http-errors": "~2.0.1",
+        "iconv-lite": "~0.4.24",
+        "on-finished": "~2.4.1",
+        "qs": "~6.14.0",
+        "raw-body": "~2.5.3",
+        "type-is": "~1.6.18",
+        "unpipe": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.8",
+        "npm": "1.2.8000 || >= 1.4.16"
+      }
+    },
+    "node_modules/bowser": {
+      "version": "2.14.1",
+      "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",
+      "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",
+      "license": "MIT"
+    },
+    "node_modules/brace-expansion": {
+      "version": "1.1.13",
+      "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",
+      "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",
+      "license": "MIT",
+      "dependencies": {
+        "balanced-match": "^1.0.0",
+        "concat-map": "0.0.1"
+      }
+    },
+    "node_modules/buffer": {
+      "version": "5.7.1",
+      "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+      "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "base64-js": "^1.3.1",
+        "ieee754": "^1.1.13"
+      }
+    },
+    "node_modules/buffer-equal-constant-time": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+      "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/bytes": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+      "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/cac": {
+      "version": "6.7.14",
+      "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
+      "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/call-bind-apply-helpers": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+      "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/call-bound": {
+      "version": "1.0.4",
+      "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+      "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "get-intrinsic": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/chai": {
+      "version": "5.3.3",
+      "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
+      "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "assertion-error": "^2.0.1",
+        "check-error": "^2.1.1",
+        "deep-eql": "^5.0.1",
+        "loupe": "^3.1.0",
+        "pathval": "^2.0.0"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/check-error": {
+      "version": "2.1.3",
+      "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
+      "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 16"
+      }
+    },
+    "node_modules/chownr": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
+      "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
+      "license": "ISC",
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/color-support": {
+      "version": "1.1.3",
+      "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
+      "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
+      "license": "ISC",
+      "bin": {
+        "color-support": "bin.js"
+      }
+    },
+    "node_modules/combined-stream": {
+      "version": "1.0.8",
+      "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+      "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "delayed-stream": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/component-emitter": {
+      "version": "1.3.1",
+      "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz",
+      "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/concat-map": {
+      "version": "0.0.1",
+      "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
+      "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+      "license": "MIT"
+    },
+    "node_modules/console-control-strings": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
+      "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==",
+      "license": "ISC"
+    },
+    "node_modules/content-disposition": {
+      "version": "0.5.4",
+      "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
+      "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
+      "license": "MIT",
+      "dependencies": {
+        "safe-buffer": "5.2.1"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/content-type": {
+      "version": "1.0.5",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+      "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie": {
+      "version": "0.7.2",
+      "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+      "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie-signature": {
+      "version": "1.0.7",
+      "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
+      "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
+      "license": "MIT"
+    },
+    "node_modules/cookiejar": {
+      "version": "2.1.4",
+      "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz",
+      "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/cors": {
+      "version": "2.8.6",
+      "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
+      "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
+      "license": "MIT",
+      "dependencies": {
+        "object-assign": "^4",
+        "vary": "^1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/debug": {
+      "version": "2.6.9",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+      "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+      "license": "MIT",
+      "dependencies": {
+        "ms": "2.0.0"
+      }
+    },
+    "node_modules/decompress-response": {
+      "version": "6.0.0",
+      "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
+      "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
+      "license": "MIT",
+      "dependencies": {
+        "mimic-response": "^3.1.0"
+      },
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/deep-eql": {
+      "version": "5.0.2",
+      "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
+      "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/deep-extend": {
+      "version": "0.6.0",
+      "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
+      "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=4.0.0"
+      }
+    },
+    "node_modules/delayed-stream": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+      "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
+    "node_modules/delegates": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
+      "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==",
+      "license": "MIT"
+    },
+    "node_modules/depd": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+      "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/destroy": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
+      "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8",
+        "npm": "1.2.8000 || >= 1.4.16"
+      }
+    },
+    "node_modules/detect-libc": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+      "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/dezalgo": {
+      "version": "1.0.4",
+      "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz",
+      "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==",
+      "dev": true,
+      "license": "ISC",
+      "dependencies": {
+        "asap": "^2.0.0",
+        "wrappy": "1"
+      }
+    },
+    "node_modules/dotenv": {
+      "version": "16.6.1",
+      "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
+      "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
+      "license": "BSD-2-Clause",
+      "engines": {
+        "node": ">=12"
+      },
+      "funding": {
+        "url": "https://dotenvx.com"
+      }
+    },
+    "node_modules/dunder-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+      "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "gopd": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/ecdsa-sig-formatter": {
+      "version": "1.0.11",
+      "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+      "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "safe-buffer": "^5.0.1"
+      }
+    },
+    "node_modules/ee-first": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+      "license": "MIT"
+    },
+    "node_modules/emoji-regex": {
+      "version": "8.0.0",
+      "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+      "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+      "license": "MIT"
+    },
+    "node_modules/encodeurl": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+      "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/end-of-stream": {
+      "version": "1.4.5",
+      "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+      "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+      "license": "MIT",
+      "dependencies": {
+        "once": "^1.4.0"
+      }
+    },
+    "node_modules/es-define-property": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+      "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-errors": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+      "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-module-lexer": {
+      "version": "1.7.0",
+      "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
+      "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
+      "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==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-set-tostringtag": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+      "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.6",
+        "has-tostringtag": "^1.0.2",
+        "hasown": "^2.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/esbuild": {
+      "version": "0.21.5",
+      "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
+      "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "bin": {
+        "esbuild": "bin/esbuild"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "optionalDependencies": {
+        "@esbuild/aix-ppc64": "0.21.5",
+        "@esbuild/android-arm": "0.21.5",
+        "@esbuild/android-arm64": "0.21.5",
+        "@esbuild/android-x64": "0.21.5",
+        "@esbuild/darwin-arm64": "0.21.5",
+        "@esbuild/darwin-x64": "0.21.5",
+        "@esbuild/freebsd-arm64": "0.21.5",
+        "@esbuild/freebsd-x64": "0.21.5",
+        "@esbuild/linux-arm": "0.21.5",
+        "@esbuild/linux-arm64": "0.21.5",
+        "@esbuild/linux-ia32": "0.21.5",
+        "@esbuild/linux-loong64": "0.21.5",
+        "@esbuild/linux-mips64el": "0.21.5",
+        "@esbuild/linux-ppc64": "0.21.5",
+        "@esbuild/linux-riscv64": "0.21.5",
+        "@esbuild/linux-s390x": "0.21.5",
+        "@esbuild/linux-x64": "0.21.5",
+        "@esbuild/netbsd-x64": "0.21.5",
+        "@esbuild/openbsd-x64": "0.21.5",
+        "@esbuild/sunos-x64": "0.21.5",
+        "@esbuild/win32-arm64": "0.21.5",
+        "@esbuild/win32-ia32": "0.21.5",
+        "@esbuild/win32-x64": "0.21.5"
+      }
+    },
+    "node_modules/escape-html": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+      "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+      "license": "MIT"
+    },
+    "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/etag": {
+      "version": "1.8.1",
+      "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+      "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/expand-template": {
+      "version": "2.0.3",
+      "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
+      "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
+      "license": "(MIT OR WTFPL)",
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/expect-type": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
+      "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=12.0.0"
+      }
+    },
+    "node_modules/express": {
+      "version": "4.22.1",
+      "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
+      "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
+      "license": "MIT",
+      "dependencies": {
+        "accepts": "~1.3.8",
+        "array-flatten": "1.1.1",
+        "body-parser": "~1.20.3",
+        "content-disposition": "~0.5.4",
+        "content-type": "~1.0.4",
+        "cookie": "~0.7.1",
+        "cookie-signature": "~1.0.6",
+        "debug": "2.6.9",
+        "depd": "2.0.0",
+        "encodeurl": "~2.0.0",
+        "escape-html": "~1.0.3",
+        "etag": "~1.8.1",
+        "finalhandler": "~1.3.1",
+        "fresh": "~0.5.2",
+        "http-errors": "~2.0.0",
+        "merge-descriptors": "1.0.3",
+        "methods": "~1.1.2",
+        "on-finished": "~2.4.1",
+        "parseurl": "~1.3.3",
+        "path-to-regexp": "~0.1.12",
+        "proxy-addr": "~2.0.7",
+        "qs": "~6.14.0",
+        "range-parser": "~1.2.1",
+        "safe-buffer": "5.2.1",
+        "send": "~0.19.0",
+        "serve-static": "~1.16.2",
+        "setprototypeof": "1.2.0",
+        "statuses": "~2.0.1",
+        "type-is": "~1.6.18",
+        "utils-merge": "1.0.1",
+        "vary": "~1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.10.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/fast-check": {
+      "version": "3.23.2",
+      "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz",
+      "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "individual",
+          "url": "https://github.com/sponsors/dubzzz"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fast-check"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "pure-rand": "^6.1.0"
+      },
+      "engines": {
+        "node": ">=8.0.0"
+      }
+    },
+    "node_modules/fast-safe-stringify": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
+      "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/fast-xml-builder": {
+      "version": "1.1.4",
+      "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.1.4.tgz",
+      "integrity": "sha512-f2jhpN4Eccy0/Uz9csxh3Nu6q4ErKxf0XIsasomfOihuSUa3/xw6w8dnOtCDgEItQFJG8KyXPzQXzcODDrrbOg==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/NaturalIntelligence"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "path-expression-matcher": "^1.1.3"
+      }
+    },
+    "node_modules/fast-xml-parser": {
+      "version": "5.5.8",
+      "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.8.tgz",
+      "integrity": "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/NaturalIntelligence"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "fast-xml-builder": "^1.1.4",
+        "path-expression-matcher": "^1.2.0",
+        "strnum": "^2.2.0"
+      },
+      "bin": {
+        "fxparser": "src/cli/cli.js"
+      }
+    },
+    "node_modules/file-uri-to-path": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
+      "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
+      "license": "MIT"
+    },
+    "node_modules/finalhandler": {
+      "version": "1.3.2",
+      "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
+      "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "2.6.9",
+        "encodeurl": "~2.0.0",
+        "escape-html": "~1.0.3",
+        "on-finished": "~2.4.1",
+        "parseurl": "~1.3.3",
+        "statuses": "~2.0.2",
+        "unpipe": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "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==",
+      "dev": true,
+      "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"
+      },
+      "engines": {
+        "node": ">= 6"
+      }
+    },
+    "node_modules/formidable": {
+      "version": "3.5.4",
+      "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz",
+      "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@paralleldrive/cuid2": "^2.2.2",
+        "dezalgo": "^1.0.4",
+        "once": "^1.4.0"
+      },
+      "engines": {
+        "node": ">=14.0.0"
+      },
+      "funding": {
+        "url": "https://ko-fi.com/tunnckoCore/commissions"
+      }
+    },
+    "node_modules/forwarded": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+      "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/fresh": {
+      "version": "0.5.2",
+      "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
+      "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/fs-constants": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+      "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+      "license": "MIT"
+    },
+    "node_modules/fs-minipass": {
+      "version": "2.1.0",
+      "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
+      "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
+      "license": "ISC",
+      "dependencies": {
+        "minipass": "^3.0.0"
+      },
+      "engines": {
+        "node": ">= 8"
+      }
+    },
+    "node_modules/fs-minipass/node_modules/minipass": {
+      "version": "3.3.6",
+      "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
+      "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
+      "license": "ISC",
+      "dependencies": {
+        "yallist": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/fs.realpath": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+      "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
+      "license": "ISC"
+    },
+    "node_modules/fsevents": {
+      "version": "2.3.3",
+      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+      "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+      }
+    },
+    "node_modules/function-bind": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+      "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/gauge": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
+      "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
+      "deprecated": "This package is no longer supported.",
+      "license": "ISC",
+      "dependencies": {
+        "aproba": "^1.0.3 || ^2.0.0",
+        "color-support": "^1.1.2",
+        "console-control-strings": "^1.0.0",
+        "has-unicode": "^2.0.1",
+        "object-assign": "^4.1.1",
+        "signal-exit": "^3.0.0",
+        "string-width": "^4.2.3",
+        "strip-ansi": "^6.0.1",
+        "wide-align": "^1.1.2"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/get-intrinsic": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+      "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "es-define-property": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "es-object-atoms": "^1.1.1",
+        "function-bind": "^1.1.2",
+        "get-proto": "^1.0.1",
+        "gopd": "^1.2.0",
+        "has-symbols": "^1.1.0",
+        "hasown": "^2.0.2",
+        "math-intrinsics": "^1.1.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+      "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+      "license": "MIT",
+      "dependencies": {
+        "dunder-proto": "^1.0.1",
+        "es-object-atoms": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/get-tsconfig": {
+      "version": "4.13.7",
+      "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz",
+      "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "resolve-pkg-maps": "^1.0.0"
+      },
+      "funding": {
+        "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
+      }
+    },
+    "node_modules/github-from-package": {
+      "version": "0.0.0",
+      "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
+      "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
+      "license": "MIT"
+    },
+    "node_modules/glob": {
+      "version": "7.2.3",
+      "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
+      "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
+      "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
+      "license": "ISC",
+      "dependencies": {
+        "fs.realpath": "^1.0.0",
+        "inflight": "^1.0.4",
+        "inherits": "2",
+        "minimatch": "^3.1.1",
+        "once": "^1.3.0",
+        "path-is-absolute": "^1.0.0"
+      },
+      "engines": {
+        "node": "*"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
+    "node_modules/gopd": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+      "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/guacamole-lite": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/guacamole-lite/-/guacamole-lite-1.2.0.tgz",
+      "integrity": "sha512-NeSYgbT5s5rxF0SE/kzJsV5Gg0IvnqoTOCbNIUMl23z1+SshaVfLExpxrEXSGTG0cdvY5lfZC1fOAepYriaXGg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "deep-extend": "^0.6.0",
+        "ws": "^8.15.1"
+      },
+      "engines": {
+        "node": ">=10.0.0"
+      }
+    },
+    "node_modules/has-symbols": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+      "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/has-tostringtag": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+      "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "has-symbols": "^1.0.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/has-unicode": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
+      "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==",
+      "license": "ISC"
+    },
+    "node_modules/hasown": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+      "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/http-errors": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+      "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+      "license": "MIT",
+      "dependencies": {
+        "depd": "~2.0.0",
+        "inherits": "~2.0.4",
+        "setprototypeof": "~1.2.0",
+        "statuses": "~2.0.2",
+        "toidentifier": "~1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "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/https-proxy-agent/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/https-proxy-agent/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/iconv-lite": {
+      "version": "0.4.24",
+      "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
+      "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
+      "license": "MIT",
+      "dependencies": {
+        "safer-buffer": ">= 2.1.2 < 3"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/ieee754": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+      "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/inflight": {
+      "version": "1.0.6",
+      "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
+      "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
+      "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
+      "license": "ISC",
+      "dependencies": {
+        "once": "^1.3.0",
+        "wrappy": "1"
+      }
+    },
+    "node_modules/inherits": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+      "license": "ISC"
+    },
+    "node_modules/ini": {
+      "version": "1.3.8",
+      "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
+      "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
+      "license": "ISC"
+    },
+    "node_modules/ipaddr.js": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+      "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/is-fullwidth-code-point": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+      "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/jsonwebtoken": {
+      "version": "9.0.3",
+      "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
+      "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
+      "license": "MIT",
+      "dependencies": {
+        "jws": "^4.0.1",
+        "lodash.includes": "^4.3.0",
+        "lodash.isboolean": "^3.0.3",
+        "lodash.isinteger": "^4.0.4",
+        "lodash.isnumber": "^3.0.3",
+        "lodash.isplainobject": "^4.0.6",
+        "lodash.isstring": "^4.0.1",
+        "lodash.once": "^4.0.0",
+        "ms": "^2.1.1",
+        "semver": "^7.5.4"
+      },
+      "engines": {
+        "node": ">=12",
+        "npm": ">=6"
+      }
+    },
+    "node_modules/jsonwebtoken/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/jwa": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
+      "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
+      "license": "MIT",
+      "dependencies": {
+        "buffer-equal-constant-time": "^1.0.1",
+        "ecdsa-sig-formatter": "1.0.11",
+        "safe-buffer": "^5.0.1"
+      }
+    },
+    "node_modules/jws": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
+      "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
+      "license": "MIT",
+      "dependencies": {
+        "jwa": "^2.0.1",
+        "safe-buffer": "^5.0.1"
+      }
+    },
+    "node_modules/lodash.includes": {
+      "version": "4.3.0",
+      "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
+      "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isboolean": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+      "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isinteger": {
+      "version": "4.0.4",
+      "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
+      "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isnumber": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
+      "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isplainobject": {
+      "version": "4.0.6",
+      "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+      "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isstring": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
+      "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.once": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
+      "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
+      "license": "MIT"
+    },
+    "node_modules/loupe": {
+      "version": "3.2.1",
+      "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
+      "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "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/make-dir": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+      "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+      "license": "MIT",
+      "dependencies": {
+        "semver": "^6.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/make-dir/node_modules/semver": {
+      "version": "6.3.1",
+      "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+      "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+      "license": "ISC",
+      "bin": {
+        "semver": "bin/semver.js"
+      }
+    },
+    "node_modules/math-intrinsics": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+      "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/media-typer": {
+      "version": "0.3.0",
+      "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+      "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/merge-descriptors": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
+      "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/methods": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
+      "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mime": {
+      "version": "1.6.0",
+      "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
+      "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
+      "license": "MIT",
+      "bin": {
+        "mime": "cli.js"
+      },
+      "engines": {
+        "node": ">=4"
+      }
+    },
+    "node_modules/mime-db": {
+      "version": "1.52.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+      "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mime-types": {
+      "version": "2.1.35",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+      "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "1.52.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mimic-response": {
+      "version": "3.1.0",
+      "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
+      "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=10"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/minimatch": {
+      "version": "3.1.5",
+      "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+      "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+      "license": "ISC",
+      "dependencies": {
+        "brace-expansion": "^1.1.7"
+      },
+      "engines": {
+        "node": "*"
+      }
+    },
+    "node_modules/minimist": {
+      "version": "1.2.8",
+      "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+      "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/minipass": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
+      "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
+      "license": "ISC",
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/minizlib": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
+      "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
+      "license": "MIT",
+      "dependencies": {
+        "minipass": "^3.0.0",
+        "yallist": "^4.0.0"
+      },
+      "engines": {
+        "node": ">= 8"
+      }
+    },
+    "node_modules/minizlib/node_modules/minipass": {
+      "version": "3.3.6",
+      "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
+      "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
+      "license": "ISC",
+      "dependencies": {
+        "yallist": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/mkdirp": {
+      "version": "1.0.4",
+      "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
+      "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
+      "license": "MIT",
+      "bin": {
+        "mkdirp": "bin/cmd.js"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/mkdirp-classic": {
+      "version": "0.5.3",
+      "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
+      "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
+      "license": "MIT"
+    },
+    "node_modules/ms": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+      "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+      "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==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "bin": {
+        "nanoid": "bin/nanoid.cjs"
+      },
+      "engines": {
+        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+      }
+    },
+    "node_modules/napi-build-utils": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
+      "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
+      "license": "MIT"
+    },
+    "node_modules/negotiator": {
+      "version": "0.6.3",
+      "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
+      "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/node-abi": {
+      "version": "3.89.0",
+      "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz",
+      "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==",
+      "license": "MIT",
+      "dependencies": {
+        "semver": "^7.3.5"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/node-addon-api": {
+      "version": "5.1.0",
+      "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
+      "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==",
+      "license": "MIT"
+    },
+    "node_modules/node-cron": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",
+      "integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
+      "license": "ISC",
+      "dependencies": {
+        "uuid": "8.3.2"
+      },
+      "engines": {
+        "node": ">=6.0.0"
+      }
+    },
+    "node_modules/node-fetch": {
+      "version": "2.7.0",
+      "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
+      "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
+      "license": "MIT",
+      "dependencies": {
+        "whatwg-url": "^5.0.0"
+      },
+      "engines": {
+        "node": "4.x || >=6.0.0"
+      },
+      "peerDependencies": {
+        "encoding": "^0.1.0"
+      },
+      "peerDependenciesMeta": {
+        "encoding": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/nopt": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
+      "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
+      "license": "ISC",
+      "dependencies": {
+        "abbrev": "1"
+      },
+      "bin": {
+        "nopt": "bin/nopt.js"
+      },
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/npmlog": {
+      "version": "5.0.1",
+      "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
+      "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
+      "deprecated": "This package is no longer supported.",
+      "license": "ISC",
+      "dependencies": {
+        "are-we-there-yet": "^2.0.0",
+        "console-control-strings": "^1.1.0",
+        "gauge": "^3.0.0",
+        "set-blocking": "^2.0.0"
+      }
+    },
+    "node_modules/object-assign": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+      "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/object-inspect": {
+      "version": "1.13.4",
+      "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+      "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/on-finished": {
+      "version": "2.4.1",
+      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+      "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+      "license": "MIT",
+      "dependencies": {
+        "ee-first": "1.1.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/once": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+      "license": "ISC",
+      "dependencies": {
+        "wrappy": "1"
+      }
+    },
+    "node_modules/parseurl": {
+      "version": "1.3.3",
+      "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+      "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/path-expression-matcher": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.2.0.tgz",
+      "integrity": "sha512-DwmPWeFn+tq7TiyJ2CxezCAirXjFxvaiD03npak3cRjlP9+OjTmSy1EpIrEbh+l6JgUundniloMLDQ/6VTdhLQ==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/NaturalIntelligence"
+        }
+      ],
+      "license": "MIT",
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/path-is-absolute": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
+      "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/path-to-regexp": {
+      "version": "0.1.13",
+      "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
+      "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
+      "license": "MIT"
+    },
+    "node_modules/pathe": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+      "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/pathval": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
+      "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">= 14.16"
+      }
+    },
+    "node_modules/picocolors": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+      "dev": true,
+      "license": "ISC"
+    },
+    "node_modules/postcss": {
+      "version": "8.5.8",
+      "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
+      "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/postcss/"
+        },
+        {
+          "type": "tidelift",
+          "url": "https://tidelift.com/funding/github/npm/postcss"
+        },
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/ai"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "nanoid": "^3.3.11",
+        "picocolors": "^1.1.1",
+        "source-map-js": "^1.2.1"
+      },
+      "engines": {
+        "node": "^10 || ^12 || >=14"
+      }
+    },
+    "node_modules/prebuild-install": {
+      "version": "7.1.3",
+      "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
+      "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
+      "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
+      "license": "MIT",
+      "dependencies": {
+        "detect-libc": "^2.0.0",
+        "expand-template": "^2.0.3",
+        "github-from-package": "0.0.0",
+        "minimist": "^1.2.3",
+        "mkdirp-classic": "^0.5.3",
+        "napi-build-utils": "^2.0.0",
+        "node-abi": "^3.3.0",
+        "pump": "^3.0.0",
+        "rc": "^1.2.7",
+        "simple-get": "^4.0.0",
+        "tar-fs": "^2.0.0",
+        "tunnel-agent": "^0.6.0"
+      },
+      "bin": {
+        "prebuild-install": "bin.js"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/proxy-addr": {
+      "version": "2.0.7",
+      "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+      "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+      "license": "MIT",
+      "dependencies": {
+        "forwarded": "0.2.0",
+        "ipaddr.js": "1.9.1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/pump": {
+      "version": "3.0.4",
+      "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+      "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+      "license": "MIT",
+      "dependencies": {
+        "end-of-stream": "^1.1.0",
+        "once": "^1.3.1"
+      }
+    },
+    "node_modules/pure-rand": {
+      "version": "6.1.0",
+      "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz",
+      "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==",
+      "dev": true,
+      "funding": [
+        {
+          "type": "individual",
+          "url": "https://github.com/sponsors/dubzzz"
+        },
+        {
+          "type": "opencollective",
+          "url": "https://opencollective.com/fast-check"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/qs": {
+      "version": "6.14.2",
+      "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz",
+      "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==",
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "side-channel": "^1.1.0"
+      },
+      "engines": {
+        "node": ">=0.6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/range-parser": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+      "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/raw-body": {
+      "version": "2.5.3",
+      "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
+      "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "~3.1.2",
+        "http-errors": "~2.0.1",
+        "iconv-lite": "~0.4.24",
+        "unpipe": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/rc": {
+      "version": "1.2.8",
+      "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
+      "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
+      "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
+      "dependencies": {
+        "deep-extend": "^0.6.0",
+        "ini": "~1.3.0",
+        "minimist": "^1.2.0",
+        "strip-json-comments": "~2.0.1"
+      },
+      "bin": {
+        "rc": "cli.js"
+      }
+    },
+    "node_modules/readable-stream": {
+      "version": "3.6.2",
+      "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+      "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+      "license": "MIT",
+      "dependencies": {
+        "inherits": "^2.0.3",
+        "string_decoder": "^1.1.1",
+        "util-deprecate": "^1.0.1"
+      },
+      "engines": {
+        "node": ">= 6"
+      }
+    },
+    "node_modules/resolve-pkg-maps": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
+      "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
+      "dev": true,
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
+      }
+    },
+    "node_modules/rimraf": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
+      "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
+      "deprecated": "Rimraf versions prior to v4 are no longer supported",
+      "license": "ISC",
+      "dependencies": {
+        "glob": "^7.1.3"
+      },
+      "bin": {
+        "rimraf": "bin.js"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/isaacs"
+      }
+    },
+    "node_modules/rollup": {
+      "version": "4.60.1",
+      "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz",
+      "integrity": "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/estree": "1.0.8"
+      },
+      "bin": {
+        "rollup": "dist/bin/rollup"
+      },
+      "engines": {
+        "node": ">=18.0.0",
+        "npm": ">=8.0.0"
+      },
+      "optionalDependencies": {
+        "@rollup/rollup-android-arm-eabi": "4.60.1",
+        "@rollup/rollup-android-arm64": "4.60.1",
+        "@rollup/rollup-darwin-arm64": "4.60.1",
+        "@rollup/rollup-darwin-x64": "4.60.1",
+        "@rollup/rollup-freebsd-arm64": "4.60.1",
+        "@rollup/rollup-freebsd-x64": "4.60.1",
+        "@rollup/rollup-linux-arm-gnueabihf": "4.60.1",
+        "@rollup/rollup-linux-arm-musleabihf": "4.60.1",
+        "@rollup/rollup-linux-arm64-gnu": "4.60.1",
+        "@rollup/rollup-linux-arm64-musl": "4.60.1",
+        "@rollup/rollup-linux-loong64-gnu": "4.60.1",
+        "@rollup/rollup-linux-loong64-musl": "4.60.1",
+        "@rollup/rollup-linux-ppc64-gnu": "4.60.1",
+        "@rollup/rollup-linux-ppc64-musl": "4.60.1",
+        "@rollup/rollup-linux-riscv64-gnu": "4.60.1",
+        "@rollup/rollup-linux-riscv64-musl": "4.60.1",
+        "@rollup/rollup-linux-s390x-gnu": "4.60.1",
+        "@rollup/rollup-linux-x64-gnu": "4.60.1",
+        "@rollup/rollup-linux-x64-musl": "4.60.1",
+        "@rollup/rollup-openbsd-x64": "4.60.1",
+        "@rollup/rollup-openharmony-arm64": "4.60.1",
+        "@rollup/rollup-win32-arm64-msvc": "4.60.1",
+        "@rollup/rollup-win32-ia32-msvc": "4.60.1",
+        "@rollup/rollup-win32-x64-gnu": "4.60.1",
+        "@rollup/rollup-win32-x64-msvc": "4.60.1",
+        "fsevents": "~2.3.2"
+      }
+    },
+    "node_modules/safe-buffer": {
+      "version": "5.2.1",
+      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+      "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "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==",
+      "license": "MIT"
+    },
+    "node_modules/semver": {
+      "version": "7.7.4",
+      "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+      "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+      "license": "ISC",
+      "bin": {
+        "semver": "bin/semver.js"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/send": {
+      "version": "0.19.2",
+      "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
+      "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "2.6.9",
+        "depd": "2.0.0",
+        "destroy": "1.2.0",
+        "encodeurl": "~2.0.0",
+        "escape-html": "~1.0.3",
+        "etag": "~1.8.1",
+        "fresh": "~0.5.2",
+        "http-errors": "~2.0.1",
+        "mime": "1.6.0",
+        "ms": "2.1.3",
+        "on-finished": "~2.4.1",
+        "range-parser": "~1.2.1",
+        "statuses": "~2.0.2"
+      },
+      "engines": {
+        "node": ">= 0.8.0"
+      }
+    },
+    "node_modules/send/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/serve-static": {
+      "version": "1.16.3",
+      "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
+      "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
+      "license": "MIT",
+      "dependencies": {
+        "encodeurl": "~2.0.0",
+        "escape-html": "~1.0.3",
+        "parseurl": "~1.3.3",
+        "send": "~0.19.1"
+      },
+      "engines": {
+        "node": ">= 0.8.0"
+      }
+    },
+    "node_modules/set-blocking": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
+      "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
+      "license": "ISC"
+    },
+    "node_modules/setprototypeof": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+      "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+      "license": "ISC"
+    },
+    "node_modules/side-channel": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+      "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.3",
+        "side-channel-list": "^1.0.0",
+        "side-channel-map": "^1.0.1",
+        "side-channel-weakmap": "^1.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-list": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+      "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-map": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+      "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-weakmap": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+      "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3",
+        "side-channel-map": "^1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "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/signal-exit": {
+      "version": "3.0.7",
+      "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
+      "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
+      "license": "ISC"
+    },
+    "node_modules/simple-concat": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
+      "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/simple-get": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
+      "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT",
+      "dependencies": {
+        "decompress-response": "^6.0.0",
+        "once": "^1.3.1",
+        "simple-concat": "^1.0.0"
+      }
+    },
+    "node_modules/source-map-js": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+      "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+      "dev": true,
+      "license": "BSD-3-Clause",
+      "engines": {
+        "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/statuses": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+      "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/std-env": {
+      "version": "3.10.0",
+      "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
+      "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/string_decoder": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+      "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+      "license": "MIT",
+      "dependencies": {
+        "safe-buffer": "~5.2.0"
+      }
+    },
+    "node_modules/string-width": {
+      "version": "4.2.3",
+      "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+      "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+      "license": "MIT",
+      "dependencies": {
+        "emoji-regex": "^8.0.0",
+        "is-fullwidth-code-point": "^3.0.0",
+        "strip-ansi": "^6.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/strip-ansi": {
+      "version": "6.0.1",
+      "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+      "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+      "license": "MIT",
+      "dependencies": {
+        "ansi-regex": "^5.0.1"
+      },
+      "engines": {
+        "node": ">=8"
+      }
+    },
+    "node_modules/strip-json-comments": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
+      "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.10.0"
+      }
+    },
+    "node_modules/strnum": {
+      "version": "2.2.2",
+      "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.2.tgz",
+      "integrity": "sha512-DnR90I+jtXNSTXWdwrEy9FakW7UX+qUZg28gj5fk2vxxl7uS/3bpI4fjFYVmdK9etptYBPNkpahuQnEwhwECqA==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/NaturalIntelligence"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/superagent": {
+      "version": "10.3.0",
+      "resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz",
+      "integrity": "sha512-B+4Ik7ROgVKrQsXTV0Jwp2u+PXYLSlqtDAhYnkkD+zn3yg8s/zjA2MeGayPoY/KICrbitwneDHrjSotxKL+0XQ==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "component-emitter": "^1.3.1",
+        "cookiejar": "^2.1.4",
+        "debug": "^4.3.7",
+        "fast-safe-stringify": "^2.1.1",
+        "form-data": "^4.0.5",
+        "formidable": "^3.5.4",
+        "methods": "^1.1.2",
+        "mime": "2.6.0",
+        "qs": "^6.14.1"
+      },
+      "engines": {
+        "node": ">=14.18.0"
+      }
+    },
+    "node_modules/superagent/node_modules/debug": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/superagent/node_modules/mime": {
+      "version": "2.6.0",
+      "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",
+      "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",
+      "dev": true,
+      "license": "MIT",
+      "bin": {
+        "mime": "cli.js"
+      },
+      "engines": {
+        "node": ">=4.0.0"
+      }
+    },
+    "node_modules/superagent/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==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/supertest": {
+      "version": "7.2.2",
+      "resolved": "https://registry.npmjs.org/supertest/-/supertest-7.2.2.tgz",
+      "integrity": "sha512-oK8WG9diS3DlhdUkcFn4tkNIiIbBx9lI2ClF8K+b2/m8Eyv47LSawxUzZQSNKUrVb2KsqeTDCcjAAVPYaSLVTA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "cookie-signature": "^1.2.2",
+        "methods": "^1.1.2",
+        "superagent": "^10.3.0"
+      },
+      "engines": {
+        "node": ">=14.18.0"
+      }
+    },
+    "node_modules/supertest/node_modules/cookie-signature": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+      "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.6.0"
+      }
+    },
+    "node_modules/tar": {
+      "version": "6.2.1",
+      "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
+      "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
+      "deprecated": "Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
+      "license": "ISC",
+      "dependencies": {
+        "chownr": "^2.0.0",
+        "fs-minipass": "^2.0.0",
+        "minipass": "^5.0.0",
+        "minizlib": "^2.1.1",
+        "mkdirp": "^1.0.3",
+        "yallist": "^4.0.0"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/tar-fs": {
+      "version": "2.1.4",
+      "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
+      "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
+      "license": "MIT",
+      "dependencies": {
+        "chownr": "^1.1.1",
+        "mkdirp-classic": "^0.5.2",
+        "pump": "^3.0.0",
+        "tar-stream": "^2.1.4"
+      }
+    },
+    "node_modules/tar-fs/node_modules/chownr": {
+      "version": "1.1.4",
+      "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+      "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
+      "license": "ISC"
+    },
+    "node_modules/tar-stream": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+      "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+      "license": "MIT",
+      "dependencies": {
+        "bl": "^4.0.3",
+        "end-of-stream": "^1.4.1",
+        "fs-constants": "^1.0.0",
+        "inherits": "^2.0.3",
+        "readable-stream": "^3.1.1"
+      },
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "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": "0.3.2",
+      "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
+      "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/tinypool": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
+      "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": "^18.0.0 || >=20.0.0"
+      }
+    },
+    "node_modules/tinyrainbow": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
+      "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/tinyspy": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
+      "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
+      "dev": true,
+      "license": "MIT",
+      "engines": {
+        "node": ">=14.0.0"
+      }
+    },
+    "node_modules/toidentifier": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+      "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.6"
+      }
+    },
+    "node_modules/tr46": {
+      "version": "0.0.3",
+      "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
+      "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
+      "license": "MIT"
+    },
+    "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==",
+      "license": "0BSD"
+    },
+    "node_modules/tsx": {
+      "version": "4.21.0",
+      "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
+      "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "esbuild": "~0.27.0",
+        "get-tsconfig": "^4.7.5"
+      },
+      "bin": {
+        "tsx": "dist/cli.mjs"
+      },
+      "engines": {
+        "node": ">=18.0.0"
+      },
+      "optionalDependencies": {
+        "fsevents": "~2.3.3"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/aix-ppc64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",
+      "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "aix"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/android-arm": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz",
+      "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/android-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz",
+      "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/android-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz",
+      "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "android"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz",
+      "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/darwin-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz",
+      "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz",
+      "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/freebsd-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz",
+      "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "freebsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-arm": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz",
+      "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==",
+      "cpu": [
+        "arm"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz",
+      "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-ia32": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz",
+      "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-loong64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz",
+      "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==",
+      "cpu": [
+        "loong64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-mips64el": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz",
+      "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==",
+      "cpu": [
+        "mips64el"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-ppc64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz",
+      "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==",
+      "cpu": [
+        "ppc64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-riscv64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz",
+      "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==",
+      "cpu": [
+        "riscv64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-s390x": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz",
+      "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==",
+      "cpu": [
+        "s390x"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/linux-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz",
+      "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "linux"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/netbsd-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz",
+      "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "netbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/openbsd-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz",
+      "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "openbsd"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/sunos-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz",
+      "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "sunos"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/win32-arm64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz",
+      "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==",
+      "cpu": [
+        "arm64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/win32-ia32": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz",
+      "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==",
+      "cpu": [
+        "ia32"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/@esbuild/win32-x64": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz",
+      "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==",
+      "cpu": [
+        "x64"
+      ],
+      "dev": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "win32"
+      ],
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/tsx/node_modules/esbuild": {
+      "version": "0.27.4",
+      "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz",
+      "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "bin": {
+        "esbuild": "bin/esbuild"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "optionalDependencies": {
+        "@esbuild/aix-ppc64": "0.27.4",
+        "@esbuild/android-arm": "0.27.4",
+        "@esbuild/android-arm64": "0.27.4",
+        "@esbuild/android-x64": "0.27.4",
+        "@esbuild/darwin-arm64": "0.27.4",
+        "@esbuild/darwin-x64": "0.27.4",
+        "@esbuild/freebsd-arm64": "0.27.4",
+        "@esbuild/freebsd-x64": "0.27.4",
+        "@esbuild/linux-arm": "0.27.4",
+        "@esbuild/linux-arm64": "0.27.4",
+        "@esbuild/linux-ia32": "0.27.4",
+        "@esbuild/linux-loong64": "0.27.4",
+        "@esbuild/linux-mips64el": "0.27.4",
+        "@esbuild/linux-ppc64": "0.27.4",
+        "@esbuild/linux-riscv64": "0.27.4",
+        "@esbuild/linux-s390x": "0.27.4",
+        "@esbuild/linux-x64": "0.27.4",
+        "@esbuild/netbsd-arm64": "0.27.4",
+        "@esbuild/netbsd-x64": "0.27.4",
+        "@esbuild/openbsd-arm64": "0.27.4",
+        "@esbuild/openbsd-x64": "0.27.4",
+        "@esbuild/openharmony-arm64": "0.27.4",
+        "@esbuild/sunos-x64": "0.27.4",
+        "@esbuild/win32-arm64": "0.27.4",
+        "@esbuild/win32-ia32": "0.27.4",
+        "@esbuild/win32-x64": "0.27.4"
+      }
+    },
+    "node_modules/tunnel-agent": {
+      "version": "0.6.0",
+      "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+      "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "safe-buffer": "^5.0.1"
+      },
+      "engines": {
+        "node": "*"
+      }
+    },
+    "node_modules/type-is": {
+      "version": "1.6.18",
+      "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
+      "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+      "license": "MIT",
+      "dependencies": {
+        "media-typer": "0.3.0",
+        "mime-types": "~2.1.24"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/typescript": {
+      "version": "5.9.3",
+      "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "tsc": "bin/tsc",
+        "tsserver": "bin/tsserver"
+      },
+      "engines": {
+        "node": ">=14.17"
+      }
+    },
+    "node_modules/undici-types": {
+      "version": "6.21.0",
+      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+      "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/unpipe": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+      "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/util-deprecate": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+      "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+      "license": "MIT"
+    },
+    "node_modules/utils-merge": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+      "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4.0"
+      }
+    },
+    "node_modules/uuid": {
+      "version": "8.3.2",
+      "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+      "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+      "license": "MIT",
+      "bin": {
+        "uuid": "dist/bin/uuid"
+      }
+    },
+    "node_modules/vary": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+      "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/vite": {
+      "version": "5.4.21",
+      "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+      "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "esbuild": "^0.21.3",
+        "postcss": "^8.4.43",
+        "rollup": "^4.20.0"
+      },
+      "bin": {
+        "vite": "bin/vite.js"
+      },
+      "engines": {
+        "node": "^18.0.0 || >=20.0.0"
+      },
+      "funding": {
+        "url": "https://github.com/vitejs/vite?sponsor=1"
+      },
+      "optionalDependencies": {
+        "fsevents": "~2.3.3"
+      },
+      "peerDependencies": {
+        "@types/node": "^18.0.0 || >=20.0.0",
+        "less": "*",
+        "lightningcss": "^1.21.0",
+        "sass": "*",
+        "sass-embedded": "*",
+        "stylus": "*",
+        "sugarss": "*",
+        "terser": "^5.4.0"
+      },
+      "peerDependenciesMeta": {
+        "@types/node": {
+          "optional": true
+        },
+        "less": {
+          "optional": true
+        },
+        "lightningcss": {
+          "optional": true
+        },
+        "sass": {
+          "optional": true
+        },
+        "sass-embedded": {
+          "optional": true
+        },
+        "stylus": {
+          "optional": true
+        },
+        "sugarss": {
+          "optional": true
+        },
+        "terser": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/vite-node": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",
+      "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "cac": "^6.7.14",
+        "debug": "^4.3.7",
+        "es-module-lexer": "^1.5.4",
+        "pathe": "^1.1.2",
+        "vite": "^5.0.0"
+      },
+      "bin": {
+        "vite-node": "vite-node.mjs"
+      },
+      "engines": {
+        "node": "^18.0.0 || >=20.0.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      }
+    },
+    "node_modules/vite-node/node_modules/debug": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/vite-node/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==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/vitest": {
+      "version": "2.1.9",
+      "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",
+      "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@vitest/expect": "2.1.9",
+        "@vitest/mocker": "2.1.9",
+        "@vitest/pretty-format": "^2.1.9",
+        "@vitest/runner": "2.1.9",
+        "@vitest/snapshot": "2.1.9",
+        "@vitest/spy": "2.1.9",
+        "@vitest/utils": "2.1.9",
+        "chai": "^5.1.2",
+        "debug": "^4.3.7",
+        "expect-type": "^1.1.0",
+        "magic-string": "^0.30.12",
+        "pathe": "^1.1.2",
+        "std-env": "^3.8.0",
+        "tinybench": "^2.9.0",
+        "tinyexec": "^0.3.1",
+        "tinypool": "^1.0.1",
+        "tinyrainbow": "^1.2.0",
+        "vite": "^5.0.0",
+        "vite-node": "2.1.9",
+        "why-is-node-running": "^2.3.0"
+      },
+      "bin": {
+        "vitest": "vitest.mjs"
+      },
+      "engines": {
+        "node": "^18.0.0 || >=20.0.0"
+      },
+      "funding": {
+        "url": "https://opencollective.com/vitest"
+      },
+      "peerDependencies": {
+        "@edge-runtime/vm": "*",
+        "@types/node": "^18.0.0 || >=20.0.0",
+        "@vitest/browser": "2.1.9",
+        "@vitest/ui": "2.1.9",
+        "happy-dom": "*",
+        "jsdom": "*"
+      },
+      "peerDependenciesMeta": {
+        "@edge-runtime/vm": {
+          "optional": true
+        },
+        "@types/node": {
+          "optional": true
+        },
+        "@vitest/browser": {
+          "optional": true
+        },
+        "@vitest/ui": {
+          "optional": true
+        },
+        "happy-dom": {
+          "optional": true
+        },
+        "jsdom": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/vitest/node_modules/debug": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/vitest/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==",
+      "dev": true,
+      "license": "MIT"
+    },
+    "node_modules/webidl-conversions": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
+      "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
+      "license": "BSD-2-Clause"
+    },
+    "node_modules/whatwg-url": {
+      "version": "5.0.0",
+      "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
+      "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
+      "license": "MIT",
+      "dependencies": {
+        "tr46": "~0.0.3",
+        "webidl-conversions": "^3.0.0"
+      }
+    },
+    "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/wide-align": {
+      "version": "1.1.5",
+      "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
+      "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
+      "license": "ISC",
+      "dependencies": {
+        "string-width": "^1.0.2 || 2 || 3 || 4"
+      }
+    },
+    "node_modules/wrappy": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+      "license": "ISC"
+    },
+    "node_modules/ws": {
+      "version": "8.20.0",
+      "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
+      "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
+      "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/yallist": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+      "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
+      "license": "ISC"
+    }
+  }
+}

+ 40 - 0
server/package.json

@@ -0,0 +1,40 @@
+{
+  "name": "bifrost-anywhere-server",
+  "version": "1.0.0",
+  "description": "Bifrost Anywhere - Backend Server",
+  "main": "dist/app.js",
+  "scripts": {
+    "build": "tsc",
+    "start": "node dist/app.js",
+    "dev": "tsx src/app.ts",
+    "test": "vitest --run",
+    "test:watch": "vitest"
+  },
+  "dependencies": {
+    "@aws-sdk/client-ec2": "^3.700.0",
+    "@aws-sdk/client-sts": "^3.1020.0",
+    "bcrypt": "^5.1.1",
+    "better-sqlite3": "^11.7.0",
+    "cors": "^2.8.5",
+    "dotenv": "^16.4.7",
+    "express": "^4.21.1",
+    "guacamole-lite": "^1.2.0",
+    "jsonwebtoken": "^9.0.2",
+    "node-cron": "^3.0.3"
+  },
+  "devDependencies": {
+    "@types/bcrypt": "^5.0.2",
+    "@types/better-sqlite3": "^7.6.12",
+    "@types/cors": "^2.8.17",
+    "@types/express": "^5.0.0",
+    "@types/jsonwebtoken": "^9.0.7",
+    "@types/node": "^22.10.0",
+    "@types/node-cron": "^3.0.11",
+    "@types/supertest": "^7.2.0",
+    "fast-check": "^3.23.1",
+    "supertest": "^7.2.2",
+    "tsx": "^4.21.0",
+    "typescript": "^5.7.2",
+    "vitest": "^2.1.8"
+  }
+}

+ 40 - 0
server/src/app.test.ts

@@ -0,0 +1,40 @@
+import { describe, it, expect } from 'vitest';
+import request from 'supertest';
+import app from './app';
+
+describe('Express App', () => {
+  it('should respond to health check', async () => {
+    const res = await request(app).get('/api/health');
+    expect(res.status).toBe(200);
+    expect(res.body).toEqual({ status: 'ok' });
+  });
+
+  it('should parse JSON request bodies', async () => {
+    const res = await request(app)
+      .post('/api/health')
+      .send({ test: 'data' })
+      .set('Content-Type', 'application/json');
+    // Even though POST /api/health doesn't exist, the JSON parser should work
+    // We just verify the server doesn't crash
+    expect(res.status).toBeDefined();
+  });
+
+  it('should include CORS headers', async () => {
+    const res = await request(app).get('/api/health');
+    expect(res.headers['access-control-allow-origin']).toBe('*');
+  });
+
+  it('should return error format for unknown routes', async () => {
+    const res = await request(app).get('/api/nonexistent');
+    expect(res.status).toBe(404);
+  });
+
+  it('should handle global errors with standard error format', async () => {
+    // The global error handler is configured - we verify it exists
+    // by checking the app has error handling middleware
+    const errorHandlers = app._router.stack.filter(
+      (layer: any) => layer.name === '<anonymous>' && layer.handle.length === 4
+    );
+    expect(errorHandlers.length).toBeGreaterThan(0);
+  });
+});

+ 89 - 0
server/src/app.ts

@@ -0,0 +1,89 @@
+import express, { Request, Response, NextFunction } from 'express';
+import cors from 'cors';
+import path from 'path';
+import dotenv from 'dotenv';
+import authRouter from './routes/auth';
+import invitationsRouter from './routes/invitations';
+import awsConfigRouter from './routes/aws-config';
+import settingsRouter, { guacamoleStatusRouter } from './routes/settings';
+import instancesRouter from './routes/instances';
+import adminInstancesRouter from './routes/admin-instances';
+import adminUsersRouter from './routes/admin-users';
+import adminLogsRouter from './routes/admin-logs';
+import { rdpSessionRouter, adminRdpRouter, guacamoleTestRouter } from './routes/rdp-sessions';
+import { requireAuth, requireAdmin } from './middleware/auth';
+import { createServer } from 'http';
+import { initDb } from './db';
+import { startLifetimeTimer } from './services/lifetime-timer';
+import { initGuacamoleProxy } from './services/guacamole-proxy';
+
+dotenv.config();
+
+// Initialize database
+initDb();
+
+// Start lifetime timer to auto-terminate expired instances
+startLifetimeTimer();
+
+const app = express();
+
+// Middleware
+app.use(cors());
+app.use(express.json());
+
+// Health check
+app.get('/api/health', (_req: Request, res: Response) => {
+  res.json({ status: 'ok' });
+});
+
+// Routes
+app.use('/api/auth', authRouter);
+app.use('/api/settings/guacamole-status', guacamoleStatusRouter);
+app.use('/api/admin/invitations', requireAuth, requireAdmin, invitationsRouter);
+app.use('/api/admin/aws-config', requireAuth, requireAdmin, awsConfigRouter);
+app.use('/api/admin/settings', requireAuth, requireAdmin, settingsRouter);
+app.use('/api/instances', requireAuth, instancesRouter);
+app.use('/api/admin/instances', requireAuth, requireAdmin, adminInstancesRouter);
+app.use('/api/admin/users', requireAuth, requireAdmin, adminUsersRouter);
+app.use('/api/admin/logs', requireAuth, requireAdmin, adminLogsRouter);
+app.use('/api/instances', requireAuth, rdpSessionRouter);
+app.use('/api/admin/rdp-sessions', requireAuth, requireAdmin, adminRdpRouter);
+app.use('/api/admin/guacamole', requireAuth, requireAdmin, guacamoleTestRouter);
+
+// Serve static frontend files in production
+const publicPath = path.join(__dirname, '..', 'public');
+app.use(express.static(publicPath));
+app.get('*', (_req: Request, res: Response) => {
+  res.sendFile(path.join(publicPath, 'index.html'));
+});
+
+// Global error handling middleware
+app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
+  console.error('Unhandled error:', err);
+
+  const statusCode = (err as any).statusCode || 500;
+  const code = (err as any).code || 'INTERNAL_ERROR';
+  const message = err.message || 'An unexpected error occurred';
+
+  res.status(statusCode).json({
+    error: {
+      code,
+      message,
+    },
+  });
+});
+
+export default app;
+
+// Start server only when run directly
+if (require.main === module) {
+  const PORT = process.env.PORT || 3000;
+  const httpServer = createServer(app);
+
+  // Attach guacamole-lite WebSocket server to the HTTP server on /ws/rdp
+  initGuacamoleProxy(httpServer);
+
+  httpServer.listen(PORT, () => {
+    console.log(`Server running on port ${PORT}`);
+  });
+}

+ 181 - 0
server/src/db.test.ts

@@ -0,0 +1,181 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import bcrypt from 'bcrypt';
+import { initDb, getDb, closeDb } from './db';
+
+describe('Database Module', () => {
+  afterEach(() => {
+    closeDb();
+  });
+
+  it('should initialize an in-memory database', () => {
+    const db = initDb(':memory:');
+    expect(db).toBeDefined();
+    expect(db.open).toBe(true);
+  });
+
+  it('should create all tables', () => {
+    const db = initDb(':memory:');
+    const tables = db
+      .prepare(
+        "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
+      )
+      .all() as { name: string }[];
+
+    const tableNames = tables.map((t) => t.name).sort();
+    expect(tableNames).toEqual([
+      'aws_config',
+      'instance_logs',
+      'instances',
+      'invitation_codes',
+      'rdp_sessions',
+      'system_settings',
+      'user_machine_guids',
+      'users',
+    ]);
+  });
+
+  it('should create default admin user on first init', () => {
+    const db = initDb(':memory:');
+    const admin = db
+      .prepare("SELECT * FROM users WHERE username = 'admin'")
+      .get() as any;
+
+    expect(admin).toBeDefined();
+    expect(admin.username).toBe('admin');
+    expect(admin.role).toBe('admin');
+    expect(bcrypt.compareSync('admin123', admin.password_hash)).toBe(true);
+  });
+
+  it('should not create duplicate admin on re-init', () => {
+    const db = initDb(':memory:');
+
+    // Simulate re-init by calling seedDefaultAdmin logic again
+    // We can't re-init the same in-memory db, but we can verify
+    // that calling initDb on a db that already has an admin doesn't duplicate
+    const countBefore = (
+      db.prepare("SELECT COUNT(*) as cnt FROM users WHERE role = 'admin'").get() as any
+    ).cnt;
+
+    // Manually call the seed logic again by re-running initDb tables + seed
+    // Since the tables already exist (IF NOT EXISTS), this is safe
+    db.exec(`
+      CREATE TABLE IF NOT EXISTS users (
+        id INTEGER PRIMARY KEY AUTOINCREMENT,
+        username TEXT NOT NULL UNIQUE,
+        password_hash TEXT NOT NULL,
+        role TEXT NOT NULL CHECK(role IN ('admin', 'user')),
+        created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
+      );
+    `);
+
+    const adminExists = db
+      .prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1")
+      .get();
+    // Admin already exists, so no new insert should happen
+    expect(adminExists).toBeDefined();
+
+    const countAfter = (
+      db.prepare("SELECT COUNT(*) as cnt FROM users WHERE role = 'admin'").get() as any
+    ).cnt;
+    expect(countAfter).toBe(countBefore);
+  });
+
+  it('getDb should throw if not initialized', () => {
+    expect(() => getDb()).toThrow('Database not initialized');
+  });
+
+  it('getDb should return the initialized database', () => {
+    initDb(':memory:');
+    const db = getDb();
+    expect(db).toBeDefined();
+    expect(db.open).toBe(true);
+  });
+
+  it('should enforce foreign key constraints on instances table', () => {
+    const db = initDb(':memory:');
+    expect(() => {
+      db.prepare(
+        "INSERT INTO instances (user_id, status) VALUES (9999, 'pending')"
+      ).run();
+    }).toThrow();
+  });
+
+  it('should enforce status check constraint on instances', () => {
+    const db = initDb(':memory:');
+    const admin = db.prepare("SELECT id FROM users WHERE username = 'admin'").get() as any;
+    expect(() => {
+      db.prepare(
+        "INSERT INTO instances (user_id, status) VALUES (?, 'invalid_status')"
+      ).run(admin.id);
+    }).toThrow();
+  });
+
+  it('should enforce role check constraint on users', () => {
+    const db = initDb(':memory:');
+    expect(() => {
+      db.prepare(
+        "INSERT INTO users (username, password_hash, role) VALUES ('test', 'hash', 'superadmin')"
+      ).run();
+    }).toThrow();
+  });
+
+  it('should enforce unique username constraint', () => {
+    const db = initDb(':memory:');
+    expect(() => {
+      db.prepare(
+        "INSERT INTO users (username, password_hash, role) VALUES ('admin', 'hash', 'user')"
+      ).run();
+    }).toThrow();
+  });
+
+  it('should enforce unique invitation code constraint', () => {
+    const db = initDb(':memory:');
+    db.prepare("INSERT INTO invitation_codes (code) VALUES ('CODE1')").run();
+    expect(() => {
+      db.prepare("INSERT INTO invitation_codes (code) VALUES ('CODE1')").run();
+    }).toThrow();
+  });
+
+  it('should seed default guacamole_host and guacamole_port settings', () => {
+    const db = initDb(':memory:');
+    const host = db
+      .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
+      .get() as any;
+    const port = db
+      .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
+      .get() as any;
+
+    expect(host).toBeDefined();
+    expect(host.value).toBe('127.0.0.1');
+    expect(port).toBeDefined();
+    expect(port.value).toBe('4822');
+  });
+
+  it('should not overwrite existing guacamole settings on re-init', () => {
+    const db = initDb(':memory:');
+
+    // Update the values to something custom
+    db.prepare("UPDATE system_settings SET value = '10.0.0.1' WHERE key = 'guacamole_host'").run();
+    db.prepare("UPDATE system_settings SET value = '9999' WHERE key = 'guacamole_port'").run();
+
+    // Re-run the seed (INSERT OR IGNORE should not overwrite)
+    db.prepare("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('guacamole_host', '127.0.0.1')").run();
+    db.prepare("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('guacamole_port', '4822')").run();
+
+    const host = db
+      .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
+      .get() as any;
+    const port = db
+      .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
+      .get() as any;
+
+    expect(host.value).toBe('10.0.0.1');
+    expect(port.value).toBe('9999');
+  });
+
+  it('closeDb should close the database connection', () => {
+    initDb(':memory:');
+    closeDb();
+    expect(() => getDb()).toThrow('Database not initialized');
+  });
+});

+ 157 - 0
server/src/db.ts

@@ -0,0 +1,157 @@
+import Database from 'better-sqlite3';
+import bcrypt from 'bcrypt';
+import path from 'path';
+
+const DEFAULT_DB_PATH = path.join(__dirname, '..', 'data', 'ec2-manager.db');
+
+let db: Database.Database;
+
+export function getDb(): Database.Database {
+  if (!db) {
+    throw new Error('Database not initialized. Call initDb() first.');
+  }
+  return db;
+}
+
+export function initDb(dbPath?: string): Database.Database {
+  const isInMemory = dbPath === ':memory:';
+
+  if (!isInMemory) {
+    const resolvedPath = dbPath || DEFAULT_DB_PATH;
+    const fs = require('fs');
+    const dir = path.dirname(resolvedPath);
+    if (!fs.existsSync(dir)) {
+      fs.mkdirSync(dir, { recursive: true });
+    }
+    db = new Database(resolvedPath);
+  } else {
+    db = new Database(':memory:');
+  }
+
+  db.pragma('journal_mode = WAL');
+  db.pragma('foreign_keys = ON');
+
+  createTables(db);
+  seedDefaultAdmin(db);
+  seedGuacamoleDefaults(db);
+
+  return db;
+}
+
+function createTables(db: Database.Database): void {
+  db.exec(`
+    CREATE TABLE IF NOT EXISTS users (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      username TEXT NOT NULL UNIQUE,
+      password_hash TEXT NOT NULL,
+      role TEXT NOT NULL CHECK(role IN ('admin', 'user')),
+      invitation_code TEXT,
+      created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
+    );
+
+    CREATE TABLE IF NOT EXISTS user_machine_guids (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      user_id INTEGER NOT NULL,
+      label TEXT NOT NULL DEFAULT '',
+      machine_guid TEXT NOT NULL,
+      created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
+      FOREIGN KEY (user_id) REFERENCES users(id)
+    );
+
+    CREATE TABLE IF NOT EXISTS invitation_codes (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      code TEXT NOT NULL UNIQUE,
+      is_active INTEGER NOT NULL DEFAULT 1,
+      usage_count INTEGER NOT NULL DEFAULT 0,
+      created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
+    );
+
+    CREATE TABLE IF NOT EXISTS aws_config (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      access_key TEXT,
+      secret_key_encrypted TEXT,
+      region TEXT,
+      ami_id TEXT,
+      instance_type TEXT,
+      key_pair_name TEXT,
+      security_group_id TEXT,
+      subnet_id TEXT,
+      updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
+    );
+
+    CREATE TABLE IF NOT EXISTS system_settings (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      key TEXT NOT NULL UNIQUE,
+      value TEXT,
+      updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
+    );
+
+    CREATE TABLE IF NOT EXISTS instances (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      user_id INTEGER NOT NULL,
+      ec2_instance_id TEXT UNIQUE,
+      machine_guid TEXT,
+      status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'running', 'stopped', 'terminated')),
+      public_ip TEXT,
+      rdp_username TEXT,
+      rdp_password_encrypted TEXT,
+      started_at INTEGER,
+      expires_at INTEGER,
+      created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
+      FOREIGN KEY (user_id) REFERENCES users(id)
+    );
+
+    CREATE TABLE IF NOT EXISTS instance_logs (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      user_id INTEGER NOT NULL,
+      username TEXT NOT NULL,
+      ec2_instance_id TEXT,
+      action TEXT NOT NULL,
+      duration_seconds INTEGER,
+      created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
+    );
+
+    CREATE TABLE IF NOT EXISTS rdp_sessions (
+      id TEXT PRIMARY KEY,
+      user_id INTEGER NOT NULL,
+      instance_id INTEGER NOT NULL,
+      ec2_instance_id TEXT NOT NULL,
+      token_hash TEXT NOT NULL,
+      status TEXT NOT NULL DEFAULT 'connecting'
+        CHECK(status IN ('connecting', 'connected', 'disconnected')),
+      created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
+      expires_at INTEGER NOT NULL,
+      used_at INTEGER,
+      FOREIGN KEY (user_id) REFERENCES users(id),
+      FOREIGN KEY (instance_id) REFERENCES instances(id)
+    );
+  `);
+}
+
+function seedDefaultAdmin(db: Database.Database): void {
+  const adminExists = db.prepare(
+    "SELECT id FROM users WHERE role = 'admin' LIMIT 1"
+  ).get();
+
+  if (!adminExists) {
+    const passwordHash = bcrypt.hashSync('admin123', 10);
+    db.prepare(
+      'INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)'
+    ).run('admin', passwordHash, 'admin');
+  }
+}
+
+function seedGuacamoleDefaults(db: Database.Database): void {
+  const stmt = db.prepare(
+    'INSERT OR IGNORE INTO system_settings (key, value) VALUES (?, ?)'
+  );
+  stmt.run('guacamole_host', '127.0.0.1');
+  stmt.run('guacamole_port', '4822');
+}
+
+export function closeDb(): void {
+  if (db) {
+    db.close();
+    db = undefined as any;
+  }
+}

+ 402 - 0
server/src/integration.test.ts

@@ -0,0 +1,402 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import request from 'supertest';
+import app from './app';
+import { initDb, closeDb, getDb } from './db';
+
+// Mock the instance-manager service so we don't hit real AWS
+vi.mock('./services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('./services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+// Mock AWS SDK DescribeRegions for aws-config credential validation
+vi.mock('@aws-sdk/client-ec2', () => {
+  const mockSend = vi.fn().mockResolvedValue({ Regions: [{ RegionName: 'us-east-1' }] });
+  return {
+    EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
+    DescribeRegionsCommand: vi.fn(),
+    RunInstancesCommand: vi.fn(),
+    DescribeInstancesCommand: vi.fn(),
+    GetPasswordDataCommand: vi.fn(),
+    StopInstancesCommand: vi.fn(),
+    StartInstancesCommand: vi.fn(),
+    RebootInstancesCommand: vi.fn(),
+    TerminateInstancesCommand: vi.fn(),
+  };
+});
+
+import {
+  launchInstance,
+  getInstanceRdpInfo,
+} from './services/instance-manager';
+import { encrypt } from './utils/crypto';
+
+const mockedLaunch = vi.mocked(launchInstance);
+const mockedGetRdp = vi.mocked(getInstanceRdpInfo);
+
+describe('Integration Tests', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+    vi.clearAllMocks();
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  /**
+   * Flow 1: Register with invitation code → Login → Launch instance → Get RDP info
+   * Validates: Requirements 1.1, 1.4, 6.1, 6.4
+   */
+  describe('Flow 1: Register → Login → Launch Instance → Get RDP Info', () => {
+    it('should complete the full user flow end-to-end', async () => {
+      // Step 1: Admin logs in to create an invitation code
+      const adminLogin = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'admin', password: 'admin123' });
+
+      expect(adminLogin.status).toBe(200);
+      const adminToken = adminLogin.body.token;
+      expect(adminToken).toBeDefined();
+      expect(adminLogin.body.user.role).toBe('admin');
+
+      // Step 2: Admin creates an invitation code
+      const createInvitation = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'INVITE-FLOW1' });
+
+      expect(createInvitation.status).toBe(201);
+      expect(createInvitation.body.code).toBe('INVITE-FLOW1');
+
+      // Step 3: New user registers with the invitation code
+      const register = await request(app)
+        .post('/api/auth/register')
+        .send({
+          username: 'testuser1',
+          password: 'securepass',
+          invitationCode: 'INVITE-FLOW1',
+        });
+
+      expect(register.status).toBe(201);
+      expect(register.body.token).toBeDefined();
+      expect(register.body.user.username).toBe('testuser1');
+      expect(register.body.user.role).toBe('user');
+      const userToken = register.body.token;
+
+      // Step 4: User logs in (verify login works too)
+      const login = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'testuser1', password: 'securepass' });
+
+      expect(login.status).toBe(200);
+      expect(login.body.token).toBeDefined();
+      const loginToken = login.body.token;
+
+      // Step 5: User verifies identity via /me
+      const me = await request(app)
+        .get('/api/auth/me')
+        .set('Authorization', `Bearer ${loginToken}`);
+
+      expect(me.status).toBe(200);
+      expect(me.body.user.username).toBe('testuser1');
+
+      // Step 6: User launches an EC2 instance
+      const machineGuid = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
+      const now = Math.floor(Date.now() / 1000);
+
+      mockedLaunch.mockResolvedValue({
+        instanceId: 1,
+        ec2InstanceId: 'i-flow1test',
+        machineGuid,
+        status: 'running',
+        publicIp: '54.123.45.67',
+        rdpUsername: 'Administrator',
+        rdpPassword: 'WindowsPass123!',
+        startedAt: now,
+        expiresAt: now + 86400,
+      });
+
+      const launch = await request(app)
+        .post('/api/instances')
+        .set('Authorization', `Bearer ${loginToken}`)
+        .send({ machineGuid });
+
+      expect(launch.status).toBe(201);
+      expect(launch.body.ec2InstanceId).toBe('i-flow1test');
+      expect(launch.body.publicIp).toBe('54.123.45.67');
+      expect(launch.body.rdpUsername).toBe('Administrator');
+      expect(launch.body.rdpPassword).toBe('WindowsPass123!');
+      expect(launch.body.machineGuid).toBe(machineGuid);
+      expect(mockedLaunch).toHaveBeenCalledWith(me.body.user.id, machineGuid);
+
+      // Step 7: Insert a real DB record so GET endpoints work
+      const db = getDb();
+      db.prepare(
+        `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+         VALUES (?, ?, ?, 'running', ?, 'Administrator', ?, ?, ?, ?)`,
+      ).run(
+        me.body.user.id,
+        'i-flow1test',
+        machineGuid,
+        '54.123.45.67',
+        encrypt('WindowsPass123!'),
+        now,
+        now + 86400,
+        now,
+      );
+
+      // Step 8: User lists instances
+      const list = await request(app)
+        .get('/api/instances')
+        .set('Authorization', `Bearer ${loginToken}`);
+
+      expect(list.status).toBe(200);
+      expect(list.body.length).toBeGreaterThanOrEqual(1);
+      const inst = list.body.find((i: any) => i.ec2_instance_id === 'i-flow1test');
+      expect(inst).toBeDefined();
+      expect(inst.status).toBe('running');
+      expect(inst.public_ip).toBe('54.123.45.67');
+      expect(inst.remaining_time).toBeGreaterThan(0);
+
+      // Step 9: User gets RDP info
+      mockedGetRdp.mockReturnValue({
+        publicIp: '54.123.45.67',
+        rdpUsername: 'Administrator',
+        rdpPassword: 'WindowsPass123!',
+      });
+
+      const rdp = await request(app)
+        .get(`/api/instances/${inst.id}/rdp`)
+        .set('Authorization', `Bearer ${loginToken}`);
+
+      expect(rdp.status).toBe(200);
+      expect(rdp.body.publicIp).toBe('54.123.45.67');
+      expect(rdp.body.rdpUsername).toBe('Administrator');
+      expect(rdp.body.rdpPassword).toBe('WindowsPass123!');
+    });
+
+    it('should reject registration with invalid invitation code', async () => {
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({
+          username: 'baduser',
+          password: 'pass',
+          invitationCode: 'NONEXISTENT',
+        });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INVITATION_CODE');
+    });
+
+    it('should prevent unauthenticated users from launching instances', async () => {
+      const res = await request(app)
+        .post('/api/instances')
+        .send({ machineGuid: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' });
+
+      expect(res.status).toBe(401);
+    });
+  });
+
+  /**
+   * Flow 2: Admin login → Configure AWS → User registers → User launches instance
+   * Validates: Requirements 1.1, 1.4, 6.1, 6.4
+   */
+  describe('Flow 2: Admin Configure AWS → User Register → User Launch Instance', () => {
+    it('should complete the admin config + user launch flow end-to-end', async () => {
+      // Step 1: Admin logs in
+      const adminLogin = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'admin', password: 'admin123' });
+
+      expect(adminLogin.status).toBe(200);
+      const adminToken = adminLogin.body.token;
+
+      // Step 2: Admin configures AWS credentials
+      const awsConfig = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({
+          accessKey: 'AKIAIOSFODNN7EXAMPLE',
+          secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
+          region: 'us-east-1',
+          amiId: 'ami-0abcdef1234567890',
+          instanceType: 't3.medium',
+          keyPairName: 'my-key-pair',
+          securityGroupId: 'sg-12345678',
+        });
+
+      expect(awsConfig.status).toBe(200);
+      expect(awsConfig.body.accessKey).toBe('AKIAIOSFODNN7EXAMPLE');
+      expect(awsConfig.body.region).toBe('us-east-1');
+      expect(awsConfig.body.amiId).toBe('ami-0abcdef1234567890');
+      // Secret key should be masked
+      expect(awsConfig.body.secretKey).toContain('****');
+
+      // Step 3: Admin verifies AWS config is saved
+      const getConfig = await request(app)
+        .get('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(getConfig.status).toBe(200);
+      expect(getConfig.body.accessKey).toBe('AKIAIOSFODNN7EXAMPLE');
+      expect(getConfig.body.region).toBe('us-east-1');
+
+      // Step 4: Admin sets instance lifetime
+      const setLifetime = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 48 });
+
+      expect(setLifetime.status).toBe(200);
+      expect(setLifetime.body.max_instance_lifetime_hours).toBe(48);
+
+      // Step 5: Admin creates invitation code
+      const createInvitation = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'INVITE-FLOW2' });
+
+      expect(createInvitation.status).toBe(201);
+
+      // Step 6: User registers with invitation code
+      const register = await request(app)
+        .post('/api/auth/register')
+        .send({
+          username: 'flow2user',
+          password: 'userpass123',
+          invitationCode: 'INVITE-FLOW2',
+        });
+
+      expect(register.status).toBe(201);
+      const userToken = register.body.token;
+
+      // Step 7: Verify invitation code usage count incremented
+      const invitations = await request(app)
+        .get('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(invitations.status).toBe(200);
+      const inv = invitations.body.find((i: any) => i.code === 'INVITE-FLOW2');
+      expect(inv.usage_count).toBe(1);
+
+      // Step 8: User launches instance (uses the AWS config admin set up)
+      const machineGuid = 'deadbeef-1234-5678-9abc-def012345678';
+      const now = Math.floor(Date.now() / 1000);
+
+      mockedLaunch.mockResolvedValue({
+        instanceId: 1,
+        ec2InstanceId: 'i-flow2test',
+        machineGuid,
+        status: 'running',
+        publicIp: '3.14.159.26',
+        rdpUsername: 'Administrator',
+        rdpPassword: 'AnotherPass!',
+        startedAt: now,
+        expiresAt: now + 48 * 3600,
+      });
+
+      const launch = await request(app)
+        .post('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ machineGuid });
+
+      expect(launch.status).toBe(201);
+      expect(launch.body.ec2InstanceId).toBe('i-flow2test');
+      expect(launch.body.publicIp).toBe('3.14.159.26');
+      expect(launch.body.rdpUsername).toBe('Administrator');
+      expect(launch.body.rdpPassword).toBe('AnotherPass!');
+
+      // Step 9: Insert DB record for admin monitoring
+      const db = getDb();
+      db.prepare(
+        `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+         VALUES (?, ?, ?, 'running', ?, 'Administrator', ?, ?, ?, ?)`,
+      ).run(
+        register.body.user.id,
+        'i-flow2test',
+        machineGuid,
+        '3.14.159.26',
+        encrypt('AnotherPass!'),
+        now,
+        now + 48 * 3600,
+        now,
+      );
+
+      // Step 10: Admin can see the user's instance in admin panel
+      const adminInstances = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(adminInstances.status).toBe(200);
+      const userInst = adminInstances.body.find(
+        (i: any) => i.ec2_instance_id === 'i-flow2test',
+      );
+      expect(userInst).toBeDefined();
+      expect(userInst.username).toBe('flow2user');
+      expect(userInst.status).toBe('running');
+      expect(userInst.public_ip).toBe('3.14.159.26');
+
+      // Step 11: Admin checks running instance stats
+      const stats = await request(app)
+        .get('/api/admin/instances/stats')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(stats.status).toBe(200);
+      expect(stats.body.running_count).toBeGreaterThanOrEqual(1);
+    });
+
+    it('should prevent non-admin from configuring AWS', async () => {
+      // Register a regular user first
+      const db = getDb();
+      db.prepare(
+        "INSERT INTO invitation_codes (code, is_active, usage_count) VALUES ('TEMP', 1, 0)",
+      ).run();
+
+      const register = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'regularuser', password: 'pass', invitationCode: 'TEMP' });
+
+      const userToken = register.body.token;
+
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({
+          accessKey: 'AKIA...',
+          secretKey: 'secret',
+          region: 'us-east-1',
+          amiId: 'ami-123',
+        });
+
+      expect(res.status).toBe(403);
+    });
+
+    it('should prevent non-admin from viewing admin instances', async () => {
+      const db = getDb();
+      db.prepare(
+        "INSERT INTO invitation_codes (code, is_active, usage_count) VALUES ('TEMP2', 1, 0)",
+      ).run();
+
+      const register = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'normaluser', password: 'pass', invitationCode: 'TEMP2' });
+
+      const userToken = register.body.token;
+
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(403);
+    });
+  });
+});

+ 85 - 0
server/src/middleware/auth.property.test.ts

@@ -0,0 +1,85 @@
+// Feature: ec2-management-platform, Property 4: 管理员拥有双重权限
+import { describe, it, expect } from 'vitest';
+import fc from 'fast-check';
+import express, { Response } from 'express';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import { requireAuth, requireAdmin, JWT_SECRET, AuthRequest } from './auth';
+
+/**
+ * Validates: Requirements 3.2
+ *
+ * Property 4: 管理员拥有双重权限
+ * 对于任意角色为 admin 的用户,该用户应能同时访问所有管理员 API 端点和所有普通用户 API 端点。
+ */
+
+function createTestApp() {
+  const app = express();
+  app.use(express.json());
+
+  // User-only route (requireAuth)
+  app.get('/user-only', requireAuth, (req: AuthRequest, res: Response) => {
+    res.json({ user: req.user });
+  });
+
+  // Admin-only route (requireAuth + requireAdmin)
+  app.get('/admin-only', requireAuth, requireAdmin, (req: AuthRequest, res: Response) => {
+    res.json({ user: req.user });
+  });
+
+  return app;
+}
+
+function signToken(payload: { id: number; username: string; role: string }) {
+  return jwt.sign(payload, JWT_SECRET);
+}
+
+// Arbitrary generators
+const arbPositiveId = fc.integer({ min: 1, max: 100000 });
+const arbUsername = fc.string({ minLength: 1, maxLength: 50 }).filter((s) => s.trim().length > 0);
+
+describe('Property 4: 管理员拥有双重权限', () => {
+  const app = createTestApp();
+
+  it('admin users can access BOTH user-only and admin-only endpoints', async () => {
+    await fc.assert(
+      fc.asyncProperty(arbPositiveId, arbUsername, async (id, username) => {
+        const token = signToken({ id, username, role: 'admin' });
+
+        const userRes = await request(app)
+          .get('/user-only')
+          .set('Authorization', `Bearer ${token}`);
+        expect(userRes.status).toBe(200);
+        expect(userRes.body.user).toMatchObject({ id, username, role: 'admin' });
+
+        const adminRes = await request(app)
+          .get('/admin-only')
+          .set('Authorization', `Bearer ${token}`);
+        expect(adminRes.status).toBe(200);
+        expect(adminRes.body.user).toMatchObject({ id, username, role: 'admin' });
+      }),
+      { numRuns: 100 }
+    );
+  });
+
+  it('non-admin users can access user-only but NOT admin-only endpoints', async () => {
+    await fc.assert(
+      fc.asyncProperty(arbPositiveId, arbUsername, async (id, username) => {
+        const token = signToken({ id, username, role: 'user' });
+
+        const userRes = await request(app)
+          .get('/user-only')
+          .set('Authorization', `Bearer ${token}`);
+        expect(userRes.status).toBe(200);
+        expect(userRes.body.user).toMatchObject({ id, username, role: 'user' });
+
+        const adminRes = await request(app)
+          .get('/admin-only')
+          .set('Authorization', `Bearer ${token}`);
+        expect(adminRes.status).toBe(403);
+        expect(adminRes.body.error.code).toBe('FORBIDDEN');
+      }),
+      { numRuns: 100 }
+    );
+  });
+});

+ 162 - 0
server/src/middleware/auth.test.ts

@@ -0,0 +1,162 @@
+import { describe, it, expect, vi } from 'vitest';
+import express, { Request, Response } from 'express';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import { requireAuth, requireAdmin, JWT_SECRET, AuthRequest } from './auth';
+
+function createTestApp() {
+  const app = express();
+  app.use(express.json());
+
+  // Route protected by requireAuth only
+  app.get('/user-only', requireAuth, (req: AuthRequest, res: Response) => {
+    res.json({ user: req.user });
+  });
+
+  // Route protected by requireAuth + requireAdmin
+  app.get('/admin-only', requireAuth, requireAdmin, (req: AuthRequest, res: Response) => {
+    res.json({ user: req.user });
+  });
+
+  return app;
+}
+
+function signToken(payload: { id: number; username: string; role: string }, options?: jwt.SignOptions) {
+  return jwt.sign(payload, JWT_SECRET, options);
+}
+
+describe('requireAuth middleware', () => {
+  const app = createTestApp();
+
+  it('should return 401 when no Authorization header is provided', async () => {
+    const res = await request(app).get('/user-only');
+    expect(res.status).toBe(401);
+    expect(res.body.error.code).toBe('UNAUTHORIZED');
+  });
+
+  it('should return 401 when Authorization header has no Bearer prefix', async () => {
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', 'Basic some-token');
+    expect(res.status).toBe(401);
+    expect(res.body.error.code).toBe('UNAUTHORIZED');
+  });
+
+  it('should return 401 when token is invalid', async () => {
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', 'Bearer invalid-token');
+    expect(res.status).toBe(401);
+    expect(res.body.error.code).toBe('UNAUTHORIZED');
+  });
+
+  it('should return 401 when token is expired', async () => {
+    const token = signToken({ id: 1, username: 'test', role: 'user' }, { expiresIn: '0s' });
+    // Small delay to ensure expiry
+    await new Promise((r) => setTimeout(r, 10));
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(401);
+    expect(res.body.error.code).toBe('UNAUTHORIZED');
+  });
+
+  it('should pass and attach user info for valid user token', async () => {
+    const token = signToken({ id: 1, username: 'testuser', role: 'user' });
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(200);
+    expect(res.body.user).toMatchObject({
+      id: 1,
+      username: 'testuser',
+      role: 'user',
+    });
+  });
+
+  it('should pass and attach user info for valid admin token', async () => {
+    const token = signToken({ id: 2, username: 'admin', role: 'admin' });
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(200);
+    expect(res.body.user).toMatchObject({
+      id: 2,
+      username: 'admin',
+      role: 'admin',
+    });
+  });
+});
+
+describe('requireAdmin middleware', () => {
+  const app = createTestApp();
+
+  it('should return 403 when user role is not admin', async () => {
+    const token = signToken({ id: 1, username: 'testuser', role: 'user' });
+    const res = await request(app)
+      .get('/admin-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(403);
+    expect(res.body.error.code).toBe('FORBIDDEN');
+  });
+
+  it('should pass for admin role', async () => {
+    const token = signToken({ id: 2, username: 'admin', role: 'admin' });
+    const res = await request(app)
+      .get('/admin-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(200);
+    expect(res.body.user).toMatchObject({
+      id: 2,
+      username: 'admin',
+      role: 'admin',
+    });
+  });
+
+  it('should return 401 when requireAdmin is called without prior auth', async () => {
+    // Create an app where requireAdmin is used without requireAuth
+    const bareApp = express();
+    bareApp.get('/bare-admin', requireAdmin, (_req: Request, res: Response) => {
+      res.json({ ok: true });
+    });
+    const res = await request(bareApp).get('/bare-admin');
+    expect(res.status).toBe(401);
+    expect(res.body.error.code).toBe('UNAUTHORIZED');
+  });
+});
+
+describe('Admin dual permissions (Requirement 3.2)', () => {
+  const app = createTestApp();
+
+  it('admin can access user-only routes', async () => {
+    const token = signToken({ id: 1, username: 'admin', role: 'admin' });
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(200);
+  });
+
+  it('admin can access admin-only routes', async () => {
+    const token = signToken({ id: 1, username: 'admin', role: 'admin' });
+    const res = await request(app)
+      .get('/admin-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(200);
+  });
+
+  it('regular user can access user-only routes', async () => {
+    const token = signToken({ id: 2, username: 'user1', role: 'user' });
+    const res = await request(app)
+      .get('/user-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(200);
+  });
+
+  it('regular user cannot access admin-only routes', async () => {
+    const token = signToken({ id: 2, username: 'user1', role: 'user' });
+    const res = await request(app)
+      .get('/admin-only')
+      .set('Authorization', `Bearer ${token}`);
+    expect(res.status).toBe(403);
+  });
+});

+ 68 - 0
server/src/middleware/auth.ts

@@ -0,0 +1,68 @@
+import { Request, Response, NextFunction } from 'express';
+import jwt from 'jsonwebtoken';
+
+const JWT_SECRET = process.env.JWT_SECRET || 'ec2-mgmt-default-secret';
+
+export interface JwtPayload {
+  id: number;
+  username: string;
+  role: 'admin' | 'user';
+}
+
+export interface AuthRequest extends Request {
+  user?: JwtPayload;
+}
+
+export { JWT_SECRET };
+
+/**
+ * Middleware: Verify JWT token from Authorization header.
+ * Attaches decoded user info (id, username, role) to req.user.
+ * Returns 401 on missing/invalid token.
+ */
+export function requireAuth(req: AuthRequest, res: Response, next: NextFunction): void {
+  const authHeader = req.headers.authorization;
+
+  if (!authHeader || !authHeader.startsWith('Bearer ')) {
+    res.status(401).json({
+      error: { code: 'UNAUTHORIZED', message: '未提供认证令牌' },
+    });
+    return;
+  }
+
+  const token = authHeader.split(' ')[1];
+
+  try {
+    const decoded = jwt.verify(token, JWT_SECRET) as JwtPayload;
+    req.user = decoded;
+    next();
+  } catch {
+    res.status(401).json({
+      error: { code: 'UNAUTHORIZED', message: '认证令牌无效或已过期' },
+    });
+  }
+}
+
+/**
+ * Middleware: Require admin role. Must be used after requireAuth.
+ * Admin users have both admin and user permissions.
+ * Returns 403 if user role is not admin.
+ */
+export function requireAdmin(req: AuthRequest, res: Response, next: NextFunction): void {
+  if (!req.user) {
+    res.status(401).json({
+      error: { code: 'UNAUTHORIZED', message: '未提供认证令牌' },
+    });
+    return;
+  }
+
+  if (req.user.role !== 'admin') {
+    res.status(403).json({
+      error: { code: 'FORBIDDEN', message: '需要管理员权限' },
+    });
+    return;
+  }
+
+  // Admin has both admin and user permissions
+  next();
+}

+ 95 - 0
server/src/routes/admin-instances.property.test.ts

@@ -0,0 +1,95 @@
+// Feature: ec2-management-platform, Property 17: 运行中实例计数
+// **Validates: Requirements 9.3**
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb, getDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { encrypt } from '../utils/crypto';
+
+// Mock the instance-manager service
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+const STATUSES = ['pending', 'running', 'stopped', 'terminated'] as const;
+
+let adminToken: string;
+
+beforeEach(() => {
+  initDb(':memory:');
+  adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+});
+
+afterEach(() => {
+  vi.clearAllMocks();
+  closeDb();
+});
+
+describe('Property 17: 运行中实例计数', () => {
+  it('running_count should equal the number of instances with status "running"', async () => {
+    await fc.assert(
+      fc.asyncProperty(
+        // Generate an array of 0-20 instance statuses
+        fc.array(
+          fc.constantFrom(...STATUSES),
+          { minLength: 0, maxLength: 20 },
+        ),
+        async (statuses) => {
+          const db = getDb();
+          // Clean instances for this iteration
+          db.prepare('DELETE FROM instances').run();
+
+          const now = Math.floor(Date.now() / 1000);
+
+          // Insert instances with the generated statuses
+          for (let i = 0; i < statuses.length; i++) {
+            db.prepare(
+              `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+            ).run(
+              1, // admin user
+              `i-p17-${i}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+              '12345678-1234-1234-1234-123456789abc',
+              statuses[i],
+              '1.2.3.4',
+              'Administrator',
+              encrypt('testpass'),
+              now,
+              now + 86400,
+              now,
+            );
+          }
+
+          // Calculate expected running count
+          const expectedRunningCount = statuses.filter((s) => s === 'running').length;
+
+          // Call the stats endpoint
+          const res = await request(app)
+            .get('/api/admin/instances/stats')
+            .set('Authorization', `Bearer ${adminToken}`);
+
+          expect(res.status).toBe(200);
+          expect(res.body.running_count).toBe(expectedRunningCount);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 253 - 0
server/src/routes/admin-instances.test.ts

@@ -0,0 +1,253 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb, getDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { encrypt } from '../utils/crypto';
+
+// Mock the instance-manager service
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+import { terminateInstance } from '../services/instance-manager';
+const mockedTerminate = vi.mocked(terminateInstance);
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+function insertInstance(
+  userId: number,
+  overrides: Partial<{
+    ec2_instance_id: string;
+    machine_guid: string;
+    status: string;
+    public_ip: string;
+    started_at: number;
+    expires_at: number;
+  }> = {},
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      overrides.ec2_instance_id ?? `i-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+      overrides.machine_guid ?? '12345678-1234-1234-1234-123456789abc',
+      overrides.status ?? 'running',
+      overrides.public_ip ?? '1.2.3.4',
+      'Administrator',
+      encrypt('testpass'),
+      overrides.started_at ?? now,
+      overrides.expires_at ?? now + 86400,
+      now,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+describe('Admin Instances Routes', () => {
+  let adminToken: string;
+  let userToken: string;
+
+  beforeEach(() => {
+    initDb(':memory:');
+    adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+    const db = getDb();
+    db.prepare("INSERT INTO users (username, password_hash, role) VALUES ('user1', 'hash', 'user')").run();
+    userToken = makeToken({ id: 2, username: 'user1', role: 'user' });
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  describe('Authorization', () => {
+    it('should return 401 without token', async () => {
+      const res = await request(app).get('/api/admin/instances');
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 403 for non-admin user', async () => {
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+  });
+
+  describe('GET /api/admin/instances', () => {
+    it('should return empty list when no instances exist', async () => {
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+      expect(res.status).toBe(200);
+      expect(res.body).toEqual([]);
+    });
+
+    it('should return all instances across all users', async () => {
+      insertInstance(1, { ec2_instance_id: 'i-admin1' });
+      insertInstance(2, { ec2_instance_id: 'i-user1' });
+
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body).toHaveLength(2);
+    });
+
+    it('should include username from users table', async () => {
+      insertInstance(1, { ec2_instance_id: 'i-admin1' });
+      insertInstance(2, { ec2_instance_id: 'i-user1' });
+
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      const usernames = res.body.map((i: any) => i.username).sort();
+      expect(usernames).toEqual(['admin', 'user1']);
+    });
+
+    it('should include remaining_time and expiring_soon fields', async () => {
+      const now = Math.floor(Date.now() / 1000);
+      insertInstance(1, { expires_at: now + 3600 });
+
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body[0].remaining_time).toBeGreaterThan(0);
+      expect(res.body[0].expiring_soon).toBe(false);
+    });
+
+    it('should return remaining_time=0 for terminated instances', async () => {
+      insertInstance(1, { status: 'terminated', expires_at: Math.floor(Date.now() / 1000) + 3600 });
+
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.body[0].remaining_time).toBe(0);
+    });
+
+    it('should include all required fields', async () => {
+      const now = Math.floor(Date.now() / 1000);
+      insertInstance(1, { ec2_instance_id: 'i-test', started_at: now, expires_at: now + 3600 });
+
+      const res = await request(app)
+        .get('/api/admin/instances')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      const inst = res.body[0];
+      expect(inst).toHaveProperty('id');
+      expect(inst).toHaveProperty('ec2_instance_id');
+      expect(inst).toHaveProperty('machine_guid');
+      expect(inst).toHaveProperty('status');
+      expect(inst).toHaveProperty('public_ip');
+      expect(inst).toHaveProperty('started_at');
+      expect(inst).toHaveProperty('expires_at');
+      expect(inst).toHaveProperty('remaining_time');
+      expect(inst).toHaveProperty('expiring_soon');
+      expect(inst).toHaveProperty('username');
+      expect(inst).toHaveProperty('created_at');
+    });
+  });
+
+  describe('GET /api/admin/instances/stats', () => {
+    it('should return 0 when no instances exist', async () => {
+      const res = await request(app)
+        .get('/api/admin/instances/stats')
+        .set('Authorization', `Bearer ${adminToken}`);
+      expect(res.status).toBe(200);
+      expect(res.body.running_count).toBe(0);
+    });
+
+    it('should count only running instances', async () => {
+      insertInstance(1, { ec2_instance_id: 'i-r1', status: 'running' });
+      insertInstance(1, { ec2_instance_id: 'i-r2', status: 'running' });
+      insertInstance(2, { ec2_instance_id: 'i-s1', status: 'stopped' });
+      insertInstance(2, { ec2_instance_id: 'i-t1', status: 'terminated' });
+
+      const res = await request(app)
+        .get('/api/admin/instances/stats')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.running_count).toBe(2);
+    });
+
+    it('should return 403 for non-admin', async () => {
+      const res = await request(app)
+        .get('/api/admin/instances/stats')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+  });
+
+  describe('DELETE /api/admin/instances/:id', () => {
+    it('should terminate any instance without ownership check', async () => {
+      const id = insertInstance(2); // belongs to user2
+      mockedTerminate.mockResolvedValue(undefined);
+
+      const res = await request(app)
+        .delete(`/api/admin/instances/${id}`)
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.status).toBe('terminated');
+      expect(mockedTerminate).toHaveBeenCalledWith(id);
+    });
+
+    it('should return 404 for non-existent instance', async () => {
+      const res = await request(app)
+        .delete('/api/admin/instances/999')
+        .set('Authorization', `Bearer ${adminToken}`);
+      expect(res.status).toBe(404);
+    });
+
+    it('should return 400 for invalid instance ID', async () => {
+      const res = await request(app)
+        .delete('/api/admin/instances/abc')
+        .set('Authorization', `Bearer ${adminToken}`);
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INPUT');
+    });
+
+    it('should return 400 when terminate fails', async () => {
+      const id = insertInstance(1, { status: 'terminated' });
+      mockedTerminate.mockRejectedValue(new Error('实例已终止'));
+
+      const res = await request(app)
+        .delete(`/api/admin/instances/${id}`)
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('TERMINATE_FAILED');
+    });
+
+    it('should return 403 for non-admin', async () => {
+      const id = insertInstance(2);
+      const res = await request(app)
+        .delete(`/api/admin/instances/${id}`)
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+  });
+});

+ 108 - 0
server/src/routes/admin-instances.ts

@@ -0,0 +1,108 @@
+import { Router, Response } from 'express';
+import { getDb } from '../db';
+import { AuthRequest } from '../middleware/auth';
+import { terminateInstance } from '../services/instance-manager';
+
+const router = Router();
+
+/**
+ * GET /api/admin/instances
+ * List ALL instances across all users with user info, status, IP, timing, etc.
+ */
+router.get('/', (req: AuthRequest, res: Response): void => {
+  const db = getDb();
+
+  const rows = db
+    .prepare(
+      `SELECT i.id, i.ec2_instance_id, i.machine_guid, i.status, i.public_ip,
+              i.started_at, i.expires_at, i.created_at, u.username
+       FROM instances i
+       JOIN users u ON i.user_id = u.id
+       ORDER BY i.created_at DESC`,
+    )
+    .all() as Array<{
+    id: number;
+    ec2_instance_id: string;
+    machine_guid: string;
+    status: string;
+    public_ip: string | null;
+    started_at: number | null;
+    expires_at: number | null;
+    created_at: number;
+    username: string;
+  }>;
+
+  const now = Math.floor(Date.now() / 1000);
+
+  const instances = rows.map((row) => {
+    let remaining_time = 0;
+    if (row.expires_at && row.status !== 'terminated') {
+      remaining_time = Math.max(0, row.expires_at - now);
+    }
+    const expiring_soon = row.status !== 'terminated' && remaining_time > 0 && remaining_time < 300;
+    return {
+      id: row.id,
+      ec2_instance_id: row.ec2_instance_id,
+      machine_guid: row.machine_guid,
+      status: row.status,
+      public_ip: row.public_ip,
+      started_at: row.started_at,
+      expires_at: row.expires_at,
+      remaining_time,
+      expiring_soon,
+      username: row.username,
+      created_at: row.created_at,
+    };
+  });
+
+  res.json(instances);
+});
+
+/**
+ * GET /api/admin/instances/stats
+ * Return count of running instances.
+ */
+router.get('/stats', (req: AuthRequest, res: Response): void => {
+  const db = getDb();
+  const row = db
+    .prepare("SELECT COUNT(*) as running_count FROM instances WHERE status = 'running'")
+    .get() as { running_count: number };
+
+  res.json({ running_count: row.running_count });
+});
+
+/**
+ * DELETE /api/admin/instances/:id
+ * Admin can terminate any instance (no ownership check).
+ */
+router.delete('/:id', async (req: AuthRequest, res: Response): Promise<void> => {
+  const instanceId = Number(req.params.id);
+
+  if (isNaN(instanceId)) {
+    res.status(400).json({
+      error: { code: 'INVALID_INPUT', message: '无效的实例 ID' },
+    });
+    return;
+  }
+
+  const db = getDb();
+  const row = db.prepare('SELECT id FROM instances WHERE id = ?').get(instanceId) as { id: number } | undefined;
+
+  if (!row) {
+    res.status(404).json({
+      error: { code: 'NOT_FOUND', message: '实例不存在' },
+    });
+    return;
+  }
+
+  try {
+    await terminateInstance(instanceId);
+    res.json({ message: '实例已销毁', id: instanceId, status: 'terminated' });
+  } catch (err: any) {
+    res.status(400).json({
+      error: { code: 'TERMINATE_FAILED', message: err.message },
+    });
+  }
+});
+
+export default router;

+ 20 - 0
server/src/routes/admin-logs.ts

@@ -0,0 +1,20 @@
+import { Router, Response } from 'express';
+import { getDb } from '../db';
+import { AuthRequest } from '../middleware/auth';
+
+const router = Router();
+
+/**
+ * GET /api/admin/logs
+ * List instance action logs, newest first. Supports ?limit=N (default 100).
+ */
+router.get('/', (req: AuthRequest, res: Response): void => {
+  const limit = Math.min(Number(req.query.limit) || 100, 500);
+  const db = getDb();
+  const rows = db.prepare(
+    'SELECT id, user_id, username, ec2_instance_id, action, duration_seconds, created_at FROM instance_logs ORDER BY created_at DESC LIMIT ?'
+  ).all(limit);
+  res.json(rows);
+});
+
+export default router;

+ 117 - 0
server/src/routes/admin-users.ts

@@ -0,0 +1,117 @@
+import { Router, Response } from 'express';
+import bcrypt from 'bcrypt';
+import { getDb } from '../db';
+import { AuthRequest } from '../middleware/auth';
+
+const router = Router();
+
+interface UserRow {
+  id: number;
+  username: string;
+  role: string;
+  invitation_code: string | null;
+  created_at: number;
+}
+
+interface GuidRow {
+  id: number;
+  label: string;
+  machine_guid: string;
+}
+
+/**
+ * GET /api/admin/users
+ * List all users with their saved MachineGuids.
+ */
+router.get('/', (_req: AuthRequest, res: Response): void => {
+  const db = getDb();
+  const users = db.prepare(
+    'SELECT id, username, role, invitation_code, created_at FROM users ORDER BY created_at DESC'
+  ).all() as UserRow[];
+
+  const guidStmt = db.prepare(
+    'SELECT id, label, machine_guid FROM user_machine_guids WHERE user_id = ?'
+  );
+
+  const result = users.map((user) => ({
+    ...user,
+    machine_guids: guidStmt.all(user.id) as GuidRow[],
+  }));
+
+  res.json(result);
+});
+
+/**
+ * PUT /api/admin/users/:id
+ * Update user info (username, role, password).
+ */
+router.put('/:id', (req: AuthRequest, res: Response): void => {
+  const userId = Number(req.params.id);
+  if (isNaN(userId)) {
+    res.status(400).json({ error: { code: 'INVALID_INPUT', message: '无效的用户 ID' } });
+    return;
+  }
+
+  const db = getDb();
+  const user = db.prepare('SELECT id, role FROM users WHERE id = ?').get(userId) as { id: number; role: string } | undefined;
+  if (!user) {
+    res.status(404).json({ error: { code: 'NOT_FOUND', message: '用户不存在' } });
+    return;
+  }
+
+  const { username, role, password } = req.body;
+
+  if (username !== undefined) {
+    const existing = db.prepare('SELECT id FROM users WHERE username = ? AND id != ?').get(username, userId);
+    if (existing) {
+      res.status(409).json({ error: { code: 'USERNAME_EXISTS', message: '用户名已被使用' } });
+      return;
+    }
+    db.prepare('UPDATE users SET username = ? WHERE id = ?').run(username, userId);
+  }
+
+  if (role !== undefined && (role === 'admin' || role === 'user')) {
+    db.prepare('UPDATE users SET role = ? WHERE id = ?').run(role, userId);
+  }
+
+  if (password) {
+    const hash = bcrypt.hashSync(password, 10);
+    db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(hash, userId);
+  }
+
+  const updated = db.prepare(
+    'SELECT id, username, role, invitation_code, created_at FROM users WHERE id = ?'
+  ).get(userId);
+  res.json(updated);
+});
+
+/**
+ * DELETE /api/admin/users/:id
+ * Delete a user and their MachineGuids.
+ */
+router.delete('/:id', (req: AuthRequest, res: Response): void => {
+  const userId = Number(req.params.id);
+  if (isNaN(userId)) {
+    res.status(400).json({ error: { code: 'INVALID_INPUT', message: '无效的用户 ID' } });
+    return;
+  }
+
+  const db = getDb();
+  const user = db.prepare('SELECT id FROM users WHERE id = ?').get(userId);
+  if (!user) {
+    res.status(404).json({ error: { code: 'NOT_FOUND', message: '用户不存在' } });
+    return;
+  }
+
+  // Prevent deleting yourself
+  if (userId === req.user!.id) {
+    res.status(400).json({ error: { code: 'CANNOT_DELETE_SELF', message: '不能删除自己' } });
+    return;
+  }
+
+  db.prepare('DELETE FROM user_machine_guids WHERE user_id = ?').run(userId);
+  db.prepare('DELETE FROM users WHERE id = ?').run(userId);
+  res.json({ message: '用户已删除' });
+});
+
+export default router;

+ 175 - 0
server/src/routes/auth.property.test.ts

@@ -0,0 +1,175 @@
+// Feature: ec2-management-platform, Property 1: 邀请码注册有效性
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import app from '../app';
+import { initDb, getDb, closeDb } from '../db';
+
+/**
+ * Validates: Requirements 1.1, 1.2, 2.3
+ *
+ * Property 1: 邀请码注册有效性
+ * 对于任意注册请求,注册成功当且仅当提供的邀请码存在于系统中且处于启用状态(is_active = true)。
+ * 使用无效、不存在或已禁用的邀请码的注册请求应被拒绝,且不创建用户账户。
+ */
+
+// Generators
+const arbUsername = fc
+  .stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'), { minLength: 3, maxLength: 20 })
+  .filter((s) => s.trim().length >= 3);
+
+const arbPassword = fc.string({ minLength: 4, maxLength: 30 }).filter((s) => s.trim().length >= 4);
+
+const arbInvitationCode = fc
+  .stringOf(fc.constantFrom(...'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), { minLength: 4, maxLength: 16 });
+
+describe('Property 1: 邀请码注册有效性', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  it('registration with a valid active invitation code succeeds (201) and creates user', { timeout: 60000 }, async () => {
+    let counter = 0;
+    await fc.assert(
+      fc.asyncProperty(arbUsername, arbPassword, arbInvitationCode, async (username, password, code) => {
+        const db = getDb();
+        // Insert a unique active invitation code
+        const uniqueCode = `${code}-${counter}`;
+        const uniqueUsername = `${username}${counter}`;
+        counter++;
+
+        db.prepare('INSERT OR IGNORE INTO invitation_codes (code, is_active, usage_count) VALUES (?, 1, 0)').run(uniqueCode);
+
+        const res = await request(app)
+          .post('/api/auth/register')
+          .send({ username: uniqueUsername, password, invitationCode: uniqueCode });
+
+        expect(res.status).toBe(201);
+        expect(res.body.token).toBeDefined();
+        expect(res.body.user.username).toBe(uniqueUsername);
+        expect(res.body.user.role).toBe('user');
+
+        // Verify user was created in the database
+        const user = db.prepare('SELECT id, username, role FROM users WHERE username = ?').get(uniqueUsername) as any;
+        expect(user).toBeDefined();
+        expect(user.username).toBe(uniqueUsername);
+      }),
+      { numRuns: 100 },
+    );
+  });
+
+  it('registration with a nonexistent invitation code fails (400) and does NOT create user', { timeout: 60000 }, async () => {
+    let counter = 0;
+    await fc.assert(
+      fc.asyncProperty(arbUsername, arbPassword, arbInvitationCode, async (username, password, code) => {
+        const db = getDb();
+        const uniqueUsername = `nonexist${counter}`;
+        const nonexistentCode = `NOEXIST-${code}-${counter}`;
+        counter++;
+
+        // Ensure the code does NOT exist in the database
+        const existing = db.prepare('SELECT id FROM invitation_codes WHERE code = ?').get(nonexistentCode);
+        expect(existing).toBeUndefined();
+
+        const res = await request(app)
+          .post('/api/auth/register')
+          .send({ username: uniqueUsername, password, invitationCode: nonexistentCode });
+
+        expect(res.status).toBe(400);
+        expect(res.body.error.code).toBe('INVALID_INVITATION_CODE');
+
+        // Verify user was NOT created
+        const user = db.prepare('SELECT id FROM users WHERE username = ?').get(uniqueUsername);
+        expect(user).toBeUndefined();
+      }),
+      { numRuns: 100 },
+    );
+  });
+
+  it('registration with a disabled invitation code fails (400) and does NOT create user', { timeout: 60000 }, async () => {
+    let counter = 0;
+    await fc.assert(
+      fc.asyncProperty(arbUsername, arbPassword, arbInvitationCode, async (username, password, code) => {
+        const db = getDb();
+        const uniqueCode = `DISABLED-${code}-${counter}`;
+        const uniqueUsername = `disabled${counter}`;
+        counter++;
+
+        // Insert a disabled invitation code (is_active = 0)
+        db.prepare('INSERT OR IGNORE INTO invitation_codes (code, is_active, usage_count) VALUES (?, 0, 0)').run(uniqueCode);
+
+        const res = await request(app)
+          .post('/api/auth/register')
+          .send({ username: uniqueUsername, password, invitationCode: uniqueCode });
+
+        expect(res.status).toBe(400);
+        expect(res.body.error.code).toBe('INVALID_INVITATION_CODE');
+
+        // Verify user was NOT created
+        const user = db.prepare('SELECT id FROM users WHERE username = ?').get(uniqueUsername);
+        expect(user).toBeUndefined();
+      }),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// Feature: ec2-management-platform, Property 2: 邀请码可重复使用
+
+/**
+ * Validates: Requirements 1.3
+ *
+ * Property 2: 邀请码可重复使用
+ * 对于任意有效邀请码和任意数量 N(N ≥ 1)的不同用户,使用同一邀请码连续注册 N 个用户应全部成功,
+ * 且邀请码的 usage_count 应等于 N。
+ */
+describe('Property 2: 邀请码可重复使用', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  it('the same valid invitation code can be used by N different users, and usage_count equals N', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(
+        arbInvitationCode,
+        fc.integer({ min: 1, max: 10 }),
+        async (code, n) => {
+          const db = getDb();
+          const uniqueCode = `REUSE-${code}-${iteration}`;
+          iteration++;
+
+          // Insert a valid active invitation code
+          db.prepare('INSERT OR IGNORE INTO invitation_codes (code, is_active, usage_count) VALUES (?, 1, 0)').run(uniqueCode);
+
+          // Register N different users with the same invitation code
+          for (let i = 0; i < n; i++) {
+            const username = `reuse_${iteration}_user${i}`;
+            const res = await request(app)
+              .post('/api/auth/register')
+              .send({ username, password: 'testpass123', invitationCode: uniqueCode });
+
+            expect(res.status).toBe(201);
+            expect(res.body.token).toBeDefined();
+            expect(res.body.user.username).toBe(username);
+          }
+
+          // Verify usage_count equals N
+          const inv = db.prepare('SELECT usage_count FROM invitation_codes WHERE code = ?').get(uniqueCode) as { usage_count: number };
+          expect(inv).toBeDefined();
+          expect(inv.usage_count).toBe(n);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 187 - 0
server/src/routes/auth.test.ts

@@ -0,0 +1,187 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, getDb, closeDb } from '../db';
+import { JWT_SECRET } from '../middleware/auth';
+
+describe('Auth Routes', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+    // Seed an active invitation code
+    const db = getDb();
+    db.prepare(
+      'INSERT INTO invitation_codes (code, is_active, usage_count) VALUES (?, ?, ?)'
+    ).run('VALID-CODE', 1, 0);
+    db.prepare(
+      'INSERT INTO invitation_codes (code, is_active, usage_count) VALUES (?, ?, ?)'
+    ).run('DISABLED-CODE', 0, 0);
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  describe('POST /api/auth/register', () => {
+    it('should register a user with a valid invitation code', async () => {
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'newuser', password: 'pass123', invitationCode: 'VALID-CODE' });
+
+      expect(res.status).toBe(201);
+      expect(res.body.token).toBeDefined();
+      expect(res.body.user).toEqual({
+        id: expect.any(Number),
+        username: 'newuser',
+        role: 'user',
+      });
+    });
+
+    it('should increment invitation code usage_count on success', async () => {
+      await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'user1', password: 'pass', invitationCode: 'VALID-CODE' });
+
+      const db = getDb();
+      const code = db.prepare('SELECT usage_count FROM invitation_codes WHERE code = ?').get('VALID-CODE') as any;
+      expect(code.usage_count).toBe(1);
+    });
+
+    it('should reject registration with invalid invitation code', async () => {
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'user1', password: 'pass', invitationCode: 'NONEXISTENT' });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INVITATION_CODE');
+      expect(res.body.error.message).toBe('邀请码无效');
+    });
+
+    it('should reject registration with disabled invitation code', async () => {
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'user1', password: 'pass', invitationCode: 'DISABLED-CODE' });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INVITATION_CODE');
+    });
+
+    it('should reject duplicate username with 409', async () => {
+      await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'dupuser', password: 'pass', invitationCode: 'VALID-CODE' });
+
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'dupuser', password: 'pass2', invitationCode: 'VALID-CODE' });
+
+      expect(res.status).toBe(409);
+      expect(res.body.error.code).toBe('USERNAME_EXISTS');
+      expect(res.body.error.message).toBe('用户名已被使用');
+    });
+
+    it('should return 400 when fields are missing', async () => {
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'user1' });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('MISSING_FIELDS');
+    });
+
+    it('should return a valid JWT on successful registration', async () => {
+      const res = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'jwtuser', password: 'pass', invitationCode: 'VALID-CODE' });
+
+      const decoded = jwt.verify(res.body.token, JWT_SECRET) as any;
+      expect(decoded.username).toBe('jwtuser');
+      expect(decoded.role).toBe('user');
+    });
+  });
+
+  describe('POST /api/auth/login', () => {
+    beforeEach(async () => {
+      // Register a test user
+      await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'testuser', password: 'testpass', invitationCode: 'VALID-CODE' });
+    });
+
+    it('should login with correct credentials', async () => {
+      const res = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'testuser', password: 'testpass' });
+
+      expect(res.status).toBe(200);
+      expect(res.body.token).toBeDefined();
+      expect(res.body.user.username).toBe('testuser');
+      expect(res.body.user.role).toBe('user');
+    });
+
+    it('should login as admin with default credentials', async () => {
+      const res = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'admin', password: 'admin123' });
+
+      expect(res.status).toBe(200);
+      expect(res.body.user.role).toBe('admin');
+    });
+
+    it('should reject login with wrong password', async () => {
+      const res = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'testuser', password: 'wrongpass' });
+
+      expect(res.status).toBe(401);
+      expect(res.body.error.code).toBe('INVALID_CREDENTIALS');
+    });
+
+    it('should reject login with nonexistent user', async () => {
+      const res = await request(app)
+        .post('/api/auth/login')
+        .send({ username: 'noone', password: 'pass' });
+
+      expect(res.status).toBe(401);
+      expect(res.body.error.code).toBe('INVALID_CREDENTIALS');
+    });
+
+    it('should return 400 when fields are missing', async () => {
+      const res = await request(app)
+        .post('/api/auth/login')
+        .send({});
+
+      expect(res.status).toBe(400);
+    });
+  });
+
+  describe('GET /api/auth/me', () => {
+    it('should return current user info with valid token', async () => {
+      const regRes = await request(app)
+        .post('/api/auth/register')
+        .send({ username: 'meuser', password: 'pass', invitationCode: 'VALID-CODE' });
+
+      const res = await request(app)
+        .get('/api/auth/me')
+        .set('Authorization', `Bearer ${regRes.body.token}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.user.username).toBe('meuser');
+      expect(res.body.user.role).toBe('user');
+    });
+
+    it('should return 401 without token', async () => {
+      const res = await request(app).get('/api/auth/me');
+
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 401 with invalid token', async () => {
+      const res = await request(app)
+        .get('/api/auth/me')
+        .set('Authorization', 'Bearer invalidtoken');
+
+      expect(res.status).toBe(401);
+    });
+  });
+});

+ 217 - 0
server/src/routes/auth.ts

@@ -0,0 +1,217 @@
+import { Router, Response } from 'express';
+import bcrypt from 'bcrypt';
+import jwt from 'jsonwebtoken';
+import { getDb } from '../db';
+import { JWT_SECRET, requireAuth, AuthRequest, JwtPayload } from '../middleware/auth';
+
+const router = Router();
+
+/**
+ * POST /api/auth/register
+ * Register a new user with an invitation code.
+ */
+router.post('/register', (req: AuthRequest, res: Response): void => {
+  const { username, password, invitationCode } = req.body;
+
+  if (!username || !password || !invitationCode) {
+    res.status(400).json({
+      error: { code: 'MISSING_FIELDS', message: '请提供用户名、密码和邀请码' },
+    });
+    return;
+  }
+
+  // Username format check
+  if (!/^[A-Za-z0-9]+$/.test(username)) {
+    res.status(400).json({
+      error: { code: 'INVALID_USERNAME', message: '用户名只能包含数字和大小写字母' },
+    });
+    return;
+  }
+
+  // Password complexity check
+  if (password.length < 12) {
+    res.status(400).json({
+      error: { code: 'WEAK_PASSWORD', message: '密码长度至少 12 位' },
+    });
+    return;
+  }
+  const hasUpper = /[A-Z]/.test(password);
+  const hasLower = /[a-z]/.test(password);
+  const hasDigit = /[0-9]/.test(password);
+  const hasSpecial = /[^A-Za-z0-9]/.test(password);
+  const categories = [hasUpper, hasLower, hasDigit, hasSpecial].filter(Boolean).length;
+  if (categories < 2) {
+    res.status(400).json({
+      error: { code: 'WEAK_PASSWORD', message: '密码需包含大写字母、小写字母、数字、特殊字符中的至少两种' },
+    });
+    return;
+  }
+
+  const db = getDb();
+
+  // Validate invitation code
+  const invitation = db.prepare(
+    'SELECT id, is_active FROM invitation_codes WHERE code = ?'
+  ).get(invitationCode) as { id: number; is_active: number } | undefined;
+
+  if (!invitation || !invitation.is_active) {
+    res.status(400).json({
+      error: { code: 'INVALID_INVITATION_CODE', message: '邀请码无效' },
+    });
+    return;
+  }
+
+  // Check if username already exists
+  const existingUser = db.prepare(
+    'SELECT id FROM users WHERE username = ?'
+  ).get(username) as { id: number } | undefined;
+
+  if (existingUser) {
+    res.status(409).json({
+      error: { code: 'USERNAME_EXISTS', message: '用户名已被使用' },
+    });
+    return;
+  }
+
+  // Create user
+  const passwordHash = bcrypt.hashSync(password, 10);
+  const result = db.prepare(
+    'INSERT INTO users (username, password_hash, role, invitation_code) VALUES (?, ?, ?, ?)'
+  ).run(username, passwordHash, 'user', invitationCode);
+
+  // Increment invitation code usage count
+  db.prepare(
+    'UPDATE invitation_codes SET usage_count = usage_count + 1 WHERE id = ?'
+  ).run(invitation.id);
+
+  // Generate JWT
+  const payload: JwtPayload = {
+    id: result.lastInsertRowid as number,
+    username,
+    role: 'user',
+  };
+  const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' });
+
+  res.status(201).json({
+    token,
+    user: { id: payload.id, username: payload.username, role: payload.role },
+  });
+});
+
+/**
+ * POST /api/auth/login
+ * Authenticate user and return JWT.
+ */
+router.post('/login', (req: AuthRequest, res: Response): void => {
+  const { username, password } = req.body;
+
+  if (!username || !password) {
+    res.status(400).json({
+      error: { code: 'MISSING_FIELDS', message: '请提供用户名和密码' },
+    });
+    return;
+  }
+
+  const db = getDb();
+  const user = db.prepare(
+    'SELECT id, username, password_hash, role FROM users WHERE username = ?'
+  ).get(username) as { id: number; username: string; password_hash: string; role: 'admin' | 'user' } | undefined;
+
+  if (!user || !bcrypt.compareSync(password, user.password_hash)) {
+    res.status(401).json({
+      error: { code: 'INVALID_CREDENTIALS', message: '用户名或密码错误' },
+    });
+    return;
+  }
+
+  const payload: JwtPayload = {
+    id: user.id,
+    username: user.username,
+    role: user.role,
+  };
+  const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' });
+
+  res.json({
+    token,
+    user: { id: payload.id, username: payload.username, role: payload.role },
+  });
+});
+
+/**
+ * GET /api/auth/me
+ * Get current authenticated user info.
+ */
+router.get('/me', requireAuth, (req: AuthRequest, res: Response): void => {
+  res.json({
+    user: {
+      id: req.user!.id,
+      username: req.user!.username,
+      role: req.user!.role,
+    },
+  });
+});
+
+/**
+ * GET /api/auth/machine-guids
+ * List all saved MachineGuids for the current user.
+ */
+router.get('/machine-guids', requireAuth, (req: AuthRequest, res: Response): void => {
+  const db = getDb();
+  const rows = db.prepare(
+    'SELECT id, label, machine_guid, created_at FROM user_machine_guids WHERE user_id = ? ORDER BY created_at DESC'
+  ).all(req.user!.id) as { id: number; label: string; machine_guid: string; created_at: number }[];
+  res.json(rows);
+});
+
+/**
+ * POST /api/auth/machine-guids
+ * Add a new MachineGuid for the current user.
+ */
+router.post('/machine-guids', requireAuth, (req: AuthRequest, res: Response): void => {
+  const { machine_guid, label } = req.body;
+
+  if (!machine_guid || typeof machine_guid !== 'string') {
+    res.status(400).json({ error: { code: 'INVALID_INPUT', message: '请提供 machine_guid' } });
+    return;
+  }
+
+  const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+  if (!uuidRegex.test(machine_guid)) {
+    res.status(400).json({ error: { code: 'INVALID_FORMAT', message: 'MachineGuid 格式无效,需为 UUID 格式' } });
+    return;
+  }
+
+  const db = getDb();
+  const result = db.prepare(
+    'INSERT INTO user_machine_guids (user_id, label, machine_guid) VALUES (?, ?, ?)'
+  ).run(req.user!.id, label || '', machine_guid);
+
+  res.status(201).json({ id: result.lastInsertRowid, label: label || '', machine_guid });
+});
+
+/**
+ * DELETE /api/auth/machine-guids/:id
+ * Delete a saved MachineGuid.
+ */
+router.delete('/machine-guids/:id', requireAuth, (req: AuthRequest, res: Response): void => {
+  const guidId = Number(req.params.id);
+  if (isNaN(guidId)) {
+    res.status(400).json({ error: { code: 'INVALID_INPUT', message: '无效的 ID' } });
+    return;
+  }
+
+  const db = getDb();
+  const row = db.prepare(
+    'SELECT id FROM user_machine_guids WHERE id = ? AND user_id = ?'
+  ).get(guidId, req.user!.id);
+
+  if (!row) {
+    res.status(404).json({ error: { code: 'NOT_FOUND', message: '记录不存在' } });
+    return;
+  }
+
+  db.prepare('DELETE FROM user_machine_guids WHERE id = ?').run(guidId);
+  res.json({ message: '已删除' });
+});
+
+export default router;

+ 151 - 0
server/src/routes/aws-config.property.test.ts

@@ -0,0 +1,151 @@
+// Feature: ec2-management-platform, Property 6: AWS 配置传播
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { initDb, getDb, closeDb } from '../db';
+
+/**
+ * Validates: Requirements 4.5
+ *
+ * Property 6: AWS 配置传播
+ * 对于任意 AWS 配置更新,更新后创建的新实例应使用更新后的配置参数(Region、AMI ID 等),
+ * 而非更新前的旧配置。
+ *
+ * Test approach: After updating AWS config via PUT, a subsequent GET should return the updated values.
+ * This verifies that config propagation works correctly — any new instance creation would read
+ * the latest config from the database, so verifying GET returns updated values is sufficient.
+ */
+
+// Mock the AWS SDK so DescribeRegions always succeeds
+vi.mock('@aws-sdk/client-ec2', () => {
+  const mockSend = vi.fn().mockResolvedValue({ Regions: [] });
+  return {
+    EC2Client: vi.fn().mockImplementation(() => ({
+      send: mockSend,
+    })),
+    DescribeRegionsCommand: vi.fn(),
+    __mockSend: mockSend,
+  };
+});
+
+// Get the mock send function
+import { __mockSend as mockSend } from '@aws-sdk/client-ec2';
+
+function makeAdminToken(): string {
+  const payload: JwtPayload = { id: 1, username: 'admin', role: 'admin' };
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+// Generators for AWS config fields
+const arbAccessKey = fc
+  .stringOf(fc.constantFrom(...'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), { minLength: 8, maxLength: 24 })
+  .map((s) => `AKIA${s}`);
+
+const arbSecretKey = fc
+  .stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+'), {
+    minLength: 16,
+    maxLength: 40,
+  });
+
+const arbRegion = fc.constantFrom(
+  'us-east-1', 'us-west-2', 'eu-west-1', 'ap-northeast-1',
+  'ap-southeast-1', 'eu-central-1', 'sa-east-1', 'ca-central-1',
+);
+
+const arbAmiId = fc
+  .stringOf(fc.constantFrom(...'abcdef0123456789'), { minLength: 8, maxLength: 12 })
+  .map((s) => `ami-${s}`);
+
+const arbInstanceType = fc.constantFrom(
+  't2.micro', 't2.small', 't2.medium', 't3.micro', 't3.small', 'm5.large',
+);
+
+const arbKeyPairName = fc
+  .stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789-'), { minLength: 3, maxLength: 16 })
+  .map((s) => `kp-${s}`);
+
+const arbSecurityGroupId = fc
+  .stringOf(fc.constantFrom(...'abcdef0123456789'), { minLength: 8, maxLength: 12 })
+  .map((s) => `sg-${s}`);
+
+describe('Property 6: AWS 配置传播', () => {
+  let adminToken: string;
+
+  beforeEach(() => {
+    vi.clearAllMocks();
+    // Re-setup the mock to always resolve successfully
+    (mockSend as any).mockResolvedValue({ Regions: [] });
+
+    initDb(':memory:');
+    adminToken = makeAdminToken();
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  it('after PUT update, GET returns the updated config values (not old ones)', { timeout: 60000 }, async () => {
+    const app = (await import('../app')).default;
+
+    await fc.assert(
+      fc.asyncProperty(
+        arbAccessKey,
+        arbSecretKey,
+        arbRegion,
+        arbAmiId,
+        arbInstanceType,
+        arbKeyPairName,
+        arbSecurityGroupId,
+        async (accessKey, secretKey, region, amiId, instanceType, keyPairName, securityGroupId) => {
+          // PUT: update AWS config
+          const putRes = await request(app)
+            .put('/api/admin/aws-config')
+            .set('Authorization', `Bearer ${adminToken}`)
+            .send({ accessKey, secretKey, region, amiId, instanceType, keyPairName, securityGroupId });
+
+          expect(putRes.status).toBe(200);
+
+          // GET: retrieve the config — should reflect the updated values
+          const getRes = await request(app)
+            .get('/api/admin/aws-config')
+            .set('Authorization', `Bearer ${adminToken}`);
+
+          expect(getRes.status).toBe(200);
+          expect(getRes.body).not.toBeNull();
+
+          // Verify all non-secret fields match exactly
+          expect(getRes.body.accessKey).toBe(accessKey);
+          expect(getRes.body.region).toBe(region);
+          expect(getRes.body.amiId).toBe(amiId);
+          expect(getRes.body.instanceType).toBe(instanceType);
+          expect(getRes.body.keyPairName).toBe(keyPairName);
+          expect(getRes.body.securityGroupId).toBe(securityGroupId);
+
+          // Secret key should be masked but show last 4 chars
+          if (secretKey.length > 4) {
+            const lastFour = secretKey.slice(-4);
+            expect(getRes.body.secretKey).toBe(`****${lastFour}`);
+          } else {
+            expect(getRes.body.secretKey).toBe('****');
+          }
+
+          // Also verify the database has the updated values (what new instances would read)
+          const db = getDb();
+          const row = db.prepare(
+            'SELECT access_key, region, ami_id, instance_type, key_pair_name, security_group_id FROM aws_config ORDER BY id DESC LIMIT 1'
+          ).get() as any;
+
+          expect(row.access_key).toBe(accessKey);
+          expect(row.region).toBe(region);
+          expect(row.ami_id).toBe(amiId);
+          expect(row.instance_type).toBe(instanceType);
+          expect(row.key_pair_name).toBe(keyPairName);
+          expect(row.security_group_id).toBe(securityGroupId);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 218 - 0
server/src/routes/aws-config.test.ts

@@ -0,0 +1,218 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { initDb, getDb, closeDb } from '../db';
+import { encrypt, decrypt } from '../utils/crypto';
+
+// Mock the AWS SDK
+vi.mock('@aws-sdk/client-ec2', () => {
+  const mockSend = vi.fn();
+  return {
+    EC2Client: vi.fn().mockImplementation(() => ({
+      send: mockSend,
+    })),
+    DescribeRegionsCommand: vi.fn(),
+    __mockSend: mockSend,
+  };
+});
+
+// Get the mock send function
+import { __mockSend as mockSend } from '@aws-sdk/client-ec2';
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+describe('AWS Config Routes', () => {
+  let adminToken: string;
+  let userToken: string;
+  let app: any;
+
+  beforeEach(async () => {
+    vi.clearAllMocks();
+    initDb(':memory:');
+    adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+    userToken = makeToken({ id: 99, username: 'regularuser', role: 'user' });
+    // Re-import app to get fresh module
+    const appModule = await import('../app');
+    app = appModule.default;
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  describe('Authorization', () => {
+    it('should return 401 without token', async () => {
+      const res = await request(app).get('/api/admin/aws-config');
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 403 for non-admin user on GET', async () => {
+      const res = await request(app)
+        .get('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+
+    it('should return 403 for non-admin user on PUT', async () => {
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ accessKey: 'AK', secretKey: 'SK', region: 'us-east-1', amiId: 'ami-123' });
+      expect(res.status).toBe(403);
+    });
+  });
+
+  describe('GET /api/admin/aws-config', () => {
+    it('should return null when no config exists', async () => {
+      const res = await request(app)
+        .get('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body).toBeNull();
+    });
+
+    it('should return config with masked secret key', async () => {
+      // Insert a config directly
+      const db = getDb();
+      const encryptedKey = encrypt('wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY');
+      db.prepare(
+        `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type) VALUES (?, ?, ?, ?, ?)`
+      ).run('AKIAIOSFODNN7EXAMPLE', encryptedKey, 'us-east-1', 'ami-12345678', 't2.micro');
+
+      const res = await request(app)
+        .get('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.accessKey).toBe('AKIAIOSFODNN7EXAMPLE');
+      expect(res.body.secretKey).toBe('****EKEY');
+      expect(res.body.region).toBe('us-east-1');
+      expect(res.body.amiId).toBe('ami-12345678');
+      expect(res.body.instanceType).toBe('t2.micro');
+      // Secret key should NOT contain the original value
+      expect(res.body.secretKey).not.toContain('wJalrXUtnFEMI');
+    });
+  });
+
+  describe('PUT /api/admin/aws-config', () => {
+    it('should return 400 when required fields are missing', async () => {
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ accessKey: 'AK' });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('MISSING_FIELDS');
+    });
+
+    it('should return 400 with INVALID_AWS_CREDENTIALS when credentials are invalid', async () => {
+      (mockSend as any).mockRejectedValueOnce(new Error('Invalid credentials'));
+
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({
+          accessKey: 'INVALID_KEY',
+          secretKey: 'INVALID_SECRET',
+          region: 'us-east-1',
+          amiId: 'ami-12345678',
+        });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_AWS_CREDENTIALS');
+      expect(res.body.error.message).toBe('AWS 凭证无效');
+    });
+
+    it('should save config when credentials are valid', async () => {
+      (mockSend as any).mockResolvedValueOnce({ Regions: [] });
+
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({
+          accessKey: 'AKIAIOSFODNN7EXAMPLE',
+          secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
+          region: 'us-east-1',
+          amiId: 'ami-12345678',
+          instanceType: 't2.micro',
+          keyPairName: 'my-key',
+          securityGroupId: 'sg-12345',
+        });
+
+      expect(res.status).toBe(200);
+      expect(res.body.accessKey).toBe('AKIAIOSFODNN7EXAMPLE');
+      expect(res.body.secretKey).toBe('****EKEY');
+      expect(res.body.region).toBe('us-east-1');
+      expect(res.body.amiId).toBe('ami-12345678');
+      expect(res.body.instanceType).toBe('t2.micro');
+      expect(res.body.keyPairName).toBe('my-key');
+      expect(res.body.securityGroupId).toBe('sg-12345');
+
+      // Verify secret key is encrypted in DB
+      const db = getDb();
+      const row = db.prepare('SELECT secret_key_encrypted FROM aws_config ORDER BY id DESC LIMIT 1').get() as any;
+      expect(row.secret_key_encrypted).not.toBe('wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY');
+      const decrypted = decrypt(row.secret_key_encrypted);
+      expect(decrypted).toBe('wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY');
+    });
+
+    it('should update existing config on subsequent PUT', async () => {
+      (mockSend as any).mockResolvedValue({ Regions: [] });
+
+      // First save
+      await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({
+          accessKey: 'FIRST_KEY',
+          secretKey: 'FIRST_SECRET_KEY_VALUE',
+          region: 'us-east-1',
+          amiId: 'ami-111',
+        });
+
+      // Second save (update)
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({
+          accessKey: 'SECOND_KEY',
+          secretKey: 'SECOND_SECRET_KEY_VAL',
+          region: 'us-west-2',
+          amiId: 'ami-222',
+        });
+
+      expect(res.status).toBe(200);
+      expect(res.body.accessKey).toBe('SECOND_KEY');
+      expect(res.body.region).toBe('us-west-2');
+      expect(res.body.amiId).toBe('ami-222');
+
+      // Verify only one row exists
+      const db = getDb();
+      const count = db.prepare('SELECT COUNT(*) as cnt FROM aws_config').get() as any;
+      expect(count.cnt).toBe(1);
+    });
+
+    it('should handle optional fields as null', async () => {
+      (mockSend as any).mockResolvedValueOnce({ Regions: [] });
+
+      const res = await request(app)
+        .put('/api/admin/aws-config')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({
+          accessKey: 'AKIAIOSFODNN7EXAMPLE',
+          secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
+          region: 'us-east-1',
+          amiId: 'ami-12345678',
+        });
+
+      expect(res.status).toBe(200);
+      expect(res.body.instanceType).toBeNull();
+      expect(res.body.keyPairName).toBeNull();
+      expect(res.body.securityGroupId).toBeNull();
+    });
+  });
+});

+ 202 - 0
server/src/routes/aws-config.ts

@@ -0,0 +1,202 @@
+import { Router, Response } from 'express';
+import { EC2Client, DescribeRegionsCommand } from '@aws-sdk/client-ec2';
+import { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts';
+import { getDb } from '../db';
+import { encrypt, decrypt } from '../utils/crypto';
+import { AuthRequest } from '../middleware/auth';
+
+const router = Router();
+
+/**
+ * Mask a secret key, showing only the last 4 characters.
+ * e.g., "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" → "****EKEY"
+ */
+function maskSecretKey(secretKey: string): string {
+  if (!secretKey || secretKey.length <= 4) {
+    return '****';
+  }
+  return '****' + secretKey.slice(-4);
+}
+
+/**
+ * Validate AWS credentials by calling EC2 DescribeRegions.
+ */
+async function validateAwsCredentials(accessKey: string, secretKey: string, region: string): Promise<boolean> {
+  const client = new EC2Client({
+    region,
+    credentials: {
+      accessKeyId: accessKey,
+      secretAccessKey: secretKey,
+    },
+  });
+
+  try {
+    await client.send(new DescribeRegionsCommand({}));
+    return true;
+  } catch {
+    return false;
+  }
+}
+
+/**
+ * GET /api/admin/aws-config
+ * Returns the current AWS configuration with the secret key masked.
+ */
+router.get('/', (_req: AuthRequest, res: Response): void => {
+  const db = getDb();
+  const config = db.prepare(
+    'SELECT id, access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id, subnet_id, updated_at FROM aws_config ORDER BY id DESC LIMIT 1'
+  ).get() as any;
+
+  if (!config) {
+    res.json(null);
+    return;
+  }
+
+  let maskedSecretKey = '';
+  if (config.secret_key_encrypted) {
+    try {
+      const decrypted = decrypt(config.secret_key_encrypted);
+      maskedSecretKey = maskSecretKey(decrypted);
+    } catch {
+      maskedSecretKey = '****';
+    }
+  }
+
+  res.json({
+    id: config.id,
+    accessKey: config.access_key,
+    secretKey: maskedSecretKey,
+    region: config.region,
+    amiId: config.ami_id,
+    instanceType: config.instance_type,
+    keyPairName: config.key_pair_name,
+    securityGroupId: config.security_group_id,
+    subnetId: config.subnet_id,
+    updatedAt: config.updated_at,
+  });
+});
+
+
+/**
+ * PUT /api/admin/aws-config
+ * Update AWS configuration. Validates credentials before saving.
+ * Encrypts the secret key before storing.
+ */
+router.put('/', async (req: AuthRequest, res: Response): Promise<void> => {
+  const { accessKey, secretKey, region, amiId, instanceType, keyPairName, securityGroupId, subnetId } = req.body;
+
+  if (!accessKey || !region || !amiId || !instanceType || !keyPairName || !securityGroupId || !subnetId) {
+    res.status(400).json({
+      error: { code: 'MISSING_FIELDS', message: '缺少必填字段' },
+    });
+    return;
+  }
+
+  const db = getDb();
+  const existing = db.prepare('SELECT id, secret_key_encrypted FROM aws_config ORDER BY id DESC LIMIT 1').get() as any;
+
+  // If no secretKey provided, must have existing config with a saved one
+  if (!secretKey && !existing?.secret_key_encrypted) {
+    res.status(400).json({
+      error: { code: 'MISSING_FIELDS', message: '首次配置必须提供 Secret Access Key' },
+    });
+    return;
+  }
+
+  // Only validate credentials if secretKey is provided (new key)
+  if (secretKey) {
+    const isValid = await validateAwsCredentials(accessKey, secretKey, region);
+    if (!isValid) {
+      res.status(400).json({
+        error: { code: 'INVALID_AWS_CREDENTIALS', message: 'AWS 凭证无效' },
+      });
+      return;
+    }
+  }
+
+  const encryptedSecretKey = secretKey ? encrypt(secretKey) : existing.secret_key_encrypted;
+
+  if (existing) {
+    db.prepare(
+      `UPDATE aws_config SET access_key = ?, secret_key_encrypted = ?, region = ?, ami_id = ?, instance_type = ?, key_pair_name = ?, security_group_id = ?, subnet_id = ?, updated_at = strftime('%s', 'now') WHERE id = ?`
+    ).run(accessKey, encryptedSecretKey, region, amiId, instanceType, keyPairName, securityGroupId, subnetId, existing.id);
+  } else {
+    db.prepare(
+      `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id, subnet_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
+    ).run(accessKey, encryptedSecretKey, region, amiId, instanceType, keyPairName, securityGroupId, subnetId);
+  }
+
+  const config = db.prepare(
+    'SELECT id, access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id, subnet_id, updated_at FROM aws_config ORDER BY id DESC LIMIT 1'
+  ).get() as any;
+
+  let maskedSecretKey = '';
+  if (config.secret_key_encrypted) {
+    try {
+      const decrypted = decrypt(config.secret_key_encrypted);
+      maskedSecretKey = maskSecretKey(decrypted);
+    } catch {
+      maskedSecretKey = '****';
+    }
+  }
+
+  res.json({
+    id: config.id,
+    accessKey: config.access_key,
+    secretKey: maskedSecretKey,
+    region: config.region,
+    amiId: config.ami_id,
+    instanceType: config.instance_type,
+    keyPairName: config.key_pair_name,
+    securityGroupId: config.security_group_id,
+    subnetId: config.subnet_id,
+    updatedAt: config.updated_at,
+  });
+});
+
+/**
+ * POST /api/admin/aws-config/verify
+ * Verify saved AWS credentials by calling STS GetCallerIdentity.
+ */
+router.post('/verify', async (_req: AuthRequest, res: Response): Promise<void> => {
+  const db = getDb();
+  const config = db.prepare(
+    'SELECT access_key, secret_key_encrypted, region FROM aws_config ORDER BY id DESC LIMIT 1'
+  ).get() as { access_key: string; secret_key_encrypted: string; region: string } | undefined;
+
+  if (!config || !config.access_key || !config.secret_key_encrypted) {
+    res.status(400).json({ error: { code: 'NO_CONFIG', message: '尚未配置 AWS 凭证' } });
+    return;
+  }
+
+  let secretKey: string;
+  try {
+    secretKey = decrypt(config.secret_key_encrypted);
+  } catch {
+    res.status(500).json({ error: { code: 'DECRYPT_FAILED', message: '解密 Secret Key 失败' } });
+    return;
+  }
+
+  const client = new STSClient({
+    region: config.region,
+    credentials: { accessKeyId: config.access_key, secretAccessKey: secretKey },
+  });
+
+  try {
+    const result = await client.send(new GetCallerIdentityCommand({}));
+    res.json({
+      valid: true,
+      account: result.Account,
+      arn: result.Arn,
+      userId: result.UserId,
+    });
+  } catch (err: any) {
+    res.json({
+      valid: false,
+      message: err.message || 'AWS 凭证验证失败',
+    });
+  }
+});
+
+export default router;

+ 183 - 0
server/src/routes/instances-time.property.test.ts

@@ -0,0 +1,183 @@
+// Feature: ec2-management-platform, Property 15: 剩余时间计算正确性
+// **Validates: Requirements 8.4**
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb, getDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { encrypt } from '../utils/crypto';
+
+// Mock the instance-manager service
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+function insertInstance(
+  userId: number,
+  overrides: Partial<{
+    ec2_instance_id: string;
+    machine_guid: string;
+    status: string;
+    public_ip: string;
+    started_at: number;
+    expires_at: number;
+  }> = {},
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      overrides.ec2_instance_id ?? `i-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+      overrides.machine_guid ?? '12345678-1234-1234-1234-123456789abc',
+      overrides.status ?? 'running',
+      overrides.public_ip ?? '1.2.3.4',
+      'Administrator',
+      encrypt('testpass'),
+      overrides.started_at ?? now - 3600,
+      overrides.expires_at ?? now + 3600,
+      now,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+const userId = 1; // admin user seeded by initDb
+let userToken: string;
+
+beforeEach(() => {
+  initDb(':memory:');
+  userToken = makeToken({ id: userId, username: 'admin', role: 'admin' });
+});
+
+afterEach(() => {
+  vi.clearAllMocks();
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// Property 15: 剩余时间计算正确性
+// ---------------------------------------------------------------------------
+
+describe('Property 15: 剩余时间计算正确性', () => {
+  it('remaining_time should equal expires_at - now when T < expires_at, and 0 when T >= expires_at', async () => {
+    await fc.assert(
+      fc.asyncProperty(
+        // remaining seconds: positive means not expired, negative/zero means expired
+        fc.integer({ min: -7200, max: 86400 }),
+        async (offsetSeconds) => {
+          const db = getDb();
+          // Clean instances for this iteration
+          db.prepare('DELETE FROM instances').run();
+
+          const now = Math.floor(Date.now() / 1000);
+          const expiresAt = now + offsetSeconds;
+
+          insertInstance(userId, {
+            ec2_instance_id: `i-p15-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+            status: 'running',
+            expires_at: expiresAt,
+          });
+
+          const res = await request(app)
+            .get('/api/instances')
+            .set('Authorization', `Bearer ${userToken}`);
+
+          expect(res.status).toBe(200);
+          expect(res.body).toHaveLength(1);
+
+          const instance = res.body[0];
+
+          if (offsetSeconds > 0) {
+            // T < expires_at: remaining_time should be approximately expires_at - now
+            // Allow small tolerance for time passing during test execution
+            expect(instance.remaining_time).toBeGreaterThan(0);
+            expect(instance.remaining_time).toBeLessThanOrEqual(offsetSeconds);
+            expect(instance.remaining_time).toBeGreaterThanOrEqual(offsetSeconds - 2);
+          } else {
+            // T >= expires_at: remaining_time should be 0
+            expect(instance.remaining_time).toBe(0);
+          }
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: ec2-management-platform, Property 16: 到期提醒触发
+// **Validates: Requirements 8.5**
+// ---------------------------------------------------------------------------
+
+describe('Property 16: 到期提醒触发', () => {
+  it('expiring_soon should be true when 0 < remaining_time < 1800 (30 min), false otherwise', async () => {
+    await fc.assert(
+      fc.asyncProperty(
+        // remaining seconds from -3600 to 7200
+        fc.integer({ min: -3600, max: 7200 }),
+        async (offsetSeconds) => {
+          const db = getDb();
+          db.prepare('DELETE FROM instances').run();
+
+          const now = Math.floor(Date.now() / 1000);
+          const expiresAt = now + offsetSeconds;
+
+          insertInstance(userId, {
+            ec2_instance_id: `i-p16-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+            status: 'running',
+            expires_at: expiresAt,
+          });
+
+          const res = await request(app)
+            .get('/api/instances')
+            .set('Authorization', `Bearer ${userToken}`);
+
+          expect(res.status).toBe(200);
+          expect(res.body).toHaveLength(1);
+
+          const instance = res.body[0];
+
+          if (offsetSeconds > 0 && offsetSeconds < 1800) {
+            // Remaining time is between 0 and 30 minutes -> expiring_soon = true
+            expect(instance.expiring_soon).toBe(true);
+          } else if (offsetSeconds >= 1800) {
+            // Remaining time >= 30 minutes -> expiring_soon = false
+            expect(instance.expiring_soon).toBe(false);
+          } else {
+            // Expired (remaining_time = 0) -> expiring_soon = false
+            expect(instance.expiring_soon).toBe(false);
+          }
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 186 - 0
server/src/routes/instances.property.test.ts

@@ -0,0 +1,186 @@
+// Feature: ec2-management-platform, Property 12: 实例列表数据完整性
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb, getDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { encrypt } from '../utils/crypto';
+
+/**
+ * Validates: Requirements 7.1, 9.1
+ *
+ * Property 12: 实例列表数据完整性
+ * 对于任意实例集合,查询返回的列表应包含所有属于该查询范围的实例,
+ * 且每条记录包含实例状态、公网 IP 和剩余使用时间字段。
+ * 管理员查询还应额外包含所属用户和启动时间字段。
+ */
+
+// Mock the instance-manager service (routes import it)
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+// Generators
+const arbStatus = fc.constantFrom('pending', 'running', 'stopped', 'terminated');
+
+const arbIpOctet = fc.integer({ min: 0, max: 255 });
+const arbPublicIp = fc.tuple(arbIpOctet, arbIpOctet, arbIpOctet, arbIpOctet)
+  .map(([a, b, c, d]) => `${a}.${b}.${c}.${d}`);
+
+const arbHexChar = fc.constantFrom(...'0123456789abcdef');
+const arbUuidBlock = (len: number) => fc.stringOf(arbHexChar, { minLength: len, maxLength: len });
+const arbMachineGuid = fc.tuple(
+  arbUuidBlock(8), arbUuidBlock(4), arbUuidBlock(4), arbUuidBlock(4), arbUuidBlock(12),
+).map(([a, b, c, d, e]) => `${a}-${b}-${c}-${d}-${e}`);
+
+const arbInstanceCount = fc.integer({ min: 1, max: 10 });
+
+
+/**
+ * Insert N random instances directly into the database for a given user.
+ * Returns the array of generated instance data for verification.
+ */
+function insertInstances(
+  userId: number,
+  count: number,
+  statuses: string[],
+  ips: string[],
+  guids: string[],
+): void {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+
+  for (let i = 0; i < count; i++) {
+    db.prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip,
+        rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    ).run(
+      userId,
+      `i-prop12-${userId}-${i}-${Date.now()}`,
+      guids[i % guids.length],
+      statuses[i % statuses.length],
+      ips[i % ips.length],
+      'Administrator',
+      encrypt('testpass'),
+      now - 3600,
+      now + 3600,
+      now,
+    );
+  }
+}
+
+describe('Property 12: 实例列表数据完整性', () => {
+  let userToken: string;
+  const userId = 1; // admin user seeded by initDb
+
+  beforeEach(() => {
+    initDb(':memory:');
+    userToken = makeToken({ id: userId, username: 'admin', role: 'admin' });
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  it('GET /api/instances returns exactly N items with status, public_ip, and remaining_time fields for N inserted instances', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(
+        arbInstanceCount,
+        fc.array(arbStatus, { minLength: 1, maxLength: 10 }),
+        fc.array(arbPublicIp, { minLength: 1, maxLength: 10 }),
+        fc.array(arbMachineGuid, { minLength: 1, maxLength: 10 }),
+        async (n, statuses, ips, guids) => {
+          // Re-init DB each iteration to get a clean state
+          closeDb();
+          initDb(':memory:');
+          userToken = makeToken({ id: userId, username: 'admin', role: 'admin' });
+          iteration++;
+
+          // Insert N instances for the user
+          insertInstances(userId, n, statuses, ips, guids);
+
+          // Call GET /api/instances
+          const res = await request(app)
+            .get('/api/instances')
+            .set('Authorization', `Bearer ${userToken}`);
+
+          expect(res.status).toBe(200);
+
+          // 1. The returned list has exactly N items
+          expect(res.body).toHaveLength(n);
+
+          // 2. Each item has status, public_ip, and remaining_time fields
+          for (const instance of res.body) {
+            expect(instance).toHaveProperty('status');
+            expect(typeof instance.status).toBe('string');
+            expect(['pending', 'running', 'stopped', 'terminated']).toContain(instance.status);
+
+            expect(instance).toHaveProperty('public_ip');
+            expect(typeof instance.public_ip).toBe('string');
+
+            expect(instance).toHaveProperty('remaining_time');
+            expect(typeof instance.remaining_time).toBe('number');
+            expect(instance.remaining_time).toBeGreaterThanOrEqual(0);
+          }
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+
+  it('instances belonging to other users are not returned in the list', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(
+        arbInstanceCount,
+        fc.array(arbStatus, { minLength: 1, maxLength: 5 }),
+        fc.array(arbPublicIp, { minLength: 1, maxLength: 5 }),
+        fc.array(arbMachineGuid, { minLength: 1, maxLength: 5 }),
+        async (n, statuses, ips, guids) => {
+          closeDb();
+          initDb(':memory:');
+          iteration++;
+
+          const db = getDb();
+          // Create a second user
+          db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(`otheruser${iteration}`);
+          const otherUserId = 2;
+
+          // Insert N instances for the OTHER user (not userId=1)
+          insertInstances(otherUserId, n, statuses, ips, guids);
+
+          // Query as userId=1 (admin)
+          const token = makeToken({ id: userId, username: 'admin', role: 'admin' });
+          const res = await request(app)
+            .get('/api/instances')
+            .set('Authorization', `Bearer ${token}`);
+
+          expect(res.status).toBe(200);
+          // User 1 should see 0 instances (all belong to user 2)
+          expect(res.body).toHaveLength(0);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 368 - 0
server/src/routes/instances.test.ts

@@ -0,0 +1,368 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb, getDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { encrypt } from '../utils/crypto';
+
+// Mock the instance-manager service
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+import {
+  launchInstance,
+  stopInstance,
+  startInstance,
+  rebootInstance,
+  terminateInstance,
+  getInstanceRdpInfo,
+} from '../services/instance-manager';
+
+const mockedLaunch = vi.mocked(launchInstance);
+const mockedStop = vi.mocked(stopInstance);
+const mockedStart = vi.mocked(startInstance);
+const mockedReboot = vi.mocked(rebootInstance);
+const mockedTerminate = vi.mocked(terminateInstance);
+const mockedGetRdp = vi.mocked(getInstanceRdpInfo);
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+function insertInstance(
+  userId: number,
+  overrides: Partial<{
+    ec2_instance_id: string;
+    machine_guid: string;
+    status: string;
+    public_ip: string;
+    rdp_username: string;
+    rdp_password_encrypted: string;
+    started_at: number;
+    expires_at: number;
+  }> = {},
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      overrides.ec2_instance_id ?? 'i-abc123',
+      overrides.machine_guid ?? '12345678-1234-1234-1234-123456789abc',
+      overrides.status ?? 'running',
+      overrides.public_ip ?? '1.2.3.4',
+      overrides.rdp_username ?? 'Administrator',
+      overrides.rdp_password_encrypted ?? encrypt('testpass'),
+      overrides.started_at ?? now,
+      overrides.expires_at ?? now + 86400,
+      now,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+describe('Instances Routes', () => {
+  let userToken: string;
+  let otherUserToken: string;
+  const userId = 1; // admin user seeded by initDb
+
+  beforeEach(() => {
+    initDb(':memory:');
+    userToken = makeToken({ id: userId, username: 'admin', role: 'admin' });
+    // Create another user for ownership tests
+    const db = getDb();
+    db.prepare("INSERT INTO users (username, password_hash, role) VALUES ('other', 'hash', 'user')").run();
+    otherUserToken = makeToken({ id: 2, username: 'other', role: 'user' });
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  describe('Authentication', () => {
+    it('should return 401 without token on POST /api/instances', async () => {
+      const res = await request(app).post('/api/instances').send({ machineGuid: '12345678-1234-1234-1234-123456789abc' });
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 401 without token on GET /api/instances', async () => {
+      const res = await request(app).get('/api/instances');
+      expect(res.status).toBe(401);
+    });
+  });
+
+  describe('POST /api/instances', () => {
+    it('should reject missing machineGuid', async () => {
+      const res = await request(app)
+        .post('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({});
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INPUT');
+    });
+
+    it('should reject invalid UUID format', async () => {
+      const res = await request(app)
+        .post('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ machineGuid: 'not-a-uuid' });
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_MACHINE_GUID');
+    });
+
+    it('should launch instance with valid machineGuid', async () => {
+      const guid = '12345678-1234-1234-1234-123456789abc';
+      mockedLaunch.mockResolvedValue({
+        instanceId: 1,
+        ec2InstanceId: 'i-abc123',
+        machineGuid: guid,
+        status: 'running',
+        publicIp: '1.2.3.4',
+        rdpUsername: 'Administrator',
+        rdpPassword: 'secret',
+        startedAt: 1000,
+        expiresAt: 87400,
+      });
+
+      const res = await request(app)
+        .post('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ machineGuid: guid });
+
+      expect(res.status).toBe(201);
+      expect(res.body.ec2InstanceId).toBe('i-abc123');
+      expect(res.body.publicIp).toBe('1.2.3.4');
+      expect(mockedLaunch).toHaveBeenCalledWith(userId, guid);
+    });
+
+    it('should return 502 when launch fails', async () => {
+      mockedLaunch.mockRejectedValue(new Error('EC2 实例启动失败: quota exceeded'));
+
+      const res = await request(app)
+        .post('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ machineGuid: '12345678-1234-1234-1234-123456789abc' });
+
+      expect(res.status).toBe(502);
+      expect(res.body.error.code).toBe('LAUNCH_FAILED');
+    });
+  });
+
+  describe('GET /api/instances', () => {
+    it('should return empty list when user has no instances', async () => {
+      const res = await request(app)
+        .get('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body).toEqual([]);
+    });
+
+    it('should return user instances with remaining_time', async () => {
+      const now = Math.floor(Date.now() / 1000);
+      insertInstance(userId, { expires_at: now + 3600 });
+
+      const res = await request(app)
+        .get('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body).toHaveLength(1);
+      expect(res.body[0].status).toBe('running');
+      expect(res.body[0].public_ip).toBe('1.2.3.4');
+      expect(res.body[0].remaining_time).toBeGreaterThan(0);
+      expect(res.body[0].remaining_time).toBeLessThanOrEqual(3600);
+    });
+
+    it('should return remaining_time=0 for terminated instances', async () => {
+      insertInstance(userId, { status: 'terminated', expires_at: Math.floor(Date.now() / 1000) + 3600 });
+
+      const res = await request(app)
+        .get('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body[0].remaining_time).toBe(0);
+    });
+
+    it('should not return other users instances', async () => {
+      insertInstance(2, { ec2_instance_id: 'i-other' }); // belongs to user 2
+
+      const res = await request(app)
+        .get('/api/instances')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body).toHaveLength(0);
+    });
+  });
+
+  describe('Ownership verification', () => {
+    it('should return 404 for non-existent instance', async () => {
+      const res = await request(app)
+        .post('/api/instances/999/stop')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(404);
+    });
+
+    it('should return 403 when user does not own the instance', async () => {
+      const id = insertInstance(2); // belongs to user 2
+
+      const res = await request(app)
+        .post(`/api/instances/${id}/stop`)
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+      expect(res.body.error.code).toBe('FORBIDDEN');
+    });
+
+    it('should return 400 for invalid instance ID', async () => {
+      const res = await request(app)
+        .post('/api/instances/abc/stop')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INPUT');
+    });
+  });
+
+  describe('POST /api/instances/:id/stop', () => {
+    it('should stop a running instance owned by user', async () => {
+      const id = insertInstance(userId);
+      mockedStop.mockResolvedValue(undefined);
+
+      const res = await request(app)
+        .post(`/api/instances/${id}/stop`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.status).toBe('stopped');
+      expect(mockedStop).toHaveBeenCalledWith(id);
+    });
+
+    it('should return 400 when stop fails', async () => {
+      const id = insertInstance(userId, { status: 'stopped' });
+      mockedStop.mockRejectedValue(new Error('只能关机运行中的实例'));
+
+      const res = await request(app)
+        .post(`/api/instances/${id}/stop`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('STOP_FAILED');
+    });
+  });
+
+  describe('POST /api/instances/:id/start', () => {
+    it('should start a stopped instance owned by user', async () => {
+      const id = insertInstance(userId, { status: 'stopped' });
+      mockedStart.mockResolvedValue(undefined);
+
+      const res = await request(app)
+        .post(`/api/instances/${id}/start`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.status).toBe('running');
+      expect(mockedStart).toHaveBeenCalledWith(id);
+    });
+
+    it('should return 400 when start fails', async () => {
+      const id = insertInstance(userId);
+      mockedStart.mockRejectedValue(new Error('只能启动已停止的实例'));
+
+      const res = await request(app)
+        .post(`/api/instances/${id}/start`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('START_FAILED');
+    });
+  });
+
+  describe('POST /api/instances/:id/reboot', () => {
+    it('should reboot a running instance owned by user', async () => {
+      const id = insertInstance(userId);
+      mockedReboot.mockResolvedValue(undefined);
+
+      const res = await request(app)
+        .post(`/api/instances/${id}/reboot`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.status).toBe('running');
+      expect(mockedReboot).toHaveBeenCalledWith(id);
+    });
+  });
+
+  describe('DELETE /api/instances/:id', () => {
+    it('should terminate an instance owned by user', async () => {
+      const id = insertInstance(userId);
+      mockedTerminate.mockResolvedValue(undefined);
+
+      const res = await request(app)
+        .delete(`/api/instances/${id}`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.status).toBe('terminated');
+      expect(mockedTerminate).toHaveBeenCalledWith(id);
+    });
+
+    it('should return 400 when terminate fails', async () => {
+      const id = insertInstance(userId, { status: 'terminated' });
+      mockedTerminate.mockRejectedValue(new Error('实例已终止'));
+
+      const res = await request(app)
+        .delete(`/api/instances/${id}`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('TERMINATE_FAILED');
+    });
+  });
+
+  describe('GET /api/instances/:id/rdp', () => {
+    it('should return RDP info for owned instance', async () => {
+      const id = insertInstance(userId);
+      mockedGetRdp.mockReturnValue({
+        publicIp: '1.2.3.4',
+        rdpUsername: 'Administrator',
+        rdpPassword: 'secret',
+      });
+
+      const res = await request(app)
+        .get(`/api/instances/${id}/rdp`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.publicIp).toBe('1.2.3.4');
+      expect(res.body.rdpUsername).toBe('Administrator');
+      expect(res.body.rdpPassword).toBe('secret');
+      expect(mockedGetRdp).toHaveBeenCalledWith(id);
+    });
+
+    it('should return 403 for instance not owned by user', async () => {
+      const id = insertInstance(2);
+
+      const res = await request(app)
+        .get(`/api/instances/${id}/rdp`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(403);
+    });
+  });
+});

+ 221 - 0
server/src/routes/instances.ts

@@ -0,0 +1,221 @@
+import { Router, Response } from 'express';
+import { getDb } from '../db';
+import { AuthRequest } from '../middleware/auth';
+import { isValidMachineGuid } from '../utils/validation';
+import {
+  launchInstance,
+  stopInstance,
+  startInstance,
+  rebootInstance,
+  terminateInstance,
+  getInstanceRdpInfo,
+  InstanceRecord,
+} from '../services/instance-manager';
+
+const router = Router();
+
+/**
+ * POST /api/instances
+ * Launch a new EC2 instance with the given MachineGuid.
+ */
+router.post('/', async (req: AuthRequest, res: Response): Promise<void> => {
+  const userId = req.user!.id;
+  const { machineGuid } = req.body;
+
+  if (!machineGuid || typeof machineGuid !== 'string') {
+    res.status(400).json({
+      error: { code: 'INVALID_INPUT', message: '请提供 machineGuid' },
+    });
+    return;
+  }
+
+  if (!isValidMachineGuid(machineGuid)) {
+    res.status(400).json({
+      error: { code: 'INVALID_MACHINE_GUID', message: 'MachineGuid 格式无效,需为 UUID 格式' },
+    });
+    return;
+  }
+
+  try {
+    const result = await launchInstance(userId, machineGuid, req.user!.username);
+    res.status(201).json(result);
+  } catch (err: any) {
+    res.status(502).json({
+      error: { code: 'LAUNCH_FAILED', message: err.message },
+    });
+  }
+});
+
+/**
+ * GET /api/instances
+ * List all instances for the current user with status, IP, and remaining time.
+ */
+router.get('/', (req: AuthRequest, res: Response): void => {
+  const userId = req.user!.id;
+  const db = getDb();
+
+  const rows = db
+    .prepare(
+      `SELECT id, ec2_instance_id, machine_guid, status, public_ip, started_at, expires_at, created_at
+       FROM instances WHERE user_id = ? ORDER BY created_at DESC`,
+    )
+    .all(userId) as Pick<
+    InstanceRecord,
+    'id' | 'ec2_instance_id' | 'machine_guid' | 'status' | 'public_ip' | 'started_at' | 'expires_at' | 'created_at'
+  >[];
+
+  const now = Math.floor(Date.now() / 1000);
+
+  const instances = rows.map((row) => {
+    let remaining_time = 0;
+    if (row.expires_at && row.status !== 'terminated') {
+      remaining_time = Math.max(0, row.expires_at - now);
+    }
+    const expiring_soon = row.status !== 'terminated' && remaining_time > 0 && remaining_time < 300;
+    return {
+      id: row.id,
+      ec2_instance_id: row.ec2_instance_id,
+      machine_guid: row.machine_guid,
+      status: row.status,
+      public_ip: row.public_ip,
+      started_at: row.started_at,
+      expires_at: row.expires_at,
+      remaining_time,
+      expiring_soon,
+      created_at: row.created_at,
+    };
+  });
+
+  res.json(instances);
+});
+
+/**
+ * Helper: verify instance ownership. Returns the instance row or sends an error response.
+ */
+function verifyOwnership(
+  req: AuthRequest,
+  res: Response,
+): InstanceRecord | null {
+  const userId = req.user!.id;
+  const instanceId = Number(req.params.id);
+
+  if (isNaN(instanceId)) {
+    res.status(400).json({
+      error: { code: 'INVALID_INPUT', message: '无效的实例 ID' },
+    });
+    return null;
+  }
+
+  const db = getDb();
+  const row = db
+    .prepare('SELECT * FROM instances WHERE id = ?')
+    .get(instanceId) as InstanceRecord | undefined;
+
+  if (!row) {
+    res.status(404).json({
+      error: { code: 'NOT_FOUND', message: '实例不存在' },
+    });
+    return null;
+  }
+
+  if (row.user_id !== userId) {
+    res.status(403).json({
+      error: { code: 'FORBIDDEN', message: '无权操作此实例' },
+    });
+    return null;
+  }
+
+  return row;
+}
+
+/**
+ * POST /api/instances/:id/stop
+ * Stop a running instance.
+ */
+router.post('/:id/stop', async (req: AuthRequest, res: Response): Promise<void> => {
+  const instance = verifyOwnership(req, res);
+  if (!instance) return;
+
+  try {
+    await stopInstance(instance.id);
+    res.json({ message: '实例已关机', id: instance.id, status: 'stopped' });
+  } catch (err: any) {
+    res.status(400).json({
+      error: { code: 'STOP_FAILED', message: err.message },
+    });
+  }
+});
+
+/**
+ * POST /api/instances/:id/start
+ * Start a stopped instance.
+ */
+router.post('/:id/start', async (req: AuthRequest, res: Response): Promise<void> => {
+  const instance = verifyOwnership(req, res);
+  if (!instance) return;
+
+  try {
+    await startInstance(instance.id);
+    res.json({ message: '实例已启动', id: instance.id, status: 'running' });
+  } catch (err: any) {
+    res.status(400).json({
+      error: { code: 'START_FAILED', message: err.message },
+    });
+  }
+});
+
+/**
+ * POST /api/instances/:id/reboot
+ * Reboot a running instance.
+ */
+router.post('/:id/reboot', async (req: AuthRequest, res: Response): Promise<void> => {
+  const instance = verifyOwnership(req, res);
+  if (!instance) return;
+
+  try {
+    await rebootInstance(instance.id);
+    res.json({ message: '实例已重启', id: instance.id, status: 'running' });
+  } catch (err: any) {
+    res.status(400).json({
+      error: { code: 'REBOOT_FAILED', message: err.message },
+    });
+  }
+});
+
+/**
+ * DELETE /api/instances/:id
+ * Terminate (destroy) an instance.
+ */
+router.delete('/:id', async (req: AuthRequest, res: Response): Promise<void> => {
+  const instance = verifyOwnership(req, res);
+  if (!instance) return;
+
+  try {
+    await terminateInstance(instance.id);
+    res.json({ message: '实例已销毁', id: instance.id, status: 'terminated' });
+  } catch (err: any) {
+    res.status(400).json({
+      error: { code: 'TERMINATE_FAILED', message: err.message },
+    });
+  }
+});
+
+/**
+ * GET /api/instances/:id/rdp
+ * Get RDP connection info for an instance.
+ */
+router.get('/:id/rdp', (req: AuthRequest, res: Response): void => {
+  const instance = verifyOwnership(req, res);
+  if (!instance) return;
+
+  try {
+    const rdpInfo = getInstanceRdpInfo(instance.id);
+    res.json(rdpInfo);
+  } catch (err: any) {
+    res.status(400).json({
+      error: { code: 'RDP_INFO_FAILED', message: err.message },
+    });
+  }
+});
+
+export default router;

+ 113 - 0
server/src/routes/invitations.property.test.ts

@@ -0,0 +1,113 @@
+// Feature: ec2-management-platform, Property 3: 邀请码删除即移除
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+
+/**
+ * Validates: Requirements 2.4
+ *
+ * Property 3: 邀请码删除即移除
+ * 对于任意邀请码列表,删除其中一个邀请码后,重新查询列表应不包含该邀请码,且列表长度减少 1。
+ */
+
+function makeAdminToken(): string {
+  const payload: JwtPayload = { id: 1, username: 'admin', role: 'admin' };
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+// Generator for invitation code strings
+const arbInvitationCode = fc.stringOf(
+  fc.constantFrom(...'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'),
+  { minLength: 4, maxLength: 12 },
+);
+
+describe('Property 3: 邀请码删除即移除', () => {
+  let adminToken: string;
+
+  beforeEach(() => {
+    initDb(':memory:');
+    adminToken = makeAdminToken();
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  it('deleting one invitation code removes it from the list and decreases length by 1', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(
+        // Generate N unique codes (1..8) and an index to pick which one to delete
+        fc.integer({ min: 1, max: 8 }).chain((n) =>
+          fc.tuple(
+            fc.uniqueArray(arbInvitationCode, { minLength: n, maxLength: n, comparator: 'IsStrictlyEqual' }),
+            fc.integer({ min: 0, max: n - 1 }),
+          ),
+        ),
+        async ([codes, deleteIndex]) => {
+          const prefix = `IT${iteration++}`;
+
+          // Create N invitation codes with unique prefixes
+          const createdIds: number[] = [];
+          const createdCodes: string[] = [];
+          for (let i = 0; i < codes.length; i++) {
+            const uniqueCode = `${prefix}-${codes[i]}`;
+            const res = await request(app)
+              .post('/api/admin/invitations')
+              .set('Authorization', `Bearer ${adminToken}`)
+              .send({ code: uniqueCode });
+            expect(res.status).toBe(201);
+            createdIds.push(res.body.id);
+            createdCodes.push(uniqueCode);
+          }
+
+          // Get list before deletion
+          const listBefore = await request(app)
+            .get('/api/admin/invitations')
+            .set('Authorization', `Bearer ${adminToken}`);
+          expect(listBefore.status).toBe(200);
+
+          // Filter to only our codes for this iteration
+          const ourCodesBefore = listBefore.body.filter((inv: any) =>
+            createdCodes.includes(inv.code),
+          );
+          const lengthBefore = ourCodesBefore.length;
+          expect(lengthBefore).toBe(codes.length);
+
+          // Delete one code at the chosen index
+          const idToDelete = createdIds[deleteIndex];
+          const codeToDelete = createdCodes[deleteIndex];
+
+          const deleteRes = await request(app)
+            .delete(`/api/admin/invitations/${idToDelete}`)
+            .set('Authorization', `Bearer ${adminToken}`);
+          expect(deleteRes.status).toBe(204);
+
+          // Get list after deletion
+          const listAfter = await request(app)
+            .get('/api/admin/invitations')
+            .set('Authorization', `Bearer ${adminToken}`);
+          expect(listAfter.status).toBe(200);
+
+          // Filter to only our codes for this iteration
+          const ourCodesAfter = listAfter.body.filter((inv: any) =>
+            createdCodes.includes(inv.code),
+          );
+
+          // The deleted code should not be in the list
+          const deletedFound = ourCodesAfter.find((inv: any) => inv.code === codeToDelete);
+          expect(deletedFound).toBeUndefined();
+
+          // List length should have decreased by 1
+          expect(ourCodesAfter.length).toBe(lengthBefore - 1);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 197 - 0
server/src/routes/invitations.test.ts

@@ -0,0 +1,197 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, getDb, closeDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+describe('Invitations Routes', () => {
+  let adminToken: string;
+  let userToken: string;
+
+  beforeEach(() => {
+    initDb(':memory:');
+    // admin user is seeded by initDb (id=1, username=admin, role=admin)
+    adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+    userToken = makeToken({ id: 99, username: 'regularuser', role: 'user' });
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  describe('Authorization', () => {
+    it('should return 401 without token', async () => {
+      const res = await request(app).get('/api/admin/invitations');
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 403 for non-admin user', async () => {
+      const res = await request(app)
+        .get('/api/admin/invitations')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+
+    it('should return 403 for non-admin on POST', async () => {
+      const res = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ code: 'TEST' });
+      expect(res.status).toBe(403);
+    });
+
+    it('should return 403 for non-admin on PATCH disable', async () => {
+      const res = await request(app)
+        .patch('/api/admin/invitations/1/disable')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+
+    it('should return 403 for non-admin on DELETE', async () => {
+      const res = await request(app)
+        .delete('/api/admin/invitations/1')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+  });
+
+  describe('POST /api/admin/invitations', () => {
+    it('should create an invitation with a provided code', async () => {
+      const res = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'MY-CODE-123' });
+
+      expect(res.status).toBe(201);
+      expect(res.body.code).toBe('MY-CODE-123');
+      expect(res.body.is_active).toBe(1);
+      expect(res.body.usage_count).toBe(0);
+      expect(res.body.id).toBeDefined();
+      expect(res.body.created_at).toBeDefined();
+    });
+
+    it('should auto-generate a code when none provided', async () => {
+      const res = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({});
+
+      expect(res.status).toBe(201);
+      expect(res.body.code).toBeDefined();
+      expect(res.body.code.length).toBe(8);
+    });
+
+    it('should reject duplicate code with 409', async () => {
+      await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'DUP-CODE' });
+
+      const res = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'DUP-CODE' });
+
+      expect(res.status).toBe(409);
+      expect(res.body.error.code).toBe('CODE_EXISTS');
+    });
+  });
+
+  describe('GET /api/admin/invitations', () => {
+    it('should return an empty list initially', async () => {
+      const res = await request(app)
+        .get('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(Array.isArray(res.body)).toBe(true);
+    });
+
+    it('should return created invitations with all fields', async () => {
+      await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'LIST-TEST' });
+
+      const res = await request(app)
+        .get('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.length).toBeGreaterThanOrEqual(1);
+      const inv = res.body.find((i: any) => i.code === 'LIST-TEST');
+      expect(inv).toBeDefined();
+      expect(inv.id).toBeDefined();
+      expect(inv.is_active).toBe(1);
+      expect(inv.usage_count).toBe(0);
+      expect(inv.created_at).toBeDefined();
+    });
+  });
+
+  describe('PATCH /api/admin/invitations/:id/disable', () => {
+    it('should disable an invitation code', async () => {
+      const createRes = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'TO-DISABLE' });
+
+      const id = createRes.body.id;
+
+      const res = await request(app)
+        .patch(`/api/admin/invitations/${id}/disable`)
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.is_active).toBe(0);
+      expect(res.body.code).toBe('TO-DISABLE');
+    });
+
+    it('should return 404 for non-existent invitation', async () => {
+      const res = await request(app)
+        .patch('/api/admin/invitations/99999/disable')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(404);
+      expect(res.body.error.code).toBe('NOT_FOUND');
+    });
+  });
+
+  describe('DELETE /api/admin/invitations/:id', () => {
+    it('should delete an invitation code', async () => {
+      const createRes = await request(app)
+        .post('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ code: 'TO-DELETE' });
+
+      const id = createRes.body.id;
+
+      const res = await request(app)
+        .delete(`/api/admin/invitations/${id}`)
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(204);
+
+      // Verify it's gone
+      const listRes = await request(app)
+        .get('/api/admin/invitations')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      const found = listRes.body.find((i: any) => i.code === 'TO-DELETE');
+      expect(found).toBeUndefined();
+    });
+
+    it('should return 404 for non-existent invitation', async () => {
+      const res = await request(app)
+        .delete('/api/admin/invitations/99999')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(404);
+      expect(res.body.error.code).toBe('NOT_FOUND');
+    });
+  });
+});

+ 131 - 0
server/src/routes/invitations.ts

@@ -0,0 +1,131 @@
+import { Router, Response } from 'express';
+import crypto from 'crypto';
+import { getDb } from '../db';
+import { AuthRequest } from '../middleware/auth';
+
+const router = Router();
+
+/**
+ * POST /api/admin/invitations
+ * Create a new invitation code. Optionally accepts { code } in body,
+ * otherwise auto-generates a random 8-char hex code.
+ */
+router.post('/', (req: AuthRequest, res: Response): void => {
+  const { code } = req.body;
+  const invitationCode = code || crypto.randomBytes(6).toString('hex');
+
+  const db = getDb();
+
+  // Check for duplicate code
+  const existing = db.prepare(
+    'SELECT id FROM invitation_codes WHERE code = ?'
+  ).get(invitationCode) as { id: number } | undefined;
+
+  if (existing) {
+    res.status(409).json({
+      error: { code: 'CODE_EXISTS', message: '邀请码已存在' },
+    });
+    return;
+  }
+
+  const result = db.prepare(
+    'INSERT INTO invitation_codes (code, is_active, usage_count) VALUES (?, 1, 0)'
+  ).run(invitationCode);
+
+  const created = db.prepare(
+    'SELECT id, code, is_active, usage_count, created_at FROM invitation_codes WHERE id = ?'
+  ).get(result.lastInsertRowid) as any;
+
+  res.status(201).json(created);
+});
+
+/**
+ * GET /api/admin/invitations
+ * List all invitation codes with id, code, is_active, usage_count, created_at.
+ */
+router.get('/', (_req: AuthRequest, res: Response): void => {
+  const db = getDb();
+  const invitations = db.prepare(
+    'SELECT id, code, is_active, usage_count, created_at FROM invitation_codes ORDER BY created_at DESC'
+  ).all();
+
+  res.json(invitations);
+});
+
+/**
+ * PATCH /api/admin/invitations/:id/disable
+ * Disable an invitation code (set is_active = 0).
+ */
+router.patch('/:id/disable', (req: AuthRequest, res: Response): void => {
+  const { id } = req.params;
+  const db = getDb();
+
+  const invitation = db.prepare(
+    'SELECT id FROM invitation_codes WHERE id = ?'
+  ).get(id) as { id: number } | undefined;
+
+  if (!invitation) {
+    res.status(404).json({
+      error: { code: 'NOT_FOUND', message: '邀请码不存在' },
+    });
+    return;
+  }
+
+  db.prepare('UPDATE invitation_codes SET is_active = 0 WHERE id = ?').run(id);
+
+  const updated = db.prepare(
+    'SELECT id, code, is_active, usage_count, created_at FROM invitation_codes WHERE id = ?'
+  ).get(id) as any;
+
+  res.json(updated);
+});
+
+/**
+ * PATCH /api/admin/invitations/:id/enable
+ * Enable an invitation code (set is_active = 1).
+ */
+router.patch('/:id/enable', (req: AuthRequest, res: Response): void => {
+  const { id } = req.params;
+  const db = getDb();
+
+  const invitation = db.prepare(
+    'SELECT id FROM invitation_codes WHERE id = ?'
+  ).get(id) as { id: number } | undefined;
+
+  if (!invitation) {
+    res.status(404).json({
+      error: { code: 'NOT_FOUND', message: '邀请码不存在' },
+    });
+    return;
+  }
+
+  db.prepare('UPDATE invitation_codes SET is_active = 1 WHERE id = ?').run(id);
+
+  const updated = db.prepare(
+    'SELECT id, code, is_active, usage_count, created_at FROM invitation_codes WHERE id = ?'
+  ).get(id) as any;
+
+  res.json(updated);
+});
+
+/**
+ * DELETE /api/admin/invitations/:id
+ * Delete an invitation code.
+ */
+router.delete('/:id', (req: AuthRequest, res: Response): void => {
+  const { id } = req.params;
+  const db = getDb();
+
+  const result = db.prepare('DELETE FROM invitation_codes WHERE id = ?').run(id);
+
+  if (result.changes === 0) {
+    res.status(404).json({
+      error: { code: 'NOT_FOUND', message: '邀请码不存在' },
+    });
+    return;
+  }
+
+  res.status(204).send();
+});
+
+export default router;

+ 313 - 0
server/src/routes/rdp-sessions.property.test.ts

@@ -0,0 +1,313 @@
+// Feature: web-rdp-connect, Property 3, 6, 7
+// Property-based tests for RDP Sessions API routes
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import fc from 'fast-check';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt } from '../utils/crypto';
+
+// Mock guacamole-proxy to avoid guacamole-lite dependency
+vi.mock('../services/guacamole-proxy', () => ({
+  initGuacamoleProxy: vi.fn(),
+  testGuacdConnection: vi.fn(),
+}));
+
+// Mock instance-manager to avoid AWS calls
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+import app from '../app';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+function insertUser(username: string, role: 'admin' | 'user'): number {
+  const db = getDb();
+  const result = db
+    .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', ?)")
+    .run(username, role);
+  return Number(result.lastInsertRowid);
+}
+
+function insertInstance(
+  userId: number,
+  overrides: Partial<{
+    ec2_instance_id: string;
+    status: string;
+    public_ip: string;
+    rdp_username: string;
+    rdp_password_encrypted: string;
+  }> = {},
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      overrides.ec2_instance_id ?? `i-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+      '12345678-1234-1234-1234-123456789abc',
+      overrides.status ?? 'running',
+      overrides.public_ip ?? '1.2.3.4',
+      overrides.rdp_username ?? 'Administrator',
+      overrides.rdp_password_encrypted ?? encrypt('testpass'),
+      now,
+      now + 86400,
+      now,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+function insertRdpSession(
+  userId: number,
+  instanceId: number,
+  ec2InstanceId: string,
+  status: 'connecting' | 'connected' | 'disconnected' = 'connecting',
+): string {
+  const db = getDb();
+  const id = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+  const now = Math.floor(Date.now() / 1000);
+  db.prepare(
+    `INSERT INTO rdp_sessions (id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+  ).run(id, userId, instanceId, ec2InstanceId, 'hash-' + id, status, now, now + 300);
+  return id;
+}
+
+// ---------------------------------------------------------------------------
+// Arbitraries
+// ---------------------------------------------------------------------------
+
+/** Arbitrary for valid usernames (alphanumeric, 3-20 chars) */
+const usernameArb = fc
+  .stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')), {
+    minLength: 3,
+    maxLength: 12,
+  })
+  .filter((s) => s.length >= 3);
+
+/** Arbitrary for EC2 instance IDs */
+const ec2IdArb = fc
+  .stringOf(fc.constantFrom(...'abcdef0123456789'.split('')), { minLength: 8, maxLength: 17 })
+  .map((s) => `i-${s}`);
+
+/** Arbitrary for active session statuses */
+const activeStatusArb = fc.constantFrom('connecting' as const, 'connected' as const);
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 3: 实例所有权强制检查 (via API)
+// **Validates: Requirements 3.1, 3.2**
+// ---------------------------------------------------------------------------
+
+describe('Property 3: Instance Ownership Enforcement (via API)', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  it('should return 403 and create no session when non-owner requests RDP session via API', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(usernameArb, usernameArb, ec2IdArb, async (ownerName, otherName, ec2Id) => {
+        const db = getDb();
+        const suffix = `${iteration++}_${Math.random().toString(36).slice(2, 8)}`;
+
+        // Create owner and non-owner users
+        const ownerId = insertUser(`owner_${ownerName}_${suffix}`, 'user');
+        const otherId = insertUser(`other_${otherName}_${suffix}`, 'user');
+
+        // Create instance owned by owner
+        const instanceId = insertInstance(ownerId, {
+          ec2_instance_id: `${ec2Id}${suffix}`,
+          status: 'running',
+        });
+
+        // Create token for non-owner
+        const otherToken = makeToken({ id: otherId, username: `other_${otherName}_${suffix}`, role: 'user' });
+
+        // Count sessions before attempt
+        const countBefore = (db.prepare('SELECT COUNT(*) as cnt FROM rdp_sessions').get() as any).cnt;
+
+        // Non-owner attempts to create RDP session via API
+        const res = await request(app)
+          .post(`/api/instances/${instanceId}/rdp-session`)
+          .set('Authorization', `Bearer ${otherToken}`);
+
+        // Should be rejected with 403
+        expect(res.status).toBe(403);
+        expect(res.body.error.code).toBe('FORBIDDEN');
+
+        // No session should have been created
+        const countAfter = (db.prepare('SELECT COUNT(*) as cnt FROM rdp_sessions').get() as any).cnt;
+        expect(countAfter).toBe(countBefore);
+      }),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 6: 管理员活跃会话列表完整性 (via API)
+// **Validates: Requirements 7.1, 7.3**
+// ---------------------------------------------------------------------------
+
+describe('Property 6: Admin Active Session List Completeness (via API)', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  it('should return all active sessions with correct fields and exclude disconnected ones', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(
+        fc.integer({ min: 1, max: 6 }),
+        fc.integer({ min: 0, max: 4 }),
+        async (activeCount, disconnectedCount) => {
+          const db = getDb();
+          const suffix = `${iteration++}_${Math.random().toString(36).slice(2, 8)}`;
+
+          // admin user is seeded by initDb with id=1
+          const adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+
+          // Create a regular user and instance for sessions
+          const userId = insertUser(`user_p6_${suffix}`, 'user');
+          const ec2Id = `i-p6${suffix}`;
+          const instanceId = insertInstance(userId, { ec2_instance_id: ec2Id, status: 'running' });
+
+          // Track active session IDs we create
+          const activeIds = new Set<string>();
+
+          // Create active sessions (connecting or connected)
+          for (let i = 0; i < activeCount; i++) {
+            const status = i % 2 === 0 ? 'connecting' : 'connected';
+            const sid = insertRdpSession(userId, instanceId, ec2Id, status);
+            activeIds.add(sid);
+          }
+
+          // Create disconnected sessions (should NOT appear)
+          for (let i = 0; i < disconnectedCount; i++) {
+            insertRdpSession(userId, instanceId, ec2Id, 'disconnected');
+          }
+
+          // Admin queries active sessions via API
+          const res = await request(app)
+            .get('/api/admin/rdp-sessions')
+            .set('Authorization', `Bearer ${adminToken}`);
+
+          expect(res.status).toBe(200);
+          expect(Array.isArray(res.body)).toBe(true);
+
+          // Filter to sessions from this iteration
+          const ourSessions = res.body.filter((s: any) => activeIds.has(s.id));
+
+          // All active sessions should be present
+          expect(ourSessions.length).toBe(activeCount);
+
+          // Each returned session should have required fields
+          for (const s of ourSessions) {
+            expect(s).toHaveProperty('id');
+            expect(s).toHaveProperty('userId');
+            expect(s).toHaveProperty('username');
+            expect(s).toHaveProperty('instanceId');
+            expect(s).toHaveProperty('ec2InstanceId');
+            expect(s).toHaveProperty('status');
+            expect(s).toHaveProperty('durationSeconds');
+            expect(['connecting', 'connected']).toContain(s.status);
+          }
+
+          // No disconnected sessions should appear in the full result
+          const allStatuses = res.body.map((s: any) => s.status);
+          expect(allStatuses.every((st: string) => st === 'connecting' || st === 'connected')).toBe(true);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 7: 管理员强制断开会话 (via API)
+// **Validates: Requirements 7.2**
+// ---------------------------------------------------------------------------
+
+describe('Property 7: Admin Force Disconnect Session (via API)', () => {
+  beforeEach(() => {
+    initDb(':memory:');
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  it('should disconnect session and remove it from active list after admin force disconnect via API', { timeout: 60000 }, async () => {
+    let iteration = 0;
+
+    await fc.assert(
+      fc.asyncProperty(activeStatusArb, ec2IdArb, async (initialStatus, ec2Id) => {
+        const suffix = `${iteration++}_${Math.random().toString(36).slice(2, 8)}`;
+
+        // admin user is seeded by initDb with id=1
+        const adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+
+        // Create a regular user and instance
+        const userId = insertUser(`user_p7_${suffix}`, 'user');
+        const fullEc2Id = `${ec2Id}${suffix}`;
+        const instanceId = insertInstance(userId, { ec2_instance_id: fullEc2Id, status: 'running' });
+
+        // Create an active session
+        const sessionId = insertRdpSession(userId, instanceId, fullEc2Id, initialStatus);
+
+        // Admin force disconnects the session via API
+        const deleteRes = await request(app)
+          .delete(`/api/admin/rdp-sessions/${sessionId}`)
+          .set('Authorization', `Bearer ${adminToken}`);
+
+        expect(deleteRes.status).toBe(200);
+        expect(deleteRes.body).toHaveProperty('message');
+
+        // Session should NOT appear in active sessions list
+        const listRes = await request(app)
+          .get('/api/admin/rdp-sessions')
+          .set('Authorization', `Bearer ${adminToken}`);
+
+        expect(listRes.status).toBe(200);
+        const found = listRes.body.find((s: any) => s.id === sessionId);
+        expect(found).toBeUndefined();
+      }),
+      { numRuns: 100 },
+    );
+  });
+});

+ 299 - 0
server/src/routes/rdp-sessions.test.ts

@@ -0,0 +1,299 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt } from '../utils/crypto';
+
+// Mock guacamole-proxy to avoid guacamole-lite dependency
+vi.mock('../services/guacamole-proxy', () => ({
+  initGuacamoleProxy: vi.fn(),
+  testGuacdConnection: vi.fn(),
+}));
+
+// Mock instance-manager to avoid AWS calls
+vi.mock('../services/instance-manager', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('../services/instance-manager')>();
+  return {
+    ...actual,
+    launchInstance: vi.fn(),
+    stopInstance: vi.fn(),
+    startInstance: vi.fn(),
+    rebootInstance: vi.fn(),
+    terminateInstance: vi.fn(),
+    getInstanceRdpInfo: vi.fn(),
+  };
+});
+
+import app from '../app';
+import { testGuacdConnection } from '../services/guacamole-proxy';
+
+const mockedTestGuacd = vi.mocked(testGuacdConnection);
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+function insertUser(username: string, role: 'admin' | 'user'): number {
+  const db = getDb();
+  const result = db
+    .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', ?)")
+    .run(username, role);
+  return Number(result.lastInsertRowid);
+}
+
+function insertInstance(
+  userId: number,
+  overrides: Partial<{
+    ec2_instance_id: string;
+    status: string;
+    public_ip: string;
+    rdp_username: string;
+    rdp_password_encrypted: string;
+  }> = {},
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      overrides.ec2_instance_id ?? `i-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+      '12345678-1234-1234-1234-123456789abc',
+      overrides.status ?? 'running',
+      overrides.public_ip ?? '1.2.3.4',
+      overrides.rdp_username ?? 'Administrator',
+      overrides.rdp_password_encrypted ?? encrypt('testpass'),
+      now,
+      now + 86400,
+      now,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+function insertRdpSession(
+  userId: number,
+  instanceId: number,
+  ec2InstanceId: string,
+  status: 'connecting' | 'connected' | 'disconnected' = 'connecting',
+): string {
+  const db = getDb();
+  const id = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+  const now = Math.floor(Date.now() / 1000);
+  db.prepare(
+    `INSERT INTO rdp_sessions (id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+  ).run(id, userId, instanceId, ec2InstanceId, 'hash-' + id, status, now, now + 300);
+  return id;
+}
+
+describe('RDP Sessions Routes', () => {
+  let adminToken: string;
+  let userToken: string;
+  let adminId: number;
+  let regularUserId: number;
+
+  beforeEach(() => {
+    initDb(':memory:');
+    // admin user is seeded by initDb with id=1
+    adminId = 1;
+    adminToken = makeToken({ id: adminId, username: 'admin', role: 'admin' });
+    regularUserId = insertUser('testuser', 'user');
+    userToken = makeToken({ id: regularUserId, username: 'testuser', role: 'user' });
+  });
+
+  afterEach(() => {
+    vi.clearAllMocks();
+    closeDb();
+  });
+
+  // -----------------------------------------------------------------------
+  // POST /api/instances/:id/rdp-session
+  // -----------------------------------------------------------------------
+  describe('POST /api/instances/:id/rdp-session', () => {
+    it('should return 201 with session data for valid request (instance owner, running instance)', async () => {
+      const instanceId = insertInstance(regularUserId);
+
+      const res = await request(app)
+        .post(`/api/instances/${instanceId}/rdp-session`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(201);
+      expect(res.body).toHaveProperty('id');
+      expect(res.body).toHaveProperty('token');
+      expect(res.body.userId).toBe(regularUserId);
+      expect(res.body.instanceId).toBe(instanceId);
+      expect(res.body.status).toBe('connecting');
+      expect(res.body).toHaveProperty('createdAt');
+      expect(res.body).toHaveProperty('expiresAt');
+    });
+
+    it('should return 401 without auth token', async () => {
+      const res = await request(app).post('/api/instances/1/rdp-session');
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 403 for non-owner', async () => {
+      // Instance belongs to admin (id=1), but request is from regularUser
+      const instanceId = insertInstance(adminId);
+
+      const res = await request(app)
+        .post(`/api/instances/${instanceId}/rdp-session`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(403);
+      expect(res.body.error.code).toBe('FORBIDDEN');
+    });
+
+    it('should return 404 for non-existent instance', async () => {
+      const res = await request(app)
+        .post('/api/instances/9999/rdp-session')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(404);
+      expect(res.body.error.code).toBe('NOT_FOUND');
+    });
+
+    it('should return 400 for non-running instance', async () => {
+      const instanceId = insertInstance(regularUserId, { status: 'stopped' });
+
+      const res = await request(app)
+        .post(`/api/instances/${instanceId}/rdp-session`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_STATE');
+    });
+
+    it('should return 400 for invalid instance ID', async () => {
+      const res = await request(app)
+        .post('/api/instances/abc/rdp-session')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_INPUT');
+    });
+  });
+
+  // -----------------------------------------------------------------------
+  // GET /api/admin/rdp-sessions
+  // -----------------------------------------------------------------------
+  describe('GET /api/admin/rdp-sessions', () => {
+    it('should return 200 with active sessions list for admin', async () => {
+      const instanceId = insertInstance(regularUserId, { ec2_instance_id: 'i-test123' });
+      insertRdpSession(regularUserId, instanceId, 'i-test123', 'connected');
+      insertRdpSession(regularUserId, instanceId, 'i-test123', 'connecting');
+      // disconnected session should NOT appear
+      insertRdpSession(regularUserId, instanceId, 'i-test123', 'disconnected');
+
+      const res = await request(app)
+        .get('/api/admin/rdp-sessions')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(Array.isArray(res.body)).toBe(true);
+      expect(res.body).toHaveLength(2);
+      // Verify each session has expected fields
+      for (const session of res.body) {
+        expect(session).toHaveProperty('id');
+        expect(session).toHaveProperty('userId');
+        expect(session).toHaveProperty('username');
+        expect(session).toHaveProperty('instanceId');
+        expect(session).toHaveProperty('ec2InstanceId');
+        expect(session).toHaveProperty('status');
+        expect(session).toHaveProperty('durationSeconds');
+      }
+    });
+
+    it('should return 401 without auth token', async () => {
+      const res = await request(app).get('/api/admin/rdp-sessions');
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 403 for non-admin user', async () => {
+      const res = await request(app)
+        .get('/api/admin/rdp-sessions')
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(403);
+    });
+  });
+
+  // -----------------------------------------------------------------------
+  // DELETE /api/admin/rdp-sessions/:id
+  // -----------------------------------------------------------------------
+  describe('DELETE /api/admin/rdp-sessions/:id', () => {
+    it('should return 200 for successful termination by admin', async () => {
+      const instanceId = insertInstance(regularUserId, { ec2_instance_id: 'i-del1' });
+      const sessionId = insertRdpSession(regularUserId, instanceId, 'i-del1', 'connected');
+
+      const res = await request(app)
+        .delete(`/api/admin/rdp-sessions/${sessionId}`)
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body).toHaveProperty('message');
+
+      // Verify session is now disconnected (should not appear in active list)
+      const listRes = await request(app)
+        .get('/api/admin/rdp-sessions')
+        .set('Authorization', `Bearer ${adminToken}`);
+      const found = listRes.body.find((s: any) => s.id === sessionId);
+      expect(found).toBeUndefined();
+    });
+
+    it('should return 404 for non-existent session', async () => {
+      const res = await request(app)
+        .delete('/api/admin/rdp-sessions/non-existent-id')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(404);
+      expect(res.body.error.code).toBe('SESSION_NOT_FOUND');
+    });
+
+    it('should return 403 for non-admin user', async () => {
+      const instanceId = insertInstance(regularUserId, { ec2_instance_id: 'i-del2' });
+      const sessionId = insertRdpSession(regularUserId, instanceId, 'i-del2', 'connected');
+
+      const res = await request(app)
+        .delete(`/api/admin/rdp-sessions/${sessionId}`)
+        .set('Authorization', `Bearer ${userToken}`);
+
+      expect(res.status).toBe(403);
+    });
+  });
+
+  // -----------------------------------------------------------------------
+  // POST /api/admin/guacamole/test
+  // -----------------------------------------------------------------------
+  describe('POST /api/admin/guacamole/test', () => {
+    it('should return 200 with test result', async () => {
+      mockedTestGuacd.mockResolvedValue({
+        success: true,
+        message: 'Successfully connected to guacd at 127.0.0.1:4822',
+      });
+
+      const res = await request(app)
+        .post('/api/admin/guacamole/test')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ host: '127.0.0.1', port: 4822 });
+
+      expect(res.status).toBe(200);
+      expect(res.body.success).toBe(true);
+      expect(res.body).toHaveProperty('message');
+      expect(mockedTestGuacd).toHaveBeenCalledWith('127.0.0.1', 4822);
+    });
+
+    it('should return 403 for non-admin user', async () => {
+      const res = await request(app)
+        .post('/api/admin/guacamole/test')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ host: '127.0.0.1', port: 4822 });
+
+      expect(res.status).toBe(403);
+    });
+  });
+});

+ 127 - 0
server/src/routes/rdp-sessions.ts

@@ -0,0 +1,127 @@
+import { Router, Response } from 'express';
+import { AuthRequest } from '../middleware/auth';
+import { getDb } from '../db';
+import {
+  createRdpSession,
+  getActiveSessions,
+  terminateSession,
+  ConnectionError,
+} from '../services/connection-manager';
+import { testGuacdConnection } from '../services/guacamole-proxy';
+
+// ---------------------------------------------------------------------------
+// User-facing router: mounted at /api/instances
+// ---------------------------------------------------------------------------
+
+export const rdpSessionRouter = Router();
+
+/**
+ * POST /api/instances/:id/rdp-session
+ * Create an RDP session for the given instance. Requires auth (instance owner).
+ */
+rdpSessionRouter.post('/:id/rdp-session', (req: AuthRequest, res: Response): void => {
+  const userId = req.user!.id;
+  const instanceId = Number(req.params.id);
+
+  if (isNaN(instanceId)) {
+    res.status(400).json({
+      error: { code: 'INVALID_INPUT', message: '无效的实例 ID' },
+    });
+    return;
+  }
+
+  try {
+    const session = createRdpSession(userId, instanceId);
+    res.status(201).json(session);
+  } catch (err: any) {
+    if (err instanceof ConnectionError) {
+      res.status(err.statusCode).json({
+        error: { code: err.code, message: err.message },
+      });
+      return;
+    }
+    res.status(500).json({
+      error: { code: 'INTERNAL_ERROR', message: err.message },
+    });
+  }
+});
+
+// ---------------------------------------------------------------------------
+// Admin router: mounted at /api/admin/rdp-sessions
+// ---------------------------------------------------------------------------
+
+export const adminRdpRouter = Router();
+
+/**
+ * GET /api/admin/rdp-sessions
+ * Get all active RDP sessions (admin only).
+ */
+adminRdpRouter.get('/', (_req: AuthRequest, res: Response): void => {
+  const sessions = getActiveSessions();
+  res.json(sessions);
+});
+
+/**
+ * DELETE /api/admin/rdp-sessions/:id
+ * Terminate (force disconnect) an RDP session (admin only).
+ */
+adminRdpRouter.delete('/:id', (req: AuthRequest, res: Response): void => {
+  const sessionId = req.params.id as string;
+
+  try {
+    terminateSession(sessionId);
+    res.json({ message: '会话已断开' });
+  } catch (err: any) {
+    if (err instanceof ConnectionError) {
+      res.status(err.statusCode).json({
+        error: { code: err.code, message: err.message },
+      });
+      return;
+    }
+    res.status(500).json({
+      error: { code: 'INTERNAL_ERROR', message: err.message },
+    });
+  }
+});
+
+// ---------------------------------------------------------------------------
+// Guacamole test router: mounted at /api/admin/guacamole
+// ---------------------------------------------------------------------------
+
+export const guacamoleTestRouter = Router();
+
+/**
+ * POST /api/admin/guacamole/test
+ * Test guacd connectivity. Reads host/port from body or falls back to system_settings.
+ */
+guacamoleTestRouter.post('/test', async (req: AuthRequest, res: Response): Promise<void> => {
+  let { host, port } = req.body;
+
+  // Fall back to system_settings if not provided
+  if (!host || !port) {
+    const db = getDb();
+    if (!host) {
+      const row = db
+        .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
+        .get() as { value: string } | undefined;
+      host = row?.value;
+    }
+    if (!port) {
+      const row = db
+        .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
+        .get() as { value: string } | undefined;
+      port = row?.value ? parseInt(row.value, 10) : undefined;
+    }
+  }
+
+  if (!host || !port) {
+    res.status(400).json({
+      error: { code: 'MISSING_CONFIG', message: 'Guacamole 服务地址或端口未配置' },
+    });
+    return;
+  }
+
+  const numericPort = typeof port === 'string' ? parseInt(port, 10) : port;
+  const result = await testGuacdConnection(host, numericPort);
+  res.json(result);
+});

+ 313 - 0
server/src/routes/settings.test.ts

@@ -0,0 +1,313 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import request from 'supertest';
+import jwt from 'jsonwebtoken';
+import app from '../app';
+import { initDb, closeDb, getDb } from '../db';
+import { JWT_SECRET, JwtPayload } from '../middleware/auth';
+
+function makeToken(payload: JwtPayload): string {
+  return jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
+}
+
+describe('Settings Routes', () => {
+  let adminToken: string;
+  let userToken: string;
+
+  beforeEach(() => {
+    initDb(':memory:');
+    adminToken = makeToken({ id: 1, username: 'admin', role: 'admin' });
+    userToken = makeToken({ id: 99, username: 'regularuser', role: 'user' });
+  });
+
+  afterEach(() => {
+    closeDb();
+  });
+
+  describe('Authorization', () => {
+    it('should return 401 without token on GET', async () => {
+      const res = await request(app).get('/api/admin/settings');
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 401 without token on PUT', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .send({ max_instance_lifetime_hours: 48 });
+      expect(res.status).toBe(401);
+    });
+
+    it('should return 403 for non-admin on GET', async () => {
+      const res = await request(app)
+        .get('/api/admin/settings')
+        .set('Authorization', `Bearer ${userToken}`);
+      expect(res.status).toBe(403);
+    });
+
+    it('should return 403 for non-admin on PUT', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${userToken}`)
+        .send({ max_instance_lifetime_hours: 48 });
+      expect(res.status).toBe(403);
+    });
+  });
+
+  describe('GET /api/admin/settings', () => {
+    it('should return default max_instance_lifetime_hours of 24 when not set', async () => {
+      const res = await request(app)
+        .get('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.max_instance_lifetime_hours).toBe(24);
+    });
+
+    it('should return the stored value after PUT', async () => {
+      await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 72 });
+
+      const res = await request(app)
+        .get('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.max_instance_lifetime_hours).toBe(72);
+    });
+  });
+
+  describe('PUT /api/admin/settings', () => {
+    it('should update max_instance_lifetime_hours', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 48 });
+
+      expect(res.status).toBe(200);
+      expect(res.body.max_instance_lifetime_hours).toBe(48);
+    });
+
+    it('should overwrite a previously set value', async () => {
+      await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 10 });
+
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 100 });
+
+      expect(res.status).toBe(200);
+      expect(res.body.max_instance_lifetime_hours).toBe(100);
+    });
+
+    it('should accept decimal values', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 1.5 });
+
+      expect(res.status).toBe(200);
+      expect(res.body.max_instance_lifetime_hours).toBe(1.5);
+    });
+
+    it('should reject zero', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 0 });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject negative values', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: -5 });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject non-number values', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: 'abc' });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject missing max_instance_lifetime_hours', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({});
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject Infinity', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ max_instance_lifetime_hours: Infinity });
+
+      expect(res.status).toBe(400);
+    });
+  });
+
+  describe('GET /api/admin/settings — guacamole fields', () => {
+    it('should return seeded guacamole_host and guacamole_port', async () => {
+      const res = await request(app)
+        .get('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`);
+
+      expect(res.status).toBe(200);
+      expect(res.body.guacamole_host).toBe('127.0.0.1');
+      expect(res.body.guacamole_port).toBe(4822);
+    });
+  });
+
+  describe('PUT /api/admin/settings — guacamole fields', () => {
+    it('should update guacamole_host', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_host: '192.168.1.100' });
+
+      expect(res.status).toBe(200);
+      expect(res.body.guacamole_host).toBe('192.168.1.100');
+    });
+
+    it('should update guacamole_port', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_port: 5000 });
+
+      expect(res.status).toBe(200);
+      expect(res.body.guacamole_port).toBe(5000);
+    });
+
+    it('should update both guacamole_host and guacamole_port together', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_host: '10.0.0.1', guacamole_port: 9999 });
+
+      expect(res.status).toBe(200);
+      expect(res.body.guacamole_host).toBe('10.0.0.1');
+      expect(res.body.guacamole_port).toBe(9999);
+    });
+
+    it('should reject empty guacamole_host', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_host: '' });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject non-string guacamole_host', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_host: 123 });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject guacamole_port below 1', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_port: 0 });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject guacamole_port above 65535', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_port: 70000 });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should reject non-integer guacamole_port', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_port: 4822.5 });
+
+      expect(res.status).toBe(400);
+      expect(res.body.error.code).toBe('INVALID_VALUE');
+    });
+
+    it('should allow updating guacamole fields independently of max_instance_lifetime_minutes', async () => {
+      const res = await request(app)
+        .put('/api/admin/settings')
+        .set('Authorization', `Bearer ${adminToken}`)
+        .send({ guacamole_host: 'guacd.local' });
+
+      expect(res.status).toBe(200);
+      // max_instance_lifetime_minutes should still have its default
+      expect(res.body.max_instance_lifetime_minutes).toBe(1440);
+      expect(res.body.guacamole_host).toBe('guacd.local');
+    });
+  });
+
+  describe('GET /api/settings/guacamole-status (public)', () => {
+    it('should be accessible without authentication', async () => {
+      const res = await request(app).get('/api/settings/guacamole-status');
+      expect(res.status).toBe(200);
+      expect(res.body).toHaveProperty('configured');
+    });
+
+    it('should return configured: true when defaults are seeded', async () => {
+      const res = await request(app).get('/api/settings/guacamole-status');
+      expect(res.status).toBe(200);
+      expect(res.body.configured).toBe(true);
+    });
+
+    it('should return configured: false when guacamole_host is empty', async () => {
+      const db = getDb();
+      db.prepare("UPDATE system_settings SET value = '' WHERE key = 'guacamole_host'").run();
+
+      const res = await request(app).get('/api/settings/guacamole-status');
+      expect(res.status).toBe(200);
+      expect(res.body.configured).toBe(false);
+    });
+
+    it('should return configured: false when guacamole_port is empty', async () => {
+      const db = getDb();
+      db.prepare("UPDATE system_settings SET value = '' WHERE key = 'guacamole_port'").run();
+
+      const res = await request(app).get('/api/settings/guacamole-status');
+      expect(res.status).toBe(200);
+      expect(res.body.configured).toBe(false);
+    });
+
+    it('should return configured: false when both are missing', async () => {
+      const db = getDb();
+      db.prepare("DELETE FROM system_settings WHERE key IN ('guacamole_host', 'guacamole_port')").run();
+
+      const res = await request(app).get('/api/settings/guacamole-status');
+      expect(res.status).toBe(200);
+      expect(res.body.configured).toBe(false);
+    });
+  });
+});

+ 173 - 0
server/src/routes/settings.ts

@@ -0,0 +1,173 @@
+import { Router, Request, Response } from 'express';
+import { getDb } from '../db';
+import { AuthRequest } from '../middleware/auth';
+
+const router = Router();
+
+const DEFAULT_MAX_LIFETIME_MINUTES = 1440;
+
+/** Helper: read all settings and apply type coercion for numeric fields. */
+function readAllSettings(): Record<string, any> {
+  const db = getDb();
+  const rows = db.prepare(
+    'SELECT key, value FROM system_settings'
+  ).all() as { key: string; value: string }[];
+
+  const settings: Record<string, any> = {};
+  for (const row of rows) {
+    settings[row.key] = row.value;
+  }
+
+  // Coerce numeric fields
+  const maxLifetime = settings['max_instance_lifetime_minutes'];
+  settings['max_instance_lifetime_minutes'] = maxLifetime != null
+    ? Number(maxLifetime)
+    : DEFAULT_MAX_LIFETIME_MINUTES;
+
+  if (settings['guacamole_port'] != null) {
+    settings['guacamole_port'] = Number(settings['guacamole_port']);
+  }
+
+  return settings;
+}
+
+/** Helper: upsert a single system_settings key. */
+function upsertSetting(key: string, value: string): void {
+  const db = getDb();
+  db.prepare(
+    `INSERT INTO system_settings (key, value, updated_at)
+     VALUES (?, ?, strftime('%s', 'now'))
+     ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`
+  ).run(key, value);
+}
+
+/**
+ * GET /api/admin/settings
+ * Returns all system settings as key-value pairs.
+ * Defaults max_instance_lifetime_minutes to 1440 (24h) if not set.
+ * Also returns guacamole_host (string) and guacamole_port (number).
+ */
+router.get('/', (_req: AuthRequest, res: Response): void => {
+  res.json(readAllSettings());
+});
+
+/**
+ * PUT /api/admin/settings
+ * Update system settings. Supports:
+ * - max_instance_lifetime_minutes: positive number (minutes)
+ * - guacamole_host: non-empty string
+ * - guacamole_port: integer 1-65535
+ * Any subset of these can be sent; only provided fields are updated.
+ */
+router.put('/', (req: AuthRequest, res: Response): void => {
+  const { max_instance_lifetime_minutes, guacamole_host, guacamole_port } = req.body;
+
+  // At least one recognised field must be present
+  if (
+    max_instance_lifetime_minutes === undefined &&
+    guacamole_host === undefined &&
+    guacamole_port === undefined
+  ) {
+    res.status(400).json({
+      error: {
+        code: 'INVALID_VALUE',
+        message: '请提供至少一个有效的设置字段',
+      },
+    });
+    return;
+  }
+
+  // Validate max_instance_lifetime_minutes (if provided)
+  if (max_instance_lifetime_minutes !== undefined) {
+    if (
+      max_instance_lifetime_minutes === null ||
+      typeof max_instance_lifetime_minutes !== 'number' ||
+      !isFinite(max_instance_lifetime_minutes) ||
+      max_instance_lifetime_minutes <= 0
+    ) {
+      res.status(400).json({
+        error: {
+          code: 'INVALID_VALUE',
+          message: 'max_instance_lifetime_minutes 必须为正数',
+        },
+      });
+      return;
+    }
+  }
+
+  // Validate guacamole_host (if provided)
+  if (guacamole_host !== undefined) {
+    if (
+      typeof guacamole_host !== 'string' ||
+      guacamole_host.trim().length === 0
+    ) {
+      res.status(400).json({
+        error: {
+          code: 'INVALID_VALUE',
+          message: 'guacamole_host 必须为非空字符串',
+        },
+      });
+      return;
+    }
+  }
+
+  // Validate guacamole_port (if provided)
+  if (guacamole_port !== undefined) {
+    if (
+      typeof guacamole_port !== 'number' ||
+      !Number.isInteger(guacamole_port) ||
+      guacamole_port < 1 ||
+      guacamole_port > 65535
+    ) {
+      res.status(400).json({
+        error: {
+          code: 'INVALID_VALUE',
+          message: 'guacamole_port 必须为 1-65535 之间的整数',
+        },
+      });
+      return;
+    }
+  }
+
+  // Apply updates
+  if (max_instance_lifetime_minutes !== undefined) {
+    upsertSetting('max_instance_lifetime_minutes', String(max_instance_lifetime_minutes));
+  }
+  if (guacamole_host !== undefined) {
+    upsertSetting('guacamole_host', guacamole_host.trim());
+  }
+  if (guacamole_port !== undefined) {
+    upsertSetting('guacamole_port', String(guacamole_port));
+  }
+
+  res.json(readAllSettings());
+});
+
+/**
+ * GET /api/settings/guacamole-status  (PUBLIC — no auth required)
+ * Returns { configured: boolean } — true when both guacamole_host and
+ * guacamole_port have non-empty values in system_settings.
+ */
+export const guacamoleStatusRouter = Router();
+
+guacamoleStatusRouter.get('/', (_req: Request, res: Response): void => {
+  const db = getDb();
+  const rows = db.prepare(
+    "SELECT key, value FROM system_settings WHERE key IN ('guacamole_host', 'guacamole_port')"
+  ).all() as { key: string; value: string }[];
+
+  const map: Record<string, string> = {};
+  for (const row of rows) {
+    map[row.key] = row.value;
+  }
+
+  const configured =
+    typeof map['guacamole_host'] === 'string' &&
+    map['guacamole_host'].trim().length > 0 &&
+    typeof map['guacamole_port'] === 'string' &&
+    map['guacamole_port'].trim().length > 0;
+
+  res.json({ configured });
+});
+
+export default router;

+ 492 - 0
server/src/services/connection-manager.property.test.ts

@@ -0,0 +1,492 @@
+// Feature: web-rdp-connect, Property 2-7
+// Property-based tests for Connection Manager Service
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt } from '../utils/crypto';
+import {
+  createRdpSession,
+  getActiveSessions,
+  terminateSession,
+  terminateSessionsByInstance,
+  validateToken,
+  ConnectionError,
+} from './connection-manager';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function seedUser(username = 'testuser', role = 'user'): number {
+  const db = getDb();
+  const result = db
+    .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', ?)")
+    .run(username, role);
+  return Number(result.lastInsertRowid);
+}
+
+function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
+  const db = getDb();
+  const defaults = {
+    ec2_instance_id: `i-${Math.random().toString(36).slice(2, 19)}`,
+    machine_guid: '11111111-1111-1111-1111-111111111111',
+    status: 'running',
+    public_ip: '1.2.3.4',
+    rdp_username: 'Administrator',
+    rdp_password_encrypted: encrypt('P@ssw0rd'),
+    started_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 86400,
+  };
+  const vals = { ...defaults, ...overrides };
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      vals.ec2_instance_id,
+      vals.machine_guid,
+      vals.status,
+      vals.public_ip,
+      vals.rdp_username,
+      vals.rdp_password_encrypted,
+      vals.started_at,
+      vals.expires_at,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+function ensureGuacamoleConfig(host = '127.0.0.1', port = '4822') {
+  const db = getDb();
+  db.prepare("UPDATE system_settings SET value = ? WHERE key = 'guacamole_host'").run(host);
+  db.prepare("UPDATE system_settings SET value = ? WHERE key = 'guacamole_port'").run(port);
+}
+
+/** Insert an rdp_sessions row directly for testing queries. */
+function seedSession(overrides: Record<string, any> = {}): string {
+  const db = getDb();
+  const defaults = {
+    id: crypto.randomUUID(),
+    user_id: 1,
+    instance_id: 1,
+    ec2_instance_id: 'i-abc123',
+    token_hash: 'hash-' + Math.random().toString(36).slice(2),
+    status: 'connecting',
+    created_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 300,
+    used_at: null,
+  };
+  const vals = { ...defaults, ...overrides };
+  db.prepare(
+    `INSERT INTO rdp_sessions (id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at, used_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+  ).run(vals.id, vals.user_id, vals.instance_id, vals.ec2_instance_id, vals.token_hash, vals.status, vals.created_at, vals.expires_at, vals.used_at);
+  return vals.id;
+}
+
+// ---------------------------------------------------------------------------
+// Arbitraries
+// ---------------------------------------------------------------------------
+
+/** Arbitrary for valid usernames (alphanumeric, 3-20 chars) */
+const usernameArb = fc
+  .stringOf(fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz0123456789'.split('')), { minLength: 3, maxLength: 20 })
+  .filter((s) => s.length >= 3);
+
+/** Arbitrary for IPv4 addresses */
+const ipArb = fc
+  .tuple(
+    fc.integer({ min: 1, max: 255 }),
+    fc.integer({ min: 0, max: 255 }),
+    fc.integer({ min: 0, max: 255 }),
+    fc.integer({ min: 1, max: 255 }),
+  )
+  .map(([a, b, c, d]) => `${a}.${b}.${c}.${d}`);
+
+/** Arbitrary for RDP passwords (non-empty printable strings) */
+const passwordArb = fc.string({ minLength: 4, maxLength: 32 }).filter((s) => s.trim().length > 0);
+
+/** Arbitrary for EC2 instance IDs */
+const ec2IdArb = fc
+  .stringOf(fc.constantFrom(...'abcdef0123456789'.split('')), { minLength: 8, maxLength: 17 })
+  .map((s) => `i-${s}`);
+
+/** Arbitrary for active session statuses */
+const activeStatusArb = fc.constantFrom('connecting' as const, 'connected' as const);
+
+/** Arbitrary for session count (1-10) */
+const sessionCountArb = fc.integer({ min: 1, max: 10 });
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+beforeEach(() => {
+  initDb(':memory:');
+  ensureGuacamoleConfig();
+});
+
+afterEach(() => {
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 2: RDP 会话创建包含正确连接参数
+// **Validates: Requirements 2.1, 2.2**
+// ---------------------------------------------------------------------------
+
+describe('Property 2: RDP Session Creation Contains Correct Connection Parameters', () => {
+  it('should create a session with unique token persisted in DB for any valid instance owner', () => {
+    fc.assert(
+      fc.property(
+        usernameArb,
+        ipArb,
+        passwordArb,
+        ec2IdArb,
+        (username, publicIp, rdpPassword, ec2Id) => {
+          const db = getDb();
+
+          // Seed unique user and running instance with RDP credentials
+          const userId = seedUser(`u2_${username}_${Math.random().toString(36).slice(2, 6)}`);
+          const encryptedPw = encrypt(rdpPassword);
+          const instanceId = seedInstance(userId, {
+            ec2_instance_id: ec2Id + Math.random().toString(36).slice(2, 6),
+            public_ip: publicIp,
+            rdp_username: 'Administrator',
+            rdp_password_encrypted: encryptedPw,
+            status: 'running',
+          });
+
+          const session = createRdpSession(userId, instanceId);
+
+          // Session has a unique non-empty token
+          expect(session.token).toBeDefined();
+          expect(session.token.length).toBeGreaterThan(0);
+
+          // Session has correct user and instance references
+          expect(session.userId).toBe(userId);
+          expect(session.instanceId).toBe(instanceId);
+          expect(session.status).toBe('connecting');
+
+          // Session is persisted in the database
+          const row = db
+            .prepare('SELECT * FROM rdp_sessions WHERE id = ?')
+            .get(session.id) as any;
+          expect(row).toBeDefined();
+          expect(row.user_id).toBe(userId);
+          expect(row.instance_id).toBe(instanceId);
+          expect(row.token_hash).toBeDefined();
+          expect(row.token_hash.length).toBeGreaterThan(0);
+          expect(row.expires_at).toBeGreaterThan(row.created_at);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 3: 实例所有权强制检查
+// **Validates: Requirements 3.1, 3.2**
+// ---------------------------------------------------------------------------
+
+describe('Property 3: Instance Ownership Enforcement', () => {
+  it('should throw FORBIDDEN and create no session when non-owner requests RDP session', () => {
+    fc.assert(
+      fc.property(
+        usernameArb,
+        usernameArb,
+        ec2IdArb,
+        (ownerName, otherName, ec2Id) => {
+          const db = getDb();
+          const suffix = Math.random().toString(36).slice(2, 8);
+
+          const ownerId = seedUser(`owner_${ownerName}_${suffix}`);
+          const otherId = seedUser(`other_${otherName}_${suffix}`);
+          const instanceId = seedInstance(ownerId, {
+            ec2_instance_id: ec2Id + suffix,
+            status: 'running',
+          });
+
+          // Count sessions before attempt
+          const countBefore = (
+            db.prepare('SELECT COUNT(*) as cnt FROM rdp_sessions').get() as any
+          ).cnt;
+
+          // Non-owner should be rejected
+          let thrownError: any = null;
+          try {
+            createRdpSession(otherId, instanceId);
+          } catch (e) {
+            thrownError = e;
+          }
+
+          expect(thrownError).toBeInstanceOf(ConnectionError);
+          expect(thrownError.code).toBe('FORBIDDEN');
+          expect(thrownError.statusCode).toBe(403);
+
+          // No session record should have been created
+          const countAfter = (
+            db.prepare('SELECT COUNT(*) as cnt FROM rdp_sessions').get() as any
+          ).cnt;
+          expect(countAfter).toBe(countBefore);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 4: 会话令牌有效性约束
+// **Validates: Requirements 3.3, 3.4**
+// ---------------------------------------------------------------------------
+
+describe('Property 4: Session Token Validity Constraints', () => {
+  it('should reject expired tokens, reject used tokens, and accept valid tokens', () => {
+    fc.assert(
+      fc.property(
+        fc.constantFrom('expired', 'used', 'valid'),
+        (tokenState) => {
+          const db = getDb();
+          const suffix = Math.random().toString(36).slice(2, 8);
+
+          const userId = seedUser(`u4_${suffix}`);
+          const instanceId = seedInstance(userId, {
+            ec2_instance_id: `i-p4${suffix}`,
+            status: 'running',
+          });
+
+          // Create a real session to get a valid token
+          const session = createRdpSession(userId, instanceId);
+
+          if (tokenState === 'expired') {
+            // Manually expire the session
+            const pastTime = Math.floor(Date.now() / 1000) - 100;
+            db.prepare('UPDATE rdp_sessions SET expires_at = ? WHERE id = ?').run(
+              pastTime,
+              session.id,
+            );
+
+            let thrownError: any = null;
+            try {
+              validateToken(session.token);
+            } catch (e) {
+              thrownError = e;
+            }
+            expect(thrownError).toBeInstanceOf(ConnectionError);
+            expect(thrownError.code).toBe('TOKEN_EXPIRED');
+            expect(thrownError.statusCode).toBe(401);
+          } else if (tokenState === 'used') {
+            // First use succeeds
+            validateToken(session.token);
+
+            // Second use should fail
+            let thrownError: any = null;
+            try {
+              validateToken(session.token);
+            } catch (e) {
+              thrownError = e;
+            }
+            expect(thrownError).toBeInstanceOf(ConnectionError);
+            expect(thrownError.code).toBe('TOKEN_USED');
+            expect(thrownError.statusCode).toBe(401);
+          } else {
+            // Valid token should succeed
+            const validated = validateToken(session.token);
+            expect(validated.id).toBe(session.id);
+            expect(validated.status).toBe('connected');
+
+            // Verify used_at is set
+            const row = db
+              .prepare('SELECT used_at FROM rdp_sessions WHERE id = ?')
+              .get(session.id) as any;
+            expect(row.used_at).not.toBeNull();
+          }
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 5: 实例终止级联清理会话
+// **Validates: Requirements 4.2**
+// ---------------------------------------------------------------------------
+
+describe('Property 5: Instance Termination Cascading Session Cleanup', () => {
+  it('should disconnect all active sessions for an instance when terminateSessionsByInstance is called', () => {
+    fc.assert(
+      fc.property(
+        sessionCountArb,
+        ec2IdArb,
+        (sessionCount, ec2Id) => {
+          const db = getDb();
+          const suffix = Math.random().toString(36).slice(2, 8);
+          const targetEc2Id = ec2Id + suffix;
+
+          const userId = seedUser(`u5_${suffix}`);
+          const instanceId = seedInstance(userId, {
+            ec2_instance_id: targetEc2Id,
+            status: 'running',
+          });
+
+          // Create N active sessions for this instance
+          const sessionIds: string[] = [];
+          for (let i = 0; i < sessionCount; i++) {
+            const status = i % 2 === 0 ? 'connecting' : 'connected';
+            const sid = seedSession({
+              user_id: userId,
+              instance_id: instanceId,
+              ec2_instance_id: targetEc2Id,
+              status,
+            });
+            sessionIds.push(sid);
+          }
+
+          // Terminate all sessions for this instance
+          terminateSessionsByInstance(targetEc2Id);
+
+          // All sessions should now be disconnected
+          for (const sid of sessionIds) {
+            const row = db
+              .prepare('SELECT status FROM rdp_sessions WHERE id = ?')
+              .get(sid) as any;
+            expect(row.status).toBe('disconnected');
+          }
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 6: 管理员活跃会话列表完整性
+// **Validates: Requirements 7.1, 7.3**
+// ---------------------------------------------------------------------------
+
+describe('Property 6: Admin Active Session List Completeness', () => {
+  it('should return all active sessions with correct fields for any set of sessions', () => {
+    fc.assert(
+      fc.property(
+        fc.integer({ min: 1, max: 8 }),
+        fc.integer({ min: 0, max: 5 }),
+        (activeCount, disconnectedCount) => {
+          const db = getDb();
+          const suffix = Math.random().toString(36).slice(2, 8);
+
+          const userId = seedUser(`u6_${suffix}`);
+          const instanceId = seedInstance(userId, {
+            ec2_instance_id: `i-p6${suffix}`,
+            status: 'running',
+          });
+
+          const activeIds = new Set<string>();
+          const now = Math.floor(Date.now() / 1000);
+
+          // Create active sessions (connecting or connected)
+          for (let i = 0; i < activeCount; i++) {
+            const status = i % 2 === 0 ? 'connecting' : 'connected';
+            const createdAt = now - (i + 1) * 60; // stagger creation times
+            const sid = seedSession({
+              user_id: userId,
+              instance_id: instanceId,
+              ec2_instance_id: `i-p6${suffix}`,
+              status,
+              created_at: createdAt,
+              expires_at: createdAt + 300,
+            });
+            activeIds.add(sid);
+          }
+
+          // Create disconnected sessions (should NOT appear)
+          for (let i = 0; i < disconnectedCount; i++) {
+            seedSession({
+              user_id: userId,
+              instance_id: instanceId,
+              ec2_instance_id: `i-p6${suffix}`,
+              status: 'disconnected',
+            });
+          }
+
+          const result = getActiveSessions();
+
+          // All active sessions should be present
+          const resultIds = new Set(result.map((s) => s.id));
+          for (const aid of activeIds) {
+            expect(resultIds.has(aid)).toBe(true);
+          }
+
+          // Each returned session should have required fields
+          for (const s of result) {
+            if (activeIds.has(s.id)) {
+              expect(s.username).toBeDefined();
+              expect(s.username.length).toBeGreaterThan(0);
+              expect(s.instanceId).toBe(instanceId);
+              expect(s.durationSeconds).toBeGreaterThanOrEqual(0);
+              expect(['connecting', 'connected']).toContain(s.status);
+            }
+          }
+
+          // No disconnected sessions should appear
+          const allStatuses = result.map((s) => s.status);
+          expect(allStatuses.every((st) => st === 'connecting' || st === 'connected')).toBe(true);
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: web-rdp-connect, Property 7: 管理员强制断开会话
+// **Validates: Requirements 7.2**
+// ---------------------------------------------------------------------------
+
+describe('Property 7: Admin Force Disconnect Session', () => {
+  it('should disconnect session and remove it from active list after admin terminates it', () => {
+    fc.assert(
+      fc.property(
+        activeStatusArb,
+        ec2IdArb,
+        (initialStatus, ec2Id) => {
+          const db = getDb();
+          const suffix = Math.random().toString(36).slice(2, 8);
+
+          const userId = seedUser(`u7_${suffix}`);
+          const instanceId = seedInstance(userId, {
+            ec2_instance_id: ec2Id + suffix,
+            status: 'running',
+          });
+
+          // Create an active session
+          const sessionId = seedSession({
+            user_id: userId,
+            instance_id: instanceId,
+            ec2_instance_id: ec2Id + suffix,
+            status: initialStatus,
+          });
+
+          // Admin terminates the session
+          terminateSession(sessionId);
+
+          // Session status should be disconnected in DB
+          const row = db
+            .prepare('SELECT status FROM rdp_sessions WHERE id = ?')
+            .get(sessionId) as any;
+          expect(row.status).toBe('disconnected');
+
+          // Session should NOT appear in active sessions list
+          const activeSessions = getActiveSessions();
+          const found = activeSessions.find((s) => s.id === sessionId);
+          expect(found).toBeUndefined();
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 454 - 0
server/src/services/connection-manager.test.ts

@@ -0,0 +1,454 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt } from '../utils/crypto';
+import {
+  createRdpSession,
+  getActiveSessions,
+  terminateSession,
+  terminateSessionsByInstance,
+  cleanupExpiredSessions,
+  validateToken,
+  ConnectionError,
+} from './connection-manager';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function seedUser(username = 'testuser', role = 'user'): number {
+  const db = getDb();
+  const result = db
+    .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', ?)")
+    .run(username, role);
+  return Number(result.lastInsertRowid);
+}
+
+function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
+  const db = getDb();
+  const defaults = {
+    ec2_instance_id: 'i-abc123',
+    machine_guid: '11111111-1111-1111-1111-111111111111',
+    status: 'running',
+    public_ip: '1.2.3.4',
+    rdp_username: 'Administrator',
+    rdp_password_encrypted: encrypt('P@ssw0rd'),
+    started_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 86400,
+  };
+  const vals = { ...defaults, ...overrides };
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      vals.ec2_instance_id,
+      vals.machine_guid,
+      vals.status,
+      vals.public_ip,
+      vals.rdp_username,
+      vals.rdp_password_encrypted,
+      vals.started_at,
+      vals.expires_at,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+/** Seed a guacamole config into system_settings. The default initDb already seeds defaults, but this helper can override. */
+function ensureGuacamoleConfig(host = '127.0.0.1', port = '4822') {
+  const db = getDb();
+  db.prepare("UPDATE system_settings SET value = ? WHERE key = 'guacamole_host'").run(host);
+  db.prepare("UPDATE system_settings SET value = ? WHERE key = 'guacamole_port'").run(port);
+}
+
+/** Remove guacamole settings to simulate unconfigured state. */
+function clearGuacamoleConfig() {
+  const db = getDb();
+  db.prepare("UPDATE system_settings SET value = NULL WHERE key = 'guacamole_host'").run();
+  db.prepare("UPDATE system_settings SET value = NULL WHERE key = 'guacamole_port'").run();
+}
+
+/** Insert an rdp_sessions row directly for testing queries. */
+function seedSession(overrides: Record<string, any> = {}): string {
+  const db = getDb();
+  const defaults = {
+    id: crypto.randomUUID(),
+    user_id: 1,
+    instance_id: 1,
+    ec2_instance_id: 'i-abc123',
+    token_hash: 'hash-' + Math.random().toString(36).slice(2),
+    status: 'connecting',
+    created_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 300,
+    used_at: null,
+  };
+  const vals = { ...defaults, ...overrides };
+  db.prepare(
+    `INSERT INTO rdp_sessions (id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at, used_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+  ).run(vals.id, vals.user_id, vals.instance_id, vals.ec2_instance_id, vals.token_hash, vals.status, vals.created_at, vals.expires_at, vals.used_at);
+  return vals.id;
+}
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+beforeEach(() => {
+  initDb(':memory:');
+});
+
+afterEach(() => {
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// createRdpSession
+// ---------------------------------------------------------------------------
+
+describe('createRdpSession', () => {
+  it('should successfully create a session for a valid instance owner', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    ensureGuacamoleConfig();
+
+    const session = createRdpSession(userId, instanceId);
+
+    expect(session.id).toBeDefined();
+    expect(session.userId).toBe(userId);
+    expect(session.instanceId).toBe(instanceId);
+    expect(session.ec2InstanceId).toBe('i-abc123');
+    expect(session.token).toBeDefined();
+    expect(session.token.length).toBeGreaterThan(0);
+    expect(session.status).toBe('connecting');
+    expect(session.createdAt).toBeGreaterThan(0);
+    expect(session.expiresAt).toBeGreaterThan(session.createdAt);
+  });
+
+  it('should throw NOT_FOUND for non-existent instance', () => {
+    const userId = seedUser();
+    ensureGuacamoleConfig();
+
+    expect(() => createRdpSession(userId, 9999)).toThrow(ConnectionError);
+    try {
+      createRdpSession(userId, 9999);
+    } catch (e: any) {
+      expect(e.code).toBe('NOT_FOUND');
+      expect(e.statusCode).toBe(404);
+    }
+  });
+
+  it('should throw FORBIDDEN for non-owner', () => {
+    const ownerId = seedUser('owner');
+    const otherId = seedUser('other');
+    const instanceId = seedInstance(ownerId);
+    ensureGuacamoleConfig();
+
+    expect(() => createRdpSession(otherId, instanceId)).toThrow(ConnectionError);
+    try {
+      createRdpSession(otherId, instanceId);
+    } catch (e: any) {
+      expect(e.code).toBe('FORBIDDEN');
+      expect(e.statusCode).toBe(403);
+    }
+  });
+
+  it('should throw INVALID_STATE for non-running instance', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId, { status: 'stopped' });
+    ensureGuacamoleConfig();
+
+    expect(() => createRdpSession(userId, instanceId)).toThrow(ConnectionError);
+    try {
+      createRdpSession(userId, instanceId);
+    } catch (e: any) {
+      expect(e.code).toBe('INVALID_STATE');
+      expect(e.statusCode).toBe(400);
+    }
+  });
+
+  it('should throw RDP_CREDENTIALS_MISSING when credentials are missing', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId, { rdp_username: null, rdp_password_encrypted: null });
+    ensureGuacamoleConfig();
+
+    expect(() => createRdpSession(userId, instanceId)).toThrow(ConnectionError);
+    try {
+      createRdpSession(userId, instanceId);
+    } catch (e: any) {
+      expect(e.code).toBe('RDP_CREDENTIALS_MISSING');
+      expect(e.statusCode).toBe(400);
+    }
+  });
+
+  it('should throw GUACAMOLE_NOT_CONFIGURED when guacamole settings are missing', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    clearGuacamoleConfig();
+
+    expect(() => createRdpSession(userId, instanceId)).toThrow(ConnectionError);
+    try {
+      createRdpSession(userId, instanceId);
+    } catch (e: any) {
+      expect(e.code).toBe('GUACAMOLE_NOT_CONFIGURED');
+      expect(e.statusCode).toBe(503);
+    }
+  });
+
+  it('should return session with valid token and correct fields persisted in DB', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    ensureGuacamoleConfig();
+
+    const session = createRdpSession(userId, instanceId);
+
+    // Verify DB record
+    const db = getDb();
+    const row = db.prepare('SELECT * FROM rdp_sessions WHERE id = ?').get(session.id) as any;
+    expect(row).toBeDefined();
+    expect(row.user_id).toBe(userId);
+    expect(row.instance_id).toBe(instanceId);
+    expect(row.ec2_instance_id).toBe('i-abc123');
+    expect(row.status).toBe('connecting');
+    expect(row.token_hash).toBeDefined();
+    expect(row.token_hash.length).toBeGreaterThan(0);
+    expect(row.expires_at).toBe(session.expiresAt);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// getActiveSessions
+// ---------------------------------------------------------------------------
+
+describe('getActiveSessions', () => {
+  it('should return empty array when no sessions exist', () => {
+    const result = getActiveSessions();
+    expect(result).toEqual([]);
+  });
+
+  it('should return only connecting/connected sessions, not disconnected', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+
+    seedSession({ user_id: userId, instance_id: instanceId, status: 'connecting' });
+    seedSession({ user_id: userId, instance_id: instanceId, status: 'connected', token_hash: 'h2' });
+    seedSession({ user_id: userId, instance_id: instanceId, status: 'disconnected', token_hash: 'h3' });
+
+    const result = getActiveSessions();
+    expect(result).toHaveLength(2);
+    expect(result.every((s) => s.status === 'connecting' || s.status === 'connected')).toBe(true);
+  });
+
+  it('should include username, instanceId, and durationSeconds', () => {
+    const userId = seedUser('rdpuser');
+    const instanceId = seedInstance(userId);
+    const createdAt = Math.floor(Date.now() / 1000) - 120; // 2 minutes ago
+
+    seedSession({
+      user_id: userId,
+      instance_id: instanceId,
+      status: 'connected',
+      created_at: createdAt,
+      expires_at: createdAt + 300,
+    });
+
+    const result = getActiveSessions();
+    expect(result).toHaveLength(1);
+    expect(result[0].username).toBe('rdpuser');
+    expect(result[0].instanceId).toBe(instanceId);
+    expect(result[0].durationSeconds).toBeGreaterThanOrEqual(119); // allow 1s tolerance
+  });
+});
+
+// ---------------------------------------------------------------------------
+// terminateSession
+// ---------------------------------------------------------------------------
+
+describe('terminateSession', () => {
+  it('should successfully terminate an active session', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    const sessionId = seedSession({ user_id: userId, instance_id: instanceId, status: 'connected' });
+
+    terminateSession(sessionId);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(sessionId) as any;
+    expect(row.status).toBe('disconnected');
+  });
+
+  it('should throw SESSION_NOT_FOUND for non-existent session', () => {
+    expect(() => terminateSession('non-existent-id')).toThrow(ConnectionError);
+    try {
+      terminateSession('non-existent-id');
+    } catch (e: any) {
+      expect(e.code).toBe('SESSION_NOT_FOUND');
+      expect(e.statusCode).toBe(404);
+    }
+  });
+});
+
+// ---------------------------------------------------------------------------
+// terminateSessionsByInstance
+// ---------------------------------------------------------------------------
+
+describe('terminateSessionsByInstance', () => {
+  it('should terminate all active sessions for an instance', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-abc123', status: 'connecting' });
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-abc123', status: 'connected', token_hash: 'h2' });
+
+    terminateSessionsByInstance('i-abc123');
+
+    const db = getDb();
+    const rows = db.prepare("SELECT status FROM rdp_sessions WHERE ec2_instance_id = 'i-abc123'").all() as any[];
+    expect(rows).toHaveLength(2);
+    expect(rows.every((r: any) => r.status === 'disconnected')).toBe(true);
+  });
+
+  it('should not affect sessions for other instances', () => {
+    const userId = seedUser();
+    const inst1 = seedInstance(userId, { ec2_instance_id: 'i-inst1' });
+    const inst2 = seedInstance(userId, { ec2_instance_id: 'i-inst2' });
+
+    seedSession({ user_id: userId, instance_id: inst1, ec2_instance_id: 'i-inst1', status: 'connected' });
+    seedSession({ user_id: userId, instance_id: inst2, ec2_instance_id: 'i-inst2', status: 'connected', token_hash: 'h2' });
+
+    terminateSessionsByInstance('i-inst1');
+
+    const db = getDb();
+    const row1 = db.prepare("SELECT status FROM rdp_sessions WHERE ec2_instance_id = 'i-inst1'").get() as any;
+    const row2 = db.prepare("SELECT status FROM rdp_sessions WHERE ec2_instance_id = 'i-inst2'").get() as any;
+    expect(row1.status).toBe('disconnected');
+    expect(row2.status).toBe('connected');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// cleanupExpiredSessions
+// ---------------------------------------------------------------------------
+
+describe('cleanupExpiredSessions', () => {
+  it('should mark expired sessions as disconnected', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    const pastTime = Math.floor(Date.now() / 1000) - 600; // 10 minutes ago
+
+    seedSession({
+      user_id: userId,
+      instance_id: instanceId,
+      status: 'connecting',
+      created_at: pastTime - 300,
+      expires_at: pastTime, // already expired
+    });
+
+    cleanupExpiredSessions();
+
+    const db = getDb();
+    const rows = db.prepare("SELECT status FROM rdp_sessions WHERE user_id = ?").all(userId) as any[];
+    expect(rows).toHaveLength(1);
+    expect(rows[0].status).toBe('disconnected');
+  });
+
+  it('should not affect non-expired sessions', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    const futureTime = Math.floor(Date.now() / 1000) + 600; // 10 minutes from now
+
+    seedSession({
+      user_id: userId,
+      instance_id: instanceId,
+      status: 'connected',
+      expires_at: futureTime,
+    });
+
+    cleanupExpiredSessions();
+
+    const db = getDb();
+    const rows = db.prepare("SELECT status FROM rdp_sessions WHERE user_id = ?").all(userId) as any[];
+    expect(rows).toHaveLength(1);
+    expect(rows[0].status).toBe('connected');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// validateToken
+// ---------------------------------------------------------------------------
+
+describe('validateToken', () => {
+  it('should successfully validate and mark token as used', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    ensureGuacamoleConfig();
+
+    // Create a real session to get a valid token
+    const session = createRdpSession(userId, instanceId);
+
+    const validated = validateToken(session.token);
+
+    expect(validated.id).toBe(session.id);
+    expect(validated.userId).toBe(userId);
+    expect(validated.instanceId).toBe(instanceId);
+    expect(validated.status).toBe('connected');
+
+    // Verify used_at is set in DB
+    const db = getDb();
+    const row = db.prepare('SELECT used_at, status FROM rdp_sessions WHERE id = ?').get(session.id) as any;
+    expect(row.used_at).not.toBeNull();
+    expect(row.status).toBe('connected');
+  });
+
+  it('should throw TOKEN_EXPIRED for expired token', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    ensureGuacamoleConfig();
+
+    const session = createRdpSession(userId, instanceId);
+
+    // Manually expire the session in DB
+    const db = getDb();
+    const pastTime = Math.floor(Date.now() / 1000) - 100;
+    db.prepare('UPDATE rdp_sessions SET expires_at = ? WHERE id = ?').run(pastTime, session.id);
+
+    expect(() => validateToken(session.token)).toThrow(ConnectionError);
+    try {
+      validateToken(session.token);
+    } catch (e: any) {
+      expect(e.code).toBe('TOKEN_EXPIRED');
+      expect(e.statusCode).toBe(401);
+    }
+  });
+
+  it('should throw TOKEN_USED for already-used token', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+    ensureGuacamoleConfig();
+
+    const session = createRdpSession(userId, instanceId);
+
+    // First use succeeds
+    validateToken(session.token);
+
+    // Second use should fail
+    expect(() => validateToken(session.token)).toThrow(ConnectionError);
+    try {
+      validateToken(session.token);
+    } catch (e: any) {
+      expect(e.code).toBe('TOKEN_USED');
+      expect(e.statusCode).toBe(401);
+    }
+  });
+
+  it('should throw SESSION_NOT_FOUND for invalid token', () => {
+    expect(() => validateToken('completely-invalid-token')).toThrow(ConnectionError);
+    try {
+      validateToken('completely-invalid-token');
+    } catch (e: any) {
+      expect(e.code).toBe('SESSION_NOT_FOUND');
+      expect(e.statusCode).toBe(404);
+    }
+  });
+});

+ 408 - 0
server/src/services/connection-manager.ts

@@ -0,0 +1,408 @@
+import crypto from 'crypto';
+import { getDb } from '../db';
+import { decrypt } from '../utils/crypto';
+
+// ---------------------------------------------------------------------------
+// Custom error classes matching app.ts error handling pattern
+// ---------------------------------------------------------------------------
+
+export class ConnectionError extends Error {
+  statusCode: number;
+  code: string;
+
+  constructor(message: string, code: string, statusCode: number) {
+    super(message);
+    this.name = 'ConnectionError';
+    this.code = code;
+    this.statusCode = statusCode;
+  }
+}
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export interface RdpSession {
+  id: string;
+  userId: number;
+  instanceId: number;
+  ec2InstanceId: string;
+  token: string;
+  status: 'connecting' | 'connected' | 'disconnected';
+  createdAt: number;
+  expiresAt: number;
+}
+
+export interface ActiveSessionInfo {
+  id: string;
+  userId: number;
+  username: string;
+  instanceId: number;
+  ec2InstanceId: string;
+  status: 'connecting' | 'connected';
+  createdAt: number;
+  expiresAt: number;
+  durationSeconds: number;
+}
+
+// ---------------------------------------------------------------------------
+// Constants
+// ---------------------------------------------------------------------------
+
+/** Default token expiry: 5 minutes */
+const TOKEN_EXPIRY_SECONDS = 5 * 60;
+
+const GUAC_ALGORITHM = 'aes-256-cbc';
+const GUAC_IV_LENGTH = 16;
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+
+/** Get the guacamole-lite encryption key (separate from the app encryption key). */
+function getGuacEncryptionKey(): string {
+  return process.env.GUACAMOLE_ENCRYPTION_KEY || 'default-guacamole-key-32-chars!!';
+}
+
+/**
+ * Encrypt a JSON payload for guacamole-lite using AES-256-CBC.
+ *
+ * guacamole-lite's Crypt.decrypt() expects:
+ *   base64( JSON({ iv: base64(iv), value: base64(ciphertext) }) )
+ *
+ * The key is used as-is (must match the key passed to guacamole-lite config).
+ */
+function encryptGuacToken(payload: object): string {
+  const key = getGuacEncryptionKey();
+  const iv = crypto.randomBytes(GUAC_IV_LENGTH);
+  const cipher = crypto.createCipheriv(GUAC_ALGORITHM, key, iv);
+  const jsonStr = JSON.stringify(payload);
+  let encrypted = cipher.update(jsonStr, 'utf8', 'binary');
+  encrypted += cipher.final('binary');
+
+  const data = {
+    iv: Buffer.from(iv).toString('base64'),
+    value: Buffer.from(encrypted, 'binary').toString('base64'),
+  };
+
+  return Buffer.from(JSON.stringify(data)).toString('base64');
+}
+
+/** Hash a token string using SHA-256 for storage. */
+function hashToken(token: string): string {
+  return crypto.createHash('sha256').update(token).digest('hex');
+}
+
+// ---------------------------------------------------------------------------
+// 2.1 createRdpSession
+// ---------------------------------------------------------------------------
+
+/**
+ * Create an RDP session for the given user and instance.
+ *
+ * Validates:
+ * - Instance exists
+ * - User is the instance owner
+ * - Instance is running with a public IP
+ * - RDP credentials are present
+ * - Guacamole is configured
+ *
+ * Generates an encrypted guacamole-lite token and stores the session in DB.
+ */
+export function createRdpSession(
+  userId: number,
+  instanceId: number,
+  decryptFn: (s: string) => string = decrypt,
+): RdpSession {
+  const db = getDb();
+
+  // 1. Fetch instance
+  const instance = db
+    .prepare(
+      'SELECT id, user_id, ec2_instance_id, status, public_ip, rdp_username, rdp_password_encrypted FROM instances WHERE id = ?',
+    )
+    .get(instanceId) as
+    | {
+        id: number;
+        user_id: number;
+        ec2_instance_id: string;
+        status: string;
+        public_ip: string | null;
+        rdp_username: string | null;
+        rdp_password_encrypted: string | null;
+      }
+    | undefined;
+
+  if (!instance) {
+    throw new ConnectionError('实例不存在', 'NOT_FOUND', 404);
+  }
+
+  // 2. Ownership check
+  if (instance.user_id !== userId) {
+    throw new ConnectionError('无权操作此实例', 'FORBIDDEN', 403);
+  }
+
+  // 3. Instance must be running
+  if (instance.status !== 'running') {
+    throw new ConnectionError(
+      '实例未处于运行状态,无法建立远程连接',
+      'INVALID_STATE',
+      400,
+    );
+  }
+
+  // 4. RDP credentials must exist
+  if (!instance.rdp_username || !instance.rdp_password_encrypted || !instance.public_ip) {
+    throw new ConnectionError(
+      '该实例缺少 RDP 连接信息',
+      'RDP_CREDENTIALS_MISSING',
+      400,
+    );
+  }
+
+  // 5. Guacamole must be configured
+  const guacHost = db
+    .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
+    .get() as { value: string } | undefined;
+  const guacPort = db
+    .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
+    .get() as { value: string } | undefined;
+
+  if (!guacHost?.value || !guacPort?.value) {
+    throw new ConnectionError(
+      'Guacamole 服务未配置',
+      'GUACAMOLE_NOT_CONFIGURED',
+      503,
+    );
+  }
+
+  // 6. Decrypt RDP password
+  const rdpPassword = decryptFn(instance.rdp_password_encrypted);
+
+  // 7. Build guacamole-lite token payload
+  // Include guacdHost/guacdPort for dynamic routing so config changes
+  // take effect without restarting the server.
+  const tokenPayload = {
+    connection: {
+      type: 'rdp',
+      guacdHost: guacHost.value,
+      guacdPort: parseInt(guacPort.value, 10),
+      settings: {
+        hostname: instance.public_ip,
+        port: '3389',
+        timeout: '15',
+        username: instance.rdp_username,
+        password: rdpPassword,
+        security: 'nla',
+        'ignore-cert': 'true',
+        'cert-tofu': 'true',
+        'enable-wallpaper': 'true',
+        'enable-font-smoothing': 'true',
+        'enable-desktop-composition': 'true',
+        'enable-theming': 'true',
+        'disable-gfx': 'true',
+        'resize-method': 'display-update',
+        width: 1920,
+        height: 1080,
+      },
+    },
+  };
+
+  const token = encryptGuacToken(tokenPayload);
+  const tokenHash = hashToken(token);
+
+  // 8. Create session record
+  const sessionId = crypto.randomUUID();
+  const now = Math.floor(Date.now() / 1000);
+  const expiresAt = now + TOKEN_EXPIRY_SECONDS;
+
+  db.prepare(
+    `INSERT INTO rdp_sessions (id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at)
+     VALUES (?, ?, ?, ?, ?, 'connecting', ?, ?)`,
+  ).run(sessionId, userId, instanceId, instance.ec2_instance_id, tokenHash, now, expiresAt);
+
+  return {
+    id: sessionId,
+    userId,
+    instanceId,
+    ec2InstanceId: instance.ec2_instance_id,
+    token,
+    status: 'connecting',
+    createdAt: now,
+    expiresAt,
+  };
+}
+
+// ---------------------------------------------------------------------------
+// 2.2 getActiveSessions
+// ---------------------------------------------------------------------------
+
+/**
+ * Get all active RDP sessions (status = connecting or connected).
+ * Includes username, instance ID, and connection duration.
+ */
+export function getActiveSessions(): ActiveSessionInfo[] {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+
+  const rows = db
+    .prepare(
+      `SELECT rs.id, rs.user_id, u.username, rs.instance_id, rs.ec2_instance_id,
+              rs.status, rs.created_at, rs.expires_at
+       FROM rdp_sessions rs
+       JOIN users u ON u.id = rs.user_id
+       WHERE rs.status IN ('connecting', 'connected')
+       ORDER BY rs.created_at DESC`,
+    )
+    .all() as Array<{
+    id: string;
+    user_id: number;
+    username: string;
+    instance_id: number;
+    ec2_instance_id: string;
+    status: 'connecting' | 'connected';
+    created_at: number;
+    expires_at: number;
+  }>;
+
+  return rows.map((row) => ({
+    id: row.id,
+    userId: row.user_id,
+    username: row.username,
+    instanceId: row.instance_id,
+    ec2InstanceId: row.ec2_instance_id,
+    status: row.status,
+    createdAt: row.created_at,
+    expiresAt: row.expires_at,
+    durationSeconds: now - row.created_at,
+  }));
+}
+
+// ---------------------------------------------------------------------------
+// 2.3 terminateSession
+// ---------------------------------------------------------------------------
+
+/**
+ * Terminate a specific RDP session by setting its status to disconnected.
+ */
+export function terminateSession(sessionId: string): void {
+  const db = getDb();
+
+  const session = db
+    .prepare('SELECT id, status FROM rdp_sessions WHERE id = ?')
+    .get(sessionId) as { id: string; status: string } | undefined;
+
+  if (!session) {
+    throw new ConnectionError('会话不存在', 'SESSION_NOT_FOUND', 404);
+  }
+
+  db.prepare(
+    "UPDATE rdp_sessions SET status = 'disconnected' WHERE id = ?",
+  ).run(sessionId);
+}
+
+// ---------------------------------------------------------------------------
+// 2.4 terminateSessionsByInstance
+// ---------------------------------------------------------------------------
+
+/**
+ * Terminate all active sessions for a given EC2 instance.
+ * Used when an instance is stopped or terminated.
+ */
+export function terminateSessionsByInstance(ec2InstanceId: string): void {
+  const db = getDb();
+  db.prepare(
+    "UPDATE rdp_sessions SET status = 'disconnected' WHERE ec2_instance_id = ? AND status IN ('connecting', 'connected')",
+  ).run(ec2InstanceId);
+}
+
+/**
+ * Delete all session records for a given EC2 instance.
+ * Used before deleting the instance row to avoid FK constraint violations.
+ */
+export function deleteSessionsByInstance(ec2InstanceId: string): void {
+  const db = getDb();
+  db.prepare('DELETE FROM rdp_sessions WHERE ec2_instance_id = ?').run(ec2InstanceId);
+}
+
+// ---------------------------------------------------------------------------
+// 2.5 cleanupExpiredSessions
+// ---------------------------------------------------------------------------
+
+/**
+ * Clean up expired session records by marking them as disconnected.
+ */
+export function cleanupExpiredSessions(): void {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  db.prepare(
+    "UPDATE rdp_sessions SET status = 'disconnected' WHERE expires_at < ? AND status IN ('connecting', 'connected')",
+  ).run(now);
+}
+
+// ---------------------------------------------------------------------------
+// 2.6 validateToken
+// ---------------------------------------------------------------------------
+
+/**
+ * Validate a session token: check if it's expired or already used.
+ * If valid, marks the token as used (sets used_at) and returns the session.
+ */
+export function validateToken(token: string): RdpSession {
+  const db = getDb();
+  const tokenHash = hashToken(token);
+  const now = Math.floor(Date.now() / 1000);
+
+  const session = db
+    .prepare(
+      'SELECT id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at, used_at FROM rdp_sessions WHERE token_hash = ?',
+    )
+    .get(tokenHash) as
+    | {
+        id: string;
+        user_id: number;
+        instance_id: number;
+        ec2_instance_id: string;
+        token_hash: string;
+        status: string;
+        created_at: number;
+        expires_at: number;
+        used_at: number | null;
+      }
+    | undefined;
+
+  if (!session) {
+    throw new ConnectionError('会话不存在', 'SESSION_NOT_FOUND', 404);
+  }
+
+  // Check expiry
+  if (now > session.expires_at) {
+    throw new ConnectionError(
+      '会话已过期,请重新连接',
+      'TOKEN_EXPIRED',
+      401,
+    );
+  }
+
+  // Check one-time use
+  if (session.used_at !== null) {
+    throw new ConnectionError('会话令牌已被使用', 'TOKEN_USED', 401);
+  }
+
+  // Mark as used and update status to connected
+  db.prepare(
+    "UPDATE rdp_sessions SET used_at = ?, status = 'connected' WHERE id = ?",
+  ).run(now, session.id);
+
+  return {
+    id: session.id,
+    userId: session.user_id,
+    instanceId: session.instance_id,
+    ec2InstanceId: session.ec2_instance_id,
+    token: token,
+    status: 'connected',
+    createdAt: session.created_at,
+    expiresAt: session.expires_at,
+  };
+}

+ 101 - 0
server/src/services/guacamole-proxy.ts

@@ -0,0 +1,101 @@
+import { Server as HttpServer } from 'http';
+import net from 'net';
+import { getDb } from '../db';
+
+// guacamole-lite has no TypeScript types
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const GuacamoleLite = require('guacamole-lite');
+
+// ---------------------------------------------------------------------------
+// Guacamole encryption key (shared with connection-manager token generation)
+// ---------------------------------------------------------------------------
+
+function getGuacEncryptionKey(): string {
+  return process.env.GUACAMOLE_ENCRYPTION_KEY || 'default-guacamole-key-32-chars!!';
+}
+
+// ---------------------------------------------------------------------------
+// initGuacamoleProxy
+// ---------------------------------------------------------------------------
+
+/**
+ * Initialise the guacamole-lite WebSocket server and attach it to the
+ * provided HTTP server on the `/ws/rdp` path.
+ *
+ * Reads guacd host/port from system_settings in the database.
+ */
+export function initGuacamoleProxy(httpServer: HttpServer): void {
+  const db = getDb();
+
+  const guacHostRow = db
+    .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
+    .get() as { value: string } | undefined;
+  const guacPortRow = db
+    .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
+    .get() as { value: string } | undefined;
+
+  const guacdHost = guacHostRow?.value || '127.0.0.1';
+  const guacdPort = parseInt(guacPortRow?.value || '4822', 10);
+
+  const encryptionKey = getGuacEncryptionKey();
+
+  // Create guacamole-lite server attached to the existing HTTP server
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  const _guacServer = new GuacamoleLite(
+    { server: httpServer, path: '/ws/rdp' },       // WebSocket options
+    { host: guacdHost, port: guacdPort },           // guacd connection
+    {
+      crypt: {
+        cypher: 'AES-256-CBC',
+        key: encryptionKey,
+      },
+      log: {
+        level: 0, // QUIET
+      },
+    },
+  );
+}
+
+// ---------------------------------------------------------------------------
+// testGuacdConnection
+// ---------------------------------------------------------------------------
+
+/**
+ * Test TCP connectivity to a guacd instance.
+ *
+ * Attempts a raw TCP connection and resolves with a success/failure result.
+ * Times out after 5 seconds.
+ */
+export function testGuacdConnection(
+  host: string,
+  port: number,
+): Promise<{ success: boolean; message: string }> {
+  return new Promise((resolve) => {
+    const socket = new net.Socket();
+    const TIMEOUT_MS = 5000;
+
+    const cleanup = () => {
+      socket.removeAllListeners();
+      socket.destroy();
+    };
+
+    socket.setTimeout(TIMEOUT_MS);
+
+    socket.on('connect', () => {
+      cleanup();
+      resolve({ success: true, message: `Successfully connected to guacd at ${host}:${port}` });
+    });
+
+    socket.on('timeout', () => {
+      cleanup();
+      resolve({ success: false, message: `Connection to guacd at ${host}:${port} timed out after ${TIMEOUT_MS / 1000} seconds` });
+    });
+
+    socket.on('error', (err: NodeJS.ErrnoException) => {
+      cleanup();
+      resolve({ success: false, message: `Failed to connect to guacd at ${host}:${port}: ${err.message}` });
+    });
+
+    socket.connect(port, host);
+  });
+}

+ 183 - 0
server/src/services/instance-lifecycle-rdp.test.ts

@@ -0,0 +1,183 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt } from '../utils/crypto';
+import { terminateSessionsByInstance } from './connection-manager';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function seedUser(username = 'testuser'): number {
+  const db = getDb();
+  const result = db
+    .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')")
+    .run(username);
+  return Number(result.lastInsertRowid);
+}
+
+function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
+  const db = getDb();
+  const defaults = {
+    ec2_instance_id: 'i-lifecycle01',
+    machine_guid: '11111111-1111-1111-1111-111111111111',
+    status: 'running',
+    public_ip: '1.2.3.4',
+    rdp_username: 'Administrator',
+    rdp_password_encrypted: encrypt('P@ssw0rd'),
+    started_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 86400,
+  };
+  const vals = { ...defaults, ...overrides };
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      vals.ec2_instance_id,
+      vals.machine_guid,
+      vals.status,
+      vals.public_ip,
+      vals.rdp_username,
+      vals.rdp_password_encrypted,
+      vals.started_at,
+      vals.expires_at,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+function seedSession(overrides: Record<string, any> = {}): string {
+  const db = getDb();
+  const defaults = {
+    id: crypto.randomUUID(),
+    user_id: 1,
+    instance_id: 1,
+    ec2_instance_id: 'i-lifecycle01',
+    token_hash: 'hash-' + Math.random().toString(36).slice(2),
+    status: 'connected',
+    created_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 300,
+    used_at: null,
+  };
+  const vals = { ...defaults, ...overrides };
+  db.prepare(
+    `INSERT INTO rdp_sessions (id, user_id, instance_id, ec2_instance_id, token_hash, status, created_at, expires_at, used_at)
+     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+  ).run(vals.id, vals.user_id, vals.instance_id, vals.ec2_instance_id, vals.token_hash, vals.status, vals.created_at, vals.expires_at, vals.used_at);
+  return vals.id;
+}
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+beforeEach(() => {
+  initDb(':memory:');
+});
+
+afterEach(() => {
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// Instance lifecycle → RDP session cleanup
+// ---------------------------------------------------------------------------
+
+describe('Instance lifecycle RDP session cleanup', () => {
+  it('terminateSessionsByInstance disconnects all active sessions for the instance', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+
+    const s1 = seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-lifecycle01', status: 'connecting' });
+    const s2 = seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-lifecycle01', status: 'connected' });
+
+    terminateSessionsByInstance('i-lifecycle01');
+
+    const db = getDb();
+    const r1 = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(s1) as any;
+    const r2 = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(s2) as any;
+    expect(r1.status).toBe('disconnected');
+    expect(r2.status).toBe('disconnected');
+  });
+
+  it('terminateSessionsByInstance does not affect sessions for other instances', () => {
+    const userId = seedUser();
+    const inst1 = seedInstance(userId, { ec2_instance_id: 'i-stop01' });
+    const inst2 = seedInstance(userId, { ec2_instance_id: 'i-other01' });
+
+    const s1 = seedSession({ user_id: userId, instance_id: inst1, ec2_instance_id: 'i-stop01', status: 'connected' });
+    const s2 = seedSession({ user_id: userId, instance_id: inst2, ec2_instance_id: 'i-other01', status: 'connected' });
+
+    terminateSessionsByInstance('i-stop01');
+
+    const db = getDb();
+    const r1 = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(s1) as any;
+    const r2 = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(s2) as any;
+    expect(r1.status).toBe('disconnected');
+    expect(r2.status).toBe('connected');
+  });
+
+  it('terminateSessionsByInstance ignores already-disconnected sessions', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId);
+
+    const s1 = seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-lifecycle01', status: 'disconnected' });
+    const s2 = seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-lifecycle01', status: 'connected' });
+
+    terminateSessionsByInstance('i-lifecycle01');
+
+    const db = getDb();
+    const r1 = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(s1) as any;
+    const r2 = db.prepare('SELECT status FROM rdp_sessions WHERE id = ?').get(s2) as any;
+    expect(r1.status).toBe('disconnected');
+    expect(r2.status).toBe('disconnected');
+  });
+
+  it('terminateSessionsByInstance is a no-op when no sessions exist for the instance', () => {
+    // Should not throw
+    expect(() => terminateSessionsByInstance('i-nonexistent')).not.toThrow();
+  });
+
+  it('simulates stop lifecycle: sessions are cleaned up when terminateSessionsByInstance is called', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId, { ec2_instance_id: 'i-stopme', status: 'running' });
+
+    // Create multiple active sessions
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-stopme', status: 'connecting' });
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-stopme', status: 'connected' });
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-stopme', status: 'connected' });
+
+    // Simulate what stopInstance does after AWS call succeeds
+    terminateSessionsByInstance('i-stopme');
+
+    const db = getDb();
+    const active = db
+      .prepare("SELECT COUNT(*) as cnt FROM rdp_sessions WHERE ec2_instance_id = 'i-stopme' AND status IN ('connecting', 'connected')")
+      .get() as any;
+    expect(active.cnt).toBe(0);
+
+    const total = db
+      .prepare("SELECT COUNT(*) as cnt FROM rdp_sessions WHERE ec2_instance_id = 'i-stopme'")
+      .get() as any;
+    expect(total.cnt).toBe(3);
+  });
+
+  it('simulates terminate lifecycle: sessions are cleaned up when terminateSessionsByInstance is called', () => {
+    const userId = seedUser();
+    const instanceId = seedInstance(userId, { ec2_instance_id: 'i-termme', status: 'running' });
+
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-termme', status: 'connected' });
+    seedSession({ user_id: userId, instance_id: instanceId, ec2_instance_id: 'i-termme', status: 'connecting' });
+
+    // Simulate what terminateInstance does after AWS call succeeds
+    terminateSessionsByInstance('i-termme');
+
+    const db = getDb();
+    const rows = db
+      .prepare("SELECT status FROM rdp_sessions WHERE ec2_instance_id = 'i-termme'")
+      .all() as any[];
+    expect(rows).toHaveLength(2);
+    expect(rows.every((r: any) => r.status === 'disconnected')).toBe(true);
+  });
+});

+ 286 - 0
server/src/services/instance-manager.property.test.ts

@@ -0,0 +1,286 @@
+// Feature: ec2-management-platform, Property 8: MachineGuid 持久化往返
+// **Validates: Requirements 5.4**
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt, decrypt } from '../utils/crypto';
+
+// ---------------------------------------------------------------------------
+// Mock AWS SDK
+// ---------------------------------------------------------------------------
+const mockSend = vi.fn();
+
+vi.mock('@aws-sdk/client-ec2', () => {
+  return {
+    EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
+    RunInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RunInstances', ...p })),
+    DescribeInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'DescribeInstances', ...p })),
+    GetPasswordDataCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'GetPasswordData', ...p })),
+    StopInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StopInstances', ...p })),
+    StartInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StartInstances', ...p })),
+    RebootInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RebootInstances', ...p })),
+    TerminateInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'TerminateInstances', ...p })),
+  };
+});
+
+import { launchInstance } from './instance-manager';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function seedAwsConfig() {
+  const db = getDb();
+  db.prepare(
+    `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id)
+     VALUES (?, ?, ?, ?, ?, ?, ?)`,
+  ).run('AKIAIOSFODNN7EXAMPLE', encrypt('wJalrXUtnFEMI/K7MDENG'), 'us-east-1', 'ami-12345678', 't3.medium', 'my-key', 'sg-12345');
+}
+
+function seedUser(username = 'testuser'): number {
+  const db = getDb();
+  const result = db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(username);
+  return Number(result.lastInsertRowid);
+}
+
+/** Generator for valid UUID strings (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) */
+const uuidArb = fc.tuple(
+  fc.hexaString({ minLength: 8, maxLength: 8 }),
+  fc.hexaString({ minLength: 4, maxLength: 4 }),
+  fc.hexaString({ minLength: 4, maxLength: 4 }),
+  fc.hexaString({ minLength: 4, maxLength: 4 }),
+  fc.hexaString({ minLength: 12, maxLength: 12 }),
+).map(([a, b, c, d, e]) => `${a}-${b}-${c}-${d}-${e}`);
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+let userId: number;
+
+beforeEach(() => {
+  initDb(':memory:');
+  seedAwsConfig();
+  userId = seedUser();
+});
+
+afterEach(() => {
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// Property 8: MachineGuid 持久化往返
+// ---------------------------------------------------------------------------
+
+describe('Property 8: MachineGuid 持久化往返', () => {
+  it('should persist the exact MachineGuid value submitted during launch', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, async (machineGuid) => {
+        // Reset mocks for each iteration
+        mockSend.mockReset();
+
+        // Unique ec2 instance id per iteration to avoid UNIQUE constraint
+        const ec2Id = `i-${machineGuid.replace(/-/g, '').slice(0, 17)}`;
+
+        // 1. RunInstances
+        mockSend.mockResolvedValueOnce({
+          Instances: [{ InstanceId: ec2Id }],
+        });
+        // 2. DescribeInstances (waitForState – already running)
+        mockSend.mockResolvedValueOnce({
+          Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
+        });
+        // 3. DescribeInstances (get public IP)
+        mockSend.mockResolvedValueOnce({
+          Reservations: [{ Instances: [{ PublicIpAddress: '10.0.0.1' }] }],
+        });
+        // 4. GetPasswordData
+        mockSend.mockResolvedValueOnce({
+          PasswordData: 'TestPass123',
+        });
+
+        const result = await launchInstance(userId, machineGuid, decrypt);
+
+        // Verify the returned machineGuid matches exactly
+        expect(result.machineGuid).toBe(machineGuid);
+
+        // Verify the DB record has the exact same machine_guid
+        const db = getDb();
+        const row = db
+          .prepare('SELECT machine_guid FROM instances WHERE id = ?')
+          .get(result.instanceId) as { machine_guid: string } | undefined;
+
+        expect(row).toBeDefined();
+        expect(row!.machine_guid).toBe(machineGuid);
+      }),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// Feature: ec2-management-platform, Property 10: 实例创建返回完整 RDP 凭证
+// **Validates: Requirements 6.4**
+
+/** Arbitrary for IPv4 addresses (1-255 . 0-255 . 0-255 . 0-255) */
+const ipArb = fc
+  .tuple(
+    fc.integer({ min: 1, max: 255 }),
+    fc.integer({ min: 0, max: 255 }),
+    fc.integer({ min: 0, max: 255 }),
+    fc.integer({ min: 0, max: 255 }),
+  )
+  .map(([a, b, c, d]) => `${a}.${b}.${c}.${d}`);
+
+/** Arbitrary for non-empty password strings (printable ASCII, 8-64 chars) */
+const passwordArb = fc.string({ minLength: 8, maxLength: 64 }).filter((s) => s.trim().length > 0);
+
+describe('Property 10: 实例创建返回完整 RDP 凭证', () => {
+  it('should return non-empty publicIp, rdpUsername, and rdpPassword for any successful launch', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, ipArb, passwordArb, async (machineGuid, publicIp, password) => {
+        // Reset mocks for each iteration
+        mockSend.mockReset();
+
+        // Unique ec2 instance id per iteration
+        const ec2Id = `i-${machineGuid.replace(/-/g, '').slice(0, 17)}`;
+
+        // 1. RunInstances
+        mockSend.mockResolvedValueOnce({
+          Instances: [{ InstanceId: ec2Id }],
+        });
+        // 2. DescribeInstances (waitForState – already running)
+        mockSend.mockResolvedValueOnce({
+          Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
+        });
+        // 3. DescribeInstances (get public IP)
+        mockSend.mockResolvedValueOnce({
+          Reservations: [{ Instances: [{ PublicIpAddress: publicIp }] }],
+        });
+        // 4. GetPasswordData
+        mockSend.mockResolvedValueOnce({
+          PasswordData: password,
+        });
+
+        // Need a fresh user per iteration to avoid FK issues with unique ec2_instance_id
+        const uid = seedUser(`user_p10_${machineGuid.slice(0, 8)}_${Date.now()}`);
+
+        const result = await launchInstance(uid, machineGuid, decrypt);
+
+        // The response must contain non-empty RDP credentials
+        expect(result.publicIp).toBe(publicIp);
+        expect(result.publicIp.length).toBeGreaterThan(0);
+
+        expect(result.rdpUsername).toBe('Administrator');
+        expect(result.rdpUsername.length).toBeGreaterThan(0);
+
+        expect(result.rdpPassword).toBe(password);
+        expect(result.rdpPassword.length).toBeGreaterThan(0);
+      }),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// Feature: ec2-management-platform, Property 11: 实例生命周期状态转换
+// **Validates: Requirements 7.2, 7.3, 7.4, 7.5**
+
+import { stopInstance, startInstance, rebootInstance, terminateInstance } from './instance-manager';
+
+/** Arbitrary for initial status of non-terminated instances */
+const nonTerminatedStatusArb = fc.constantFrom('pending', 'running', 'stopped');
+
+/** Helper: insert an instance row directly into the DB and return its id */
+function insertInstance(
+  userId: number,
+  ec2InstanceId: string,
+  status: string,
+  machineGuid = '00000000-0000-0000-0000-000000000000',
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, started_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?)`,
+    )
+    .run(userId, ec2InstanceId, machineGuid, status, now, now);
+  return Number(result.lastInsertRowid);
+}
+
+/** Helper: read instance status from DB */
+function getInstanceStatus(instanceId: number): string {
+  const db = getDb();
+  const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instanceId) as { status: string };
+  return row.status;
+}
+
+describe('Property 11: 实例生命周期状态转换', () => {
+  it('stop on a running instance should transition to stopped', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, async (guid) => {
+        mockSend.mockReset();
+        mockSend.mockResolvedValueOnce({}); // StopInstancesCommand
+
+        const ec2Id = `i-stop${guid.replace(/-/g, '').slice(0, 13)}`;
+        const instId = insertInstance(userId, ec2Id, 'running', guid);
+
+        await stopInstance(instId, decrypt);
+
+        expect(getInstanceStatus(instId)).toBe('stopped');
+      }),
+      { numRuns: 100 },
+    );
+  });
+
+  it('start on a stopped instance should transition to running', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, async (guid) => {
+        mockSend.mockReset();
+        mockSend.mockResolvedValueOnce({}); // StartInstancesCommand
+
+        const ec2Id = `i-strt${guid.replace(/-/g, '').slice(0, 13)}`;
+        const instId = insertInstance(userId, ec2Id, 'stopped', guid);
+
+        await startInstance(instId, decrypt);
+
+        expect(getInstanceStatus(instId)).toBe('running');
+      }),
+      { numRuns: 100 },
+    );
+  });
+
+  it('reboot on a running instance should remain running', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, async (guid) => {
+        mockSend.mockReset();
+        mockSend.mockResolvedValueOnce({}); // RebootInstancesCommand
+
+        const ec2Id = `i-rbot${guid.replace(/-/g, '').slice(0, 13)}`;
+        const instId = insertInstance(userId, ec2Id, 'running', guid);
+
+        await rebootInstance(instId, decrypt);
+
+        expect(getInstanceStatus(instId)).toBe('running');
+      }),
+      { numRuns: 100 },
+    );
+  });
+
+  it('terminate on any non-terminated instance should transition to terminated', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, nonTerminatedStatusArb, async (guid, initialStatus) => {
+        mockSend.mockReset();
+        mockSend.mockResolvedValueOnce({}); // TerminateInstancesCommand
+
+        const ec2Id = `i-term${guid.replace(/-/g, '').slice(0, 13)}`;
+        const instId = insertInstance(userId, ec2Id, initialStatus, guid);
+
+        await terminateInstance(instId, decrypt);
+
+        expect(getInstanceStatus(instId)).toBe('terminated');
+      }),
+      { numRuns: 100 },
+    );
+  });
+});

+ 387 - 0
server/src/services/instance-manager.test.ts

@@ -0,0 +1,387 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt, decrypt } from '../utils/crypto';
+
+// ---------------------------------------------------------------------------
+// Mock AWS SDK – must be declared before importing the module under test
+// ---------------------------------------------------------------------------
+const mockSend = vi.fn();
+
+vi.mock('@aws-sdk/client-ec2', () => {
+  return {
+    EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
+    RunInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RunInstances', ...p })),
+    DescribeInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'DescribeInstances', ...p })),
+    GetPasswordDataCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'GetPasswordData', ...p })),
+    StopInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StopInstances', ...p })),
+    StartInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StartInstances', ...p })),
+    RebootInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RebootInstances', ...p })),
+    TerminateInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'TerminateInstances', ...p })),
+  };
+});
+
+import {
+  launchInstance,
+  stopInstance,
+  startInstance,
+  rebootInstance,
+  terminateInstance,
+  getInstanceRdpInfo,
+  loadAwsConfig,
+  getMaxLifetimeHours,
+} from './instance-manager';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/** Seed a minimal AWS config row so the service can read it. */
+function seedAwsConfig() {
+  const db = getDb();
+  db.prepare(
+    `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id)
+     VALUES (?, ?, ?, ?, ?, ?, ?)`,
+  ).run('AKIAIOSFODNN7EXAMPLE', encrypt('wJalrXUtnFEMI/K7MDENG'), 'us-east-1', 'ami-12345678', 't3.medium', 'my-key', 'sg-12345');
+}
+
+/** Insert a system_settings row for max lifetime. */
+function seedMaxLifetime(hours: number) {
+  const db = getDb();
+  const existing = db.prepare("SELECT id FROM system_settings WHERE key = 'max_instance_lifetime_hours'").get() as any;
+  if (existing) {
+    db.prepare("UPDATE system_settings SET value = ? WHERE key = 'max_instance_lifetime_hours'").run(String(hours));
+  } else {
+    db.prepare("INSERT INTO system_settings (key, value) VALUES ('max_instance_lifetime_hours', ?)").run(String(hours));
+  }
+}
+
+/** Insert a user row and return the id. */
+function seedUser(username = 'testuser'): number {
+  const db = getDb();
+  const result = db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(username);
+  return Number(result.lastInsertRowid);
+}
+
+/** Insert an instance row directly for lifecycle tests. */
+function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
+  const db = getDb();
+  const defaults = {
+    ec2_instance_id: 'i-abc123',
+    machine_guid: '11111111-1111-1111-1111-111111111111',
+    status: 'running',
+    public_ip: '1.2.3.4',
+    rdp_username: 'Administrator',
+    rdp_password_encrypted: encrypt('P@ssw0rd'),
+    started_at: Math.floor(Date.now() / 1000),
+    expires_at: Math.floor(Date.now() / 1000) + 86400,
+  };
+  const vals = { ...defaults, ...overrides };
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(
+      userId,
+      vals.ec2_instance_id,
+      vals.machine_guid,
+      vals.status,
+      vals.public_ip,
+      vals.rdp_username,
+      vals.rdp_password_encrypted,
+      vals.started_at,
+      vals.expires_at,
+    );
+  return Number(result.lastInsertRowid);
+}
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+beforeEach(() => {
+  initDb(':memory:');
+  mockSend.mockReset();
+});
+
+afterEach(() => {
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// loadAwsConfig
+// ---------------------------------------------------------------------------
+
+describe('loadAwsConfig', () => {
+  it('should throw when no AWS config exists', () => {
+    expect(() => loadAwsConfig()).toThrow('请先配置 AWS 参数');
+  });
+
+  it('should return config when properly seeded', () => {
+    seedAwsConfig();
+    const config = loadAwsConfig();
+    expect(config.access_key).toBe('AKIAIOSFODNN7EXAMPLE');
+    expect(config.region).toBe('us-east-1');
+    expect(config.ami_id).toBe('ami-12345678');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// getMaxLifetimeHours
+// ---------------------------------------------------------------------------
+
+describe('getMaxLifetimeHours', () => {
+  it('should return 24 by default', () => {
+    expect(getMaxLifetimeHours()).toBe(24);
+  });
+
+  it('should return configured value', () => {
+    seedMaxLifetime(48);
+    expect(getMaxLifetimeHours()).toBe(48);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// launchInstance
+// ---------------------------------------------------------------------------
+
+describe('launchInstance', () => {
+  it('should launch an instance and return full RDP credentials', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    seedMaxLifetime(12);
+
+    // Mock AWS calls in order:
+    // 1. RunInstances
+    mockSend.mockResolvedValueOnce({
+      Instances: [{ InstanceId: 'i-new123' }],
+    });
+    // 2. DescribeInstances (waitForState polling – already running)
+    mockSend.mockResolvedValueOnce({
+      Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
+    });
+    // 3. DescribeInstances (get public IP)
+    mockSend.mockResolvedValueOnce({
+      Reservations: [{ Instances: [{ PublicIpAddress: '54.1.2.3' }] }],
+    });
+    // 4. GetPasswordData
+    mockSend.mockResolvedValueOnce({
+      PasswordData: 'MyWindowsP@ss',
+    });
+
+    const result = await launchInstance(userId, 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', decrypt);
+
+    expect(result.ec2InstanceId).toBe('i-new123');
+    expect(result.machineGuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
+    expect(result.status).toBe('running');
+    expect(result.publicIp).toBe('54.1.2.3');
+    expect(result.rdpUsername).toBe('Administrator');
+    expect(result.rdpPassword).toBe('MyWindowsP@ss');
+    expect(result.expiresAt).toBe(result.startedAt + 12 * 3600);
+
+    // Verify DB record
+    const db = getDb();
+    const row = db.prepare('SELECT * FROM instances WHERE ec2_instance_id = ?').get('i-new123') as any;
+    expect(row.status).toBe('running');
+    expect(row.public_ip).toBe('54.1.2.3');
+    expect(row.machine_guid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
+  });
+
+  it('should throw when AWS config is missing', async () => {
+    const userId = seedUser();
+    await expect(launchInstance(userId, '11111111-1111-1111-1111-111111111111', decrypt)).rejects.toThrow(
+      '请先配置 AWS 参数',
+    );
+  });
+
+  it('should throw and mark instance terminated when RunInstances fails', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+
+    mockSend.mockRejectedValueOnce(new Error('InsufficientInstanceCapacity'));
+
+    await expect(launchInstance(userId, '11111111-1111-1111-1111-111111111111', decrypt)).rejects.toThrow(
+      'EC2 实例启动失败',
+    );
+  });
+
+  it('should use default max lifetime of 24 hours when not configured', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+
+    mockSend.mockResolvedValueOnce({ Instances: [{ InstanceId: 'i-def456' }] });
+    mockSend.mockResolvedValueOnce({
+      Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
+    });
+    mockSend.mockResolvedValueOnce({
+      Reservations: [{ Instances: [{ PublicIpAddress: '10.0.0.1' }] }],
+    });
+    mockSend.mockResolvedValueOnce({ PasswordData: 'pass123' });
+
+    const result = await launchInstance(userId, '22222222-2222-2222-2222-222222222222', decrypt);
+    expect(result.expiresAt).toBe(result.startedAt + 24 * 3600);
+  });
+});
+
+// ---------------------------------------------------------------------------
+// stopInstance
+// ---------------------------------------------------------------------------
+
+describe('stopInstance', () => {
+  it('should stop a running instance', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'running' });
+
+    mockSend.mockResolvedValueOnce({});
+
+    await stopInstance(instId, decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('stopped');
+  });
+
+  it('should throw when instance is not running', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'stopped' });
+
+    await expect(stopInstance(instId, decrypt)).rejects.toThrow('只能关机运行中的实例');
+  });
+
+  it('should throw when instance does not exist', async () => {
+    seedAwsConfig();
+    await expect(stopInstance(9999, decrypt)).rejects.toThrow('实例不存在');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// startInstance
+// ---------------------------------------------------------------------------
+
+describe('startInstance', () => {
+  it('should start a stopped instance', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'stopped' });
+
+    mockSend.mockResolvedValueOnce({});
+
+    await startInstance(instId, decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('running');
+  });
+
+  it('should throw when instance is not stopped', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'running' });
+
+    await expect(startInstance(instId, decrypt)).rejects.toThrow('只能启动已停止的实例');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// rebootInstance
+// ---------------------------------------------------------------------------
+
+describe('rebootInstance', () => {
+  it('should reboot a running instance and keep status as running', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'running' });
+
+    mockSend.mockResolvedValueOnce({});
+
+    await rebootInstance(instId, decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('running');
+  });
+
+  it('should throw when instance is not running', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'stopped' });
+
+    await expect(rebootInstance(instId, decrypt)).rejects.toThrow('只能重启运行中的实例');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// terminateInstance
+// ---------------------------------------------------------------------------
+
+describe('terminateInstance', () => {
+  it('should terminate a running instance', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'running' });
+
+    mockSend.mockResolvedValueOnce({});
+
+    await terminateInstance(instId, decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('terminated');
+  });
+
+  it('should terminate a stopped instance', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'stopped' });
+
+    mockSend.mockResolvedValueOnce({});
+
+    await terminateInstance(instId, decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('terminated');
+  });
+
+  it('should throw when instance is already terminated', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const instId = seedInstance(userId, { status: 'terminated' });
+
+    await expect(terminateInstance(instId, decrypt)).rejects.toThrow('实例已终止');
+  });
+});
+
+// ---------------------------------------------------------------------------
+// getInstanceRdpInfo
+// ---------------------------------------------------------------------------
+
+describe('getInstanceRdpInfo', () => {
+  it('should return decrypted RDP info', () => {
+    const userId = seedUser();
+    const instId = seedInstance(userId, {
+      public_ip: '10.0.0.5',
+      rdp_username: 'Administrator',
+      rdp_password_encrypted: encrypt('SecretPass!'),
+    });
+
+    const info = getInstanceRdpInfo(instId, decrypt);
+    expect(info.publicIp).toBe('10.0.0.5');
+    expect(info.rdpUsername).toBe('Administrator');
+    expect(info.rdpPassword).toBe('SecretPass!');
+  });
+
+  it('should throw when instance does not exist', () => {
+    expect(() => getInstanceRdpInfo(9999, decrypt)).toThrow('实例不存在');
+  });
+
+  it('should return empty password when not set', () => {
+    const userId = seedUser();
+    const instId = seedInstance(userId, { rdp_password_encrypted: null });
+
+    const info = getInstanceRdpInfo(instId, decrypt);
+    expect(info.rdpPassword).toBe('');
+  });
+});

+ 433 - 0
server/src/services/instance-manager.ts

@@ -0,0 +1,433 @@
+import {
+  EC2Client,
+  RunInstancesCommand,
+  DescribeInstancesCommand,
+  CreateTagsCommand,
+  StopInstancesCommand,
+  StartInstancesCommand,
+  RebootInstancesCommand,
+  TerminateInstancesCommand,
+} from '@aws-sdk/client-ec2';
+import { getDb } from '../db';
+import { generateUserData, generateWindowsPassword } from './userdata';
+import { encrypt } from '../utils/crypto';
+import { terminateSessionsByInstance, deleteSessionsByInstance } from './connection-manager';
+
+/** Shape returned from aws_config table */
+interface AwsConfig {
+  access_key: string;
+  secret_key_encrypted: string;
+  region: string;
+  ami_id: string;
+  instance_type: string | null;
+  key_pair_name: string | null;
+  security_group_id: string | null;
+  subnet_id: string | null;
+}
+
+/** Shape of an instance row from the DB */
+export interface InstanceRecord {
+  id: number;
+  user_id: number;
+  ec2_instance_id: string;
+  machine_guid: string;
+  status: string;
+  public_ip: string | null;
+  rdp_username: string | null;
+  rdp_password_encrypted: string | null;
+  started_at: number | null;
+  expires_at: number | null;
+  created_at: number;
+}
+
+/** Result returned after launching an instance */
+export interface LaunchResult {
+  instanceId: number;
+  ec2InstanceId: string;
+  machineGuid: string;
+  status: string;
+}
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+/** Build an EC2Client from the stored AWS configuration. */
+function buildEc2Client(config: AwsConfig, decryptFn: (s: string) => string): EC2Client {
+  const secretKey = decryptFn(config.secret_key_encrypted);
+  return new EC2Client({
+    region: config.region,
+    credentials: {
+      accessKeyId: config.access_key,
+      secretAccessKey: secretKey,
+    },
+  });
+}
+
+/** Write an instance action log entry. */
+function logInstanceAction(
+  userId: number,
+  username: string,
+  ec2InstanceId: string | null,
+  action: string,
+  durationSeconds?: number,
+): void {
+  try {
+    const db = getDb();
+    db.prepare(
+      'INSERT INTO instance_logs (user_id, username, ec2_instance_id, action, duration_seconds) VALUES (?, ?, ?, ?, ?)'
+    ).run(userId, username, ec2InstanceId, action, durationSeconds ?? null);
+  } catch (err: any) {
+    console.error('[InstanceLog] 写入日志失败:', err.message);
+  }
+}
+
+/** Load the single AWS config row. Throws if not configured. */
+export function loadAwsConfig(): AwsConfig {
+  const db = getDb();
+  const config = db
+    .prepare(
+      'SELECT access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id, subnet_id FROM aws_config ORDER BY id DESC LIMIT 1',
+    )
+    .get() as AwsConfig | undefined;
+
+  if (!config || !config.access_key || !config.secret_key_encrypted || !config.region || !config.ami_id) {
+    throw new Error('请先配置 AWS 参数');
+  }
+  return config;
+}
+
+/** Read max_instance_lifetime_minutes from system_settings (default 1440 = 24h). */
+export function getMaxLifetimeMinutes(): number {
+  const db = getDb();
+  const row = db
+    .prepare("SELECT value FROM system_settings WHERE key = 'max_instance_lifetime_minutes'")
+    .get() as { value: string } | undefined;
+  if (row && row.value) {
+    const parsed = Number(row.value);
+    if (!isNaN(parsed) && parsed > 0) return parsed;
+  }
+  return 1440;
+}
+
+/**
+ * Poll DescribeInstances until the instance reaches the desired state or
+ * the timeout is exceeded.
+ */
+async function waitForState(
+  ec2: EC2Client,
+  ec2InstanceId: string,
+  desiredState: string,
+  timeoutMs = 300_000,
+  intervalMs = 5_000,
+): Promise<void> {
+  const deadline = Date.now() + timeoutMs;
+  while (Date.now() < deadline) {
+    const desc = await ec2.send(
+      new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
+    );
+    const state = desc.Reservations?.[0]?.Instances?.[0]?.State?.Name;
+    if (state === desiredState) return;
+    await new Promise((r) => setTimeout(r, intervalMs));
+  }
+  throw new Error(`实例 ${ec2InstanceId} 未在超时时间内进入 ${desiredState} 状态`);
+}
+
+// ---------------------------------------------------------------------------
+// Public API
+// ---------------------------------------------------------------------------
+
+/**
+ * Launch a new EC2 instance for the given user with the specified MachineGuid.
+ *
+ * Steps:
+ * 1. Read AWS config from DB
+ * 2. Call RunInstances with UserData script
+ * 3. Wait for "running" state
+ * 4. Retrieve public IP via DescribeInstances
+ * 5. Retrieve Windows password via GetPasswordData
+ * 6. Encrypt RDP password and persist instance record
+ * 7. Return full instance info including RDP credentials
+ */
+export async function launchInstance(
+  userId: number,
+  machineGuid: string,
+  username: string,
+  /** Injected decrypt function – defaults to the crypto util */
+  decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
+): Promise<LaunchResult> {
+  const config = loadAwsConfig();
+  const ec2 = buildEc2Client(config, decryptFn);
+
+  // Generate admin password
+  const adminPassword = generateWindowsPassword();
+
+  // 1. Build RunInstances params
+  const userData = generateUserData(machineGuid, adminPassword);
+
+  const runParams: any = {
+    ImageId: config.ami_id,
+    InstanceType: config.instance_type || 't3.medium',
+    MinCount: 1,
+    MaxCount: 1,
+    UserData: userData,
+    BlockDeviceMappings: [
+      {
+        DeviceName: '/dev/sda1',
+        Ebs: {
+          VolumeType: 'gp3',
+          DeleteOnTermination: true,
+        },
+      },
+    ],
+    NetworkInterfaces: [
+      {
+        DeviceIndex: 0,
+        AssociatePublicIpAddress: true,
+        Ipv6AddressCount: 1,
+        SubnetId: config.subnet_id || undefined,
+        Groups: config.security_group_id ? [config.security_group_id] : undefined,
+      },
+    ],
+    MetadataOptions: {
+      HttpTokens: 'required',
+      HttpEndpoint: 'enabled',
+    },
+  };
+  if (config.key_pair_name) runParams.KeyName = config.key_pair_name;
+
+  // 2. Launch
+  let ec2InstanceId: string;
+  try {
+    const runResult = await ec2.send(new RunInstancesCommand(runParams));
+    ec2InstanceId = runResult.Instances?.[0]?.InstanceId ?? '';
+    if (!ec2InstanceId) {
+      throw new Error('RunInstances 未返回实例 ID');
+    }
+  } catch (err: any) {
+    throw new Error(`EC2 实例启动失败: ${err.message}`);
+  }
+
+  // Insert a pending record immediately with password
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const encryptedPassword = encrypt(adminPassword);
+  const insertResult = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, rdp_username, rdp_password_encrypted, created_at)
+       VALUES (?, ?, ?, 'pending', 'Administrator', ?, ?)`,
+    )
+    .run(userId, ec2InstanceId, machineGuid, encryptedPassword, now);
+  const instanceId = Number(insertResult.lastInsertRowid);
+
+  // Tag the instance with Name
+  const nameTag = `BIFA-${username}-${now}-${userId}`;
+  ec2.send(new CreateTagsCommand({
+    Resources: [ec2InstanceId],
+    Tags: [{ Key: 'Name', Value: nameTag }],
+  })).catch((err) => {
+    console.error(`[LaunchInstance] 打 Name Tag 失败:`, err.message);
+  });
+
+  logInstanceAction(userId, username, ec2InstanceId, 'launch');
+
+  // 3. Async: wait for running, get IP, update record
+  finalizeInstance(instanceId, ec2InstanceId, ec2).catch((err) => {
+    console.error(`[LaunchInstance] 异步完成实例 ${instanceId} 失败:`, err.message);
+    const db2 = getDb();
+    db2.prepare("UPDATE instances SET status = 'terminated' WHERE id = ?").run(instanceId);
+  });
+
+  return {
+    instanceId,
+    ec2InstanceId,
+    machineGuid,
+    status: 'pending',
+  };
+}
+
+/**
+ * Async background work after RunInstances: wait for running, get IP/password, set expires_at.
+ */
+async function finalizeInstance(
+  instanceId: number,
+  ec2InstanceId: string,
+  ec2: EC2Client,
+): Promise<void> {
+  // Wait for running
+  await waitForState(ec2, ec2InstanceId, 'running');
+
+  // Get public IP
+  const descResult = await ec2.send(
+    new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
+  );
+  const publicIp =
+    descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? '';
+
+  // Compute expires_at from NOW (when instance is actually running)
+  const runningNow = Math.floor(Date.now() / 1000);
+  const maxLifetimeMinutes = getMaxLifetimeMinutes();
+  const expiresAt = runningNow + maxLifetimeMinutes * 60;
+
+  const db = getDb();
+  db.prepare(
+    `UPDATE instances
+     SET status = 'running',
+         public_ip = ?,
+         started_at = ?,
+         expires_at = ?
+     WHERE id = ?`,
+  ).run(publicIp, runningNow, expiresAt, instanceId);
+
+  console.log(`[LaunchInstance] 实例 ${instanceId} (${ec2InstanceId}) 已就绪`);
+}
+
+/**
+ * Stop (shut down) a running EC2 instance.
+ */
+export async function stopInstance(
+  instanceId: number,
+  decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
+): Promise<void> {
+  const db = getDb();
+  const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as
+    | (Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id' | 'started_at'>)
+    | undefined;
+
+  if (!row) throw new Error('实例不存在');
+  if (row.status !== 'running') throw new Error('只能关机运行中的实例');
+
+  const config = loadAwsConfig();
+  const ec2 = buildEc2Client(config, decryptFn);
+
+  await ec2.send(new StopInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
+
+  // Clean up all active RDP sessions for this instance
+  terminateSessionsByInstance(row.ec2_instance_id);
+
+  db.prepare("UPDATE instances SET status = 'stopped', public_ip = NULL WHERE id = ?").run(instanceId);
+
+  const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined;
+  const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
+  logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'stop', duration);
+}
+
+/**
+ * Start a previously stopped EC2 instance.
+ */
+export async function startInstance(
+  instanceId: number,
+  decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
+): Promise<void> {
+  const db = getDb();
+  const row = db.prepare('SELECT ec2_instance_id, status, user_id FROM instances WHERE id = ?').get(instanceId) as
+    | Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id'>
+    | undefined;
+
+  if (!row) throw new Error('实例不存在');
+  if (row.status !== 'stopped') throw new Error('只能启动已停止的实例');
+
+  const config = loadAwsConfig();
+  const ec2 = buildEc2Client(config, decryptFn);
+
+  await ec2.send(new StartInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
+  db.prepare("UPDATE instances SET status = 'running' WHERE id = ?").run(instanceId);
+
+  const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
+  logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'start');
+
+  // Async: wait for running and re-fetch public IP
+  (async () => {
+    try {
+      await waitForState(ec2, row.ec2_instance_id, 'running');
+      const descResult = await ec2.send(
+        new DescribeInstancesCommand({ InstanceIds: [row.ec2_instance_id] }),
+      );
+      const publicIp = descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? '';
+      db.prepare('UPDATE instances SET public_ip = ? WHERE id = ?').run(publicIp || null, instanceId);
+      console.log(`[StartInstance] 实例 ${instanceId} 新公网 IP: ${publicIp}`);
+    } catch (err: any) {
+      console.error(`[StartInstance] 获取实例 ${instanceId} 公网 IP 失败:`, err.message);
+    }
+  })();
+}
+
+/**
+ * Reboot a running EC2 instance.
+ */
+export async function rebootInstance(
+  instanceId: number,
+  decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
+): Promise<void> {
+  const db = getDb();
+  const row = db.prepare('SELECT ec2_instance_id, status FROM instances WHERE id = ?').get(instanceId) as
+    | Pick<InstanceRecord, 'ec2_instance_id' | 'status'>
+    | undefined;
+
+  if (!row) throw new Error('实例不存在');
+  if (row.status !== 'running') throw new Error('只能重启运行中的实例');
+
+  const config = loadAwsConfig();
+  const ec2 = buildEc2Client(config, decryptFn);
+
+  await ec2.send(new RebootInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
+  // Status stays 'running' after reboot
+}
+
+/**
+ * Terminate (destroy) an EC2 instance.
+ */
+export async function terminateInstance(
+  instanceId: number,
+  decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
+): Promise<void> {
+  const db = getDb();
+  const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as
+    | (Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id' | 'started_at'>)
+    | undefined;
+
+  if (!row) throw new Error('实例不存在');
+  if (row.status === 'terminated') throw new Error('实例已终止');
+
+  const config = loadAwsConfig();
+  const ec2 = buildEc2Client(config, decryptFn);
+
+  await ec2.send(new TerminateInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
+
+  // Clean up all active RDP sessions for this instance
+  terminateSessionsByInstance(row.ec2_instance_id);
+
+  const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined;
+  const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
+  logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'terminate', duration);
+
+  // Delete session records before deleting instance to avoid FK constraint violation
+  deleteSessionsByInstance(row.ec2_instance_id);
+  db.prepare('DELETE FROM instances WHERE id = ?').run(instanceId);
+}
+
+/**
+ * Get RDP connection info for an instance.
+ */
+export function getInstanceRdpInfo(
+  instanceId: number,
+  decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
+): { publicIp: string; rdpUsername: string; rdpPassword: string } {
+  const db = getDb();
+  const row = db
+    .prepare('SELECT public_ip, rdp_username, rdp_password_encrypted FROM instances WHERE id = ?')
+    .get(instanceId) as Pick<InstanceRecord, 'public_ip' | 'rdp_username' | 'rdp_password_encrypted'> | undefined;
+
+  if (!row) throw new Error('实例不存在');
+
+  let rdpPassword = '';
+  if (row.rdp_password_encrypted) {
+    rdpPassword = decryptFn(row.rdp_password_encrypted);
+  }
+
+  return {
+    publicIp: row.public_ip ?? '',
+    rdpUsername: row.rdp_username ?? '',
+    rdpPassword,
+  };
+}

+ 164 - 0
server/src/services/lifetime-timer.property.test.ts

@@ -0,0 +1,164 @@
+// Feature: ec2-management-platform, Property 13: 实例过期时间正确计算
+// **Validates: Requirements 8.2**
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt, decrypt } from '../utils/crypto';
+
+// ---------------------------------------------------------------------------
+// Mock AWS SDK
+// ---------------------------------------------------------------------------
+const mockSend = vi.fn();
+
+vi.mock('@aws-sdk/client-ec2', () => ({
+  EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
+  RunInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RunInstances', ...p })),
+  DescribeInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'DescribeInstances', ...p })),
+  GetPasswordDataCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'GetPasswordData', ...p })),
+  StopInstancesCommand: vi.fn(),
+  StartInstancesCommand: vi.fn(),
+  RebootInstancesCommand: vi.fn(),
+  TerminateInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'TerminateInstances', ...p })),
+}));
+
+import { launchInstance } from './instance-manager';
+import { checkExpiredInstances } from './lifetime-timer';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function seedAwsConfig() {
+  const db = getDb();
+  db.prepare(
+    `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id)
+     VALUES (?, ?, ?, ?, ?, ?, ?)`,
+  ).run('AKIAIOSFODNN7EXAMPLE', encrypt('wJalrXUtnFEMI/K7MDENG'), 'us-east-1', 'ami-12345678', 't3.medium', 'my-key', 'sg-12345');
+}
+
+function seedUser(username = 'testuser'): number {
+  const db = getDb();
+  const result = db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(username);
+  return Number(result.lastInsertRowid);
+}
+
+/** Generator for valid UUID strings */
+const uuidArb = fc.tuple(
+  fc.hexaString({ minLength: 8, maxLength: 8 }),
+  fc.hexaString({ minLength: 4, maxLength: 4 }),
+  fc.hexaString({ minLength: 4, maxLength: 4 }),
+  fc.hexaString({ minLength: 4, maxLength: 4 }),
+  fc.hexaString({ minLength: 12, maxLength: 12 }),
+).map(([a, b, c, d, e]) => `${a}-${b}-${c}-${d}-${e}`);
+
+/** Generator for max lifetime hours (1 to 720 hours = 30 days) */
+const lifetimeHoursArb = fc.integer({ min: 1, max: 720 });
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+let userId: number;
+
+beforeEach(() => {
+  initDb(':memory:');
+  seedAwsConfig();
+  userId = seedUser();
+});
+
+afterEach(() => {
+  vi.clearAllMocks();
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// Property 13: 实例过期时间正确计算
+// ---------------------------------------------------------------------------
+
+describe('Property 13: 实例过期时间正确计算', () => {
+  it('expires_at should equal started_at + H × 3600 for any max lifetime H hours', async () => {
+    await fc.assert(
+      fc.asyncProperty(uuidArb, lifetimeHoursArb, async (machineGuid, maxHours) => {
+        mockSend.mockReset();
+
+        const ec2Id = `i-p13${machineGuid.replace(/-/g, '').slice(0, 14)}`;
+
+        // Set max_instance_lifetime_hours in system_settings
+        const db = getDb();
+        db.prepare("DELETE FROM system_settings WHERE key = 'max_instance_lifetime_hours'").run();
+        db.prepare("INSERT INTO system_settings (key, value) VALUES ('max_instance_lifetime_hours', ?)").run(String(maxHours));
+
+        // Mock AWS calls for launchInstance
+        mockSend.mockResolvedValueOnce({ Instances: [{ InstanceId: ec2Id }] });
+        mockSend.mockResolvedValueOnce({ Reservations: [{ Instances: [{ State: { Name: 'running' } }] }] });
+        mockSend.mockResolvedValueOnce({ Reservations: [{ Instances: [{ PublicIpAddress: '10.0.0.1' }] }] });
+        mockSend.mockResolvedValueOnce({ PasswordData: 'TestPass123' });
+
+        const uid = seedUser(`user_p13_${machineGuid.slice(0, 8)}_${Date.now()}`);
+        const result = await launchInstance(uid, machineGuid, decrypt);
+
+        // Verify: expires_at = started_at + maxHours * 3600
+        expect(result.expiresAt).toBe(result.startedAt + maxHours * 3600);
+      }),
+      { numRuns: 100 },
+    );
+  });
+});
+
+// ---------------------------------------------------------------------------
+// Feature: ec2-management-platform, Property 14: 过期实例自动终止
+// **Validates: Requirements 8.3**
+// ---------------------------------------------------------------------------
+
+/** Helper: insert an instance row directly */
+function insertInstance(
+  userId: number,
+  ec2InstanceId: string,
+  status: string,
+  expiresAt: number,
+): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at, created_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(userId, ec2InstanceId, '00000000-0000-0000-0000-000000000000', status, '1.2.3.4', 'Administrator', encrypt('pass'), now - 86400, expiresAt, now - 86400);
+  return Number(result.lastInsertRowid);
+}
+
+/** Arbitrary for non-terminated statuses */
+const nonTerminatedStatusArb = fc.constantFrom('pending', 'running', 'stopped');
+
+describe('Property 14: 过期实例自动终止', () => {
+  it('expired non-terminated instances should be terminated by lifecycle checker', async () => {
+    await fc.assert(
+      fc.asyncProperty(
+        nonTerminatedStatusArb,
+        fc.integer({ min: 1, max: 86400 }),
+        async (status, secondsAgo) => {
+          mockSend.mockReset();
+          mockSend.mockResolvedValue({}); // TerminateInstancesCommand
+
+          const now = Math.floor(Date.now() / 1000);
+          const expiresAt = now - secondsAgo; // expired
+          const ec2Id = `i-p14-${status}-${secondsAgo}-${Date.now()}`;
+
+          const instId = insertInstance(userId, ec2Id, status, expiresAt);
+
+          await checkExpiredInstances(decrypt);
+
+          const db = getDb();
+          const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as { status: string };
+          expect(row.status).toBe('terminated');
+
+          // Verify AWS terminate was called
+          expect(mockSend).toHaveBeenCalled();
+        },
+      ),
+      { numRuns: 100 },
+    );
+  });
+});

+ 243 - 0
server/src/services/lifetime-timer.test.ts

@@ -0,0 +1,243 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { initDb, closeDb, getDb } from '../db';
+import { encrypt, decrypt } from '../utils/crypto';
+
+// ---------------------------------------------------------------------------
+// Mock AWS SDK
+// ---------------------------------------------------------------------------
+const mockSend = vi.fn();
+
+vi.mock('@aws-sdk/client-ec2', () => ({
+  EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
+  RunInstancesCommand: vi.fn(),
+  DescribeInstancesCommand: vi.fn(),
+  GetPasswordDataCommand: vi.fn(),
+  StopInstancesCommand: vi.fn(),
+  StartInstancesCommand: vi.fn(),
+  RebootInstancesCommand: vi.fn(),
+  TerminateInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'TerminateInstances', ...p })),
+}));
+
+// Mock node-cron
+const mockSchedule = vi.fn();
+const mockStop = vi.fn();
+
+vi.mock('node-cron', () => ({
+  default: {
+    schedule: (...args: any[]) => {
+      mockSchedule(...args);
+      return { stop: mockStop };
+    },
+  },
+}));
+
+import { checkExpiredInstances, startLifetimeTimer, stopLifetimeTimer } from './lifetime-timer';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function seedAwsConfig() {
+  const db = getDb();
+  db.prepare(
+    `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id)
+     VALUES (?, ?, ?, ?, ?, ?, ?)`,
+  ).run('AKIAIOSFODNN7EXAMPLE', encrypt('wJalrXUtnFEMI/K7MDENG'), 'us-east-1', 'ami-12345678', 't3.medium', 'my-key', 'sg-12345');
+}
+
+function seedUser(username = 'testuser'): number {
+  const db = getDb();
+  const result = db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(username);
+  return Number(result.lastInsertRowid);
+}
+
+function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+  const defaults = {
+    ec2_instance_id: `i-${Math.random().toString(36).slice(2, 10)}`,
+    machine_guid: '11111111-1111-1111-1111-111111111111',
+    status: 'running',
+    public_ip: '1.2.3.4',
+    rdp_username: 'Administrator',
+    rdp_password_encrypted: encrypt('P@ssw0rd'),
+    started_at: now - 86400,
+    expires_at: now + 86400,
+  };
+  const vals = { ...defaults, ...overrides };
+  const result = db
+    .prepare(
+      `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
+       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+    )
+    .run(userId, vals.ec2_instance_id, vals.machine_guid, vals.status, vals.public_ip, vals.rdp_username, vals.rdp_password_encrypted, vals.started_at, vals.expires_at);
+  return Number(result.lastInsertRowid);
+}
+
+// ---------------------------------------------------------------------------
+// Setup / Teardown
+// ---------------------------------------------------------------------------
+
+beforeEach(() => {
+  initDb(':memory:');
+  mockSend.mockReset();
+  mockSchedule.mockClear();
+  mockStop.mockClear();
+});
+
+afterEach(() => {
+  closeDb();
+});
+
+// ---------------------------------------------------------------------------
+// checkExpiredInstances
+// ---------------------------------------------------------------------------
+
+describe('checkExpiredInstances', () => {
+  it('should terminate expired instances', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const now = Math.floor(Date.now() / 1000);
+
+    // Expired instance (expires_at in the past)
+    const instId = seedInstance(userId, {
+      ec2_instance_id: 'i-expired1',
+      status: 'running',
+      expires_at: now - 60,
+    });
+
+    mockSend.mockResolvedValueOnce({}); // TerminateInstances
+
+    await checkExpiredInstances(decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('terminated');
+  });
+
+  it('should not terminate non-expired instances', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const now = Math.floor(Date.now() / 1000);
+
+    // Instance that hasn't expired yet
+    const instId = seedInstance(userId, {
+      ec2_instance_id: 'i-active1',
+      status: 'running',
+      expires_at: now + 3600,
+    });
+
+    await checkExpiredInstances(decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('running');
+    expect(mockSend).not.toHaveBeenCalled();
+  });
+
+  it('should not terminate already terminated instances', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const now = Math.floor(Date.now() / 1000);
+
+    seedInstance(userId, {
+      ec2_instance_id: 'i-terminated1',
+      status: 'terminated',
+      expires_at: now - 3600,
+    });
+
+    await checkExpiredInstances(decrypt);
+
+    // terminateInstance should not be called for already terminated instances
+    expect(mockSend).not.toHaveBeenCalled();
+  });
+
+  it('should handle termination failure gracefully and continue', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const now = Math.floor(Date.now() / 1000);
+
+    // Two expired instances
+    const instId1 = seedInstance(userId, {
+      ec2_instance_id: 'i-fail1',
+      status: 'running',
+      expires_at: now - 120,
+    });
+    const instId2 = seedInstance(userId, {
+      ec2_instance_id: 'i-ok1',
+      status: 'running',
+      expires_at: now - 60,
+    });
+
+    // First call fails, second succeeds
+    mockSend.mockRejectedValueOnce(new Error('AWS API error'));
+    mockSend.mockResolvedValueOnce({});
+
+    // Should not throw
+    await checkExpiredInstances(decrypt);
+
+    const db = getDb();
+    // First instance: terminateInstance threw, but the error in terminateInstance
+    // is caught by checkExpiredInstances. The status depends on whether
+    // terminateInstance itself updates the DB before the AWS call fails.
+    // Looking at terminateInstance: it calls AWS first, then updates DB.
+    // So if AWS fails, DB status stays 'running'.
+    const row1 = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId1) as any;
+    expect(row1.status).toBe('running'); // failed, stays running
+
+    const row2 = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId2) as any;
+    expect(row2.status).toBe('terminated'); // succeeded
+  });
+
+  it('should terminate expired stopped instances', async () => {
+    seedAwsConfig();
+    const userId = seedUser();
+    const now = Math.floor(Date.now() / 1000);
+
+    const instId = seedInstance(userId, {
+      ec2_instance_id: 'i-stopped-expired',
+      status: 'stopped',
+      expires_at: now - 300,
+    });
+
+    mockSend.mockResolvedValueOnce({});
+
+    await checkExpiredInstances(decrypt);
+
+    const db = getDb();
+    const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
+    expect(row.status).toBe('terminated');
+  });
+
+  it('should do nothing when no instances exist', async () => {
+    await checkExpiredInstances(decrypt);
+    expect(mockSend).not.toHaveBeenCalled();
+  });
+});
+
+// ---------------------------------------------------------------------------
+// startLifetimeTimer / stopLifetimeTimer
+// ---------------------------------------------------------------------------
+
+describe('startLifetimeTimer', () => {
+  it('should schedule a cron job with every-minute pattern', () => {
+    startLifetimeTimer();
+    expect(mockSchedule).toHaveBeenCalledWith('* * * * *', expect.any(Function));
+    // Clean up
+    stopLifetimeTimer();
+  });
+});
+
+describe('stopLifetimeTimer', () => {
+  it('should stop the cron job', () => {
+    startLifetimeTimer();
+    stopLifetimeTimer();
+    expect(mockStop).toHaveBeenCalled();
+  });
+
+  it('should be safe to call when no timer is running', () => {
+    // Should not throw
+    stopLifetimeTimer();
+    expect(mockStop).not.toHaveBeenCalled();
+  });
+});

+ 71 - 0
server/src/services/lifetime-timer.ts

@@ -0,0 +1,71 @@
+import cron from 'node-cron';
+import { getDb } from '../db';
+import { terminateInstance } from './instance-manager';
+
+let cronTask: cron.ScheduledTask | null = null;
+
+interface ExpiredInstance {
+  id: number;
+  ec2_instance_id: string;
+}
+
+/**
+ * Core logic: find all expired, non-terminated instances and terminate them.
+ * Exported separately for testability.
+ */
+export async function checkExpiredInstances(
+  decryptFn?: (s: string) => string,
+): Promise<void> {
+  const db = getDb();
+  const now = Math.floor(Date.now() / 1000);
+
+  const expiredInstances = db
+    .prepare(
+      `SELECT id, ec2_instance_id FROM instances
+       WHERE expires_at IS NOT NULL AND expires_at <= ? AND status IN ('running', 'stopped')`,
+    )
+    .all(now) as ExpiredInstance[];
+
+  for (const instance of expiredInstances) {
+    try {
+      await terminateInstance(instance.id, decryptFn);
+      console.log(
+        `[Lifetime_Timer] 已终止过期实例: id=${instance.id}, ec2=${instance.ec2_instance_id}`,
+      );
+    } catch (err: any) {
+      console.error(
+        `[Lifetime_Timer] 终止实例失败: id=${instance.id}, ec2=${instance.ec2_instance_id}, error=${err.message}`,
+      );
+    }
+  }
+}
+
+/**
+ * Start the cron job that checks for expired instances every minute.
+ */
+export function startLifetimeTimer(): void {
+  if (cronTask) return;
+  cronTask = cron.schedule('* * * * *', () => {
+    checkExpiredInstances().catch((err) => {
+      console.error('[Lifetime_Timer] 检查过期实例时出错:', err.message);
+    });
+    // Clean up logs older than 30 days
+    try {
+      const db = getDb();
+      const cutoff = Math.floor(Date.now() / 1000) - 30 * 86400;
+      db.prepare('DELETE FROM instance_logs WHERE created_at < ?').run(cutoff);
+    } catch { /* ignore */ }
+  });
+  console.log('[Lifetime_Timer] 定时任务已启动');
+}
+
+/**
+ * Stop the cron job.
+ */
+export function stopLifetimeTimer(): void {
+  if (cronTask) {
+    cronTask.stop();
+    cronTask = null;
+    console.log('[Lifetime_Timer] 定时任务已停止');
+  }
+}

+ 77 - 0
server/src/services/userdata.property.test.ts

@@ -0,0 +1,77 @@
+// Feature: ec2-management-platform, Property 9: UserData 脚本包含 MachineGuid
+import { describe, it, expect } from 'vitest';
+import fc from 'fast-check';
+import { generateUserData } from './userdata';
+
+/**
+ * Validates: Requirements 6.2
+ *
+ * Property 9: UserData 脚本包含 MachineGuid
+ * 对于任意有效的 MachineGuid,生成的 EC2 UserData 脚本应包含该 MachineGuid 值,
+ * 且目标注册表路径为 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography 的 MachineGuid 键。
+ */
+
+/** Arbitrary that generates valid UUIDs in 8-4-4-4-12 hex format */
+const hexChar = fc.mapToConstant(
+  { num: 10, build: (v) => String.fromCharCode(0x30 + v) }, // 0-9
+  { num: 6, build: (v) => String.fromCharCode(0x61 + v) },  // a-f
+  { num: 6, build: (v) => String.fromCharCode(0x41 + v) }   // A-F
+);
+
+function hexBlock(length: number): fc.Arbitrary<string> {
+  return fc.array(hexChar, { minLength: length, maxLength: length }).map((chars) => chars.join(''));
+}
+
+const validUuidArb: fc.Arbitrary<string> = fc.tuple(
+  hexBlock(8),
+  hexBlock(4),
+  hexBlock(4),
+  hexBlock(4),
+  hexBlock(12)
+).map(([a, b, c, d, e]) => `${a}-${b}-${c}-${d}-${e}`);
+
+describe('Property 9: UserData 脚本包含 MachineGuid', () => {
+  it('should contain the MachineGuid value in the decoded UserData script', () => {
+    fc.assert(
+      fc.property(validUuidArb, (machineGuid) => {
+        const base64 = generateUserData(machineGuid);
+        const decoded = Buffer.from(base64, 'base64').toString('utf-8');
+        expect(decoded).toContain(machineGuid);
+      }),
+      { numRuns: 100 }
+    );
+  });
+
+  it('should contain the correct registry path HKLM:\\SOFTWARE\\Microsoft\\Cryptography', () => {
+    fc.assert(
+      fc.property(validUuidArb, (machineGuid) => {
+        const base64 = generateUserData(machineGuid);
+        const decoded = Buffer.from(base64, 'base64').toString('utf-8');
+        expect(decoded).toContain('HKLM:\\SOFTWARE\\Microsoft\\Cryptography');
+      }),
+      { numRuns: 100 }
+    );
+  });
+
+  it('should target the MachineGuid registry key name', () => {
+    fc.assert(
+      fc.property(validUuidArb, (machineGuid) => {
+        const base64 = generateUserData(machineGuid);
+        const decoded = Buffer.from(base64, 'base64').toString('utf-8');
+        expect(decoded).toContain('-Name "MachineGuid"');
+      }),
+      { numRuns: 100 }
+    );
+  });
+
+  it('should set the MachineGuid as the registry value', () => {
+    fc.assert(
+      fc.property(validUuidArb, (machineGuid) => {
+        const base64 = generateUserData(machineGuid);
+        const decoded = Buffer.from(base64, 'base64').toString('utf-8');
+        expect(decoded).toContain(`-Value "${machineGuid}"`);
+      }),
+      { numRuns: 100 }
+    );
+  });
+});

+ 47 - 0
server/src/services/userdata.test.ts

@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest';
+import { generateUserData } from './userdata';
+
+describe('generateUserData', () => {
+  const sampleGuid = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
+
+  it('should return a base64-encoded string', () => {
+    const result = generateUserData(sampleGuid);
+    // Should not throw when decoding
+    const decoded = Buffer.from(result, 'base64').toString('utf-8');
+    // Re-encoding should produce the same result (valid base64 round-trip)
+    expect(Buffer.from(decoded, 'utf-8').toString('base64')).toBe(result);
+  });
+
+  it('should contain <powershell> tags when decoded', () => {
+    const result = generateUserData(sampleGuid);
+    const decoded = Buffer.from(result, 'base64').toString('utf-8');
+    expect(decoded).toContain('<powershell>');
+    expect(decoded).toContain('</powershell>');
+  });
+
+  it('should contain the MachineGuid value in the decoded script', () => {
+    const result = generateUserData(sampleGuid);
+    const decoded = Buffer.from(result, 'base64').toString('utf-8');
+    expect(decoded).toContain(sampleGuid);
+  });
+
+  it('should target the correct registry path', () => {
+    const result = generateUserData(sampleGuid);
+    const decoded = Buffer.from(result, 'base64').toString('utf-8');
+    expect(decoded).toContain('HKLM:\\SOFTWARE\\Microsoft\\Cryptography');
+  });
+
+  it('should use Set-ItemProperty to write the registry key', () => {
+    const result = generateUserData(sampleGuid);
+    const decoded = Buffer.from(result, 'base64').toString('utf-8');
+    expect(decoded).toContain('Set-ItemProperty');
+    expect(decoded).toContain('-Name "MachineGuid"');
+    expect(decoded).toContain(`-Value "${sampleGuid}"`);
+  });
+
+  it('should produce different output for different MachineGuids', () => {
+    const guid1 = '11111111-1111-1111-1111-111111111111';
+    const guid2 = '22222222-2222-2222-2222-222222222222';
+    expect(generateUserData(guid1)).not.toBe(generateUserData(guid2));
+  });
+});

+ 52 - 0
server/src/services/userdata.ts

@@ -0,0 +1,52 @@
+import crypto from 'crypto';
+
+/**
+ * Generate a random password that meets Windows Server complexity requirements:
+ * - At least 12 characters
+ * - Contains uppercase, lowercase, digits, and special characters
+ */
+export function generateWindowsPassword(length = 16): string {
+  const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+  const lower = 'abcdefghijklmnopqrstuvwxyz';
+  const digits = '0123456789';
+  const special = '!@#%&_+-=';
+  const all = upper + lower + digits + special;
+
+  // Ensure at least one of each category
+  const required = [
+    upper[crypto.randomInt(upper.length)],
+    lower[crypto.randomInt(lower.length)],
+    digits[crypto.randomInt(digits.length)],
+    special[crypto.randomInt(special.length)],
+  ];
+
+  const remaining = Array.from({ length: length - required.length }, () =>
+    all[crypto.randomInt(all.length)]
+  );
+
+  // Shuffle
+  const chars = [...required, ...remaining];
+  for (let i = chars.length - 1; i > 0; i--) {
+    const j = crypto.randomInt(i + 1);
+    [chars[i], chars[j]] = [chars[j], chars[i]];
+  }
+
+  return chars.join('');
+}
+
+/**
+ * Generate a base64-encoded EC2 UserData PowerShell script that:
+ * 1. Sets the MachineGuid registry value
+ * 2. Changes the Administrator password
+ */
+export function generateUserData(machineGuid: string, adminPassword: string): string {
+  const script = [
+    '<powershell>',
+    `Set-ItemProperty -Path "HKLM:\\SOFTWARE\\Microsoft\\Cryptography" -Name "MachineGuid" -Value "${machineGuid}"`,
+    `net user Administrator '${adminPassword}'`,
+    '</powershell>',
+    '<persist>true</persist>',
+  ].join('\n');
+
+  return Buffer.from(script, 'utf-8').toString('base64');
+}

+ 37 - 0
server/src/utils/crypto.property.test.ts

@@ -0,0 +1,37 @@
+// Feature: ec2-management-platform, Property 5: AWS Secret Key 加密存储往返
+import { describe, it, expect } from 'vitest';
+import fc from 'fast-check';
+import { encrypt, decrypt } from './crypto';
+
+/**
+ * Validates: Requirements 4.4
+ *
+ * Property 5: AWS Secret Key 加密存储往返
+ * 对于任意 AWS Secret Key 字符串,加密后存储再解密应得到与原始值完全相同的字符串,
+ * 且加密后的值不等于原始明文。
+ */
+describe('Property 5: AWS Secret Key 加密存储往返', () => {
+  it('encrypt then decrypt returns the original string for any input', () => {
+    fc.assert(
+      fc.property(fc.string(), (plaintext) => {
+        const encrypted = encrypt(plaintext);
+        const decrypted = decrypt(encrypted);
+        expect(decrypted).toBe(plaintext);
+      }),
+      { numRuns: 100 }
+    );
+  });
+
+  it('encrypted value is different from the original for any non-empty string', () => {
+    fc.assert(
+      fc.property(
+        fc.string({ minLength: 1 }),
+        (plaintext) => {
+          const encrypted = encrypt(plaintext);
+          expect(encrypted).not.toBe(plaintext);
+        }
+      ),
+      { numRuns: 100 }
+    );
+  });
+});

+ 112 - 0
server/src/utils/crypto.test.ts

@@ -0,0 +1,112 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { encrypt, decrypt } from './crypto';
+
+describe('crypto utils', () => {
+  const originalEnv = process.env.ENCRYPTION_KEY;
+
+  afterEach(() => {
+    if (originalEnv !== undefined) {
+      process.env.ENCRYPTION_KEY = originalEnv;
+    } else {
+      delete process.env.ENCRYPTION_KEY;
+    }
+  });
+
+  describe('encrypt/decrypt roundtrip', () => {
+    it('should decrypt to the original plaintext', () => {
+      const plaintext = 'my-secret-aws-key-12345';
+      const encrypted = encrypt(plaintext);
+      const decrypted = decrypt(encrypted);
+      expect(decrypted).toBe(plaintext);
+    });
+
+    it('should produce ciphertext different from plaintext', () => {
+      const plaintext = 'AKIAIOSFODNN7EXAMPLE';
+      const encrypted = encrypt(plaintext);
+      expect(encrypted).not.toBe(plaintext);
+      expect(encrypted).not.toContain(plaintext);
+    });
+
+    it('should produce different ciphertext for the same plaintext (random IV)', () => {
+      const plaintext = 'same-secret';
+      const encrypted1 = encrypt(plaintext);
+      const encrypted2 = encrypt(plaintext);
+      expect(encrypted1).not.toBe(encrypted2);
+      // Both should still decrypt to the same value
+      expect(decrypt(encrypted1)).toBe(plaintext);
+      expect(decrypt(encrypted2)).toBe(plaintext);
+    });
+  });
+
+  describe('output format', () => {
+    it('should produce output in iv:encryptedData hex format', () => {
+      const encrypted = encrypt('test');
+      const parts = encrypted.split(':');
+      expect(parts).toHaveLength(2);
+      // IV should be 16 bytes = 32 hex chars
+      expect(parts[0]).toMatch(/^[0-9a-f]{32}$/);
+      // Encrypted data should be hex
+      expect(parts[1]).toMatch(/^[0-9a-f]+$/);
+    });
+  });
+
+  describe('edge cases', () => {
+    it('should handle empty string', () => {
+      const encrypted = encrypt('');
+      const decrypted = decrypt(encrypted);
+      expect(decrypted).toBe('');
+    });
+
+    it('should handle long strings', () => {
+      const plaintext = 'a'.repeat(10000);
+      const encrypted = encrypt(plaintext);
+      const decrypted = decrypt(encrypted);
+      expect(decrypted).toBe(plaintext);
+    });
+
+    it('should handle unicode characters', () => {
+      const plaintext = '密钥测试 🔑 émojis';
+      const encrypted = encrypt(plaintext);
+      const decrypted = decrypt(encrypted);
+      expect(decrypted).toBe(plaintext);
+    });
+
+    it('should handle special characters', () => {
+      const plaintext = '!@#$%^&*()_+-=[]{}|;:,.<>?/\\\'\"';
+      const encrypted = encrypt(plaintext);
+      const decrypted = decrypt(encrypted);
+      expect(decrypted).toBe(plaintext);
+    });
+  });
+
+  describe('error handling', () => {
+    it('should throw on invalid ciphertext format (no colon)', () => {
+      expect(() => decrypt('invalidciphertext')).toThrow('Invalid ciphertext format');
+    });
+
+    it('should throw on tampered ciphertext', () => {
+      const encrypted = encrypt('test');
+      const [iv, data] = encrypted.split(':');
+      const tampered = `${iv}:${'ff'.repeat(data.length / 2)}`;
+      expect(() => decrypt(tampered)).toThrow();
+    });
+  });
+
+  describe('encryption key from environment', () => {
+    it('should work with custom ENCRYPTION_KEY', () => {
+      process.env.ENCRYPTION_KEY = 'my-custom-encryption-key-for-test';
+      const plaintext = 'secret-with-custom-key';
+      const encrypted = encrypt(plaintext);
+      const decrypted = decrypt(encrypted);
+      expect(decrypted).toBe(plaintext);
+    });
+
+    it('should not decrypt with a different key', () => {
+      process.env.ENCRYPTION_KEY = 'key-one';
+      const encrypted = encrypt('secret');
+
+      process.env.ENCRYPTION_KEY = 'key-two';
+      expect(() => decrypt(encrypted)).toThrow();
+    });
+  });
+});

+ 40 - 0
server/src/utils/crypto.ts

@@ -0,0 +1,40 @@
+import crypto from 'crypto';
+
+const ALGORITHM = 'aes-256-cbc';
+const IV_LENGTH = 16;
+
+function getEncryptionKey(): Buffer {
+  const key = process.env.ENCRYPTION_KEY || 'default-encryption-key-32-chars!';
+  // Ensure key is exactly 32 bytes for AES-256
+  return crypto.createHash('sha256').update(key).digest();
+}
+
+/**
+ * Encrypt a plaintext string using AES-256-CBC.
+ * Returns the result in "iv:encryptedData" format (both hex encoded).
+ */
+export function encrypt(plaintext: string): string {
+  const key = getEncryptionKey();
+  const iv = crypto.randomBytes(IV_LENGTH);
+  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
+  let encrypted = cipher.update(plaintext, 'utf8', 'hex');
+  encrypted += cipher.final('hex');
+  return `${iv.toString('hex')}:${encrypted}`;
+}
+
+/**
+ * Decrypt a ciphertext string produced by encrypt().
+ * Expects input in "iv:encryptedData" format (both hex encoded).
+ */
+export function decrypt(ciphertext: string): string {
+  const key = getEncryptionKey();
+  const [ivHex, encryptedHex] = ciphertext.split(':');
+  if (!ivHex || !encryptedHex) {
+    throw new Error('Invalid ciphertext format. Expected "iv:encryptedData".');
+  }
+  const iv = Buffer.from(ivHex, 'hex');
+  const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
+  let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
+  decrypted += decipher.final('utf8');
+  return decrypted;
+}

+ 69 - 0
server/src/utils/validation.property.test.ts

@@ -0,0 +1,69 @@
+// Feature: ec2-management-platform, Property 7: MachineGuid UUID 格式校验
+import { describe, it, expect } from 'vitest';
+import fc from 'fast-check';
+import { isValidMachineGuid } from './validation';
+
+/**
+ * Validates: Requirements 5.2, 5.3
+ *
+ * Property 7: MachineGuid UUID 格式校验
+ * 对于任意字符串输入,MachineGuid 校验函数应接受该输入当且仅当它严格匹配 UUID 格式
+ * (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,其中 x 为十六进制字符)。
+ * 对于任意纯空白字符串或格式不符的字符串,校验应拒绝。
+ */
+
+/** Arbitrary that generates valid UUIDs in 8-4-4-4-12 hex format */
+const hexChar = fc.mapToConstant(
+  { num: 10, build: (v) => String.fromCharCode(0x30 + v) }, // 0-9
+  { num: 6, build: (v) => String.fromCharCode(0x61 + v) },  // a-f
+  { num: 6, build: (v) => String.fromCharCode(0x41 + v) }   // A-F
+);
+
+function hexBlock(length: number): fc.Arbitrary<string> {
+  return fc.array(hexChar, { minLength: length, maxLength: length }).map((chars) => chars.join(''));
+}
+
+const validUuidArb: fc.Arbitrary<string> = fc.tuple(
+  hexBlock(8),
+  hexBlock(4),
+  hexBlock(4),
+  hexBlock(4),
+  hexBlock(12)
+).map(([a, b, c, d, e]) => `${a}-${b}-${c}-${d}-${e}`);
+
+describe('Property 7: MachineGuid UUID 格式校验', () => {
+  it('should accept any valid UUID (8-4-4-4-12 hex with dashes)', () => {
+    fc.assert(
+      fc.property(validUuidArb, (uuid) => {
+        expect(isValidMachineGuid(uuid)).toBe(true);
+      }),
+      { numRuns: 100 }
+    );
+  });
+
+  it('should reject arbitrary strings that do not match UUID format', () => {
+    fc.assert(
+      fc.property(
+        fc.string().filter((s) => !/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(s)),
+        (s) => {
+          expect(isValidMachineGuid(s)).toBe(false);
+        }
+      ),
+      { numRuns: 100 }
+    );
+  });
+
+  it('should reject whitespace-only strings', () => {
+    const whitespaceArb = fc.stringOf(
+      fc.constantFrom(' ', '\t', '\n', '\r', '\f', '\v'),
+      { minLength: 1 }
+    );
+
+    fc.assert(
+      fc.property(whitespaceArb, (ws) => {
+        expect(isValidMachineGuid(ws)).toBe(false);
+      }),
+      { numRuns: 100 }
+    );
+  });
+});

+ 73 - 0
server/src/utils/validation.test.ts

@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest';
+import { isValidMachineGuid } from './validation';
+
+describe('isValidMachineGuid', () => {
+  describe('valid UUIDs', () => {
+    it('should accept a standard lowercase UUID', () => {
+      expect(isValidMachineGuid('550e8400-e29b-41d4-a716-446655440000')).toBe(true);
+    });
+
+    it('should accept a standard uppercase UUID', () => {
+      expect(isValidMachineGuid('550E8400-E29B-41D4-A716-446655440000')).toBe(true);
+    });
+
+    it('should accept a mixed-case UUID', () => {
+      expect(isValidMachineGuid('550e8400-E29B-41d4-A716-446655440000')).toBe(true);
+    });
+
+    it('should accept all-zero UUID', () => {
+      expect(isValidMachineGuid('00000000-0000-0000-0000-000000000000')).toBe(true);
+    });
+
+    it('should accept all-f UUID', () => {
+      expect(isValidMachineGuid('ffffffff-ffff-ffff-ffff-ffffffffffff')).toBe(true);
+    });
+  });
+
+  describe('invalid formats', () => {
+    it('should reject an empty string', () => {
+      expect(isValidMachineGuid('')).toBe(false);
+    });
+
+    it('should reject a whitespace-only string', () => {
+      expect(isValidMachineGuid('   ')).toBe(false);
+      expect(isValidMachineGuid('\t')).toBe(false);
+      expect(isValidMachineGuid('\n')).toBe(false);
+    });
+
+    it('should reject UUID without dashes', () => {
+      expect(isValidMachineGuid('550e8400e29b41d4a716446655440000')).toBe(false);
+    });
+
+    it('should reject UUID with wrong dash positions', () => {
+      expect(isValidMachineGuid('550e840-0e29b-41d4-a716-446655440000')).toBe(false);
+    });
+
+    it('should reject UUID with too few characters in a group', () => {
+      expect(isValidMachineGuid('550e840-e29b-41d4-a716-446655440000')).toBe(false);
+    });
+
+    it('should reject UUID with non-hex characters', () => {
+      expect(isValidMachineGuid('550g8400-e29b-41d4-a716-446655440000')).toBe(false);
+      expect(isValidMachineGuid('zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz')).toBe(false);
+    });
+
+    it('should reject UUID with leading/trailing spaces', () => {
+      expect(isValidMachineGuid(' 550e8400-e29b-41d4-a716-446655440000')).toBe(false);
+      expect(isValidMachineGuid('550e8400-e29b-41d4-a716-446655440000 ')).toBe(false);
+    });
+
+    it('should reject UUID with braces', () => {
+      expect(isValidMachineGuid('{550e8400-e29b-41d4-a716-446655440000}')).toBe(false);
+    });
+
+    it('should reject random strings', () => {
+      expect(isValidMachineGuid('not-a-uuid')).toBe(false);
+      expect(isValidMachineGuid('hello world')).toBe(false);
+    });
+
+    it('should reject UUID with extra segments', () => {
+      expect(isValidMachineGuid('550e8400-e29b-41d4-a716-446655440000-extra')).toBe(false);
+    });
+  });
+});

+ 9 - 0
server/src/utils/validation.ts

@@ -0,0 +1,9 @@
+const UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+
+/**
+ * Validate that a string is a valid MachineGuid in UUID format.
+ * Strictly matches: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12 hex chars with dashes).
+ */
+export function isValidMachineGuid(value: string): boolean {
+  return UUID_REGEX.test(value);
+}

+ 20 - 0
server/tsconfig.json

@@ -0,0 +1,20 @@
+{
+  "compilerOptions": {
+    "target": "ES2020",
+    "module": "commonjs",
+    "lib": ["ES2020"],
+    "outDir": "./dist",
+    "rootDir": "./src",
+    "strict": true,
+    "esModuleInterop": true,
+    "skipLibCheck": true,
+    "forceConsistentCasingInFileNames": true,
+    "resolveJsonModule": true,
+    "declaration": true,
+    "declarationMap": true,
+    "sourceMap": true,
+    "moduleResolution": "node"
+  },
+  "include": ["src/**/*"],
+  "exclude": ["node_modules", "dist", "**/*.test.ts"]
+}

+ 14 - 0
server/vitest.config.ts

@@ -0,0 +1,14 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+  test: {
+    globals: true,
+    environment: 'node',
+    include: ['src/**/*.test.ts'],
+    coverage: {
+      provider: 'v8',
+      include: ['src/**/*.ts'],
+      exclude: ['src/**/*.test.ts'],
+    },
+  },
+});

Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov