Integrate Venix sales portal with private libvirt engine

dev
admin 2 months ago
parent f535424087
commit 4bfda1cc9a

4
.gitignore vendored

@ -32,3 +32,7 @@ id_ed25519
*.tar.gz
*.tgz
*.sql.gz
runtime/
web/config/config.php
engine/.venv/
engine/**/__pycache__/

@ -15,9 +15,12 @@
`web/public/`, not the repository root.
- Only the venix theme is retained. Ordinary users must not receive host
administration or retired node-management routes.
- This is a pruned, not-yet-integrated development project. Host preparation
pages do not save credentials or connect to Python. Purchasing must remain
disabled until the virtual machine provisioning and billing integration is
implemented and tested.
- PHP owns accounts, wallet purchases, orders, public-key ownership and public
HTTP authorization. The Python engine owns libvirt, host credentials and VM
operations. Keep the engine private and authenticate every internal request.
- Purchases provision one VM from the plan snapshot. This release does not
implement expiry or renewal. Never retry an ambiguous destructive operation
or refund it without confirmed cleanup; reconcile its operation identifier.
- Users share the original VM-panel styling; administrator pages retain venix.
- See `docs/PRUNING_REPORT.md` for retained/removed feature boundaries and
`docs/INTEGRATION_PLAN.md` for the planned Python engine integration.

@ -1,38 +1,37 @@
# Virt Cloud 集成开发副本
# Virt Cloud
当前阶段:已按确认范围清理 PHP 旧业务,尚未实现 PHP 与 libvirt 服务的对接。
PHP 8.5 网站与私有 Python/libvirt 引擎集成的虚拟机销售面板。使用 `venix` 分支;`main` 的原 virsh-panel 不受影响。
## 仓库与分支
## 本版功能
- 仓库:`https://g.luoli.live/root/virt.git`。
- 新项目使用 `venix` 分支;后续修改、提交和推送均在此分支进行。
- `main` 保留现有 virsh-panel,本分支独立存放新项目,尚未包含 Python 引擎。
- 拉取新项目:`git clone --branch venix --single-branch https://g.luoli.live/root/virt.git virt-cloud`。
- PHP 统一注册、邮箱登录、账户、充值、支付、SMTP、工单;注册后无需创建审核。
- 用户购买套餐开通 VM,余额扣款、库存扣减、确认创建失败退款;不包含到期、续费和周期扣费。
- 套餐绑定宿主机,提供 CPU、内存、磁盘、网络带宽规格,用户不能随意修改套餐资源。
- 管理员管理多宿主机、云镜像和独立救援 ISO;用户选择已有模板及自己的 SSH 公钥。
- 用户仅操作自己的 VM:控制台、开关机、软/硬重启、重装、救援、删除、初始 root 密码查看/复制。
- CPU、内存、磁盘 I/O、网络带宽图表;后台持续采集,写入日志库,最长保留 30 天。
- 全部用户页及登录页使用原虚拟机面板风格;管理员后台保留 venix 样式。
- 宿主机凭据及任务密码等敏感数据加密保存;内部请求签名,控制台使用短时一次性凭据。
## 已完成
## 目录与部署
- `web/` 来自 `/Users/admin/Documents/www/html` 的工作目录源码。
- PHP 来源分支:`php8.5`;来源提交:`f2055f0fca86d84e6b525e54df86c6c685c7eff7`。
- 虚拟化/UI 参考项目:`/Users/admin/Documents/www/virsh-panel`,参考提交:`626055a42274a43737d636a622661be9223f5ae7`。
- 原来的两个项目没有修改;副本不继承原 PHP 仓库的 `.git`。
- 未复制实际 `.env`、`config/.config.php`、监控脚本实际环境文件、依赖目录和运行缓存/日志。保留配置示例、源码、模板、SQL 和静态资源。
- 未启动网站,未连接真实数据库或宿主机。
- 仅保留 venix 主题;用户侧节点列表已删除,管理员宿主机页面暂为准备页。
- 账户表去除代理、流量和账户/等级到期字段;密码改为 bcrypt,保留邮箱账户安全功能。
- 商城改为 CPU、内存、带宽、硬盘套餐;接入引擎前购买返回 409,不扣余额。
- 清理前源码已完整备份,删除的主题和检测器也保留了可恢复副本。
```text
virt-cloud/
web/ PHP 网站、页面、SQL、测试
engine/ 私有 FastAPI/libvirt 引擎及测试
deploy/ 引擎与开通 worker 的 systemd 配置
runtime/ 私有配置、密钥、引擎数据(安装生成,不入 Git)
docs/ 架构、部署、原清理记录
```
## 当前不要部署
网站文档根目录必须是 `web/public`。引擎仅监听 `127.0.0.1:8000`;不能把整个网站反代到引擎,只有 `/engine-console` 的 WebSocket 转发给引擎。
这是一份已裁剪、待集成的开发副本,还不是可部署的虚拟机销售面板。
全新安装见 [部署说明](docs/DEPLOYMENT.md),职责边界见 [集成架构](docs/INTEGRATION_PLAN.md)。配置使用 `web/config/config.php`,兼容旧文件名 `.config.php`;两者存在时前者优先。本版不导入原 Python 面板数据,也不提供在线更新按钮。
- `web/crontab` 是禁用的任务示例;不要在测试副本中启用真实支付扫描或备份邮件。
- `web/sql/ss.sql` 是清理后的 PHP 全新账户/销售基础结构,不包含虚拟化引擎和 VM 表;不要在生产数据库中直接执行。
- 旧节点、订阅、AI、Apple 等路由与实现已删除。
- 网页首次初始化、引擎集成、统一 CSRF、SMTP 证书校验等仍需继续完成。
## 验证范围
## 建议方向
已进行隔离 PHP 8.5 语法、模板、协议、SQLite 订单状态机和 Python 引擎测试。没有使用真实 MariaDB、SSH/KVM、付款或邮件通道完成生产联调。首次部署请先在测试宿主机验收,再开放销售。
保留 virsh-panel 的 HTML/CSS/交互布局,PHP 提供同源兼容 API 并负责账户与销售业务;Python 保留 libvirt、宿主机凭据、虚拟机任务、指标和 VNC 转发。
超时后状态不明的任务保持 `uncertain`,不会直接退款或再次毁盘/创建。管理员需核对宿主机与任务状态,不能靠重复购买处理。这不是自动故障迁移、资源超售防护或高可用平台。
本轮具体改动与验证见 [清理报告](docs/PRUNING_REPORT.md),后续架构见 [集成方案](docs/INTEGRATION_PLAN.md)。
原清理边界见 [清理报告](docs/PRUNING_REPORT.md)。原 `/html` 与 `/virsh-panel` 项目未在本轮修改。

@ -0,0 +1,25 @@
[Unit]
Description=Virt Cloud private libvirt engine
After=network-online.target
Wants=network-online.target
[Service]
Type=exec
User=root
Group=root
WorkingDirectory=/home/virt-cloud/engine
Environment=CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStart=/home/virt-cloud/engine/.venv/bin/python -m uvicorn virsh_panel.internal:create_engine --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1 --no-access-log
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=/home/virt-cloud/runtime
LimitCORE=0
[Install]
WantedBy=multi-user.target

@ -0,0 +1,25 @@
[Unit]
Description=Virt Cloud purchased VM provisioning worker
After=network-online.target virt-cloud-engine.service
Wants=network-online.target
[Service]
Type=simple
# AlmaLinux PHP-FPM normally runs as apache; use the same user as your PHP pool.
User=apache
Group=apache
WorkingDirectory=/home/virt-cloud/web
ExecStart=/usr/bin/php /home/virt-cloud/web/xcat cloudWorker
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=false
ProtectSystem=strict
ReadWritePaths=-/home/virt-cloud/runtime/php
ReadWritePaths=-/home/virt-cloud/web/storage
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

@ -0,0 +1,150 @@
# 全新安装与启动
没有安装器,不迁移旧 virsh-panel 数据。示例默认 AlmaLinux 面板服务器、项目 `/home/virt-cloud`、PHP-FPM 用户 `apache`;调整实际 PHP 路径、FPM 用户及 service 路径。宿主机是另外的 SSH/libvirt 服务器。
## 1. 自行安装依赖
- PHP 8.5 CLI/FPM:PDO MySQL、sodium、mbstring、curl、XML/DOM、OpenSSL、session 等扩展,Composer 2。
- MariaDB/MySQL:业务库、日志库,初始化账号需要建表权限。
- Redis 或兼容的 Valkey:沿用 venix 会话、验证码与限流。
- Python 3.12 或更新的项目支持版本、venv/pip、libvirt 客户端及开发头文件、C 编译工具、pkg-config、OpenSSH 客户端。
- Nginx/Apache、HTTPS、PHP-FPM,网站配置由你自行管理。
`libvirt-python` 是面板依赖,不代表面板服务器需要运行 KVM 宿主服务;远端宿主另需现有 KVM/QEMU、libvirt、网桥、UEFI 固件和存储目录。
AlmaLinux 编译 Python libvirt 绑定常用系统依赖:`dnf install gcc pkgconf-pkg-config python3-devel libvirt-devel openssh-clients`。Python 可执行文件与开发头文件应使用相同版本。
## 2. 拉取与安装程序依赖
```bash
git clone --branch venix --single-branch https://g.luoli.live/root/virt.git /home/virt-cloud
cd /home/virt-cloud/web
composer install --no-dev --prefer-dist --optimize-autoloader
cd /home/virt-cloud
python3 -m venv engine/.venv
engine/.venv/bin/python -m pip install -r engine/requirements.txt
engine/.venv/bin/python -c 'import libvirt; print(libvirt.getVersion())'
```
已拉取则从安装依赖开始,不要覆盖目录 clone。Python 依赖编译失败先核对系统 `libvirt-devel`、Python 开发头文件与 Python 版本。
## 3. 配置与全新数据库
```bash
cd /home/virt-cloud/web
cp config/.config.php.example config/config.php
```
编辑 `config/config.php`:
- `db_host/db_port/db_database/db_username/db_password`:业务库。
- `enable_log` 设置为字符串 `'true'`;`log_db_host/log_db_port/log_db_database/log_db_user/log_db_password`:日志库。空日志库地址沿用本机默认,远程数据库请填写明确地址。
- `db_prefix` 留空,网站域名、HTTPS Cookie、Redis/Valkey、账户安全、SMTP 按 venix 设置。
- `cloud_*` 默认路径适配 `/home/virt-cloud`,私有密钥自动生成;宿主机凭据稍后在页面设置。
- `cloud_introspection_url` 必须指向 PHP 网站,不是引擎 8000。默认 `http://127.0.0.1/api/internal/cloud/session-introspection`;多虚拟主机可设置 `cloud_introspection_host` 为网站域名,或改为正确的本机 HTTPS URL。
在**两个全新空数据库**分别导入,替换命令中的地址、端口、账号、库名;`-p` 提示密码,不把密码写入历史:
```bash
mariadb -h DB_HOST -P DB_PORT -u DB_USER -p BUSINESS_DB < /home/virt-cloud/web/sql/ss.sql
mariadb -h LOG_DB_HOST -P LOG_DB_PORT -u LOG_DB_USER -p LOG_DB < /home/virt-cloud/web/sql/user_log.sql
cd /home/virt-cloud/web
php xcat cloudInit
php xcat createAdmin
```
`cloudInit` 新建云业务/指标表、生成独立签名和加密密钥及 `runtime/engine.json`,不连接宿主机。按 CLI 提示创建管理员,邮箱应真实可用;核对 `super_admin` UID 包含有宿主机管理权限的管理员。
数据库或内省 URL 修改后重新导出并重启引擎(保留现有密钥):
```bash
cd /home/virt-cloud/web
php xcat cloudExportConfig
```
**不要删除** `runtime/php/payload.key`、`engine.hmac` 或 `runtime/engine/master.key`。备份数据库时同步安全备份密钥,否则加密记录无法使用。
## 4. 权限
`cloudInit` 成功后以 root 执行,FPM 用户不是 apache 时替换。PHP 不需要读取引擎私钥数据:
```bash
chown root:apache /home/virt-cloud/runtime
chmod 0750 /home/virt-cloud/runtime
chown -R apache:apache /home/virt-cloud/runtime/php
chmod 0700 /home/virt-cloud/runtime/php
chmod 0600 /home/virt-cloud/runtime/php/engine.hmac /home/virt-cloud/runtime/php/payload.key
chown root:root /home/virt-cloud/runtime/engine.json
chmod 0600 /home/virt-cloud/runtime/engine.json
chown root:apache /home/virt-cloud/web/config/config.php
chmod 0640 /home/virt-cloud/web/config/config.php
mkdir -p /home/virt-cloud/web/storage/framework/smarty/compile /home/virt-cloud/web/storage/framework/smarty/cache
chown -R apache:apache /home/virt-cloud/web/storage
```
代码/依赖只需可读,不要整项目 `chmod 777`。在 `/home` 发布需配置父目录遍历权限、SELinux 网站文件标签和所需网络访问策略,不要关闭 SELinux。引擎 root 运行,自行创建私有 `runtime/engine`。
## 5. 启动
前台调试引擎:
```bash
cd /home/virt-cloud/engine
PYTHONDONTWRITEBYTECODE=1 CLOUD_ENGINE_CONFIG=/home/virt-cloud/runtime/engine.json .venv/bin/python -m uvicorn virsh_panel.internal:create_engine --factory --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips 127.0.0.1
```
另一个终端以前台方式运行任务 worker(与 FPM 相同用户):
```bash
cd /home/virt-cloud/web
sudo -u apache php xcat cloudWorker
```
常驻 service:
```bash
cp /home/virt-cloud/deploy/virt-cloud-engine.service /etc/systemd/system/virt-cloud-engine.service
cp /home/virt-cloud/deploy/virt-cloud-worker.service /etc/systemd/system/virt-cloud-worker.service
systemctl daemon-reload
systemctl enable --now virt-cloud-engine.service virt-cloud-worker.service
systemctl status virt-cloud-engine.service virt-cloud-worker.service --no-pager
journalctl -u virt-cloud-engine -u virt-cloud-worker -n 100 --no-pager
```
worker 使用 `/usr/bin/php`,须为 PHP 8.5,否则修改 unit。引擎使用一个 worker。购买排队不执行时先检查 `virt-cloud-worker`。PHP 网站由你现有的 Web/FPM 服务提供。
## 6. 网站与控制台
文档根目录 `/home/virt-cloud/web/public`,未命中文件的请求交给 Slim 的 `index.php`。**不再使用原面板 `ProxyPass / http://127.0.0.1:8000/`**,普通页面/API 现在由 PHP 提供。
仅把 `/engine-console` WebSocket 转发到引擎,保留 Host、Origin、WebSocket 子协议与 Upgrade;发送可信 `X-Forwarded-Proto`。Nginx 示例,map 放在 http 级,location 放在现有 HTTPS server 内:
```nginx
map $http_upgrade $cloud_connection_upgrade {
default upgrade;
'' close;
}
location = /engine-console {
proxy_pass http://127.0.0.1:8000/engine-console;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $cloud_connection_upgrade;
proxy_set_header Host $host;
proxy_set_header Origin $http_origin;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
}
```
不要公开 `/internal/v1/*` 或开放 8000 防火墙。PHP `/api/internal/cloud/session-introspection` 建议在 Web 层限定本机访问,仍有内部签名认证。救援上传需要合适的 FPM/反代超时和请求体上限,最大 ISO 8 GiB,入口只对管理员开放。
## 7. 页面配置与验收
1. 管理员添加宿主机:现有 SSH/root/私钥口令、核验指纹,设置区域、网桥、目录、地址池/网关/DNS/网卡前缀,测试连接。
2. 导入云镜像与救援模板;无已有模板不能开通云镜像 VM。当前云镜像下载沿用 AlmaLinux 9/10 官方源校验规则,预存其他系统图标不代表已实现其云模板导入;其他系统可用合适 ISO 安装,云镜像适配后续扩展。
3. 套餐设置规格、价格、库存、已启用宿主机。本版价格是一次开通金额,不是自动月费。
4. 测试用户注册/充值/购买,验证任务、VM 控制台、SSH、重装、救援、删除与图表。
5. 日志库 `engine_vm_metric_samples` 应在所有用户退出后继续新增;首批图表需等待采样间隔。
先不要启用旧 `web/crontab`,付款扫描/备份任务按保留业务单独核对。真实 MariaDB/KVM/SMTP/支付未在开发环境联调,先验收测试环境。`uncertain` 状态先核对宿主机,不直接改库退款或重复毁盘任务。

@ -1,156 +1,64 @@
# PHP 与虚拟化面板集成方案
# Virt Cloud 集成架构
初次审查:2026-09-26;清理状态更新:2026-09-27。本文保留原始架构审查和后续集成建议;已经执行的清理以 [清理报告](PRUNING_REPORT.md) 为准。
更新:2026-09-27。替代此前“尚未集成”的计划,描述本版实现边界;真实部署仍需测试环境联调。
## 1. 目标和当前进度
## 请求链路
用户确认 PHP 项目为 `/Users/admin/Documents/www/html`,要求继续使用 virsh-panel 现有 UI 与布局,最多微调,不使用旧 PHP 主题替换现有界面。
```text
浏览器
├─ HTTPS 页面/API → PHP:账户、授权、CSRF、套餐、钱包、订单
│ └─ HMAC 内部 API → Python → SSH/libvirt → 宿主机
└─ WSS /engine-console ──────────────────→ Python → SSH 隧道 → VM VNC
已经在 `/Users/admin/Documents/www/virt-cloud/web` 的独立副本完成用户确认的旧业务裁剪、账户/套餐结构改造。原 PHP 和 Python 项目没有修改。按最新要求,当前清理阶段只保留 venix,用户侧不再有节点列表,管理员提供未接入的宿主机设置页。Python 引擎与现有虚拟化面板 UI 尚未集成。
PHP cloudWorker → 持久任务 → Python operation_id → 实例关联/核对/退款
Python 后台采集 → 日志库 engine_vm_metric_samples → 详情页四项图表
```
最终建议在 `virt-cloud` 一个项目目录内管理 PHP 网站、Python 引擎、部署文件和文档;PHP 的 HTTP 文档根目录只指向 `web/public`。内部服务、源码、密钥、数据和部署文件不能成为公开网站目录。
PHP 是唯一账户入口,所有用户页面使用原虚拟化面板 CSS;后台保留 venix。没有第二套 Python 注册、SMTP、数据库设置或审核流程。
## 2. 两份代码的实际特点
## 数据职责
| 方面 | PHP 项目 | virsh-panel | 集成选择 |
| --- | --- | --- | --- |
| 页面 | Smarty,多套主题,大量旧业务资源 | 独立 HTML/CSS/原生 JS,本地 noVNC | 保留虚拟化面板 UI,不混用旧主题 CSS |
| 框架 | Composer 声明 PHP 8.5、Slim 3、Eloquent 13 | FastAPI、Uvicorn、Pydantic | 暂不进行额外框架升级,先建立清晰服务边界 |
| 账户 | 已有验证码、TOTP、可信设备、会话撤销等,混入代理节点规则 | 独立用户表、邮箱验证、审核、管理员、VM 归属 | PHP 作为唯一账户来源,抽离旧代理规则 |
| 支付 | 易支付、Paytaro、USDT,含回调事务与重复回调处理 | 尚无销售订单或计费领域 | 复用支付网关与钱包基础,新建 VPS 订单和套餐 |
| 虚拟化 | 没有 libvirt 管理能力 | SSH/libvirt、镜像、创建、重装、救援、IP、指标、VNC | 保留 Python 的核心功能及测试 |
| 资源销售 | 原套餐修改流量、等级和订阅期限 | 仅 VM 参数范围校验,无完整销售配额 | 新建套餐、库存、预留、实例期限,不沿用代理套餐 |
| 数据 | 权威写入方 | 存储 |
| --- | --- | --- |
| 用户、钱包、套餐、原财务/工单 | PHP | 原业务库表 |
| 宿主机索引、订单、实例、公钥、会话、任务 | PHP | `cloud_hosts/orders/instances/ssh_keys/sessions/jobs` |
| 宿主机凭据、VM 元数据、镜像、操作进度 | Python | 主库 `engine_records`,敏感记录加密 |
| 引擎签名防重放 | Python | 主库 `engine_request_nonces` |
| 四项性能指标样本 | Python | 日志库 `engine_vm_metric_samples`,保留 30 天 |
PHP 基础入口为 `public/index.php` → `bootstrap.php` → `config/routes.php`。当前 bootstrap 强制读取 `config/.config.php`,不能直接实现用户要求的网页首次初始化;后续必须改造引导流程,不能再要求两套手工配置和两次创建账户。
多个宿主机使用稳定 `host_id`,不共用一个可切换的全局“当前宿主机”。模板、IP 地址池、网关、DNS、虚拟机网卡前缀、磁盘/ISO/救援目录均按宿主机设置。地址池与网卡前缀分开:供应商地址池可以为 /28,虚拟机网卡可以为 /24,不能因此把售卖范围扩大为 /24。
PHP `UserController.php` 有 2254 行、`AuthController.php` 有 1265 行、`AdminController.php` 有 793 行。它们不是干净的通用账户模块,需要拆分而不是继续往里面堆虚拟机业务。
PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志库可同实例或分别配置地址/端口。敏感业务数据加密;部署数据库连接配置仍是权限受限配置文件,不代表配置文件本身加密。
## 3. UI 保留方式
## 购买状态机
保留 `/Users/admin/Documents/www/virsh-panel/static/index.html`、`styles.css`、`app.js`、系统图标和本地 noVNC,移到新网站自身的公开资源位置。保留面板的侧栏、卡片、虚拟机列表、详情、创建、重装、救援和四项指标布局。
1. 用户选择启用套餐、已有系统来源、公钥/强 root 密码,提交幂等键。
2. PHP 事务锁定用户钱包与套餐,校验余额、库存、宿主机与实例配额,保存不可由浏览器改写的规格快照,扣款并保存加密任务。
3. 独立 `cloudWorker` 获取租约,携带唯一 `operation_id` 请求引擎。只有经过签名的开通上下文可以创建 VM,用户不能免费创建。
4. 成功关联实例和凭据;确认创建失败且无残留时只退款、恢复库存一次。
5. 超时、引擎中断或残留无法确认时保持待核对,只查询原操作,不重复创建或盲目退款。
不把旧 Material/Codex/Venix 主题的 CSS、导航或布局加入这些页面;现有面板样式含全局 `body`、通配符等规则,直接混合会互相覆盖。首版在根路径提供现有面板页面,避免无必要地改动绝对资源路径;如果后续挂载到 `/virt`,再明确处理 UI 路径与 API 路径。
金额通过精确小数与整数最小单位换算处理,不用浮点完成扣款比较。套餐带宽转换成 libvirt 网卡双向 KiB/s 限制。本轮没有续费、月结、到期停机、自动回收或套餐升级。
面板的 HTTP 请求集中于 `static/app.js` 的 `api()`,因此 PHP 实现兼容的 `/api/v1/...` 接口门面即可保留大部分交互。不要把 4000 多行 JS 全部改写成 Smarty 页面,也不要把现有网站 iframe 嵌到面板或反过来嵌入。
## 安全与控制台
新增余额、套餐、订单、续费、工单等功能时,用现有面板的组件和样式补充页面,不引入第二套用户界面。
- 用户 ID、角色、VM 归属由 PHP 确定,不能相信浏览器身份字段;引擎再次检查归属。
- 管理员与 `super_admin` 白名单权限分开;跨用户只读不自动获得跨用户写权限。
- 云 API 写操作校验 CSRF;未登录/无权限返回 JSON,不重定向 HTML。
- HMAC 覆盖方法、完整路径/查询、请求体摘要、时间戳、nonce、身份。防重放存储是共享的持久数据库/Redis。
- PHP 签名密钥与任务加密密钥独立生成;任务使用 sodium secretbox 随机 nonce,引擎有独立 master.key。备份时保存密钥,不能删除后期待解密数据。
- root 公钥和密码可以同时设置,未填密码时生成强密码;root 密码策略独立于网站 bcrypt 的 72 字节限制。
### 需要保持的接口契约
VNC 凭据 60 秒有效、单次、绑定用户/VM/会话,通过 WebSocket 子协议传递而非 URL。连接期间持续校验 PHP 会话,退出或停权会阻止继续访问。线上使用 HTTPS/WSS。
- 会话字段:`authenticated`、`admin`、`approved`、`host_ready` 必须是 JSON 布尔值,不是 `"1"` 字符串;保留 `username`、`csrf_token` 等字段。
- 列表、模板、VM 详情、指标和任务的响应字段、状态码需要建立契约测试。
- API 未登录返回 JSON 401,无权限返回 JSON 403;不能沿用 PHP 页面中间件的 302 HTML 登录重定向。
- 浏览器写操作使用统一 CSRF 校验,覆盖普通用户与管理员。
- 当前前端先查询数据库状态、初始化状态和会话。整合后统一由 PHP 首次引导管理,避免又进入 Python 的第二套注册流程。
- `/api/v1` 当前未与 PHP 的旧 `/api` 路由重名,但仍应使用新的限定路由表,不携带旧代理 API。
## 原虚拟化功能与限制
## 4. 服务与数据职责
保留云镜像/ISO 创建、UEFI/ACPI、host-passthrough、virtio 队列随 vCPU、开机自启、首次安装重启停止并弹出 ISO、磁盘删除、重装网络保留、救援挂载/卸载、SSH 隧道 VNC。救援正常关机失败不会自动断电,用户可确认硬重启,主动退出救援前 ISO 保持挂载。
### PHP:网站和销售控制面
重装、救援、删除使用持久操作编号,进程中断不盲目重复破坏性步骤。救援 ISO 为管理员授权原始流上传及摘要校验;线上需配置 FPM/反代超时与大小限制。
负责唯一账户体系、邮箱验证、管理员权限、账户批准/禁用、用户公钥管理、套餐、订单、充值、支付、续费、工单和用户操作授权。管理员宿主机和镜像页面仍保留原 UI,由 PHP API 转交引擎。
尚未实现宿主容量调度、分布式资源预留、IP/MAC 防伪、套餐磁盘 IOPS、备份、热迁移或 HA。线程中断进入待核对,并非完整步骤恢复;后续应增加运维对账与独立执行器。
### Python:私有虚拟化引擎
上线前必须验收真实 MariaDB 并发、两库权限、宿主机固件/网桥/SELinux、cloud-init 与 SSH、浏览器 WSS、会话撤销、失败清理/退款。SMTP 沿用 venix,TLS 证书校验已恢复,自签邮件证书需修复信任链。
负责宿主机 SSH/libvirt、宿主机密钥、实际 IP 占用、镜像文件、虚拟机生命周期、磁盘、重装/救援状态、指标、控制台转发及底层资源校验。
PHP 不直接解密或修改 Python 的 `panel_records`,也不直接执行客户端传来的 SSH/virsh 命令。宿主机私钥与口令不需要发给浏览器或存入 PHP 用户表。
### 服务认证和归属隔离
- Python 内部 API 增加独立的服务认证与经过验证的租户上下文;不能复用一个 Python 管理员 Cookie 代表所有客户。
- 用户 ID、角色和 VM 归属由 PHP 服务确定,不能直接相信浏览器提交的 `user_id`、`admin` 或 HTTP 自定义身份头。
- 使用稳定外部用户 ID 与稳定 VM ID,明确映射到引擎归属;不要通过复制两套用户表或共享用户密码来建立身份。
- 引擎仍核验每个 VM 操作的归属、角色和状态,不能只靠前端隐藏按钮。
- 订单开通使用幂等键,重复支付回调、网络超时重试不能重复创建 VM 或重复扣款。
可以继续用同一 MariaDB 实例,但 PHP 与 Python 按职责区分表/库和数据库账号。建议有明确的账户、套餐、订单、服务实例、宿主机、VM、IP 预留、任务和审计模型;同一数据只能有一个权威写入方。订单中的期望配置由 PHP 管理,宿主实际运行状态由引擎返回并对账。
现有 Python 仍然只有一个宿主机配置。此次集成不会自动成为多宿主机平台,多宿主机需要稳定 `host_id`、调度和资源预留另外开发。
## 5. VNC、大文件和耗时任务
### VNC
保留 noVNC 与 Python WSS→SSH→宿主机本地 VNC 链路。PHP 校验用户后向引擎申请短时、单 VM、可撤销的控制台凭据;浏览器通过同源反代直接连接 Python WebSocket。不让普通 PHP-FPM 请求持续搬运控制台二进制流,也不向客户开放宿主机 VNC 端口或暴露内部服务凭据。
凭据需要绑定用户、VM、过期时间与会话状态,握手验证,并保留注销/停权后的持续访问检查。不能只把当前 Python console 的 Cookie 校验删掉。
### 救援 ISO 上传
当前 UI 发送 `application/octet-stream` 原始流,最大 8 GiB,不是 multipart。需要专门的授权和流式上传通道,避免 PHP 全量读进内存、重复暂存文件或长时间占用普通 FPM worker。禁止先完整接收再检查上传权限。
### 后台任务
创建、重装、救援和镜像下载应返回任务编号,由 UI 查询进度。现有 Python 重装/救援等任务仍运行在 Web 进程中的线程;集成不会自动获得重启恢复。长期要拆独立 worker 与指标采集,持久记录任务步骤、锁、租约、失败状态和宿主实际状态对账,不能对毁盘/删除操作盲目重试。
## 6. PHP 代码保留与移除边界
### 提取后保留
- Composer、Slim 路由、Eloquent 连接和模型基础。
- 注册登录、验证码、密码找回、TOTP、可信设备、会话撤销、邮箱/IP 限制等可选账户安全能力。
- 管理员权限、CSRF、SMTP/邮件投递记录;与 Python 现有 UI 统一。
- `app/Services/Payment/` 中需要使用的支付网关、签名校验、重复回调与钱包充值能力。
- 工单、公告、必要的访问安全日志和用户操作审计。
- Redis 暂时保留:认证、验证码限流、可信设备和缓存仍有依赖,不能仅删除节点模块就删除 Redis。
### 默认不带入首版虚拟化业务
- AI:`config/routes_ai.php`、`app/Services/Ai/`、AI 控制器/模型/路由/定时任务。
- 代理节点、订阅、客户端配置生成:Node/Link/Conf/EdgeConfig/代理 DNS 分发,以及 `resources/conf/`。
- 代理流量、在线人数、TCP 与 Gemini 节点监控及相应采集脚本。
- Apple 账号池、账号检测配套目录、Apple 用户权限与领取日志。
- 原代理 `Shop`/`Bought` 套餐、流量重置、会员等级过期和代理自动续费规则。
- 与首版无关的社区、问卷、Telegram/机器人、付费注册等功能。
- 原多主题页面和 `public/theme/` 大量资源:迁入现有面板 UI 并确认无依赖后退役。
- 旧 SQL、旧部署 cron 和仅针对退役模块的测试/文档/依赖。
以上为初次审查建议,不是最终删除清单。实际按用户反馈保留了商城、支付、工单、问卷、人工限制以及管理员专用 Telegram 工单通知;套餐已改为资源规格但不能购买。保留/删除细节见清理报告。
### 不能盲目删除的耦合
- `Services/Auth/Redis.php`、`Auth/Cookie.php` 的身份查询还访问 Node,删除节点前先移除这条依赖。
- `AuthController.php` 注册会分配代理密码、端口、协议、流量和等级,需改成干净账户初始化。
- `Models/Shop.php::buy()` 修改流量和会员等级,不会创建虚拟机;不能只改文字当作 VPS 套餐。
- `UserFeatureRestrictionService`、`UserRestrictionEnforcementService` 按代理使用量与旧套餐判断限制,可能把正常 VPS 客户误封。
- `View.php` 和用户首页依赖旧套餐/AI 服务,删除模块后需要解除共用渲染依赖。
- `UserDataDeletionService` 跨主库/日志库批量清理旧业务。VPS 用户删除必须先处理仍在运行的实例、磁盘、订单与归属,不能只删账户。
- `Job.php`、`AccountLifecycleService`、`TransientDataCleanupService` 不是通用云服务任务,不直接保留原行为。
- 原日志库还有邮件/安全统计用途,不能因删除代理日志就移除所有日志连接。
## 7. 集成前必须修复的安全和数据问题
1. 密码:`app/Utils/Hash.php` 使用 MD5 或单次 SHA-256 + 全局盐。新账户改用 `password_hash()` / `password_verify()`,使用足够宽的哈希列;不沿用旧 `pass VARCHAR(64)`。全新安装不必兼容旧散列。
2. 邮件 TLS:`Services/Mail/Smtp.php` 的部分 SSL 路径关闭证书/主机名验证,需要恢复验证,不能把关闭验证作为解决证书错误的默认方式。
3. 权限:统一 `is_admin` 与配置中的 `super_admin` UID 白名单;所有 API 写操作增加一致 CSRF 与资源归属检查。
4. 找回密码:一次性 token 事务消费、过期限制、修改后撤销旧会话,删除旧订阅清理副作用。
5. 金额:新销售逻辑采用整数最小货币单位或精确 Decimal 运算,保留币种和价格快照,避免 PHP float 处理扣款。
6. 配额:支付成功不等于可以无限开机。增加用户/套餐资源限制、宿主容量预留、IP/MAC 防伪与带宽/磁盘 I/O 约束。
7. 更新:原在线更新器固定指向旧 virsh-panel 仓库。新复合项目必须设计自己的版本与更新范围;不能直接搬入后让其覆盖整个 PHP 新项目。
相关官方资料:[PHP 密码哈希](https://www.php.net/manual/en/function.password-hash.php)、[PHP 密码验证](https://www.php.net/manual/en/function.password-verify.php)、[Guzzle JSON/TLS 请求选项](https://docs.guzzlephp.org/en/stable/request-options.html)、[FastAPI WebSocket 认证与依赖](https://fastapi.tiangolo.com/advanced/websockets/)。
## 8. 建议实施顺序与验收
### 第一阶段:无销售的最小集成
建立新的限定路由表与干净账户模型;统一首次网页初始化、邮箱验证/审核、管理员权限、CSRF;引入现有面板 UI;完成私有引擎认证、用户归属和控制台凭据。先验证登录、自己的公钥和 VM、创建、开关机、重装、救援、指标、管理员配置均与原面板相当。
不要启用副本里的旧 `crontab`,不要直接导入 `sql/ss.sql`。后续新数据库不需要兼容原测试数据,但仍需正式初始化/版本化迁移和备份方案。
### 第二阶段:按依赖清理
在保留功能的测试覆盖下,按“路由和 cron → 共享调用拆分 → 控制器/服务 → 模型/SQL → 模板和资源 → Composer 依赖”顺序删除旧模块。不通过隐藏菜单代替关闭旧 API。
保留支付回调签名校验、重复回调与并发入账测试;新增跨用户 VM/公钥隔离、非管理员宿主机操作拒绝、CSRF、错误响应格式、noVNC 和 ISO 流式上传测试。
### 第三阶段:销售能力
新增 VPS 套餐、区域、价格、订单、实例期限和续费,再连接已审查的支付网关;建立支付入账与实例开通的幂等状态机。开通失败要能重试/退款,不直接用旧 `Shop::buy()`。
### 第四阶段:平台可靠性
稳定宿主机/VM ID、多宿主机调度与库存、独立 worker/采集进程、备份恢复、审计与报警。再考虑在线扩容、迁移和 HA,不把 PHP UI 集成等同于这些能力已经存在。
清理后的代码已进行隔离 PHP 8.5 语法和边界测试。尚未进行真实数据库初始化、邮件/TG/支付通道联调、宿主机操作或生产部署;这些需要在后续集成验收中完成。原始安全审查中密码及找回流程已改造,SMTP TLS 和统一普通用户 CSRF 等仍需后续处理。
全新安装见 [DEPLOYMENT.md](DEPLOYMENT.md),历史清理见 [PRUNING_REPORT.md](PRUNING_REPORT.md)。

@ -0,0 +1,26 @@
# 本版验证记录
2026-09-27,集成代码的隔离验证,不代表生产验收。
- Python 3.12:445 passed、10 skipped、39 subtests passed。覆盖原虚拟化逻辑及私有 API、签名/重放、多宿主机归属、持久幂等、一次性 VNC、退出后断权、带宽 XML、救援上传摘要。
- 隔离 PHP 8.5.10:源码语法、70 个 Smarty 模板、178 个路由目标、精确金额/HMAC、SQLite 购买开通/退款/超时核对/配额/租户隔离、Cookie/Redis 会话撤销及内省、统一用户资源和 52 个 noVNC 模块检查通过。
- Chrome 使用模拟 API 检查套餐购买、VM 详情/指标/凭据、公钥、重装/救援、后台宿主机/镜像操作与 CSRF;用户账户及登录等页面进行桌面/手机布局检查。不连接真实数据库或宿主机。
- PHP 隔离环境不提供 sodium:`CloudSecretsTest` 明确跳过,原 Paytaro/易支付密钥加密测试因同一缺失无法运行;财务/会话测试的加密存储仅用明确标注的测试替身,不作为实际加密验证。生产必须安装 sodium,没有弱加密回退。
- Python 的跳过项需要真实 libvirt/网络环境。没有验证真实 MariaDB 并发、AlmaLinux systemd、宿主机 VM 操作、SMTP、支付和大文件上传。
## 在具备依赖的环境复测
不要使用生产数据库/宿主机运行额外真实集成测试;以下默认单元/隔离测试:
```bash
cd /home/virt-cloud/web
for test_file in tests/*Test.php; do php "$test_file" || exit $?; done
cd /home/virt-cloud/engine
.venv/bin/python -m pip install -r requirements-dev.txt
PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -q -p no:cacheprovider
```
PHP 测试需 Composer 开发可用依赖和测试所用 PDO SQLite。测试中的模拟凭据、地址与密钥不是部署配置。
上线前按 [部署说明](DEPLOYMENT.md) 完成测试用户的实际购买、首次 SSH 登录、重装、救援、VNC 撤销、故障清理退款与无人登录时持续采样。共享公网网桥的 IP/MAC 防欺骗及宿主容量调度尚未提供,不能只凭单元测试开放不受信任客户的资源销售。

5
engine/.gitignore vendored

@ -0,0 +1,5 @@
.venv/
data/
__pycache__/
*.py[cod]
.pytest_cache/

@ -0,0 +1,3 @@
-r requirements.txt
httpx>=0.27,<1
pytest>=8,<10

@ -0,0 +1,8 @@
fastapi>=0.115,<1
uvicorn[standard]>=0.34,<1
pydantic>=2,<3
pycdlib>=1.14,<2
passlib>=1.7.4,<2
PyMySQL>=1.1,<2
cryptography>=44,<49
libvirt-python>=10,<13; sys_platform == "linux"

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Слой_1" x="0px" y="0px" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xmlns="http://www.w3.org/2000/svg">
<style type="text/css">
.st0{fill:#86DA2F;}
.st1{fill:#24C2FF;}
.st2{fill:#FFCB12;}
.st3{fill:#0069DA;}
.st4{fill:#FF4649;}
</style>
<ellipse style="fill: rgb(255, 255, 255); stroke: rgb(255, 255, 255);" cx="50" cy="50" rx="50" ry="50"/>
<g>
<g>
<path class="st0" d="M86,55.9c3.6-0.3,6.5,2.1,6.8,5.7c0.3,3.8-2.4,6.8-6,7.1c-3.5,0.3-6.5-2.4-6.8-5.8 C79.7,59.1,82.2,56.3,86,55.9z"/>
<path class="st1" d="M42.1,85.5c0-3.6,2.8-6.4,6.1-6.4s6.5,3.1,6.5,6.5c0,3.3-2.8,6.3-6,6.4C44.7,92,42.1,89.5,42.1,85.5z"/>
<path class="st2" d="M51.9,44.9c-0.6,0.3-0.8-0.1-1-0.6c-5.1-9.6-3.6-21.7,5.4-28.9c2.4-1.9,6.8-2.4,8.8-0.4 c0.8,0.7,1,1.5,1.1,2.5c0.3,2.1,0.7,4.2,2.1,5.8c1.5,1.8,3.5,2.5,5.7,2.4c1.9,0,3.9-0.3,5.1,1.9c0.7,1.3,0.4,6.1-0.7,7.1 c-0.6,0.4-1,0.1-1.4,0c-3.2-1.3-6.5-1.3-9.9-0.7c-1.1,0.1-1.7-0.1-1.7-1.4c-0.1-2.1-0.6-4-1.7-5.8c-2.1-3.8-6-3.9-8.5-0.4 c-2.1,2.8-2.6,6.1-3.2,9.4C51.6,38.8,51.8,41.9,51.9,44.9C51.9,44.9,51.8,44.9,51.9,44.9z"/>
<path class="st0" d="M55.4,47c-0.3-0.4-0.1-0.8,0.3-1.1c7.9-7.2,19.7-8.6,28.9-1.5c2.4,1.9,3.9,6,2.6,8.3c-0.6,1-1.3,1.4-2.1,1.7 c-1.9,0.8-3.8,1.7-5,3.5c-1.3,1.8-1.5,3.9-1,6.1c0.4,1.8,1.1,3.8-0.7,5.4c-1,1-5.7,1.8-6.9,1c-0.6-0.4-0.4-0.8-0.3-1.4 c0.4-3.5-0.4-6.7-1.7-9.7c-0.4-1.1-0.3-1.7,0.8-1.9c1.9-0.6,3.8-1.5,5.1-2.9c3.1-2.9,2.4-6.7-1.7-8.3c-3.2-1.4-6.5-1.1-9.7-0.8 C61.1,45.3,58.2,46.2,55.4,47L55.4,47z"/>
<path class="st1" d="M53.6,50.6c0.4-0.4,0.7-0.3,1.1,0c9.2,5.6,13.9,16.5,9.7,27.2c-1.1,2.8-4.7,5.6-7.4,4.9 c-1.1-0.3-1.7-0.8-2.2-1.5c-1.3-1.7-2.6-3.2-4.7-3.9c-2.2-0.7-4.2-0.3-6.1,0.8c-1.7,1-3.3,2.2-5.4,1c-1.3-0.7-3.3-5-2.9-6.4 c0.3-0.6,0.8-0.6,1.4-0.6c3.5-0.6,6.3-2.2,8.9-4.4c0.8-0.7,1.5-0.7,2.2,0.3c1.1,1.7,2.5,3.1,4.3,4c3.6,2.1,7.1,0.3,7.5-3.9 c0.4-3.5-0.8-6.5-1.9-9.6C56.8,55.7,55.3,53.1,53.6,50.6L53.6,50.6z"/>
<path class="st3" d="M49.1,51.4c-0.6,2.8-1.8,5.4-3.5,7.8c-5,7.5-12.2,10.6-21.1,9.7c-3.2-0.3-5.8-2.9-6.1-5.6 c-0.1-1.1,0.1-1.9,0.8-2.8c1-1.3,1.8-2.4,2.2-3.9c0.8-3.1-0.3-5.6-2.5-7.8c-3.1-3.1-2.6-5.8,1-8.1c0.4-0.3,1-0.6,1.5-0.8 c0.8-0.4,1.5-0.4,1.8,0.6c1.3,3.2,3.8,5.6,6.5,7.5c1,0.8,1,1.4,0.1,2.4c-1.7,1.8-2.6,4-2.8,6.5c-0.3,3.1,1.5,5,4.6,5 c1.9,0,3.8-0.7,5.4-1.5c4.3-2.2,7.6-5.4,10.8-8.8C48.4,51.6,48.6,51.3,49.1,51.4z"/>
<path class="st4" d="M26.3,22.3c0.3,0,1,0.1,1.7,0.3c5.1,1,8.3-0.8,10-5.7c1.1-3.2,3.5-4.2,6.5-2.5c0.1,0,0.1,0.1,0.3,0.1 c3.1,1.8,3.1,2.1,1,4.9c-1.7,2.2-2.5,4.7-2.9,7.4c-0.3,1.5-0.8,1.8-2.2,1.3c-2.2-0.8-4.6-0.8-6.9,0c-2.6,0.8-3.8,3.2-2.9,5.8 c1.1,3.5,4.2,5,6.8,6.8s5.7,2.8,8.6,4c0.4,0.1,1.1,0.1,1,0.8c-0.1,0.4-0.7,0.4-1.3,0.4c-6.3,0.3-12.2-0.7-17.1-4.9 c-4.6-3.8-7.9-8.3-7.4-14.7C22.2,24.2,23.7,22.7,26.3,22.3z"/>
<path class="st3" d="M15,61.3c-3.3,0.4-6.7-2.4-6.9-5.8c-0.3-3.3,2.5-6.7,5.7-6.9c3.6-0.4,6.9,2.1,7.2,5.4 C21.1,57.1,19,61,15,61.3z"/>
<path class="st2" d="M73.3,11.8c3.5-0.3,6.8,2.5,7.1,6c0.3,3.3-2.5,6.5-5.8,6.8c-3.6,0.3-6.8-2.4-7.1-5.8 C67.2,15.3,69.7,12.1,73.3,11.8z"/>
<path class="st4" d="M37,14.5c0.4,3.6-2.1,6.7-5.8,7.2c-3.2,0.4-6.5-2.2-6.9-5.3c-0.4-4,1.8-6.9,5.6-7.4 C33.3,8.6,36.6,11.3,37,14.5z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

File diff suppressed because it is too large Load Diff

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160" viewBox="0 0 42.333 42.333"><g transform="matrix(1.0529 0 0 1.05289 -387.492 265.985)"><circle cx="435.079" cy="-124.144" r="20.103" style="fill:#a14f8c;fill-opacity:1;stroke:none;stroke-width:1.32292;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:fill markers stroke;stop-color:#000" transform="rotate(-15)"/><path d="m384.257-249.617-3.875 3.875h-5.479v5.48l-3.875 3.875 3.875 3.874v5.48h5.48l3.874 3.875 3.875-3.875h5.48v-5.48l3.874-3.874-3.875-3.875-5.48-5.48zm1.176 3.875v4.18l-1.176 1.176-1.176-1.176v-4.18zm-6.959 1.908 2.956 2.957v1.662h-1.663l-2.956-2.956zm-3.571 6.27h4.18l1.176 1.177-1.176 1.176h-4.18zm14.434 0h4.18v2.353h-4.18l-1.176-1.176zm-9.503 3.937h1.663v1.663l-2.956 2.956-1.663-1.663zm7.184 0h1.663l2.956 2.956-1.663 1.663-2.956-2.956zm-2.76 1.143 1.175 1.176v4.18h-2.352v-4.18z" style="fill:#fff;fill-opacity:1;stroke-width:7.93746;stroke-linecap:round;paint-order:fill markers stroke;stop-color:#000" transform="translate(-53.772 39.325)scale(1.15)"/><path d="m385.433-239.09-1.176 1.04-1.176-1.04v1.526h-1.526l1.039 1.177-1.04 1.176h1.527v1.526l1.176-1.04 1.176 1.04v-1.526h1.527l-1.04-1.176 1.04-1.177h-1.527z" style="fill:#efa724;fill-opacity:1;stroke-width:8.59212;stroke-linecap:round;paint-order:fill markers stroke;stop-color:#000" transform="translate(-53.772 39.325)scale(1.15)"/><path d="m388.135-245.738 1.905 1.905-2.956 2.956v1.663h1.663l2.956-2.956 1.911 1.911-.003-5.483z" style="fill:#efa724;fill-opacity:1;stroke-width:6.14231;stroke-linecap:round;paint-order:fill markers stroke;stop-color:#000" transform="translate(-53.772 39.325)scale(1.15)"/></g></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@ -0,0 +1,51 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 87.041 108.445">
<path fill="#A80030" d="M51.986,57.297c-1.797,0.025,0.34,0.926,2.686,1.287
c0.648-0.506,1.236-1.018,1.76-1.516C54.971,57.426,53.484,57.434,51.986,57.297"/>
<path fill="#A80030" d="M61.631,54.893c1.07-1.477,1.85-3.094,2.125-4.766c-0.24,1.192-0.887,2.221-1.496,3.307
c-3.359,2.115-0.316-1.256-0.002-2.537C58.646,55.443,61.762,53.623,61.631,54.893"/>
<path fill="#A80030" d="M65.191,45.629c0.217-3.236-0.637-2.213-0.924-0.978
C64.602,44.825,64.867,46.932,65.191,45.629"/>
<path fill="#A80030" d="M45.172,1.399c0.959,0.172,2.072,0.304,1.916,0.533
C48.137,1.702,48.375,1.49,45.172,1.399"/>
<path fill="#A80030" d="M47.088,1.932l-0.678,0.14l0.631-0.056L47.088,1.932"/>
<path fill="#A80030" d="M76.992,46.856c0.107,2.906-0.85,4.316-1.713,6.812l-1.553,0.776
c-1.271,2.468,0.123,1.567-0.787,3.53c-1.984,1.764-6.021,5.52-7.313,5.863c-0.943-0.021,0.639-1.113,0.846-1.541
c-2.656,1.824-2.131,2.738-6.193,3.846l-0.119-0.264c-10.018,4.713-23.934-4.627-23.751-17.371
c-0.107,0.809-0.304,0.607-0.526,0.934c-0.517-6.557,3.028-13.143,9.007-15.832c5.848-2.895,12.704-1.707,16.893,2.197
c-2.301-3.014-6.881-6.209-12.309-5.91c-5.317,0.084-10.291,3.463-11.951,7.131c-2.724,1.715-3.04,6.611-4.227,7.507
C31.699,56.271,36.3,61.342,44.083,67.307c1.225,0.826,0.345,0.951,0.511,1.58c-2.586-1.211-4.954-3.039-6.901-5.277
c1.033,1.512,2.148,2.982,3.589,4.137c-2.438-0.826-5.695-5.908-6.646-6.115c4.203,7.525,17.052,13.197,23.78,10.383
c-3.113,0.115-7.068,0.064-10.566-1.229c-1.469-0.756-3.467-2.322-3.11-2.615c9.182,3.43,18.667,2.598,26.612-3.771
c2.021-1.574,4.229-4.252,4.867-4.289c-0.961,1.445,0.164,0.695-0.574,1.971c2.014-3.248-0.875-1.322,2.082-5.609l1.092,1.504
c-0.406-2.696,3.348-5.97,2.967-10.234c0.861-1.304,0.961,1.403,0.047,4.403c1.268-3.328,0.334-3.863,0.66-6.609
c0.352,0.923,0.814,1.904,1.051,2.878c-0.826-3.216,0.848-5.416,1.262-7.285c-0.408-0.181-1.275,1.422-1.473-2.377
c0.029-1.65,0.459-0.865,0.625-1.271c-0.324-0.186-1.174-1.451-1.691-3.877c0.375-0.57,1.002,1.478,1.512,1.562
c-0.328-1.929-0.893-3.4-0.916-4.88c-1.49-3.114-0.527,0.415-1.736-1.337c-1.586-4.947,1.316-1.148,1.512-3.396
c2.404,3.483,3.775,8.881,4.404,11.117c-0.48-2.726-1.256-5.367-2.203-7.922c0.73,0.307-1.176-5.609,0.949-1.691
c-2.27-8.352-9.715-16.156-16.564-19.818c0.838,0.767,1.896,1.73,1.516,1.881c-3.406-2.028-2.807-2.186-3.295-3.043
c-2.775-1.129-2.957,0.091-4.795,0.002c-5.23-2.774-6.238-2.479-11.051-4.217l0.219,1.023c-3.465-1.154-4.037,0.438-7.782,0.004
c-0.228-0.178,1.2-0.644,2.375-0.815c-3.35,0.442-3.193-0.66-6.471,0.122c0.808-0.567,1.662-0.942,2.524-1.424
c-2.732,0.166-6.522,1.59-5.352,0.295c-4.456,1.988-12.37,4.779-16.811,8.943l-0.14-0.933c-2.035,2.443-8.874,7.296-9.419,10.46
l-0.544,0.127c-1.059,1.793-1.744,3.825-2.584,5.67c-1.385,2.36-2.03,0.908-1.833,1.278c-2.724,5.523-4.077,10.164-5.246,13.97
c0.833,1.245,0.02,7.495,0.335,12.497c-1.368,24.704,17.338,48.69,37.785,54.228c2.997,1.072,7.454,1.031,11.245,1.141
c-4.473-1.279-5.051-0.678-9.408-2.197c-3.143-1.48-3.832-3.17-6.058-5.102l0.881,1.557c-4.366-1.545-2.539-1.912-6.091-3.037
l0.941-1.229c-1.415-0.107-3.748-2.385-4.386-3.646l-1.548,0.061c-1.86-2.295-2.851-3.949-2.779-5.23l-0.5,0.891
c-0.567-0.973-6.843-8.607-3.587-6.83c-0.605-0.553-1.409-0.9-2.281-2.484l0.663-0.758c-1.567-2.016-2.884-4.6-2.784-5.461
c0.836,1.129,1.416,1.34,1.99,1.533c-3.957-9.818-4.179-0.541-7.176-9.994l0.634-0.051c-0.486-0.732-0.781-1.527-1.172-2.307
l0.276-2.75C4.667,58.121,6.719,47.409,7.13,41.534c0.285-2.389,2.378-4.932,3.97-8.92l-0.97-0.167
c1.854-3.234,10.586-12.988,14.63-12.486c1.959-2.461-0.389-0.009-0.772-0.629c4.303-4.453,5.656-3.146,8.56-3.947
c3.132-1.859-2.688,0.725-1.203-0.709c5.414-1.383,3.837-3.144,10.9-3.846c0.745,0.424-1.729,0.655-2.35,1.205
c4.511-2.207,14.275-1.705,20.617,1.225c7.359,3.439,15.627,13.605,15.953,23.17l0.371,0.1
c-0.188,3.802,0.582,8.199-0.752,12.238L76.992,46.856"/>
<path fill="#A80030" d="M32.372,59.764l-0.252,1.26c1.181,1.604,2.118,3.342,3.626,4.596
C34.661,63.502,33.855,62.627,32.372,59.764"/>
<path fill="#A80030" d="M35.164,59.654c-0.625-0.691-0.995-1.523-1.409-2.352
c0.396,1.457,1.207,2.709,1.962,3.982L35.164,59.654"/>
<path fill="#A80030" d="M84.568,48.916l-0.264,0.662c-0.484,3.438-1.529,6.84-3.131,9.994
C82.943,56.244,84.088,52.604,84.568,48.916"/>
<path fill="#A80030" d="M45.527,0.537C46.742,0.092,48.514,0.293,49.803,0c-1.68,0.141-3.352,0.225-5.003,0.438
L45.527,0.537"/>
<path fill="#A80030" d="M2.872,23.219c0.28,2.592-1.95,3.598,0.494,1.889
C4.676,22.157,2.854,24.293,2.872,23.219"/>
<path fill="#A80030" d="M0,35.215c0.563-1.728,0.665-2.766,0.88-3.766C-0.676,33.438,0.164,33.862,0,35.215"/>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

@ -0,0 +1,493 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#101d2c" />
<title>VirtPilot · 虚拟机管理</title>
<link rel="stylesheet" href="/static/styles.css?v=rescue-iso-pool-1" />
<script type="module" src="/static/app.js?v=rescue-iso-pool-1"></script>
</head>
<body>
<div id="boot-screen" class="boot-screen" role="status" aria-live="polite">
<span class="brand-mark" aria-hidden="true"><span></span></span>
<span>正在连接控制面板…</span>
</div>
<main id="database-view" class="setup-layout" hidden>
<div class="setup-intro">
<div class="setup-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<span class="eyebrow light">FIRST RUN SETUP</span>
<h1>先连接数据库,<br />再开始管理。</h1>
<p>面板业务数据保存在 MariaDB 中。只需在首次启用时填写连接信息,无需预先编辑面板配置文件。</p>
<div class="setup-steps"><span class="current">01 · 配置数据库</span><span>02 · 创建初始用户</span><span>03 · 授予管理员权限</span></div>
</div>
<div class="setup-form-side">
<section class="setup-card" aria-labelledby="database-title">
<span class="eyebrow">步骤 01 / 03</span>
<h2 id="database-title">连接 MariaDB</h2>
<p class="muted">请先准备可连接的数据库与账号。连接信息只提交给面板服务,不会保存在浏览器中。</p>
<p class="setup-security-note">请先完成你自己的 HTTPS 反向代理,并核对证书和域名,再输入数据库密码与初始化令牌。</p>
<form id="database-form" class="form-stack">
<label for="database-host">数据库 IP 或主机名</label>
<input id="database-host" name="host" type="text" autocomplete="off" maxlength="253" required placeholder="例如 127.0.0.1" />
<label for="database-port">端口</label>
<input id="database-port" name="port" type="number" min="1" max="65535" value="3306" required />
<label for="database-name">数据库名</label>
<input id="database-name" name="database" type="text" autocomplete="off" maxlength="64" required placeholder="例如 virsh_panel" />
<label for="database-username">数据库用户名</label>
<input id="database-username" name="username" type="text" autocomplete="off" maxlength="128" required />
<label for="database-password">数据库密码</label>
<input id="database-password" name="password" type="password" autocomplete="off" maxlength="1024" required />
<label for="database-token">初始化令牌</label>
<input id="database-token" name="setup_token" type="password" autocomplete="off" maxlength="256" required placeholder="粘贴面板启动终端输出中的令牌" />
<p id="database-error" class="form-error" role="alert" hidden></p>
<button id="database-submit" class="button button-primary setup-submit" type="submit">连接数据库并继续 <span aria-hidden="true">→</span></button>
</form>
<p class="setup-note">数据库需由你预先创建并授权;面板不会自动安装 MariaDB。初始化令牌完成初始用户创建后失效。</p>
</section>
</div>
</main>
<main id="setup-view" class="setup-layout" hidden>
<div class="setup-intro">
<div class="setup-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<span class="eyebrow light">FIRST RUN SETUP</span>
<h1>欢迎使用<br />VirtPilot</h1>
<p>完成数据库连接后先创建初始用户,再由你在数据库中将其 admin 字段改为管理员权限。</p>
<div class="setup-steps"><span>01 · 配置数据库</span><span class="current">02 · 创建初始用户</span><span>03 · 授予管理员权限</span></div>
</div>
<div class="setup-form-side">
<section class="setup-card" aria-labelledby="setup-title">
<span class="eyebrow">步骤 02 / 03</span>
<h2 id="setup-title">创建初始用户</h2>
<p class="muted">使用面板首次启动时在终端输出的一次性初始化令牌。完成后令牌将失效。</p>
<p class="setup-security-note">安全检查:请先完成你自己的 HTTPS 反向代理,并确认浏览器连接的是你信任的证书和域名,再输入令牌、密码或宿主机私钥。</p>
<form id="setup-form" class="form-stack">
<label for="setup-token">初始化令牌</label>
<input id="setup-token" name="token" type="password" autocomplete="off" maxlength="256" required placeholder="粘贴启动终端输出中的令牌" />
<label for="setup-username">初始用户名</label>
<input id="setup-username" name="username" type="text" autocomplete="username" minlength="3" maxlength="32" pattern="[A-Za-z][A-Za-z0-9._-]{2,31}" value="admin" required />
<label for="setup-password">初始用户密码</label>
<input id="setup-password" name="password" type="password" autocomplete="new-password" minlength="12" maxlength="1024" required placeholder="至少 12 个字符" />
<label for="setup-password-confirm">确认密码</label>
<input id="setup-password-confirm" type="password" autocomplete="new-password" minlength="12" maxlength="1024" required placeholder="再次输入密码" />
<p id="setup-error" class="form-error" role="alert" hidden></p>
<button id="setup-submit" class="button button-primary setup-submit" type="submit">创建初始用户 <span aria-hidden="true">→</span></button>
</form>
<p class="setup-note">初始用户默认没有管理员权限。创建后请由你在数据库中将该用户 admin 字段设为 1,并手动补充登录邮箱,再用邮箱登录配置 SMTP 和宿主机。面板账号与宿主机 root 账号相互独立。</p>
</section>
</div>
</main>
<main id="login-view" class="login-layout" hidden>
<div class="login-art" aria-hidden="true">
<div class="login-art-grid"></div>
<div class="login-art-inner">
<div class="login-art-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<div class="login-art-copy">
<span class="eyebrow light">LIBVIRT CONTROL CENTER</span>
<h1>让每一台虚拟机<br />都尽在掌控。</h1>
<p>从一个安全、清晰的界面,管理远端宿主机上的虚拟机。</p>
</div>
<div class="login-art-footer"><span class="online-dot"></span> 远端 libvirt 管理面板</div>
</div>
<div class="art-orbit orbit-one"></div>
<div class="art-orbit orbit-two"></div>
<div class="art-core"><span></span><span></span><span></span></div>
</div>
<div class="login-form-side">
<div id="login-card" class="login-card">
<div class="login-mobile-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<span class="eyebrow">欢迎回来</span>
<h2>登录管理面板</h2>
<p class="muted">使用注册邮箱访问虚拟机控制台。</p>
<form id="login-form" class="form-stack">
<label for="login-email">邮箱</label>
<input id="login-email" name="email" type="email" autocomplete="username" maxlength="254" required autofocus placeholder="输入注册邮箱" />
<label for="login-password">密码</label>
<input id="login-password" name="password" type="password" autocomplete="current-password" maxlength="1024" required placeholder="输入密码" />
<p id="login-error" class="form-error" role="alert" hidden></p>
<p id="login-success" class="register-code-status" role="status" hidden></p>
<button id="login-submit" class="button button-primary login-submit" type="submit">登录面板 <span aria-hidden="true">→</span></button>
</form>
<p class="auth-switch">还没有账号?<button id="show-register-button" type="button">邮箱注册</button></p>
<p class="login-hint">通过 HTTPS 安全访问面板;虚拟机操作将在远端宿主机执行。</p>
</div>
<div id="register-card" class="login-card" hidden>
<div class="login-mobile-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<span class="eyebrow">创建账号</span>
<h2>邮箱注册</h2>
<p class="muted">验证邮箱后创建账号;新账号只能管理自己创建的虚拟机。</p>
<form id="register-form" class="form-stack">
<label for="register-username">用户名</label>
<input id="register-username" type="text" autocomplete="username" minlength="3" maxlength="32" pattern="[A-Za-z][A-Za-z0-9._-]{2,31}" required placeholder="至少 3 个字符" />
<label for="register-email">邮箱</label>
<input id="register-email" type="email" autocomplete="email" maxlength="254" required placeholder="接收验证码的邮箱" />
<label for="register-password">密码</label>
<input id="register-password" type="password" autocomplete="new-password" minlength="12" maxlength="1024" required placeholder="至少 12 个字符" />
<label for="register-password-confirm">确认密码</label>
<input id="register-password-confirm" type="password" autocomplete="new-password" minlength="12" maxlength="1024" required placeholder="再次输入密码" />
<label for="register-code">邮箱验证码</label>
<div class="register-code-row"><input id="register-code" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="8" required placeholder="输入邮件中的验证码" /><button id="register-code-send" class="button button-outline" type="button">发送验证码</button></div>
<p id="register-code-status" class="register-code-status" role="status" hidden></p>
<p id="register-error" class="form-error" role="alert" hidden></p>
<button id="register-submit" class="button button-primary login-submit" type="submit">验证并注册 <span aria-hidden="true">→</span></button>
</form>
<p class="auth-switch">已有账号?<button id="show-login-button" type="button">返回登录</button></p>
<p class="login-hint">请使用 HTTPS 连接面板,密码和验证码不会写入浏览器存储。</p>
</div>
</div>
</main>
<main id="access-wait-view" class="host-layout" hidden>
<header class="host-topbar"><div class="host-brand"><span class="brand-mark"><span></span></span> VirtPilot</div><div class="host-topbar-actions"><span id="wait-current-user" class="host-user"></span><button id="wait-logout-button" class="button button-ghost small" type="button">退出登录</button></div></header>
<div class="unlock-content"><section class="host-card unlock-card" aria-labelledby="wait-title"><span id="wait-eyebrow" class="eyebrow">ACCOUNT STATUS</span><h1 id="wait-title">等待管理员审核</h1><p id="wait-description" class="muted">邮箱已验证,账号正在等待管理员审核。审核通过后才能创建和管理虚拟机。</p><div class="host-submit-actions"><button id="wait-refresh-button" class="button button-outline" type="button">刷新状态</button><button id="wait-ssh-keys-button" class="button button-primary" type="button">管理我的公钥</button></div></section></div>
</main>
<main id="host-view" class="host-layout" hidden>
<header class="host-topbar">
<div class="host-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<div class="host-topbar-actions"><span id="host-current-user" class="host-user"></span><button id="host-logout-button" class="button button-ghost small" type="button">退出登录</button></div>
</header>
<div class="host-content">
<div class="host-heading"><div><span id="host-step-label" class="eyebrow">步骤 03 / 03</span><h1 id="host-page-title">连接 libvirt 宿主机</h1><p>填入现有的 root SSH 信息,面板将通过 libvirt API 管理远端虚拟机。</p></div><button id="host-update-button" class="button button-outline" type="button">网站更新</button><button id="host-back-button" class="button button-outline" type="button" hidden>返回虚拟机</button></div>
<div class="host-columns">
<section class="host-card" aria-labelledby="host-form-title">
<div class="host-card-heading"><span class="host-card-number">1</span><div><h2 id="host-form-title">SSH 连接信息</h2><p>使用宿主机已有的 root 私钥,不创建额外的系统账号。</p></div></div>
<form id="host-form">
<div class="form-grid">
<div class="field"><label for="host-address">宿主机地址 <span>*</span></label><input id="host-address" name="host" type="text" required maxlength="253" autocomplete="off" placeholder="例如 192.0.2.10" /></div>
<div class="field"><label for="host-port">SSH 端口 <span>*</span></label><input id="host-port" name="port" type="number" min="1" max="65535" value="22" required /></div>
<div class="field"><label for="host-region">虚拟机地区</label><input id="host-region" name="region" type="text" maxlength="64" autocomplete="off" placeholder="例如 中国香港 / 东京 / 洛杉矶" /><small>用于展示这台宿主机上的虚拟机所在地区;留空时显示“未设置”。</small></div>
<div class="field"><label for="host-username">SSH 用户</label><input id="host-username" type="text" value="root" disabled /></div>
<div class="field"><label for="host-storage-pool">虚拟机磁盘目录或存储池名</label><input id="host-storage-pool" name="storage_pool" type="text" maxlength="4096" value="default" required autocomplete="off" placeholder="例如 /home/kvm 或 default" /><small>可直接填写宿主机上的绝对路径,如 /home/kvm;也兼容现有 libvirt 存储池名称。</small></div>
<div class="field"><label for="host-iso-pool">安装 ISO 目录或存储池名</label><input id="host-iso-pool" name="iso_pool" type="text" maxlength="4096" value="iso" required autocomplete="off" placeholder="例如 /home/iso 或 iso" /><small>供创建虚拟机安装系统时选择;填写宿主机上的绝对路径,如 /home/iso,或现有存储池名称。</small></div>
<div class="field"><label for="host-rescue-iso-pool">救援 ISO 目录或存储池名</label><input id="host-rescue-iso-pool" name="rescue_iso_pool" type="text" maxlength="4096" autocomplete="off" placeholder="例如 /home/rescue-iso" /><small>专供上传救援模版使用,不能与安装 ISO 目录相同,也不要通过软链接或绑定挂载指向同一目录。请先在宿主机创建目录;面板只注册已存在的目录,不会自动创建。</small></div>
<div class="field"><label for="host-network">默认虚拟网络或网桥</label><input id="host-network" name="default_network" type="text" maxlength="128" value="default" required autocomplete="off" placeholder="例如 default 或 bridge:br0" /><small>libvirt 虚拟网络填名称;宿主机现有 Linux 网桥 br0 填 bridge:br0。</small></div>
<div class="host-public-pool full" role="group" aria-labelledby="host-public-pool-title">
<div class="host-public-pool-heading"><strong id="host-public-pool-title">公网 IPv4 地址池</strong><small>仅用于云镜像虚拟机;配置后面板只从填写的服务商获配网段自动分配地址。请按真实前缀填写,不要把仅获配的 /28 误填成 /24。</small></div>
<div class="form-grid">
<div class="field"><label for="host-public-pool-cidr">服务商分配的公网网段(/24 至 /30)</label><input id="host-public-pool-cidr" name="public_pool_cidr" type="text" maxlength="18" inputmode="decimal" autocomplete="off" placeholder="例如 123.123.123.112/28" /><small>可填网段或段内地址/前缀,例如 123.123.123.113/28 会保存为 123.123.123.112/28;留空则手动指定公网 IP。</small><small id="host-public-pool-preview" role="status" hidden></small></div>
<div class="field"><label for="host-public-gateway">网关 IPv4</label><input id="host-public-gateway" name="public_gateway" type="text" maxlength="15" inputmode="decimal" autocomplete="off" placeholder="例如 123.123.123.113" /><small>网关不会被分配给虚拟机。</small></div>
<div class="field"><label for="host-public-vm-prefix">虚拟机网卡前缀(可选)</label><input id="host-public-vm-prefix" name="public_vm_prefix" type="number" min="24" max="30" step="1" inputmode="numeric" autocomplete="off" placeholder="默认与地址池前缀相同" /><small>只影响虚拟机内的网络掩码,不扩大可分配 IP 范围。如果你的服务商要求客体使用 /24,而获配地址池是 /28,这里填 24。</small></div>
<div class="field full"><label for="host-public-dns">DNS IPv4</label><input id="host-public-dns" name="public_dns_servers" type="text" maxlength="128" autocomplete="off" placeholder="例如 1.1.1.1, 8.8.8.8" /><small>填写 1 至 4 个 DNS 地址,用逗号或空格分隔。</small></div>
<div class="field full"><label for="host-public-reserved">额外保留的公网 IP(可选)</label><textarea id="host-public-reserved" name="public_reserved_ips" rows="3" maxlength="4096" spellcheck="false" autocomplete="off" placeholder="已有其他用途的地址,每行一个;也可用逗号或空格分隔"></textarea><small>这些地址不会自动分配。请填写面板之外已占用的地址;若宿主机地址填的是域名,也请把宿主机自身的公网 IP 填在这里。</small></div>
</div>
</div>
<div class="field full"><label for="host-private-key">现有 SSH 私钥 <span id="host-key-required-mark">*</span></label><textarea id="host-private-key" name="private_key" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" placeholder="粘贴 -----BEGIN OPENSSH PRIVATE KEY----- 开头的完整内容,或从下方选择文件"></textarea><small id="host-key-hint">仅通过 HTTPS 传输并保存在面板服务器。请确保这把密钥已在宿主机 root 账号上获得授权。</small></div>
<div class="field full"><label for="host-private-key-file">或从本机选择私钥文件</label><input id="host-private-key-file" type="file" /><small id="host-key-file-label">未选择文件;已保存的密钥不会在这里显示。</small></div>
<div class="field full"><label for="host-private-key-passphrase">SSH 私钥口令(如果设置了)</label><input id="host-private-key-passphrase" name="private_key_passphrase" type="password" maxlength="1024" autocomplete="off" spellcheck="false" placeholder="输入用于解锁私钥的口令" /><small id="host-passphrase-hint">保存时会加密写入面板数据库,供重启后自动连接和后台持续采样;面板不会回显口令或写入浏览器存储。</small></div>
</div>
</form>
</section>
<div class="host-side-stack">
<section class="host-card" aria-labelledby="host-fingerprint-title">
<div class="host-card-heading"><span class="host-card-number">2</span><div><h2 id="host-fingerprint-title">核对 SSH 主机指纹</h2><p>先扫描面板看到的公钥,再与宿主机控制台显示的指纹对比。</p></div></div>
<button id="host-scan-button" class="button button-outline" type="button">扫描主机指纹</button>
<div id="host-fingerprint-result" class="fingerprint-result" hidden><span>扫描到的指纹 · <span id="host-key-type"></span></span><code id="host-fingerprint"></code></div>
<p class="host-security-note">请在宿主机 B 的控制台执行 <code>ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub</code> 并逐字核对。当前仅支持 Ed25519 主机密钥;不要仅凭网页显示就信任该指纹。</p>
<label id="host-confirm-row" class="checkbox-row host-confirm" hidden><input id="host-fingerprint-confirm" type="checkbox" /><span><strong>我已通过宿主机控制台独立核对,指纹完全一致</strong><small>主机密钥变更时需要重新核对。</small></span></label>
</section>
<section class="host-card" aria-labelledby="host-connect-title">
<div class="host-card-heading"><span class="host-card-number">3</span><div><h2 id="host-connect-title">测试并保存</h2><p>测试 root SSH、libvirt、存储池和虚拟网络是否可用。</p></div></div>
<p id="host-test-status" class="host-test-status" role="status">尚未测试连接</p>
<p id="host-error" class="form-error" role="alert" hidden></p>
<div class="host-submit-actions"><button id="host-test-button" class="button button-outline" type="button">测试连接</button><button id="host-save-button" class="button button-primary" type="submit" form="host-form">保存并进入面板</button></div>
<p class="host-security-note">root 私钥拥有很高权限。请保护面板管理员密码,仅通过 HTTPS 访问面板,并限制能访问面板的网络范围。</p>
</section>
</div>
</div>
</div>
</main>
<main id="unlock-view" class="host-layout" hidden>
<header class="host-topbar">
<div class="host-brand"><span class="brand-mark"><span></span></span> VirtPilot</div>
<div class="host-topbar-actions"><span id="unlock-current-user" class="host-user"></span><button id="unlock-logout-button" class="button button-ghost small" type="button">退出登录</button></div>
</header>
<div class="unlock-content">
<section class="host-card unlock-card" aria-labelledby="unlock-title">
<span class="eyebrow">HOST KEY LOCKED</span>
<h1 id="unlock-title">解锁宿主机 SSH 私钥</h1>
<p class="muted">宿主机 <strong id="unlock-host-label"></strong> 的私钥尚未自动解锁。请输入口令以恢复连接;若要重启后自动连接,请随后在“宿主机设置”中重新保存口令。</p>
<form id="unlock-form" class="form-stack">
<label for="unlock-passphrase">私钥口令</label>
<input id="unlock-passphrase" type="password" maxlength="1024" autocomplete="off" spellcheck="false" required autofocus placeholder="输入现有私钥口令" />
<p id="unlock-error" class="form-error" role="alert" hidden></p>
<button id="unlock-submit" class="button button-primary unlock-submit" type="submit">解锁并进入面板</button>
</form>
<p class="host-security-note">在这里输入只用于本次解锁;在“宿主机设置”重新保存后,口令会加密写入数据库供后台使用。面板不会将口令写入浏览器存储;请通过 HTTPS 连接面板。</p>
<button id="unlock-settings-button" class="button button-ghost small unlock-settings-button" type="button">修改宿主机设置</button>
<button id="unlock-update-button" class="button button-ghost small unlock-settings-button" type="button">网站更新</button>
</section>
</div>
</main>
<div id="dashboard-view" class="dashboard" hidden>
<aside class="sidebar">
<div class="sidebar-brand"><span class="brand-mark"><span></span></span><span>VirtPilot<small>CONTROL PANEL</small></span></div>
<div class="sidebar-section-label">工作区</div>
<button id="vm-navigation-button" class="sidebar-link sidebar-button active" type="button" aria-current="page"><span class="nav-icon" aria-hidden="true">▦</span> 虚拟机 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="ssh-keys-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">⌑</span> 公钥管理 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="template-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">◈</span> 云镜像模板 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="rescue-templates-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">✚</span> 救援模版 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="host-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">⌁</span> 宿主机设置 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="update-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">↻</span> 网站更新 <span class="nav-arrow" aria-hidden="true">›</span></button>
<button id="smtp-settings-button" class="sidebar-link sidebar-button" type="button"><span class="nav-icon" aria-hidden="true">✉</span> 邮件与用户 <span class="nav-arrow" aria-hidden="true">›</span></button>
<div class="sidebar-bottom">
<div class="host-panel"><div class="host-panel-icon" aria-hidden="true">⌁</div><div><strong>远端宿主机</strong><span id="host-connection-label">连接中…</span></div><span id="host-connection-dot" class="connection-dot"></span></div>
<div class="sidebar-caption">Powered by libvirt</div>
</div>
</aside>
<div class="main-area">
<header class="topbar">
<div class="breadcrumb">工作区 <span>/</span> <strong id="breadcrumb-current">虚拟机</strong></div>
<div class="topbar-right"><details id="admin-menu" class="admin-menu"><summary>菜单 <span aria-hidden="true">▾</span></summary><div class="admin-menu-options"><button id="vm-navigation-mobile-button" class="button button-ghost small" type="button">虚拟机</button><button id="ssh-keys-mobile-button" class="button button-ghost small" type="button">公钥管理</button><button id="template-settings-mobile-button" class="button button-ghost small" type="button">云镜像模板</button><button id="rescue-templates-mobile-button" class="button button-ghost small" type="button">救援模版</button><button id="host-settings-mobile-button" class="button button-ghost small" type="button">宿主机设置</button><button id="update-settings-mobile-button" class="button button-ghost small" type="button">网站更新</button><button id="smtp-settings-mobile-button" class="button button-ghost small" type="button">邮件与用户</button></div></details><span class="topbar-user"><span class="avatar" aria-hidden="true">A</span><span id="current-username">用户</span></span><button id="logout-button" class="button button-ghost small" type="button">退出登录</button></div>
</header>
<main class="content">
<div id="vm-workspace">
<div id="vm-list-view">
<div class="page-heading"><div><span class="eyebrow">VIRTUAL MACHINES</span><h1 id="vm-list-title" tabindex="-1">虚拟机管理</h1><p>查看虚拟机信息;点击名称进入管理页面执行操作。</p></div><div class="heading-actions"><button id="refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button><button id="create-button" class="button button-primary" type="button"><span aria-hidden="true">+</span> 创建虚拟机</button></div></div>
<div id="resource-warning" class="resource-warning" role="alert" hidden></div>
<div class="overview-grid" aria-label="虚拟机概览">
<section class="stat-card"><div class="stat-top"><span>虚拟机总数</span><span class="stat-icon total" aria-hidden="true">▦</span></div><strong id="stat-total">—</strong><small>当前宿主机</small></section>
<section class="stat-card"><div class="stat-top"><span>运行中</span><span class="stat-icon running" aria-hidden="true">▶</span></div><strong id="stat-running">—</strong><small><span class="tiny-dot green"></span> 正在提供服务</small></section>
<section class="stat-card"><div class="stat-top"><span>已关机</span><span class="stat-icon stopped" aria-hidden="true">⏻</span></div><strong id="stat-stopped">—</strong><small>可随时启动</small></section>
</div>
<section class="inventory-panel" aria-labelledby="inventory-title">
<div class="panel-heading"><div><h2 id="inventory-title">虚拟机列表</h2><p id="inventory-count">正在加载…</p></div><div class="panel-tools"><label class="search-box"><span aria-hidden="true">⌕</span><span class="sr-only">搜索虚拟机</span><input id="search-input" type="search" placeholder="搜索名称、地区、系统或 IP" /></label><select id="state-filter" aria-label="按状态筛选"><option value="all">全部状态</option><option value="running">运行中</option><option value="stopped">已关机</option><option value="other">其他状态</option></select></div></div>
<div class="table-scroll"><table class="vm-table"><thead><tr><th>虚拟机</th><th>状态</th><th>地区</th><th>系统 / 安装镜像</th><th>已配置公网 IP</th><th>规格</th><th>磁盘</th></tr></thead><tbody id="vm-table-body"></tbody></table></div>
<div id="empty-state" class="empty-state" hidden><div class="empty-icon" aria-hidden="true">▦</div><h3 id="empty-title">还没有虚拟机</h3><p id="empty-description">点击右上角“创建虚拟机”开始。</p></div>
</section>
<div class="footer-note">状态每 15 秒自动更新 · 操作会发送至远端 libvirt 宿主机</div>
</div>
<section id="vm-detail-view" class="vm-detail-view" aria-labelledby="vm-detail-name" hidden>
<button id="vm-detail-back-button" class="button button-ghost vm-detail-back" type="button">← 返回虚拟机列表</button>
<div class="page-heading vm-detail-heading"><div><span class="eyebrow">VIRTUAL MACHINE DETAILS</span><h1 id="vm-detail-name" tabindex="-1">虚拟机</h1><p class="vm-detail-summary"><span><span class="sr-only">服务器 IP:</span><strong id="vm-detail-header-ip">未获取</strong></span><span><span class="sr-only">区域:</span><strong id="vm-detail-header-region">未设置</strong></span><span><strong id="vm-detail-header-created-at">未记录</strong></span></p></div><div class="heading-actions"><span id="vm-detail-state" class="state-pill other">未知</span><button id="vm-detail-refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button></div></div>
<div class="vm-detail-grid">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-info-title"><div class="panel-heading"><div><h2 id="vm-detail-info-title">虚拟机信息</h2><p>状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。</p></div></div><dl class="vm-detail-facts">
<div><dt>地区</dt><dd id="vm-detail-region">未设置</dd></div><div><dt id="vm-detail-os-label">系统</dt><dd id="vm-detail-os">未识别</dd></div>
<div><dt>已配置公网 IP</dt><dd class="vm-detail-inline"><span id="vm-detail-ip">未获取</span><button id="vm-detail-ip-copy" class="vm-copy-icon" type="button" aria-label="复制公网 IP" title="复制公网 IP" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button></dd></div><div><dt>计算规格</dt><dd id="vm-detail-spec">—</dd></div>
<div><dt>硬盘大小</dt><dd id="vm-detail-disk">—</dd></div>
<div><dt>SSH 登录名</dt><dd id="vm-detail-ssh-user">未记录</dd></div>
<div class="vm-detail-credential-row"><dt>面板记录的初始 root 密码</dt><dd class="vm-detail-inline"><code id="vm-detail-root-password" class="vm-detail-secret">未记录</code>
<button id="vm-detail-password-reveal" class="vm-copy-icon vm-credential-icon" type="button" aria-label="查看初始 root 密码" title="查看初始 root 密码" aria-controls="vm-detail-root-password" aria-pressed="false" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2.3 12S5.8 6.5 12 6.5s9.7 5.5 9.7 5.5-3.5 5.5-9.7 5.5S2.3 12 2.3 12Z"/><circle cx="12" cy="12" r="2.6"/><path class="vm-eye-slash" d="M3 3 21 21"/></svg></button>
<button id="vm-detail-password-copy" class="vm-copy-icon vm-credential-icon" type="button" aria-label="复制初始 root 密码" title="复制初始 root 密码" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button>
</dd></div>
</dl></section>
<div class="vm-detail-operations"><section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"></div></section></div>
</div>
<section class="vm-metrics" aria-labelledby="vm-metrics-title">
<div class="vm-metrics-heading"><div><span class="eyebrow">PERFORMANCE HISTORY</span><h2 id="vm-metrics-title">性能监控</h2><p>每分钟采样并自动刷新,历史数据最长保留 30 天;长时间范围会聚合,较长的采样缺口留空。</p></div><label class="vm-metrics-range-control" for="vm-metrics-range">时间范围 <select id="vm-metrics-range"><option value="1h">最近 1 小时</option><option value="24h" selected>最近 24 小时</option><option value="7d">最近 7 天</option><option value="30d">最近 30 天</option></select></label></div>
<p id="vm-metrics-status" class="vm-metrics-status" role="status">选择虚拟机后加载监控数据。</p>
<div class="vm-metrics-grid">
<section class="vm-metric-card" aria-labelledby="vm-metric-cpu-title"><div class="vm-metric-card-heading"><span class="vm-metric-icon cpu" aria-hidden="true">◴</span><div><h3 id="vm-metric-cpu-title">CPU 使用率</h3><p id="vm-metric-cpu-summary">—</p></div></div><div id="vm-metric-cpu-plot" class="vm-metric-plot"></div><div class="vm-metric-legend"><span><i class="vm-metric-swatch cpu"></i>使用率</span></div></section>
<section class="vm-metric-card" aria-labelledby="vm-metric-memory-title"><div class="vm-metric-card-heading"><span class="vm-metric-icon memory" aria-hidden="true">▤</span><div><h3 id="vm-metric-memory-title">内存用量</h3><p id="vm-metric-memory-summary">—</p></div></div><div id="vm-metric-memory-plot" class="vm-metric-plot"></div><div class="vm-metric-legend"><span><i class="vm-metric-swatch memory"></i>已使用(估算)</span><span><i class="vm-metric-swatch memory-total"></i>总量</span></div></section>
<section class="vm-metric-card" aria-labelledby="vm-metric-disk-title"><div class="vm-metric-card-heading"><span class="vm-metric-icon disk" aria-hidden="true">▥</span><div><h3 id="vm-metric-disk-title">磁盘 I/O</h3><p id="vm-metric-disk-summary">—</p></div></div><div id="vm-metric-disk-plot" class="vm-metric-plot"></div><div class="vm-metric-legend"><span><i class="vm-metric-swatch disk-read"></i>读取</span><span><i class="vm-metric-swatch disk-write"></i>写入</span></div></section>
<section class="vm-metric-card" aria-labelledby="vm-metric-network-title"><div class="vm-metric-card-heading"><span class="vm-metric-icon network" aria-hidden="true">⇄</span><div><h3 id="vm-metric-network-title">网络速率</h3><p id="vm-metric-network-summary">—</p></div></div><div id="vm-metric-network-plot" class="vm-metric-plot"></div><div class="vm-metric-legend"><span><i class="vm-metric-swatch network-rx"></i>接收</span><span><i class="vm-metric-swatch network-tx"></i>发送</span></div></section>
</div>
<p class="vm-metrics-footnote">磁盘 I/O 为每秒读写量,仅统计 libvirt 提供计数的设备;网络收发为虚拟机视角的每秒速率,不代表套餐带宽上限。内存已用量为估算值,取决于虚拟机是否提供气球驱动统计。</p>
</section>
</section>
<section id="create-view" class="workspace-form-page" aria-labelledby="create-title" hidden>
<button id="create-back" class="button button-ghost workspace-form-back" type="button">← 返回虚拟机列表</button>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow">NEW VIRTUAL MACHINE</span><h1 id="create-title" tabindex="-1">创建虚拟机</h1><p>选择 ISO 安装,或从云镜像模板直接创建系统。</p></div></div>
<form id="create-form" class="inventory-panel workspace-form-card">
<div class="workspace-form-body">
<fieldset class="create-source-picker"><legend>系统来源</legend><label><input type="radio" name="source" value="iso" checked /><span><strong>ISO 安装</strong><small>通过 VNC 安装系统</small></span></label><label><input type="radio" name="source" value="cloud" /><span><strong>公网云镜像</strong><small>自动或手动配置公网 IP 后直接开机</small></span></label></fieldset>
<div class="form-grid">
<div class="field full"><label for="vm-name">名称 <span>*</span></label><input id="vm-name" name="name" type="text" required minlength="1" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" placeholder="例如 web-prod-01" /><small>使用英文字母、数字、点、下划线或连字符。</small></div>
<div class="field"><label for="vm-vcpu">vCPU <span>*</span></label><div class="input-suffix"><input id="vm-vcpu" name="vcpu" type="number" min="1" max="64" value="2" required /><span>核</span></div></div>
<div class="field"><label for="vm-memory">内存 <span>*</span></label><div class="input-suffix"><input id="vm-memory" name="memory_mib" type="number" min="512" max="262144" step="1" value="2048" required /><span>MiB</span></div></div>
<div class="field"><label for="vm-disk">系统盘 <span>*</span></label><div class="input-suffix"><input id="vm-disk" name="disk_gib" type="number" min="1" max="4096" value="20" required /><span>GiB</span></div></div>
<div class="field"><label for="vm-network">虚拟网络或网桥 <span>*</span></label><select id="vm-network" name="network" required><option value="">正在加载网络…</option></select></div>
<div class="field full" id="vm-iso-field"><label for="vm-iso">安装 ISO <span>*</span></label><select id="vm-iso" name="iso" required><option value="">正在加载镜像…</option></select><small>镜像来自宿主机允许使用的 ISO 目录。</small></div>
<div class="field full" id="vm-template-field" hidden><span id="vm-template-label" class="template-field-label">系统镜像 <span>*</span></span><input id="vm-template" name="template_id" type="hidden" value="" disabled /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="vm-template-label" aria-describedby="vm-template-hint" aria-required="true"></div><small id="vm-template-hint">点击系统图标下方的箭头展开版本,再选择已导入的镜像;模板需支持 cloud-init。</small></div>
<div class="cloud-fields full" id="vm-cloud-fields" hidden>
<div class="cloud-fields-heading"><strong>公网网络配置</strong><small>仅支持已配置的 Linux 网桥,例如 bridge:br0;上游网络还需允许虚拟机的 MAC 地址。</small></div>
<div id="vm-auto-public-pool" class="vm-auto-public-pool" role="status" hidden><strong>自动分配公网 IP</strong><span id="vm-auto-public-pool-description">创建时将从宿主机地址池中选择未使用的 IP,并自动写入网关和 DNS。</span></div>
<div class="form-grid" id="vm-manual-public-network">
<div class="field"><label for="vm-public-ip-cidr">公网 IPv4/CIDR <span>*</span></label><input id="vm-public-ip-cidr" name="public_ip_cidr" type="text" maxlength="18" inputmode="decimal" autocomplete="off" placeholder="填写服务商分配的公网 IP/28" disabled /><small>填写具体 IP 和前缀长度,不是网段地址。</small></div>
<div class="field"><label for="vm-gateway">同网段网关 IPv4 <span>*</span></label><input id="vm-gateway" name="gateway" type="text" maxlength="15" inputmode="decimal" autocomplete="off" placeholder="填写服务商提供的网关" disabled /></div>
<div class="field full"><label for="vm-dns">DNS IPv4 <span>*</span></label><input id="vm-dns" name="dns_servers" type="text" maxlength="128" autocomplete="off" placeholder="例如 1.1.1.1, 8.8.8.8" disabled /><small>多个地址用逗号或空格分隔。</small></div>
</div>
<div class="form-grid vm-cloud-auth-fields">
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="创建虚拟机时选择 SSH 公钥"></div><small>只显示你在“公钥管理”中添加的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><button id="vm-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="vm-root-password-hint" placeholder="可自行设置,留空时自动生成强密码" disabled /><small id="vm-root-password-hint" aria-live="polite">留空时自动生成强密码,即使选择了 SSH 公钥;自行设置需至少 12 个字符,包含大写字母、小写字母和符号。</small></div>
</div>
</div>
</div><div id="create-iso-tip" class="form-tip"><span aria-hidden="true">ⓘ</span><p>创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。</p></div><div id="create-cloud-tip" class="form-tip" hidden><span aria-hidden="true">ⓘ</span><p>云镜像首次启动由 cloud-init 写入静态 IP、DNS 和 root 登录凭据,无需 VNC 安装。可同时使用已保存的 SSH 公钥和 root 密码;密码留空时,即使选择了公钥也会自动生成强密码。初始密码可在虚拟机详情页查看。</p></div><p id="create-error" class="form-error" role="alert" hidden></p></div>
<div class="workspace-form-actions"><button id="create-submit" class="button button-primary" type="submit">创建并启动</button></div>
</form>
</section>
<section id="reinstall-view" class="workspace-form-page" aria-labelledby="reinstall-title" hidden>
<button id="reinstall-back" class="button button-ghost workspace-form-back" type="button">← 返回虚拟机详情</button>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow danger-text">REINSTALL SYSTEM</span><h1 id="reinstall-title" tabindex="-1">重装云镜像系统</h1><p id="reinstall-subtitle">保留原有公网网络参数,重新创建系统盘。</p></div></div>
<form id="reinstall-form" class="inventory-panel workspace-form-card">
<div class="workspace-form-body">
<div id="reinstall-fields">
<p class="reinstall-warning"><strong>重装将永久清除原系统盘中的全部数据。</strong>面板会先请求虚拟机正常关机;若关机超时,重装会停止,不会强制断电。libvirt/QEMU 报告虚拟机已从新盘启动后,原系统盘将自动删除。这个“启动”不保证客户机系统、网络或 SSH 已经可用,请确认模板和网络配置。</p>
<p class="reinstall-network">沿用首次创建的公网网络信息:<strong id="reinstall-public-ip"></strong>。网桥、MAC、网关和 DNS 也会保持原配置。</p>
<div class="form-grid">
<div class="field full"><span id="reinstall-template-label" class="template-field-label">重装镜像 <span>*</span></span><input id="reinstall-template" name="template_id" type="hidden" value="" /><div id="reinstall-template-catalog" class="template-catalog" role="group" aria-labelledby="reinstall-template-label" aria-describedby="reinstall-template-hint" aria-required="true"></div><small id="reinstall-template-hint">点击系统图标下方的箭头展开版本,选择当前宿主机已导入的云镜像。</small></div>
<div class="field full"><span class="ssh-key-picker-title">SSH 公钥(可选)</span><div id="reinstall-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="重装系统时选择 SSH 公钥"></div><small>直接选择“公钥管理”中保存的公钥;再次点击已选公钥可取消。填写密码时可与公钥同时使用。</small><button id="reinstall-open-ssh-keys" class="ssh-key-picker-manage" type="button">管理我的公钥</button></div>
<div class="field full" id="reinstall-root-password-field"><label for="reinstall-root-password">初始 root 密码(可选)</label><input id="reinstall-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="reinstall-root-password-hint" placeholder="可自行设置,留空时按公钥选择决定" /><small id="reinstall-root-password-hint" aria-live="polite">不选公钥且留空时自动生成强密码;自行设置需至少 12 个字符,包含大写字母、小写字母和符号。</small></div>
<div class="field full"><label for="reinstall-confirm-name">输入虚拟机名称以确认删除旧系统盘 <span>*</span></label><input id="reinstall-confirm-name" name="confirmation_name" type="text" required autocomplete="off" spellcheck="false" placeholder="请输入完整的虚拟机名称" /><small id="reinstall-confirm-hint"></small></div>
</div>
</div>
<div id="reinstall-progress" class="reinstall-progress" role="status" aria-live="polite" hidden><span class="console-spinner" aria-hidden="true"></span><div><strong>正在重装,请保持此页面打开</strong><p id="reinstall-phase">准备重装任务…</p><small>刷新此标签页后会自动恢复任务;如有初始密码,将加密保存在面板数据库中。</small></div></div>
<div id="reinstall-result" class="reinstall-result" role="status" aria-live="polite" hidden><h3 id="reinstall-result-title"></h3><p id="reinstall-result-message"></p><div id="reinstall-password-box" class="reinstall-password-box" hidden><span>新系统的 root 初始密码</span><div><code id="reinstall-generated-password"></code><button id="reinstall-copy-password" class="button button-outline small" type="button">复制</button></div><small>请先保存到安全位置,再点击“已保存密码,完成”。页面中的明文届时会清除,面板记录的初始密码仍可在虚拟机详情页按需查看。</small></div><p id="reinstall-result-warning" class="reinstall-result-warning" hidden></p></div>
<p id="reinstall-error" class="form-error" role="alert" hidden></p>
</div>
<div class="workspace-form-actions"><button id="reinstall-cancel" class="button button-outline" type="button">取消</button><button id="reinstall-submit" class="button button-danger" type="submit">确认重装并删除旧盘</button><button id="reinstall-forget" class="button button-outline" type="button" hidden>放弃恢复任务</button><button id="reinstall-retry" class="button button-outline" type="button" hidden>重新查询任务</button><button id="reinstall-done" class="button button-primary" type="button" hidden>完成</button></div>
</form>
</section>
<section id="rescue-view" class="workspace-form-page" aria-labelledby="rescue-title" hidden>
<button id="rescue-back" class="button button-ghost workspace-form-back" type="button">← 返回虚拟机详情</button>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow danger-text">EMERGENCY RESCUE</span><h1 id="rescue-title" tabindex="-1">紧急救援</h1><p id="rescue-subtitle">选择救援 ISO 并启动救援环境。</p></div></div>
<section class="inventory-panel workspace-form-card" aria-labelledby="rescue-status-title">
<div class="workspace-form-body">
<h2 id="rescue-status-title">当前救援状态</h2><p id="rescue-status" class="rescue-status" role="status" aria-live="polite">正在检查虚拟机状态…</p>
<p class="reinstall-warning"><strong>救援操作会中断服务。</strong>面板先将救援 ISO 预挂载为下一次完整开机的启动介质,再请求正常关机并开机。若正常关机失败或超时,只有救援页显示“已预挂载”时,才能确认风险后点击“强制重启进入救援”:这会强制断电并冷启动,可能丢失未保存数据。也可返回详情页,手动“强制断电”后再“开机”。若预挂载未成功,请先核查错误,切勿直接强制重启。普通“强制重置”不保证读取新保存的启动配置。退出救援会卸载 ISO 并恢复原系统启动;若退出时关机超时,可通过救援系统的 VNC 控制台手动关机,待显示“已关机”后重试退出。面板不会自动强制断电,也不会删除或格式化原系统盘。</p>
<p class="rescue-login-note">救援系统的登录方式和密码由该 ISO 自身决定;面板不会注入原虚拟机的 root 密码或 SSH 公钥。通常请先通过 VNC 控制台操作。</p>
<form id="rescue-form" class="form-stack">
<span id="rescue-template-label" class="template-field-label">救援模版 <span>*</span></span><input id="rescue-template-id" type="hidden" value="" /><div id="rescue-template-cards" class="rescue-template-cards" role="group" aria-labelledby="rescue-template-label"></div>
<label for="rescue-confirm-name">输入虚拟机名称确认 <span>*</span></label><input id="rescue-confirm-name" type="text" required autocomplete="off" spellcheck="false" placeholder="请输入完整的虚拟机名称" /><small id="rescue-confirm-hint"></small>
<p id="rescue-error" class="form-error" role="alert" hidden></p>
<div class="rescue-actions"><button id="rescue-submit" class="button button-danger" type="submit">加载救援镜像并重启</button><button id="rescue-force-start" class="button button-danger" type="button" hidden>强制重启进入救援</button><button id="rescue-exit" class="button button-outline" type="button" hidden>退出救援并重启原系统</button></div>
</form>
</div>
</section>
</section>
</div>
<div id="ssh-keys-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">ACCOUNT SSH KEYS</span><h1>公钥管理</h1><p>保存自己的 SSH 公钥,创建云镜像虚拟机时直接选择。每个用户只能管理自己的公钥。</p></div><button id="ssh-keys-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="ssh-keys-grid">
<section class="host-card" aria-labelledby="ssh-key-add-title">
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="ssh-key-add-title">导入公钥</h2><p>仅粘贴单行 OpenSSH 公钥;不要上传私钥或填写私钥口令。</p></div></div>
<form id="ssh-key-form" class="form-stack">
<label for="ssh-key-name">公钥名称</label><input id="ssh-key-name" type="text" maxlength="80" required autocomplete="off" placeholder="例如 我的电脑" />
<label for="ssh-key-public-key">OpenSSH 公钥</label><textarea id="ssh-key-public-key" maxlength="16384" rows="5" required spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="ssh-ed25519 AAAA…"></textarea>
<label for="ssh-key-file">或选择本地 .pub 文件</label><input id="ssh-key-file" type="file" accept=".pub,text/plain" aria-describedby="ssh-key-file-hint" /><small id="ssh-key-file-hint" class="ssh-key-file-hint">仅在浏览器读取文件内容;不会上传私钥文件。</small>
<p id="ssh-key-form-error" class="form-error" role="alert" hidden></p>
<button id="ssh-key-save-button" class="button button-primary" type="submit">保存公钥</button>
</form>
</section>
<section class="host-card" aria-labelledby="ssh-key-list-title">
<div class="host-card-heading"><span class="host-card-number">⌑</span><div><h2 id="ssh-key-list-title">我的公钥</h2><p>公钥不会向其他用户显示;删除后,不影响已经创建的虚拟机。</p></div></div>
<p id="ssh-keys-list-error" class="form-error" role="alert" hidden></p>
<div id="ssh-keys-list" class="ssh-keys-list" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>
</div>
</div>
<div id="template-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">CLOUD IMAGE CATALOG</span><h1>云镜像模板</h1><p>仅管理员可以导入官方云镜像和修改模板名称;用户创建虚拟机时选择已导入的版本。</p></div><button id="template-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="template-admin-grid">
<section class="host-card" aria-labelledby="template-import-title">
<div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="template-import-title">导入云镜像</h2><p>从 AlmaLinux 官方仓库下载,校验 SHA-256 后导入当前宿主机。</p></div></div>
<form id="template-import-form" class="form-stack" novalidate>
<label for="template-name">模板名称</label><input id="template-name" type="text" maxlength="64" required autocomplete="off" placeholder="例如 AlmaLinux 10 Cloud" />
<label for="template-url">云镜像下载地址</label><input id="template-url" type="url" inputmode="url" maxlength="2048" required autocomplete="off" placeholder="粘贴官方 GenericCloud qcow2 完整 HTTPS 地址" /><small class="template-field-help">支持 repo.almalinux.org 的 AlmaLinux 9 / 10 x86_64 GenericCloud qcow2 镜像。</small>
<label for="template-sha256">镜像 SHA-256 校验值</label><input id="template-sha256" type="text" maxlength="64" minlength="64" required spellcheck="false" autocomplete="off" placeholder="64 位十六进制校验值" /><small class="template-field-help">从镜像发布方核对;面板下载后会校验文件。</small>
<p id="template-import-status" class="template-import-status" role="status" hidden></p><p id="template-import-error" class="form-error" role="alert" hidden></p><button id="template-import-button" class="button button-primary" type="submit">导入模板</button>
</form>
</section>
<section class="host-card" aria-labelledby="template-list-title">
<div class="host-card-heading"><span class="host-card-number">◈</span><div><h2 id="template-list-title">已导入模板</h2><p>修改名称不会改变镜像文件或已创建虚拟机的系统。</p></div></div>
<p id="template-list-error" class="form-error" role="alert" hidden></p>
<div id="template-admin-list" class="template-admin-list" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>
</div>
</div>
<div id="rescue-templates-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">RESCUE IMAGE CATALOG</span><h1>救援模版</h1><p>仅管理员上传救援 ISO;虚拟机所有者可在详情页选择已导入的镜像。</p></div><button id="rescue-templates-back" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="template-admin-grid">
<section class="host-card" aria-labelledby="rescue-template-upload-title"><div class="host-card-heading"><span class="host-card-number">+</span><div><h2 id="rescue-template-upload-title">上传救援 ISO</h2><p>文件将上传到面板并导入宿主机单独配置的救援 ISO 目录,不会出现在创建虚拟机的安装 ISO 列表中;上传期间请保持页面打开。</p></div></div>
<p id="rescue-directory-note" class="rescue-directory-note" role="status" hidden></p>
<form id="rescue-template-upload-form" class="form-stack" novalidate>
<label for="rescue-template-name">模版名称</label><input id="rescue-template-name" type="text" maxlength="64" required autocomplete="off" placeholder="例如 AlmaLinux Rescue" />
<label for="rescue-template-file">救援 ISO 文件</label><input id="rescue-template-file" type="file" accept=".iso,application/x-iso9660-image,application/octet-stream" required /><small class="template-field-help">只接受 ISO;文件最大 8 GiB。请确认来源可信、启动模式兼容目标 VM 的 BIOS/UEFI,并保证宿主机有足够空间。</small>
<p id="rescue-template-upload-status" class="template-import-status" role="status" hidden></p><p id="rescue-template-upload-error" class="form-error" role="alert" hidden></p><button id="rescue-template-upload-button" class="button button-primary" type="submit">上传并导入</button>
</form>
</section>
<section class="host-card" aria-labelledby="rescue-template-list-title"><div class="host-card-heading"><span class="host-card-number">✚</span><div><h2 id="rescue-template-list-title">已上传模版</h2><p>删除模版前,请确认没有虚拟机正在使用。</p></div></div><p id="rescue-template-list-error" class="form-error" role="alert" hidden></p><div id="rescue-template-list" class="template-admin-list" aria-live="polite"><p class="muted">正在加载…</p></div></section>
</div>
</div>
<div id="update-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">PANEL UPDATE</span><h1>网站更新</h1><p>从当前项目的私有 Gitea 仓库检查并安装新版本。</p></div><button id="update-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<div class="update-grid">
<section class="host-card" aria-labelledby="update-repository-title">
<div class="host-card-heading"><span class="host-card-number">1</span><div><h2 id="update-repository-title">更新来源</h2><p>这一版固定使用当前项目仓库的 main 分支;只需设置私有仓库访问令牌。</p></div></div>
<form id="update-settings-form" class="form-stack">
<label for="update-repository-url">仓库地址</label>
<input id="update-repository-url" type="url" value="https://g.luoli.live/root/virt.git" readonly aria-readonly="true" />
<label for="update-branch">更新分支</label>
<input id="update-branch" type="text" value="main" readonly aria-readonly="true" />
<label for="update-access-token">Gitea 访问令牌</label>
<input id="update-access-token" type="password" autocomplete="off" maxlength="4096" placeholder="填写具有仓库读取权限的令牌" />
<small id="update-token-hint" class="field-hint">令牌需要仓库读取权限。保存后不会回显,也不会写入浏览器存储。</small>
<p id="update-settings-error" class="form-error" role="alert" hidden></p>
<button id="update-settings-submit" class="button button-primary" type="submit">保存访问令牌</button>
</form>
</section>
<section class="host-card" aria-labelledby="update-run-title">
<div class="host-card-heading"><span class="host-card-number">2</span><div><h2 id="update-run-title">检查并更新</h2><p>先检查可用版本,确认后再执行更新。</p></div></div>
<div class="update-versions"><div><span>当前版本</span><strong id="update-current-version">—</strong></div><div><span>仓库版本</span><strong id="update-latest-version">—</strong></div></div>
<p id="update-status" class="host-test-status" role="status">尚未检查更新。</p>
<p id="update-action-error" class="form-error" role="alert" hidden></p>
<div class="host-submit-actions"><button id="update-check-button" class="button button-outline" type="button">检查更新</button><button id="update-apply-button" class="button button-primary" type="button" disabled>一键更新</button></div>
<p class="host-security-note">更新可能短暂中断面板服务。请先备份数据库及面板数据目录,并确保有服务端控制台可用于恢复。</p>
</section>
</div>
</div>
<div id="smtp-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">ADMIN SETTINGS</span><h1>邮件与用户审核</h1><p>配置注册验证码的 SMTP 发信服务器,并审核新注册用户。</p></div><button id="smtp-back-button" class="button button-outline" type="button">返回虚拟机</button></div>
<section class="host-card smtp-card" aria-labelledby="smtp-title">
<div class="host-card-heading"><span class="host-card-number">✉</span><div><h2 id="smtp-title">SMTP 连接信息</h2><p>凭据在服务端加密保存;已保存密码不会在页面回显。</p></div></div>
<form id="smtp-settings-form" class="form-grid">
<div class="field"><label for="smtp-host">SMTP 服务器 <span>*</span></label><input id="smtp-host" type="text" autocomplete="off" maxlength="253" required placeholder="例如 smtp.example.com" /></div>
<div class="field"><label for="smtp-port">端口 <span>*</span></label><input id="smtp-port" type="number" min="1" max="65535" value="465" required /></div>
<div class="field"><label for="smtp-tls-mode">加密方式 <span>*</span></label><select id="smtp-tls-mode" required><option value="ssl">SSL / TLS</option><option value="starttls">STARTTLS</option><option value="none">无加密</option></select></div>
<div class="field"><label for="smtp-username">SMTP 用户名</label><input id="smtp-username" type="text" autocomplete="off" maxlength="254" placeholder="发信账号" /></div>
<div class="field full"><label for="smtp-password">SMTP 密码</label><input id="smtp-password" type="password" autocomplete="new-password" maxlength="1024" placeholder="填写 SMTP 密码或应用专用密码" /><small id="smtp-password-hint">保存后不会回显,也不会写入浏览器存储。</small></div>
<div class="field full"><label for="smtp-from-address">发件人邮箱 <span>*</span></label><input id="smtp-from-address" type="email" autocomplete="off" maxlength="254" required placeholder="例如 noreply@example.com" /></div>
<p id="smtp-error" class="form-error full" role="alert" hidden></p>
<p id="smtp-status" class="smtp-status full" role="status" hidden></p>
<div class="field full"><button id="smtp-save-button" class="button button-primary" type="submit">保存邮件设置</button></div>
</form>
</section>
<section class="host-card smtp-card" aria-labelledby="pending-users-title">
<div class="host-card-heading"><span class="host-card-number">✓</span><div><h2 id="pending-users-title">待审核用户</h2><p>邮箱已验证的用户仍需管理员审核,审核通过后才能使用虚拟机功能。</p></div></div>
<p id="pending-users-error" class="form-error" role="alert" hidden></p>
<div id="pending-users-list" class="pending-users-list" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>
</div>
</main>
</div>
</div>
<div id="delete-modal" class="modal-backdrop" hidden>
<section class="modal narrow-modal" role="dialog" aria-modal="true" aria-labelledby="delete-title">
<div class="modal-header"><div><span class="eyebrow danger-text">DESTRUCTIVE ACTION</span><h2 id="delete-title">删除虚拟机</h2></div><button class="icon-button" type="button" data-close-modal aria-label="关闭">×</button></div>
<form id="delete-form"><div class="modal-body"><p class="delete-copy">确定删除 <strong id="delete-vm-name"></strong> 吗?虚拟机定义将被移除,此操作不可撤销。</p><label class="checkbox-row"><input id="delete-disks" type="checkbox" /><span><strong>同时删除虚拟磁盘</strong><small>勾选后,磁盘数据也会永久删除。</small></span></label><p id="delete-error" class="form-error" role="alert" hidden></p></div><div class="modal-footer"><button class="button button-outline" type="button" data-close-modal>取消</button><button id="delete-submit" class="button button-danger" type="submit">确认删除</button></div></form>
</section>
</div>
<div id="confirm-modal" class="modal-backdrop" hidden>
<section class="modal narrow-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title"><div class="modal-header"><div><span class="eyebrow danger-text">POWER ACTION</span><h2 id="confirm-title">确认操作</h2></div><button class="icon-button" type="button" data-close-modal aria-label="关闭">×</button></div><div class="modal-body"><p id="confirm-message" class="delete-copy"></p><p id="confirm-error" class="form-error" role="alert" hidden></p></div><div class="modal-footer"><button class="button button-outline" type="button" data-close-modal>取消</button><button id="confirm-submit" class="button button-danger" type="button">确认操作</button></div></section>
</div>
<div id="console-modal" class="modal-backdrop console-backdrop" hidden>
<section class="modal console-modal" role="dialog" aria-modal="true" aria-labelledby="console-title"><div class="console-toolbar"><div><span class="eyebrow">VNC CONSOLE</span><h2 id="console-title">虚拟机控制台</h2><p id="console-status">正在连接…</p></div><div class="console-tools"><button id="console-cad" class="button button-outline small" type="button" disabled>发送 Ctrl+Alt+Del</button><button id="console-fullscreen" class="button button-outline small" type="button">全屏</button><button class="icon-button" type="button" data-close-modal aria-label="关闭">×</button></div></div><div id="console-stage" class="console-stage"><div id="console-placeholder" class="console-placeholder"><span class="console-spinner" aria-hidden="true"></span><span>正在连接到虚拟机画面…</span></div></div><form id="console-password-form" class="console-password" hidden><label for="console-password">VNC 密码</label><input id="console-password" type="password" autocomplete="off" required /><button class="button button-primary small" type="submit">连接</button></form></section>
</div>
<div id="toast-region" class="toast-region" aria-live="polite"></div>
</body>
</html>

@ -0,0 +1,193 @@
:root{font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif;color:#15243a;background:#f4f7fb;font-synthesis:none;-webkit-font-smoothing:antialiased}
*{box-sizing:border-box}
[hidden]{display:none!important}
body{margin:0;min-width:320px}
button,input,select{font:inherit}
button{cursor:pointer}
button:disabled{cursor:not-allowed;opacity:.52}
input,select{outline:none}
input:focus,select:focus,button:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.brand-mark{display:inline-flex;width:34px;height:34px;align-items:center;justify-content:center;border-radius:10px;background:#2ac6ca;box-shadow:0 7px 17px rgba(16,172,184,.18);flex:none}
.brand-mark:before,.brand-mark span{content:"";display:block;width:11px;height:17px;border:3px solid #0c2a3f;transform:skewY(-22deg);border-radius:2px}
.brand-mark:before{border-right:0;margin-right:-1px}
.brand-mark span{border-left:0;margin-left:-1px}
.boot-screen{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;gap:13px;background:#f4f7fb;color:#607087;font-size:14px;z-index:50}
.login-layout{min-height:100vh;display:grid;grid-template-columns:minmax(390px,48%) 1fr;background:#fff}
.login-art{position:relative;min-height:650px;overflow:hidden;background:radial-gradient(circle at 78% 44%,#174c64 0,#122d44 36%,#0d1d31 75%);color:#fff}
.login-art-grid{position:absolute;inset:0;background-image:linear-gradient(rgba(143,221,226,.065) 1px,transparent 1px),linear-gradient(90deg,rgba(143,221,226,.065) 1px,transparent 1px);background-size:50px 50px;mask-image:linear-gradient(90deg,transparent,black)}
.login-art-inner{position:relative;height:100%;min-height:650px;display:flex;flex-direction:column;justify-content:space-between;padding:43px clamp(38px,5vw,90px);z-index:2}
.login-art-brand{display:flex;gap:13px;align-items:center;font-weight:800;font-size:23px;letter-spacing:-.6px}
.login-art-copy{max-width:500px;margin-bottom:70px}
.eyebrow{display:inline-block;color:#159da9;font-size:11px;letter-spacing:.14em;font-weight:800}
.eyebrow.light{color:#53dce0}
.login-art-copy h1{font-size:clamp(38px,4vw,62px);line-height:1.25;letter-spacing:-1.8px;margin:20px 0 19px;font-weight:750}
.login-art-copy p{max-width:380px;color:#bbd1dc;font-size:16px;line-height:1.85;margin:0}
.login-art-footer{color:#bed5dc;font-size:12px;letter-spacing:.04em;display:flex;align-items:center;gap:10px}
.online-dot,.tiny-dot,.connection-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#35d49b;box-shadow:0 0 0 4px rgba(53,212,155,.12)}
.art-orbit{position:absolute;border:1px solid rgba(90,220,220,.19);border-radius:50%;width:560px;height:560px;right:-220px;top:20%;transform:rotate(-28deg)}
.orbit-two{width:390px;height:390px;right:-135px;top:29%;border-color:rgba(90,220,220,.27)}
.art-core{position:absolute;right:5%;top:40%;width:240px;height:240px;transform:rotate(-22deg);opacity:.72}
.art-core span{position:absolute;display:block;border-radius:23px;width:140px;height:140px;border:1px solid rgba(82,220,224,.3);background:linear-gradient(135deg,rgba(75,205,213,.2),rgba(13,35,57,.1));box-shadow:0 25px 55px rgba(0,0,0,.18)}
.art-core span:nth-child(2){top:43px;left:38px}.art-core span:nth-child(3){top:86px;left:76px;background:linear-gradient(135deg,rgba(62,210,210,.42),rgba(9,46,67,.45))}
.login-form-side{display:flex;align-items:center;justify-content:center;padding:40px}
.login-card{width:min(100%,410px)}
.login-mobile-brand{display:none}
.login-card h2{font-size:34px;letter-spacing:-1px;margin:14px 0 8px}
.muted{color:#7a8798;margin:0 0 43px;font-size:14px;line-height:1.7}
.form-stack{display:flex;flex-direction:column}
.form-stack label,.field label,.console-password label{font-size:13px;font-weight:700;color:#34445a;margin:0 0 9px}
.form-stack input,.field input,.field select,.console-password input{height:46px;width:100%;border:1px solid #dce4eb;background:#fff;border-radius:9px;padding:0 13px;color:#15243a;transition:border-color .15s,box-shadow .15s}
.form-stack input:focus,.field input:focus,.field select:focus,.console-password input:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none}
.form-stack input::placeholder,.field input::placeholder{color:#a6b1be}
.form-stack input{margin-bottom:23px}
.form-error{color:#bf3e48;font-size:13px;line-height:1.5;margin:0 0 16px}
.button{border:1px solid transparent;display:inline-flex;align-items:center;justify-content:center;gap:8px;border-radius:9px;padding:10px 17px;min-height:41px;background:#fff;color:#304158;font-size:13px;font-weight:700;white-space:nowrap;transition:transform .15s,box-shadow .15s,background .15s,border-color .15s}
.button:not(:disabled):hover{transform:translateY(-1px)}
.button-primary{background:#0f9eaa;color:#fff;box-shadow:0 8px 17px rgba(15,158,170,.16)}
.button-primary:not(:disabled):hover{background:#0b8c98;box-shadow:0 10px 19px rgba(15,158,170,.22)}
.button-outline{border-color:#d7e0e8;background:#fff;color:#445368}
.button-outline:not(:disabled):hover{border-color:#aebfc8;background:#f8fbfc}
.button-ghost{background:transparent;color:#6a798d}
.button-ghost:not(:disabled):hover{background:#f3f6f9}
.button-danger{background:#d94350;color:#fff}
.button-danger:not(:disabled):hover{background:#c73441}
.button.small{min-height:34px;padding:7px 11px;font-size:12px}
.login-submit{height:48px;justify-content:space-between;padding:0 17px;margin-top:6px;font-size:14px}
.login-submit span{font-size:20px;font-weight:400}
.login-hint{margin:27px 0 0;color:#9aa5b2;font-size:12px;line-height:1.7}
.auth-switch{display:flex;align-items:center;gap:5px;margin:20px 0 0;color:#708093;font-size:12px}.auth-switch button{padding:2px 0;border:0;background:transparent;color:#0f8f9a;font-size:12px;font-weight:800}.auth-switch button:hover{text-decoration:underline}.register-code-row{display:flex;align-items:flex-start;gap:9px;margin-bottom:19px}.register-code-row input{min-width:0;flex:1;margin:0}.register-code-row .button{flex:none;height:46px}.register-code-status,.smtp-status{margin:0 0 16px;padding:10px 12px;border-radius:8px;background:#ecf8f7;color:#267d78;font-size:12px;line-height:1.6}.smtp-status{margin:0}.smtp-card{max-width:780px;margin-bottom:18px}.smtp-card .form-error{margin:0}.pending-users-list{display:grid;gap:10px}.pending-users-list>.muted{margin:0}.pending-user-row{display:flex;align-items:center;justify-content:space-between;gap:15px;border:1px solid #e2ebef;border-radius:9px;padding:13px 15px}.pending-user-details{min-width:0;display:grid;gap:4px;overflow-wrap:anywhere}.pending-user-details strong{font-size:13px;color:#2f455a}.pending-user-details span{font-size:12px;color:#5b7285}.pending-user-details small{font-size:11px;color:#9aabba}
.setup-layout{display:grid;grid-template-columns:minmax(330px,40%) 1fr;min-height:100vh;background:#fff}
.setup-intro{min-height:640px;background:radial-gradient(circle at 90% 95%,#1b5d68,#122d44 40%,#0e1e31 85%);color:#fff;padding:clamp(35px,5vw,75px);display:flex;flex-direction:column;align-items:flex-start}
.setup-brand,.host-brand{display:flex;align-items:center;gap:11px;font-size:22px;font-weight:800;letter-spacing:-.5px}.setup-brand{margin-bottom:auto}
.setup-intro h1{font-size:clamp(40px,4vw,62px);line-height:1.2;margin:18px 0}.setup-intro p{max-width:420px;color:#bed1dc;font-size:15px;line-height:1.85;margin:0 0 47px}
.setup-steps{display:flex;gap:12px;flex-wrap:wrap;width:100%;margin-top:auto}.setup-steps span{padding:10px 15px;border:1px solid #3b596a;border-radius:8px;color:#91aebf;font-size:12px;font-weight:700}.setup-steps .current{background:#1b5260;border-color:#2e8791;color:#6be0df}
.setup-form-side{display:flex;align-items:center;justify-content:center;padding:45px clamp(24px,5vw,80px)}.setup-card{width:min(100%,440px)}.setup-card h2{font-size:31px;letter-spacing:-.8px;margin:13px 0 9px}.setup-card .muted{margin-bottom:29px}.setup-submit{height:47px;justify-content:space-between;margin-top:6px}.setup-submit span{font-size:20px;font-weight:400}.setup-note{font-size:11px;line-height:1.8;color:#9aa8b5;margin:24px 0 0}
.setup-security-note{font-size:11px;line-height:1.75;color:#496372;background:#edf8f8;border:1px solid #d2eeee;border-radius:9px;padding:11px 13px;margin:-10px 0 23px}
.host-layout{min-height:100vh;background:#f4f7fb}.host-topbar{height:75px;background:#fff;border-bottom:1px solid #e7edf2;padding:0 clamp(22px,5vw,76px);display:flex;align-items:center;justify-content:space-between}.host-brand{font-size:20px}.host-topbar-actions{display:flex;align-items:center;gap:14px}.host-user{font-size:12px;color:#65778a;font-weight:700}
.host-content{max-width:1380px;padding:39px clamp(22px,5vw,76px) 70px;margin:0 auto}.host-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;margin-bottom:29px}.host-heading h1{font-size:29px;letter-spacing:-.6px;margin:8px 0}.host-heading p{color:#8090a0;font-size:13px;line-height:1.6;margin:0}
.host-columns{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(350px,.85fr);gap:19px;align-items:start}.host-side-stack{display:grid;gap:19px}.host-card{background:#fff;border:1px solid #e6edf2;border-radius:13px;padding:26px;box-shadow:0 10px 30px rgba(19,42,65,.027)}.host-card-heading{display:flex;gap:12px;align-items:flex-start;margin-bottom:24px}.host-card-number{display:flex;align-items:center;justify-content:center;flex:none;width:31px;height:31px;background:#e7f8f8;color:#0e919b;border-radius:9px;font-size:13px;font-weight:800}.host-card-heading h2{font-size:17px;margin:2px 0 5px;letter-spacing:-.2px}.host-card-heading p{font-size:11px;color:#91a1b0;margin:0;line-height:1.6}
.host-card textarea{width:100%;min-height:125px;padding:12px 13px;border:1px solid #dce4eb;border-radius:9px;color:#15243a;font:11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;resize:vertical;background:#fff}.host-card textarea:focus{border-color:#35b9c0;box-shadow:0 0 0 4px rgba(25,179,187,.1);outline:none}.host-card input[type=file]{height:auto;min-height:43px;padding:9px;font-size:11px}.host-card input[type=file]::file-selector-button{border:0;border-radius:6px;padding:5px 10px;margin-right:9px;background:#e9f6f6;color:#137e89;font-weight:700;cursor:pointer}
.host-public-pool{grid-column:1/-1;border-top:1px solid #e8eef2;padding-top:18px}.host-public-pool-heading{margin-bottom:16px}.host-public-pool-heading strong{display:block;color:#34445a;font-size:13px}.host-public-pool-heading small{display:block;margin-top:6px;color:#8798a7;font-size:10px;line-height:1.6}.host-public-pool textarea{min-height:78px}
.fingerprint-result{margin:18px 0 14px;padding:14px;border:1px solid #b9e6e5;background:#effafa;border-radius:9px}.fingerprint-result>span{display:block;color:#417c85;font-size:11px;font-weight:700;margin-bottom:8px}.fingerprint-result code{display:block;color:#1b5260;font-size:12px;font-weight:800;line-height:1.7;overflow-wrap:anywhere}.host-security-note{font-size:11px;color:#8191a1;line-height:1.75;margin:16px 0 0}.host-security-note code{color:#41566e;font-size:10px;overflow-wrap:anywhere}.host-confirm{margin-top:17px;background:#f0fbf8;border-color:#cce9e0}.host-confirm strong{color:#217d6e}.host-confirm small{color:#659a90}
.host-test-status{font-size:12px;color:#708095;background:#f4f7fa;padding:12px 14px;border-radius:8px;line-height:1.55;margin:0 0 15px}.host-test-status.success{background:#e7f8ef;color:#1d9168}.host-test-status.warning{background:#fff4e6;color:#9a641d}.host-submit-actions{display:flex;gap:9px;flex-wrap:wrap}.host-submit-actions .button{flex:1}.host-card .form-error{margin:0 0 13px}
.update-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:19px;align-items:start}.update-grid .host-card{min-width:0}.update-grid .form-stack input{margin-bottom:17px}.update-grid .form-stack .field-hint{display:block;color:#8395a5;font-size:11px;line-height:1.6;margin:-7px 0 17px}.update-grid .form-stack .button{align-self:flex-start}.update-grid .host-test-status{margin-top:17px;overflow-wrap:anywhere}.update-versions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.update-versions>div{border:1px solid #e2ebf0;border-radius:9px;padding:13px;background:#fbfdfd;min-width:0}.update-versions span{display:block;color:#8291a1;font-size:11px;margin-bottom:9px}.update-versions strong{display:block;color:#284459;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
.update-grid .form-stack input[readonly]{background:#f4f7f9;color:#6c7d8d}
.ssh-keys-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);gap:19px;align-items:start}.ssh-keys-grid .host-card{min-width:0}.ssh-keys-grid .form-stack .button{align-self:flex-start}.ssh-keys-grid .form-stack textarea{margin-bottom:19px}.ssh-key-file-hint{display:block;color:#8b9bab;font-size:11px;line-height:1.5;margin:-14px 0 20px}.ssh-keys-list{display:grid;gap:11px}.ssh-keys-list>.muted{margin:0}.ssh-key-row{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:14px;border:1px solid #e2ebef;border-radius:9px;background:#fbfdfd}.ssh-key-details{min-width:0;display:grid;gap:5px}.ssh-key-details strong{font-size:13px;color:#2b4358;overflow-wrap:anywhere}.ssh-key-details code{font-size:11px;color:#3b7a87;overflow-wrap:anywhere}.ssh-key-details small{font-size:10px;color:#95a4b2}.ssh-key-actions{display:flex;flex:none;gap:7px}.ssh-key-delete{color:#b94b57;border-color:#efd8dc}
.ssh-key-picker-title{display:block;color:#34445a;font-size:12px;font-weight:700}.ssh-key-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px}.ssh-key-option{display:flex;align-items:center;width:100%;min-width:0;min-height:74px;padding:12px 14px;text-align:left;border:1px solid #dce4eb;border-radius:9px;background:#fff;color:#334a5f;cursor:pointer}.ssh-key-option strong{font-size:12px;line-height:1.5;overflow-wrap:anywhere}.ssh-key-option[aria-pressed="true"]{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.ssh-key-option:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.ssh-key-picker-empty{grid-column:1/-1;margin:0;color:#8b9bab;font-size:11px}.ssh-key-picker-manage{margin-top:9px;padding:0;border:0;background:transparent;color:#148c98;font-size:11px;font-weight:700;cursor:pointer}.ssh-key-picker-manage:hover{text-decoration:underline}.field small.root-password-hint-error{color:#b73e4c}.field small.root-password-hint-success{color:#247f67}
@media(max-width:510px){.ssh-key-picker{grid-template-columns:1fr}}
.unlock-content{min-height:calc(100vh - 75px);display:flex;align-items:center;justify-content:center;padding:40px 24px}.unlock-card{width:min(100%,480px);padding:35px}.unlock-card h1{font-size:28px;letter-spacing:-.5px;margin:12px 0}.unlock-card .muted{margin:0 0 27px}.unlock-card .muted strong{color:#30445a;overflow-wrap:anywhere}.unlock-submit{width:100%;min-height:46px}.unlock-settings-button{margin-top:18px;padding-left:0}
.dashboard{min-height:100vh;display:grid;grid-template-columns:244px minmax(0,1fr)}
.sidebar{position:sticky;top:0;height:100vh;background:#101d2c;color:#d2dce6;padding:32px 15px 22px;display:flex;flex-direction:column}
.sidebar-brand{display:flex;align-items:center;gap:11px;padding:0 13px 46px;font-size:19px;color:#fff;letter-spacing:-.3px;font-weight:800}
.sidebar-brand small{display:block;color:#668197;font-size:8px;letter-spacing:.2em;margin-top:2px}
.sidebar-section-label{color:#64798f;text-transform:uppercase;letter-spacing:.14em;font-size:10px;font-weight:800;margin:0 15px 16px}
.sidebar-link{height:43px;display:flex;align-items:center;gap:13px;padding:0 14px;border-radius:9px;color:#8da2b6;font-size:13px;font-weight:700}
.sidebar-button{width:100%;border:0;background:transparent;text-align:left;font:inherit;cursor:pointer}.sidebar-button:hover{background:#1a3445;color:#d0eeee}
.sidebar-link.active{background:#1d3949;color:#57d4d3}
.nav-icon{font-size:20px;line-height:1}.nav-arrow{margin-left:auto;font-size:20px;opacity:.7}
.sidebar-bottom{margin-top:auto}
.host-panel{display:flex;align-items:center;gap:10px;padding:14px 11px;border:1px solid #274050;border-radius:10px;background:#172c3e}
.host-panel-icon{width:31px;height:31px;border-radius:8px;background:#213e4e;color:#5fd4d1;display:flex;align-items:center;justify-content:center;font-size:20px}
.host-panel strong,.host-panel span{display:block}.host-panel strong{font-size:11px;color:#dce8ec}.host-panel div:nth-child(2) span{font-size:10px;color:#8ca6b6;margin-top:3px}
.host-panel .connection-dot{margin-left:auto;width:7px;height:7px;box-shadow:none;flex:none}.host-panel .connection-dot.offline{background:#e68a7d}
.sidebar-caption{font-size:10px;color:#577086;margin:20px 10px 0;letter-spacing:.06em}
.main-area{min-width:0}
.topbar{height:74px;background:#fff;border-bottom:1px solid #e7edf2;display:flex;align-items:center;justify-content:space-between;padding:0 clamp(24px,3.3vw,55px)}
.breadcrumb{font-size:12px;color:#8c9bac}.breadcrumb span{padding:0 11px;color:#bbc5d0}.breadcrumb strong{color:#344961;font-weight:700}
.topbar-right{display:flex;align-items:center;gap:19px}.topbar-user{display:flex;align-items:center;gap:9px;color:#34455b;font-size:12px;font-weight:700}
.host-settings-mobile{display:none}
.admin-menu{display:none;position:relative;z-index:11}.admin-menu summary{list-style:none;display:flex;align-items:center;gap:5px;min-height:32px;padding:5px 9px;border-radius:7px;color:#536b7e;font-size:11px;font-weight:700;cursor:pointer;white-space:nowrap}.admin-menu summary::-webkit-details-marker{display:none}.admin-menu summary:hover,.admin-menu[open] summary{background:#edf6f6;color:#117f88}.admin-menu-options{position:absolute;right:0;top:calc(100% + 5px);display:grid;gap:3px;min-width:148px;padding:6px;border:1px solid #dde7ed;border-radius:9px;background:#fff;box-shadow:0 12px 30px rgba(17,42,59,.14)}.admin-menu-options .button{width:100%;justify-content:flex-start}
.avatar{display:inline-flex;align-items:center;justify-content:center;border-radius:50%;height:30px;width:30px;background:#e9f8f7;color:#118e9a;font-size:12px;font-weight:800}
.content{max-width:1600px;margin:0 auto;padding:37px clamp(24px,3.3vw,55px) 24px}
.page-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:24px;margin-bottom:32px}
.page-heading h1{font-size:28px;letter-spacing:-.6px;margin:9px 0 8px}.page-heading p{margin:0;color:#8390a2;font-size:13px}
.resource-warning{margin:-11px 0 23px;padding:13px 16px;border:1px solid #f0d8aa;border-radius:9px;background:#fff8eb;color:#916323;font-size:12px;line-height:1.65;overflow-wrap:anywhere}
.heading-actions{display:flex;gap:10px;padding-bottom:3px}
.overview-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:17px;margin-bottom:25px}
.stat-card{min-height:148px;padding:22px 24px;background:#fff;border:1px solid #e9eef3;border-radius:13px;box-shadow:0 9px 27px rgba(18,47,71,.025)}
.stat-top{display:flex;align-items:center;justify-content:space-between;color:#79889a;font-size:12px;font-weight:700}
.stat-icon{display:flex;align-items:center;justify-content:center;width:33px;height:33px;border-radius:9px;font-size:16px}
.stat-icon.total{background:#e9f4fb;color:#4387b4}.stat-icon.running{background:#e7f9f1;color:#27b07c}.stat-icon.stopped{background:#f0f1f7;color:#8191a9}
.stat-card>strong{display:block;font-size:32px;line-height:1.1;margin-top:14px;letter-spacing:-1px}.stat-card>small{display:flex;align-items:center;gap:9px;color:#a2acb8;font-size:11px;margin-top:10px}.tiny-dot{width:6px;height:6px;box-shadow:none}.tiny-dot.green{background:#39c78e}
.inventory-panel{background:#fff;border:1px solid #e7ecf2;border-radius:13px;box-shadow:0 10px 30px rgba(19,42,65,.027);min-height:390px}
.panel-heading{display:flex;justify-content:space-between;gap:20px;align-items:center;padding:23px 25px 20px;border-bottom:1px solid #edf1f5}
.panel-heading h2{font-size:17px;letter-spacing:-.2px;margin:0 0 6px}.panel-heading p{color:#9aa6b3;font-size:11px;margin:0}
.panel-tools{display:flex;gap:9px}.search-box{position:relative;display:flex;align-items:center}.search-box>span:first-child{position:absolute;left:12px;color:#9aa8b8;font-size:19px;line-height:1}
.search-box input,.panel-tools select{height:37px;border:1px solid #e0e6ec;border-radius:8px;background:#fff;color:#516075;font-size:12px}
.search-box input{width:220px;padding:0 12px 0 34px}.search-box input::placeholder{color:#a4afbb}.panel-tools select{padding:0 29px 0 11px}
.table-scroll{overflow-x:auto;min-height:100px}
table{border-collapse:collapse;width:100%;min-width:850px}.vm-table{min-width:1060px}.vm-table th,.vm-table td{padding-left:15px;padding-right:15px}
thead{background:#fbfcfe}th{height:47px;text-align:left;font-size:10px;letter-spacing:.05em;color:#9ba8b7;text-transform:uppercase;font-weight:800;padding:0 24px}
th.actions-heading{text-align:right;padding-right:28px}
td{height:83px;border-top:1px solid #edf1f5;padding:15px 24px;font-size:12px;color:#607087}
tbody tr:hover{background:#fcfefe}
.vm-identity{display:flex;align-items:center;gap:12px;min-width:160px}.vm-icon{width:38px;height:38px;border-radius:10px;background:#e9f8f8;color:#239eaa;display:flex;align-items:center;justify-content:center;font-size:19px;flex:none}.vm-name{display:block;color:#25384e;font-size:13px;font-weight:800;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-uuid-row{display:flex;align-items:center;gap:5px;margin-top:6px;max-width:265px}.vm-id{display:block;min-width:0;color:#a6b1bf;font-size:10px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vm-uuid-row .vm-copy-icon{width:21px;min-height:21px;padding:2px}.vm-uuid-row .vm-copy-icon svg{width:13px;height:13px}
.vm-public-ip{display:block;color:#16868f;font-size:10px;font-weight:700;margin-top:5px;white-space:nowrap}
.vm-name-link{display:block;max-width:230px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;padding:2px 0;color:#25384e;font-size:13px;font-weight:800;text-align:left;text-decoration:underline;text-decoration-color:transparent;text-underline-offset:3px;cursor:pointer}.vm-name-link:not(:disabled):hover,.vm-name-link:not(:disabled):focus-visible{color:#118e98;text-decoration-color:currentColor}.vm-metadata{display:block;max-width:205px;color:#53647a;line-height:1.5;overflow-wrap:anywhere}.vm-ip{color:#16868f;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;white-space:nowrap}
.state-pill{display:inline-flex;align-items:center;gap:7px;padding:6px 9px;border-radius:6px;font-size:11px;font-weight:800;background:#f1f3f6;color:#758499;white-space:nowrap}.state-pill:before{content:"";width:6px;height:6px;background:currentColor;border-radius:50%}.state-pill.running{background:#e7f8ef;color:#20a46f}.state-pill.stopped{background:#f2f4f7;color:#8290a3}.state-pill.other{background:#fff4e5;color:#b98129}
.vm-spec{color:#53647a;white-space:nowrap}.vm-spec strong{color:#283a50;font-weight:700}.vm-spec small{display:block;color:#a2aeb9;font-size:10px;margin-top:5px}
.row-actions{display:flex;align-items:center;justify-content:flex-end;gap:5px;white-space:nowrap}.row-button{border:1px solid transparent;background:transparent;color:#577083;border-radius:7px;padding:7px 8px;min-height:31px;font-size:11px;font-weight:700}.row-button:not(:disabled):hover{background:#e8f7f7;color:#117f88}.row-button.primary{background:#e7f7f7;color:#118e98}.row-button.danger{color:#bf6470}.row-button.danger:not(:disabled):hover{background:#fff0f1;color:#ba3a49}
.empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0}
.footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px}
.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 18px}.vm-detail-summary span{white-space:nowrap}.vm-detail-summary strong{color:#455a70;font-weight:700;margin-left:4px}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef}
.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
.vm-credential-icon{width:30px;min-height:30px}.vm-credential-icon svg{width:17px;height:17px}.vm-credential-icon .vm-eye-slash{visibility:hidden}.vm-credential-icon[aria-pressed="true"] .vm-eye-slash{visibility:visible}
.vm-detail-facts .vm-detail-credential-row{grid-column:1/-1}
.vm-metrics{margin-top:25px}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6}
.modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)}
.modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)}
.modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:26px 29px 18px;border-bottom:1px solid #edf1f5}.modal-header h2{font-size:21px;letter-spacing:-.35px;margin:7px 0 5px}.modal-header p{font-size:12px;color:#95a1af;margin:0}.icon-button{border:0;border-radius:8px;background:transparent;color:#8a98a8;width:31px;height:31px;font-size:23px;line-height:1;display:flex;align-items:center;justify-content:center}.icon-button:hover{background:#f1f5f8;color:#30445a}
.modal-body{padding:23px 29px 25px}.modal-footer{display:flex;justify-content:flex-end;gap:9px;padding:18px 29px;border-top:1px solid #edf1f5}
.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}.workspace-form-back{padding-left:0;margin-bottom:15px;min-height:34px}.workspace-form-heading{margin-bottom:22px}.workspace-form-heading h1{margin-top:8px}.workspace-form-card{overflow:hidden}.workspace-form-body{padding:28px clamp(22px,3vw,36px) 32px}.workspace-form-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:10px;padding:18px clamp(22px,3vw,36px);border-top:1px solid #edf1f5;background:#fbfdfe}.workspace-form-actions .button{min-width:120px}.workspace-form-body>.form-error{margin:18px 0 0}
.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 17px}.field.full{grid-column:1/-1}.field label{display:block}.field label span{color:#dc5965}.field small{display:block;color:#a1adbb;font-size:10px;margin-top:7px;line-height:1.5}.field select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2393a1ae' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:35px}
.create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px}
.template-field-label{display:block;color:#34445a;font-size:13px;font-weight:700;margin-bottom:10px}.template-field-label span{color:#dc5965}.template-catalog{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:14px}.template-catalog-empty{grid-column:1/-1;margin:0;padding:17px;border:1px dashed #cbdbe3;border-radius:10px;background:#f8fbfc;color:#698094;font-size:12px}.template-family-card{min-width:0;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden}.template-family-card[open]{border-color:#46b6ba;box-shadow:0 0 0 2px rgba(20,166,175,.07)}.template-family-summary{display:flex;align-items:center;flex-direction:column;gap:9px;min-height:153px;padding:20px 13px 13px;cursor:pointer;text-align:center;list-style:none}.template-family-summary::-webkit-details-marker{display:none}.template-family-summary:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:-3px}.template-family-summary strong{color:#30465a;font-size:13px}.template-family-icon{display:flex;align-items:center;justify-content:center;width:65px;height:65px;border-radius:17px;background:linear-gradient(145deg,#2a6385,#173d58);color:#fff;font-size:31px;font-weight:800;box-shadow:0 6px 16px rgba(24,68,90,.15)}.template-family-arrow{color:#258f9b;font-size:20px;line-height:1;transition:transform .2s}.template-family-card[open] .template-family-arrow{transform:rotate(180deg)}.template-versions{display:grid;gap:7px;padding:12px;border-top:1px solid #e7edf2;background:#fbfdfd}.template-version-option{width:100%;display:grid;gap:3px;padding:11px 12px;border:1px solid #dee8ed;border-radius:8px;background:#fff;text-align:left;color:#344e60}.template-version-option strong{font-size:12px}.template-version-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)}.template-version-option:hover{border-color:#48b6bd}.template-admin-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);align-items:start;gap:19px}.template-admin-grid .host-card{min-width:0}.template-admin-grid .form-stack .button{align-self:flex-start}.template-field-help{display:block;margin:-16px 0 19px;color:#8b9bab;font-size:11px;line-height:1.55}.template-import-status{margin:0 0 14px;padding:10px 12px;border-radius:8px;background:#edf8f8;color:#317c85;font-size:11px;line-height:1.6}.template-admin-list{display:grid;gap:10px}.template-admin-list>.muted{margin:0}.template-admin-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:9px 11px;align-items:end;padding:14px;border:1px solid #e0e9ee;border-radius:10px;background:#fbfdfd}.template-admin-row-heading{grid-column:1/-1;display:flex;align-items:center;gap:9px;margin-bottom:3px;color:#34495c;font-size:12px}.template-admin-icon{display:flex;align-items:center;justify-content:center;width:27px;height:27px;border-radius:7px;background:#e3f6f3;color:#138d8f;font-weight:800}.template-admin-row label{grid-column:1/-1;margin:0;color:#75899b;font-size:11px;font-weight:700}.template-admin-row input{width:100%;min-width:0;height:37px;padding:0 10px;border:1px solid #dce4eb;border-radius:7px;background:#fff;color:#20364a;font-size:12px}.template-admin-row .button{min-height:37px}.template-admin-row .form-error{grid-column:1/-1;margin:0}
.template-family-icon.system,.template-admin-icon.system{background:transparent;border:0;box-shadow:none;color:inherit;text-shadow:none}.template-system-logo{display:block;width:100%;height:100%;object-fit:contain}.template-version-option{display:flex;align-items:center;justify-content:center;text-align:center}.template-version-option strong{overflow-wrap:anywhere}
.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px}
.vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px}
.input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px}
.form-tip{display:flex;gap:10px;background:#f1f9fa;border:1px solid #e1f2f3;border-radius:9px;padding:12px 14px;color:#318b96;margin-top:22px}.form-tip>span{font-size:16px;line-height:1}.form-tip p{font-size:11px;line-height:1.55;margin:0}.modal-body>.form-error{margin:18px 0 0}
.delete-copy{font-size:13px;color:#647388;line-height:1.8;margin:0 0 19px}.delete-copy strong{color:#263c54;overflow-wrap:anywhere}.danger-text{color:#d64753}
.reinstall-warning{margin:0 0 15px;padding:14px 16px;border:1px solid #f2cbd0;border-radius:9px;background:#fff4f5;color:#99414d;font-size:12px;line-height:1.7}.reinstall-warning strong{display:block;margin-bottom:4px;color:#a82f3f;font-size:13px}.reinstall-network{margin:0 0 21px;color:#51677c;font-size:12px;line-height:1.7}.reinstall-network strong{color:#174458;overflow-wrap:anywhere}
.reinstall-progress{display:flex;align-items:flex-start;gap:15px;padding:14px 2px;min-height:105px}.reinstall-progress .console-spinner{flex:none;margin-top:2px}.reinstall-progress strong{display:block;color:#274459;font-size:14px}.reinstall-progress p{margin:8px 0;color:#238894;font-size:12px;line-height:1.6}.reinstall-progress small{display:block;color:#8192a4;font-size:11px;line-height:1.6}
.reinstall-result{padding:4px 0 10px}.reinstall-result h3{margin:0 0 10px;color:#167f72;font-size:18px}.reinstall-result.failed h3{color:#b1404c}.reinstall-result.unknown h3{color:#916425}.reinstall-result>p{margin:0 0 14px;color:#4f6478;font-size:12px;line-height:1.75;overflow-wrap:anywhere}.reinstall-password-box{border:1px solid #b9e2d5;border-radius:9px;background:#f1fbf7;padding:14px;margin-top:15px}.reinstall-password-box>span{display:block;color:#286f60;font-size:12px;font-weight:700}.reinstall-password-box>div{display:flex;align-items:center;gap:9px;margin:10px 0}.reinstall-password-box code{display:block;flex:1;min-width:0;padding:11px;border-radius:7px;background:#fff;color:#1d4a41;font-size:14px;overflow-wrap:anywhere;user-select:all}.reinstall-password-box small{display:block;color:#617f76;font-size:11px;line-height:1.6}.reinstall-result-warning{padding:10px 12px;border-radius:8px;background:#fff6e7;color:#916425!important}
.checkbox-row{border:1px solid #f0dadd;background:#fffafa;border-radius:9px;padding:14px;display:flex;align-items:flex-start;gap:11px;cursor:pointer}.checkbox-row input{margin:3px 0 0;accent-color:#d94350}.checkbox-row strong{display:block;font-size:12px;color:#9e3440}.checkbox-row small{display:block;margin-top:4px;font-size:11px;line-height:1.5;color:#bd7a81}
.console-backdrop{padding:24px}.console-modal{width:min(100%,1200px);max-height:95vh;display:flex;flex-direction:column;overflow:hidden;background:#101820}.console-toolbar{display:flex;align-items:center;justify-content:space-between;gap:20px;background:#fff;padding:15px 20px}.console-toolbar h2{margin:4px 0 1px;font-size:16px}.console-toolbar p{margin:0;font-size:11px;color:#93a1af}.console-tools{display:flex;align-items:center;gap:8px}.console-stage{position:relative;min-height:280px;height:min(70vh,720px);background:#101820;display:flex;align-items:center;justify-content:center;overflow:hidden}.console-stage canvas{max-width:100%;max-height:100%}.console-placeholder{display:flex;align-items:center;gap:13px;color:#a9b9c5;font-size:12px}.console-spinner{height:20px;width:20px;border-radius:50%;border:2px solid #4f6673;border-top-color:#40ccd0;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.console-password{display:flex;align-items:center;gap:10px;background:#fff;padding:13px 20px}.console-password label{margin:0;white-space:nowrap}.console-password input{width:220px;height:35px}
.toast-region{position:fixed;right:23px;bottom:22px;display:flex;flex-direction:column;gap:9px;z-index:80;pointer-events:none}.toast{max-width:min(430px,calc(100vw - 36px));padding:12px 16px;border-radius:9px;color:#fff;background:#20364a;box-shadow:0 10px 24px rgba(15,30,44,.2);font-size:12px;line-height:1.5;pointer-events:auto}.toast.error{background:#ae3c49}.toast.success{background:#157e75}
@media(max-width:1150px){th,td{padding-left:15px;padding-right:15px}.row-button{padding:6px}.content{padding-left:28px;padding-right:28px}}
@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.admin-menu{display:block}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}}
@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}}
@media(max-width:960px){.update-grid{grid-template-columns:1fr}}
@media(max-width:960px){.template-admin-grid{grid-template-columns:1fr}}
@media(max-width:960px){.ssh-keys-grid{grid-template-columns:1fr}}
@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}}
@media(max-width:740px){.vm-metrics-grid{grid-template-columns:1fr}.vm-metrics-heading{align-items:flex-start;flex-direction:column}.vm-metric-plot{height:190px}}
@media(max-width:740px){.login-layout{display:block;min-height:100vh}.login-art{display:none}.login-form-side{min-height:100vh;padding:32px 25px}.login-mobile-brand{display:flex;align-items:center;gap:10px;font-size:21px;font-weight:800;margin-bottom:70px}.login-card h2{font-size:29px}.page-heading{align-items:flex-start;flex-direction:column;gap:20px}.heading-actions{width:100%}.heading-actions .button{flex:1}.overview-grid{gap:9px}.stat-card{min-height:121px;padding:16px}.stat-card>strong{font-size:25px}.stat-top{font-size:10px}.stat-icon{width:27px;height:27px;font-size:12px}.stat-card>small{font-size:9px}.panel-heading{align-items:flex-start;flex-direction:column;padding:19px}.panel-tools{width:100%}.search-box{flex:1}.search-box input{width:100%}.footer-note{text-align:left}.console-toolbar{align-items:flex-start}.console-tools{flex-wrap:wrap;justify-content:flex-end}.console-tools .button{font-size:10px}}
@media(max-width:740px){.vm-table{min-width:0}.vm-table thead{display:none}.vm-table tbody{display:grid;gap:12px;padding:12px}.vm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border:1px solid #e4ebf0;border-radius:10px;overflow:hidden}.vm-table td{display:block;min-width:0;height:auto;border:0;padding:12px 14px}.vm-table td:first-child{grid-column:1/-1;border-bottom:1px solid #edf1f5}.vm-table td:not(:first-child):before{content:attr(data-label);display:block;color:#9ba8b7;font-size:10px;font-weight:800;margin-bottom:7px}.vm-table .vm-metadata{max-width:none}.vm-table .vm-ip{white-space:normal}.vm-detail-facts{padding:4px 17px 12px}.vm-detail-actions{padding:16px 19px 19px}}
@media(max-width:740px){.setup-layout{display:block}.setup-intro{min-height:0;padding:28px 25px}.setup-brand{margin:0 0 38px}.setup-intro h1{font-size:31px;margin:11px 0}.setup-intro p{font-size:12px;margin-bottom:24px}.setup-steps{margin-top:0}.setup-form-side{padding:36px 25px 55px}.setup-card h2{font-size:27px}.host-side-stack{grid-template-columns:1fr}.host-heading{align-items:flex-start;flex-direction:column}.host-topbar{height:65px}.host-content{padding-top:27px}.host-card{padding:20px}}
@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}}
@media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}}
@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.template-catalog{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.template-family-summary{min-height:137px;padding:16px 9px 11px}.template-family-icon{width:55px;height:55px;font-size:27px}.template-versions{padding:8px}.template-version-option{padding:9px 8px}.template-admin-row{grid-template-columns:1fr}.template-admin-row .button{justify-self:start}}
@media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}}
@media(max-width:510px){.host-public-pool>.form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.ssh-key-row{align-items:flex-start;flex-direction:column}.ssh-key-actions{width:100%}.ssh-key-actions .button{flex:1}}
@media(max-width:510px){.vm-detail-heading .heading-actions{justify-content:space-between}.vm-detail-heading .heading-actions .button{flex:0 0 auto}.vm-detail-facts{grid-template-columns:1fr}.vm-detail-facts>div{padding:12px 0}.vm-detail-actions .row-button{flex:1 1 135px}.vm-table td{padding:10px 11px}.vm-identity{min-width:0}.vm-name-link{max-width:calc(100vw - 130px)}}
.rescue-status{margin:8px 0 17px;padding:12px 14px;border:1px solid #c8e9e8;border-radius:9px;background:#f0fbfa;color:#236d71;font-size:12px;line-height:1.6}
.rescue-directory-note{margin:0 0 17px;padding:10px 12px;border:1px solid #d6e8ee;border-radius:8px;background:#f6fafc;color:#557085;font-size:11px;line-height:1.6;overflow-wrap:anywhere}
.rescue-login-note{margin:0 0 19px;color:#557085;font-size:12px;line-height:1.7}
#rescue-status-title{margin:0;color:#2c465a;font-size:16px}
.rescue-template-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin:0 0 21px}
.rescue-template-card{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;min-height:130px;padding:16px 13px;border:1px solid #dce7ec;border-radius:11px;background:#fff;color:#314b5c;text-align:center;cursor:pointer;overflow-wrap:anywhere}
.rescue-template-card:hover,.rescue-template-card:focus-visible{border-color:#38aeb7;outline:none;box-shadow:0 0 0 3px rgba(25,179,187,.1)}
.rescue-template-card[aria-pressed="true"]{border-color:#28a8b0;background:#eaf8f8;box-shadow:0 0 0 2px rgba(25,179,187,.12)}
.rescue-template-card:disabled{cursor:wait;opacity:.7}
.rescue-template-symbol{display:grid;place-items:center;width:43px;height:43px;border-radius:10px;background:#e2f6f5;color:#168d94;font-size:24px;font-weight:800}
.rescue-template-card strong{font-size:12px}.rescue-template-card small{font-size:11px;color:#8798a5}
.rescue-actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px}.rescue-actions .button{min-width:190px}
.rescue-template-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 14px;border:1px solid #e0e9ee;border-radius:9px;background:#fbfdfd}
.rescue-template-row-label{display:grid;gap:5px;min-width:0;overflow-wrap:anywhere}.rescue-template-row-label strong{font-size:12px;color:#34495c}.rescue-template-row-label small{font-size:11px;color:#8a9caa}
#rescue-template-file{height:auto;padding:10px 12px}
@media(max-width:510px){.rescue-template-cards{grid-template-columns:repeat(2,minmax(0,1fr))}.rescue-actions .button{width:100%}.rescue-template-row{align-items:flex-start;flex-direction:column}}

@ -0,0 +1 @@
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 767.40668 738.31421"><defs><style>.cls-1{fill:#e9500e;}</style></defs><circle class="cls-1" cx="109.02696" cy="348.09412" r="109.02696"/><circle class="cls-1" cx="563.08369" cy="109.02698" r="109.02698"/><path class="cls-1" d="M492.48194,1336.66577a265.52505,265.52505,0,0,1-181.0712-138.09814,156.94784,156.94784,0,0,1-93.21911,11.45825,354.93524,354.93524,0,0,0,255.53723,214.16455,359.20777,359.20777,0,0,0,77.41949,7.967,156.00313,156.00313,0,0,1-31.92236-91.15466C510.24622,1340.00525,501.27735,1338.548,492.48194,1336.66577Z" transform="translate(-137.56155 -707.97998)"/><circle class="cls-1" cx="538.52046" cy="629.28723" r="109.02698"/><path class="cls-1" d="M827.798,1297.22095A356.70056,356.70056,0,0,0,845.67283,878.702a157.14441,157.14441,0,0,1-61.30975,71.8031,267.293,267.293,0,0,1-8.73688,265.4884A156.34677,156.34677,0,0,1,827.798,1297.22095Z" transform="translate(-137.56155 -707.97998)"/><path class="cls-1" d="M238.17644,899.71906q4.1505-.22779,8.30533-.22553A157.34626,157.34626,0,0,1,329.16416,923.039,265.90653,265.90653,0,0,1,543.27238,808.52966a158.0877,158.0877,0,0,1,33.076-88.42022C439.24549,709.25177,306.02421,780.001,238.17644,899.71906Z" transform="translate(-137.56155 -707.97998)"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@ -0,0 +1,62 @@
noVNC is Copyright (C) 2022 The noVNC authors
(./AUTHORS)
The noVNC core library files are licensed under the MPL 2.0 (Mozilla
Public License 2.0). The noVNC core library is composed of the
Javascript code necessary for full noVNC operation. This includes (but
is not limited to):
core/**/*.js
app/*.js
test/playback.js
The HTML, CSS, font and images files that included with the noVNC
source distibution (or repository) are not considered part of the
noVNC core library and are licensed under more permissive licenses.
The intent is to allow easy integration of noVNC into existing web
sites and web applications.
The HTML, CSS, font and image files are licensed as follows:
*.html : 2-Clause BSD license
app/styles/*.css : 2-Clause BSD license
app/styles/Orbitron* : SIL Open Font License 1.1
(Copyright 2009 Matt McInerney)
app/images/ : Creative Commons Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
Some portions of noVNC are copyright to their individual authors.
Please refer to the individual source files and/or to the noVNC commit
history: https://github.com/novnc/noVNC/commits/master
The are several files and projects that have been incorporated into
the noVNC core library. Here is a list of those files and the original
licenses (all MPL 2.0 compatible):
core/base64.js : MPL 2.0
core/des.js : Various BSD style licenses
vendor/pako/ : MIT
Any other files not mentioned above are typically marked with
a copyright/license header at the top of the file. The default noVNC
license is MPL-2.0.
The following license texts are included:
docs/LICENSE.MPL-2.0
docs/LICENSE.OFL-1.1
docs/LICENSE.BSD-3-Clause (New BSD)
docs/LICENSE.BSD-2-Clause (Simplified BSD / FreeBSD)
vendor/pako/LICENSE (MIT)
Or alternatively the license texts may be found here:
http://www.mozilla.org/MPL/2.0/
http://scripts.sil.org/OFL
http://en.wikipedia.org/wiki/BSD_licenses
https://opensource.org/licenses/MIT

@ -0,0 +1,104 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// From: http://hg.mozilla.org/mozilla-central/raw-file/ec10630b1a54/js/src/devtools/jint/sunspider/string-base64.js
import * as Log from './util/logging.js';
export default {
/* Convert data (an array of integers) to a Base64 string. */
toBase64Table: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''),
base64Pad: '=',
encode(data) {
"use strict";
let result = '';
const length = data.length;
const lengthpad = (length % 3);
// Convert every three bytes to 4 ascii characters.
for (let i = 0; i < (length - 2); i += 3) {
result += this.toBase64Table[data[i] >> 2];
result += this.toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)];
result += this.toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)];
result += this.toBase64Table[data[i + 2] & 0x3f];
}
// Convert the remaining 1 or 2 bytes, pad out to 4 characters.
const j = length - lengthpad;
if (lengthpad === 2) {
result += this.toBase64Table[data[j] >> 2];
result += this.toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)];
result += this.toBase64Table[(data[j + 1] & 0x0f) << 2];
result += this.toBase64Table[64];
} else if (lengthpad === 1) {
result += this.toBase64Table[data[j] >> 2];
result += this.toBase64Table[(data[j] & 0x03) << 4];
result += this.toBase64Table[64];
result += this.toBase64Table[64];
}
return result;
},
/* Convert Base64 data to a string */
/* eslint-disable comma-spacing */
toBinaryTable: [
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
],
/* eslint-enable comma-spacing */
decode(data, offset = 0) {
let dataLength = data.indexOf('=') - offset;
if (dataLength < 0) { dataLength = data.length - offset; }
/* Every four characters is 3 resulting numbers */
const resultLength = (dataLength >> 2) * 3 + Math.floor((dataLength % 4) / 1.5);
const result = new Array(resultLength);
// Convert one by one.
let leftbits = 0; // number of bits decoded, but yet to be appended
let leftdata = 0; // bits decoded, but yet to be appended
for (let idx = 0, i = offset; i < data.length; i++) {
const c = this.toBinaryTable[data.charCodeAt(i) & 0x7f];
const padding = (data.charAt(i) === this.base64Pad);
// Skip illegal characters and whitespace
if (c === -1) {
Log.Error("Illegal character code " + data.charCodeAt(i) + " at position " + i);
continue;
}
// Collect data into leftdata, update bitcount
leftdata = (leftdata << 6) | c;
leftbits += 6;
// If we have 8 or more bits, append 8 bits to the result
if (leftbits >= 8) {
leftbits -= 8;
// Append if not padding.
if (!padding) {
result[idx++] = (leftdata >> leftbits) & 0xff;
}
leftdata &= (1 << leftbits) - 1;
}
}
// If there are any bits left, the base64 string was corrupted
if (leftbits) {
const err = new Error('Corrupted base64 string');
err.name = 'Base64-Error';
throw err;
}
return result;
}
}; /* End of Base64 namespace */

@ -0,0 +1,178 @@
export class AESECBCipher {
constructor() {
this._key = null;
}
get algorithm() {
return { name: "AES-ECB" };
}
static async importKey(key, _algorithm, extractable, keyUsages) {
const cipher = new AESECBCipher;
await cipher._importKey(key, extractable, keyUsages);
return cipher;
}
async _importKey(key, extractable, keyUsages) {
this._key = await window.crypto.subtle.importKey(
"raw", key, {name: "AES-CBC"}, extractable, keyUsages);
}
async encrypt(_algorithm, plaintext) {
const x = new Uint8Array(plaintext);
if (x.length % 16 !== 0 || this._key === null) {
return null;
}
const n = x.length / 16;
for (let i = 0; i < n; i++) {
const y = new Uint8Array(await window.crypto.subtle.encrypt({
name: "AES-CBC",
iv: new Uint8Array(16),
}, this._key, x.slice(i * 16, i * 16 + 16))).slice(0, 16);
x.set(y, i * 16);
}
return x;
}
}
export class AESEAXCipher {
constructor() {
this._rawKey = null;
this._ctrKey = null;
this._cbcKey = null;
this._zeroBlock = new Uint8Array(16);
this._prefixBlock0 = this._zeroBlock;
this._prefixBlock1 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
this._prefixBlock2 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]);
}
get algorithm() {
return { name: "AES-EAX" };
}
async _encryptBlock(block) {
const encrypted = await window.crypto.subtle.encrypt({
name: "AES-CBC",
iv: this._zeroBlock,
}, this._cbcKey, block);
return new Uint8Array(encrypted).slice(0, 16);
}
async _initCMAC() {
const k1 = await this._encryptBlock(this._zeroBlock);
const k2 = new Uint8Array(16);
const v = k1[0] >>> 6;
for (let i = 0; i < 15; i++) {
k2[i] = (k1[i + 1] >> 6) | (k1[i] << 2);
k1[i] = (k1[i + 1] >> 7) | (k1[i] << 1);
}
const lut = [0x0, 0x87, 0x0e, 0x89];
k2[14] ^= v >>> 1;
k2[15] = (k1[15] << 2) ^ lut[v];
k1[15] = (k1[15] << 1) ^ lut[v >> 1];
this._k1 = k1;
this._k2 = k2;
}
async _encryptCTR(data, counter) {
const encrypted = await window.crypto.subtle.encrypt({
name: "AES-CTR",
counter: counter,
length: 128
}, this._ctrKey, data);
return new Uint8Array(encrypted);
}
async _decryptCTR(data, counter) {
const decrypted = await window.crypto.subtle.decrypt({
name: "AES-CTR",
counter: counter,
length: 128
}, this._ctrKey, data);
return new Uint8Array(decrypted);
}
async _computeCMAC(data, prefixBlock) {
if (prefixBlock.length !== 16) {
return null;
}
const n = Math.floor(data.length / 16);
const m = Math.ceil(data.length / 16);
const r = data.length - n * 16;
const cbcData = new Uint8Array((m + 1) * 16);
cbcData.set(prefixBlock);
cbcData.set(data, 16);
if (r === 0) {
for (let i = 0; i < 16; i++) {
cbcData[n * 16 + i] ^= this._k1[i];
}
} else {
cbcData[(n + 1) * 16 + r] = 0x80;
for (let i = 0; i < 16; i++) {
cbcData[(n + 1) * 16 + i] ^= this._k2[i];
}
}
let cbcEncrypted = await window.crypto.subtle.encrypt({
name: "AES-CBC",
iv: this._zeroBlock,
}, this._cbcKey, cbcData);
cbcEncrypted = new Uint8Array(cbcEncrypted);
const mac = cbcEncrypted.slice(cbcEncrypted.length - 32, cbcEncrypted.length - 16);
return mac;
}
static async importKey(key, _algorithm, _extractable, _keyUsages) {
const cipher = new AESEAXCipher;
await cipher._importKey(key);
return cipher;
}
async _importKey(key) {
this._rawKey = key;
this._ctrKey = await window.crypto.subtle.importKey(
"raw", key, {name: "AES-CTR"}, false, ["encrypt", "decrypt"]);
this._cbcKey = await window.crypto.subtle.importKey(
"raw", key, {name: "AES-CBC"}, false, ["encrypt"]);
await this._initCMAC();
}
async encrypt(algorithm, message) {
const ad = algorithm.additionalData;
const nonce = algorithm.iv;
const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0);
const encrypted = await this._encryptCTR(message, nCMAC);
const adCMAC = await this._computeCMAC(ad, this._prefixBlock1);
const mac = await this._computeCMAC(encrypted, this._prefixBlock2);
for (let i = 0; i < 16; i++) {
mac[i] ^= nCMAC[i] ^ adCMAC[i];
}
const res = new Uint8Array(16 + encrypted.length);
res.set(encrypted);
res.set(mac, encrypted.length);
return res;
}
async decrypt(algorithm, data) {
const encrypted = data.slice(0, data.length - 16);
const ad = algorithm.additionalData;
const nonce = algorithm.iv;
const mac = data.slice(data.length - 16);
const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0);
const adCMAC = await this._computeCMAC(ad, this._prefixBlock1);
const computedMac = await this._computeCMAC(encrypted, this._prefixBlock2);
for (let i = 0; i < 16; i++) {
computedMac[i] ^= nCMAC[i] ^ adCMAC[i];
}
if (computedMac.length !== mac.length) {
return null;
}
for (let i = 0; i < mac.length; i++) {
if (computedMac[i] !== mac[i]) {
return null;
}
}
const res = await this._decryptCTR(encrypted, nCMAC);
return res;
}
}

@ -0,0 +1,34 @@
export function modPow(b, e, m) {
let r = 1n;
b = b % m;
while (e > 0n) {
if ((e & 1n) === 1n) {
r = (r * b) % m;
}
e = e >> 1n;
b = (b * b) % m;
}
return r;
}
export function bigIntToU8Array(bigint, padLength=0) {
let hex = bigint.toString(16);
if (padLength === 0) {
padLength = Math.ceil(hex.length / 2);
}
hex = hex.padStart(padLength * 2, '0');
const length = hex.length / 2;
const arr = new Uint8Array(length);
for (let i = 0; i < length; i++) {
arr[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return arr;
}
export function u8ArrayToBigInt(arr) {
let hex = '0x';
for (let i = 0; i < arr.length; i++) {
hex += arr[i].toString(16).padStart(2, '0');
}
return BigInt(hex);
}

@ -0,0 +1,90 @@
import { AESECBCipher, AESEAXCipher } from "./aes.js";
import { DESCBCCipher, DESECBCipher } from "./des.js";
import { RSACipher } from "./rsa.js";
import { DHCipher } from "./dh.js";
import { MD5 } from "./md5.js";
// A single interface for the cryptographic algorithms not supported by SubtleCrypto.
// Both synchronous and asynchronous implmentations are allowed.
class LegacyCrypto {
constructor() {
this._algorithms = {
"AES-ECB": AESECBCipher,
"AES-EAX": AESEAXCipher,
"DES-ECB": DESECBCipher,
"DES-CBC": DESCBCCipher,
"RSA-PKCS1-v1_5": RSACipher,
"DH": DHCipher,
"MD5": MD5,
};
}
encrypt(algorithm, key, data) {
if (key.algorithm.name !== algorithm.name) {
throw new Error("algorithm does not match");
}
if (typeof key.encrypt !== "function") {
throw new Error("key does not support encryption");
}
return key.encrypt(algorithm, data);
}
decrypt(algorithm, key, data) {
if (key.algorithm.name !== algorithm.name) {
throw new Error("algorithm does not match");
}
if (typeof key.decrypt !== "function") {
throw new Error("key does not support encryption");
}
return key.decrypt(algorithm, data);
}
importKey(format, keyData, algorithm, extractable, keyUsages) {
if (format !== "raw") {
throw new Error("key format is not supported");
}
const alg = this._algorithms[algorithm.name];
if (typeof alg === "undefined" || typeof alg.importKey !== "function") {
throw new Error("algorithm is not supported");
}
return alg.importKey(keyData, algorithm, extractable, keyUsages);
}
generateKey(algorithm, extractable, keyUsages) {
const alg = this._algorithms[algorithm.name];
if (typeof alg === "undefined" || typeof alg.generateKey !== "function") {
throw new Error("algorithm is not supported");
}
return alg.generateKey(algorithm, extractable, keyUsages);
}
exportKey(format, key) {
if (format !== "raw") {
throw new Error("key format is not supported");
}
if (typeof key.exportKey !== "function") {
throw new Error("key does not support exportKey");
}
return key.exportKey();
}
digest(algorithm, data) {
const alg = this._algorithms[algorithm];
if (typeof alg !== "function") {
throw new Error("algorithm is not supported");
}
return alg(data);
}
deriveBits(algorithm, key, length) {
if (key.algorithm.name !== algorithm.name) {
throw new Error("algorithm does not match");
}
if (typeof key.deriveBits !== "function") {
throw new Error("key does not support deriveBits");
}
return key.deriveBits(algorithm, length);
}
}
export default new LegacyCrypto;

@ -0,0 +1,330 @@
/*
* Ported from Flashlight VNC ActionScript implementation:
* http://www.wizhelp.com/flashlight-vnc/
*
* Full attribution follows:
*
* -------------------------------------------------------------------------
*
* This DES class has been extracted from package Acme.Crypto for use in VNC.
* The unnecessary odd parity code has been removed.
*
* These changes are:
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* DesCipher - the DES encryption method
*
* The meat of this code is by Dave Zimmerman <dzimm@widget.com>, and is:
*
* Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
* without fee is hereby granted, provided that this copyright notice is kept
* intact.
*
* WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY
* OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE
* FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*
*
* The rest is:
*
* Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Visit the ACME Labs Java page for up-to-date versions of this and other
* fine Java utilities: http://www.acme.com/java/
*/
/* eslint-disable comma-spacing */
// Tables, permutations, S-boxes, etc.
const PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3,
25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39,
50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ],
totrot = [ 1, 2, 4, 6, 8,10,12,14,15,17,19,21,23,25,27,28];
const z = 0x0;
let a,b,c,d,e,f;
a=1<<16; b=1<<24; c=a|b; d=1<<2; e=1<<10; f=d|e;
const SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d,
z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z,
a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f,
c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d];
a=1<<20; b=1<<31; c=a|b; d=1<<5; e=1<<15; f=d|e;
const SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d,
a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f,
z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z,
z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e];
a=1<<17; b=1<<27; c=a|b; d=1<<3; e=1<<9; f=d|e;
const SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f,
b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z,
c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d,
b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e];
a=1<<13; b=1<<23; c=a|b; d=1<<0; e=1<<7; f=d|e;
const SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d,
z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f,
b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e,
c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e];
a=1<<25; b=1<<30; c=a|b; d=1<<8; e=1<<19; f=d|e;
const SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z,
a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f,
z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e,
c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d];
a=1<<22; b=1<<29; c=a|b; d=1<<4; e=1<<14; f=d|e;
const SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f,
z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z,
b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z,
a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f];
a=1<<21; b=1<<26; c=a|b; d=1<<1; e=1<<11; f=d|e;
const SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f,
b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e,
b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e,
z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d];
a=1<<18; b=1<<28; c=a|b; d=1<<6; e=1<<12; f=d|e;
const SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d,
c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z,
a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f,
z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e];
/* eslint-enable comma-spacing */
class DES {
constructor(password) {
this.keys = [];
// Set the key.
const pc1m = [], pcr = [], kn = [];
for (let j = 0, l = 56; j < 56; ++j, l -= 8) {
l += l < -5 ? 65 : l < -3 ? 31 : l < -1 ? 63 : l === 27 ? 35 : 0; // PC1
const m = l & 0x7;
pc1m[j] = ((password[l >>> 3] & (1<<m)) !== 0) ? 1: 0;
}
for (let i = 0; i < 16; ++i) {
const m = i << 1;
const n = m + 1;
kn[m] = kn[n] = 0;
for (let o = 28; o < 59; o += 28) {
for (let j = o - 28; j < o; ++j) {
const l = j + totrot[i];
pcr[j] = l < o ? pc1m[l] : pc1m[l - 28];
}
}
for (let j = 0; j < 24; ++j) {
if (pcr[PC2[j]] !== 0) {
kn[m] |= 1 << (23 - j);
}
if (pcr[PC2[j + 24]] !== 0) {
kn[n] |= 1 << (23 - j);
}
}
}
// cookey
for (let i = 0, rawi = 0, KnLi = 0; i < 16; ++i) {
const raw0 = kn[rawi++];
const raw1 = kn[rawi++];
this.keys[KnLi] = (raw0 & 0x00fc0000) << 6;
this.keys[KnLi] |= (raw0 & 0x00000fc0) << 10;
this.keys[KnLi] |= (raw1 & 0x00fc0000) >>> 10;
this.keys[KnLi] |= (raw1 & 0x00000fc0) >>> 6;
++KnLi;
this.keys[KnLi] = (raw0 & 0x0003f000) << 12;
this.keys[KnLi] |= (raw0 & 0x0000003f) << 16;
this.keys[KnLi] |= (raw1 & 0x0003f000) >>> 4;
this.keys[KnLi] |= (raw1 & 0x0000003f);
++KnLi;
}
}
// Encrypt 8 bytes of text
enc8(text) {
const b = text.slice();
let i = 0, l, r, x; // left, right, accumulator
// Squash 8 bytes to 2 ints
l = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++];
r = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++];
x = ((l >>> 4) ^ r) & 0x0f0f0f0f;
r ^= x;
l ^= (x << 4);
x = ((l >>> 16) ^ r) & 0x0000ffff;
r ^= x;
l ^= (x << 16);
x = ((r >>> 2) ^ l) & 0x33333333;
l ^= x;
r ^= (x << 2);
x = ((r >>> 8) ^ l) & 0x00ff00ff;
l ^= x;
r ^= (x << 8);
r = (r << 1) | ((r >>> 31) & 1);
x = (l ^ r) & 0xaaaaaaaa;
l ^= x;
r ^= x;
l = (l << 1) | ((l >>> 31) & 1);
for (let i = 0, keysi = 0; i < 8; ++i) {
x = (r << 28) | (r >>> 4);
x ^= this.keys[keysi++];
let fval = SP7[x & 0x3f];
fval |= SP5[(x >>> 8) & 0x3f];
fval |= SP3[(x >>> 16) & 0x3f];
fval |= SP1[(x >>> 24) & 0x3f];
x = r ^ this.keys[keysi++];
fval |= SP8[x & 0x3f];
fval |= SP6[(x >>> 8) & 0x3f];
fval |= SP4[(x >>> 16) & 0x3f];
fval |= SP2[(x >>> 24) & 0x3f];
l ^= fval;
x = (l << 28) | (l >>> 4);
x ^= this.keys[keysi++];
fval = SP7[x & 0x3f];
fval |= SP5[(x >>> 8) & 0x3f];
fval |= SP3[(x >>> 16) & 0x3f];
fval |= SP1[(x >>> 24) & 0x3f];
x = l ^ this.keys[keysi++];
fval |= SP8[x & 0x0000003f];
fval |= SP6[(x >>> 8) & 0x3f];
fval |= SP4[(x >>> 16) & 0x3f];
fval |= SP2[(x >>> 24) & 0x3f];
r ^= fval;
}
r = (r << 31) | (r >>> 1);
x = (l ^ r) & 0xaaaaaaaa;
l ^= x;
r ^= x;
l = (l << 31) | (l >>> 1);
x = ((l >>> 8) ^ r) & 0x00ff00ff;
r ^= x;
l ^= (x << 8);
x = ((l >>> 2) ^ r) & 0x33333333;
r ^= x;
l ^= (x << 2);
x = ((r >>> 16) ^ l) & 0x0000ffff;
l ^= x;
r ^= (x << 16);
x = ((r >>> 4) ^ l) & 0x0f0f0f0f;
l ^= x;
r ^= (x << 4);
// Spread ints to bytes
x = [r, l];
for (i = 0; i < 8; i++) {
b[i] = (x[i>>>2] >>> (8 * (3 - (i % 4)))) % 256;
if (b[i] < 0) { b[i] += 256; } // unsigned
}
return b;
}
}
export class DESECBCipher {
constructor() {
this._cipher = null;
}
get algorithm() {
return { name: "DES-ECB" };
}
static importKey(key, _algorithm, _extractable, _keyUsages) {
const cipher = new DESECBCipher;
cipher._importKey(key);
return cipher;
}
_importKey(key, _extractable, _keyUsages) {
this._cipher = new DES(key);
}
encrypt(_algorithm, plaintext) {
const x = new Uint8Array(plaintext);
if (x.length % 8 !== 0 || this._cipher === null) {
return null;
}
const n = x.length / 8;
for (let i = 0; i < n; i++) {
x.set(this._cipher.enc8(x.slice(i * 8, i * 8 + 8)), i * 8);
}
return x;
}
}
export class DESCBCCipher {
constructor() {
this._cipher = null;
}
get algorithm() {
return { name: "DES-CBC" };
}
static importKey(key, _algorithm, _extractable, _keyUsages) {
const cipher = new DESCBCCipher;
cipher._importKey(key);
return cipher;
}
_importKey(key) {
this._cipher = new DES(key);
}
encrypt(algorithm, plaintext) {
const x = new Uint8Array(plaintext);
let y = new Uint8Array(algorithm.iv);
if (x.length % 8 !== 0 || this._cipher === null) {
return null;
}
const n = x.length / 8;
for (let i = 0; i < n; i++) {
for (let j = 0; j < 8; j++) {
y[j] ^= plaintext[i * 8 + j];
}
y = this._cipher.enc8(y);
x.set(y, i * 8);
}
return x;
}
}

@ -0,0 +1,55 @@
import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js";
class DHPublicKey {
constructor(key) {
this._key = key;
}
get algorithm() {
return { name: "DH" };
}
exportKey() {
return this._key;
}
}
export class DHCipher {
constructor() {
this._g = null;
this._p = null;
this._gBigInt = null;
this._pBigInt = null;
this._privateKey = null;
}
get algorithm() {
return { name: "DH" };
}
static generateKey(algorithm, _extractable) {
const cipher = new DHCipher;
cipher._generateKey(algorithm);
return { privateKey: cipher, publicKey: new DHPublicKey(cipher._publicKey) };
}
_generateKey(algorithm) {
const g = algorithm.g;
const p = algorithm.p;
this._keyBytes = p.length;
this._gBigInt = u8ArrayToBigInt(g);
this._pBigInt = u8ArrayToBigInt(p);
this._privateKey = window.crypto.getRandomValues(new Uint8Array(this._keyBytes));
this._privateKeyBigInt = u8ArrayToBigInt(this._privateKey);
this._publicKey = bigIntToU8Array(modPow(
this._gBigInt, this._privateKeyBigInt, this._pBigInt), this._keyBytes);
}
deriveBits(algorithm, length) {
const bytes = Math.ceil(length / 8);
const pkey = new Uint8Array(algorithm.public);
const len = bytes > this._keyBytes ? bytes : this._keyBytes;
const secret = modPow(u8ArrayToBigInt(pkey), this._privateKeyBigInt, this._pBigInt);
return bigIntToU8Array(secret, len).slice(0, len);
}
}

@ -0,0 +1,82 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2021 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
/*
* Performs MD5 hashing on an array of bytes, returns an array of bytes
*/
export async function MD5(d) {
let s = "";
for (let i = 0; i < d.length; i++) {
s += String.fromCharCode(d[i]);
}
return M(V(Y(X(s), 8 * s.length)));
}
function M(d) {
let f = new Uint8Array(d.length);
for (let i=0;i<d.length;i++) {
f[i] = d.charCodeAt(i);
}
return f;
}
function X(d) {
let r = Array(d.length >> 2);
for (let m = 0; m < r.length; m++) r[m] = 0;
for (let m = 0; m < 8 * d.length; m += 8) r[m >> 5] |= (255 & d.charCodeAt(m / 8)) << m % 32;
return r;
}
function V(d) {
let r = "";
for (let m = 0; m < 32 * d.length; m += 8) r += String.fromCharCode(d[m >> 5] >>> m % 32 & 255);
return r;
}
function Y(d, g) {
d[g >> 5] |= 128 << g % 32, d[14 + (g + 64 >>> 9 << 4)] = g;
let m = 1732584193, f = -271733879, r = -1732584194, i = 271733878;
for (let n = 0; n < d.length; n += 16) {
let h = m,
t = f,
g = r,
e = i;
f = ii(f = ii(f = ii(f = ii(f = hh(f = hh(f = hh(f = hh(f = gg(f = gg(f = gg(f = gg(f = ff(f = ff(f = ff(f = ff(f, r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 0], 7, -680876936), f, r, d[n + 1], 12, -389564586), m, f, d[n + 2], 17, 606105819), i, m, d[n + 3], 22, -1044525330), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 4], 7, -176418897), f, r, d[n + 5], 12, 1200080426), m, f, d[n + 6], 17, -1473231341), i, m, d[n + 7], 22, -45705983), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 8], 7, 1770035416), f, r, d[n + 9], 12, -1958414417), m, f, d[n + 10], 17, -42063), i, m, d[n + 11], 22, -1990404162), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 12], 7, 1804603682), f, r, d[n + 13], 12, -40341101), m, f, d[n + 14], 17, -1502002290), i, m, d[n + 15], 22, 1236535329), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 1], 5, -165796510), f, r, d[n + 6], 9, -1069501632), m, f, d[n + 11], 14, 643717713), i, m, d[n + 0], 20, -373897302), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 5], 5, -701558691), f, r, d[n + 10], 9, 38016083), m, f, d[n + 15], 14, -660478335), i, m, d[n + 4], 20, -405537848), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 9], 5, 568446438), f, r, d[n + 14], 9, -1019803690), m, f, d[n + 3], 14, -187363961), i, m, d[n + 8], 20, 1163531501), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 13], 5, -1444681467), f, r, d[n + 2], 9, -51403784), m, f, d[n + 7], 14, 1735328473), i, m, d[n + 12], 20, -1926607734), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 5], 4, -378558), f, r, d[n + 8], 11, -2022574463), m, f, d[n + 11], 16, 1839030562), i, m, d[n + 14], 23, -35309556), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 1], 4, -1530992060), f, r, d[n + 4], 11, 1272893353), m, f, d[n + 7], 16, -155497632), i, m, d[n + 10], 23, -1094730640), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 13], 4, 681279174), f, r, d[n + 0], 11, -358537222), m, f, d[n + 3], 16, -722521979), i, m, d[n + 6], 23, 76029189), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 9], 4, -640364487), f, r, d[n + 12], 11, -421815835), m, f, d[n + 15], 16, 530742520), i, m, d[n + 2], 23, -995338651), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 0], 6, -198630844), f, r, d[n + 7], 10, 1126891415), m, f, d[n + 14], 15, -1416354905), i, m, d[n + 5], 21, -57434055), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 12], 6, 1700485571), f, r, d[n + 3], 10, -1894986606), m, f, d[n + 10], 15, -1051523), i, m, d[n + 1], 21, -2054922799), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 8], 6, 1873313359), f, r, d[n + 15], 10, -30611744), m, f, d[n + 6], 15, -1560198380), i, m, d[n + 13], 21, 1309151649), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 4], 6, -145523070), f, r, d[n + 11], 10, -1120210379), m, f, d[n + 2], 15, 718787259), i, m, d[n + 9], 21, -343485551), m = add(m, h), f = add(f, t), r = add(r, g), i = add(i, e);
}
return Array(m, f, r, i);
}
function cmn(d, g, m, f, r, i) {
return add(rol(add(add(g, d), add(f, i)), r), m);
}
function ff(d, g, m, f, r, i, n) {
return cmn(g & m | ~g & f, d, g, r, i, n);
}
function gg(d, g, m, f, r, i, n) {
return cmn(g & f | m & ~f, d, g, r, i, n);
}
function hh(d, g, m, f, r, i, n) {
return cmn(g ^ m ^ f, d, g, r, i, n);
}
function ii(d, g, m, f, r, i, n) {
return cmn(m ^ (g | ~f), d, g, r, i, n);
}
function add(d, g) {
let m = (65535 & d) + (65535 & g);
return (d >> 16) + (g >> 16) + (m >> 16) << 16 | 65535 & m;
}
function rol(d, g) {
return d << g | d >>> 32 - g;
}

@ -0,0 +1,132 @@
import Base64 from "../base64.js";
import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js";
export class RSACipher {
constructor() {
this._keyLength = 0;
this._keyBytes = 0;
this._n = null;
this._e = null;
this._d = null;
this._nBigInt = null;
this._eBigInt = null;
this._dBigInt = null;
this._extractable = false;
}
get algorithm() {
return { name: "RSA-PKCS1-v1_5" };
}
_base64urlDecode(data) {
data = data.replace(/-/g, "+").replace(/_/g, "/");
data = data.padEnd(Math.ceil(data.length / 4) * 4, "=");
return Base64.decode(data);
}
_padArray(arr, length) {
const res = new Uint8Array(length);
res.set(arr, length - arr.length);
return res;
}
static async generateKey(algorithm, extractable, _keyUsages) {
const cipher = new RSACipher;
await cipher._generateKey(algorithm, extractable);
return { privateKey: cipher };
}
async _generateKey(algorithm, extractable) {
this._keyLength = algorithm.modulusLength;
this._keyBytes = Math.ceil(this._keyLength / 8);
const key = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: algorithm.modulusLength,
publicExponent: algorithm.publicExponent,
hash: {name: "SHA-256"},
},
true, ["encrypt", "decrypt"]);
const privateKey = await window.crypto.subtle.exportKey("jwk", key.privateKey);
this._n = this._padArray(this._base64urlDecode(privateKey.n), this._keyBytes);
this._nBigInt = u8ArrayToBigInt(this._n);
this._e = this._padArray(this._base64urlDecode(privateKey.e), this._keyBytes);
this._eBigInt = u8ArrayToBigInt(this._e);
this._d = this._padArray(this._base64urlDecode(privateKey.d), this._keyBytes);
this._dBigInt = u8ArrayToBigInt(this._d);
this._extractable = extractable;
}
static async importKey(key, _algorithm, extractable, keyUsages) {
if (keyUsages.length !== 1 || keyUsages[0] !== "encrypt") {
throw new Error("only support importing RSA public key");
}
const cipher = new RSACipher;
await cipher._importKey(key, extractable);
return cipher;
}
async _importKey(key, extractable) {
const n = key.n;
const e = key.e;
if (n.length !== e.length) {
throw new Error("the sizes of modulus and public exponent do not match");
}
this._keyBytes = n.length;
this._keyLength = this._keyBytes * 8;
this._n = new Uint8Array(this._keyBytes);
this._e = new Uint8Array(this._keyBytes);
this._n.set(n);
this._e.set(e);
this._nBigInt = u8ArrayToBigInt(this._n);
this._eBigInt = u8ArrayToBigInt(this._e);
this._extractable = extractable;
}
async encrypt(_algorithm, message) {
if (message.length > this._keyBytes - 11) {
return null;
}
const ps = new Uint8Array(this._keyBytes - message.length - 3);
window.crypto.getRandomValues(ps);
for (let i = 0; i < ps.length; i++) {
ps[i] = Math.floor(ps[i] * 254 / 255 + 1);
}
const em = new Uint8Array(this._keyBytes);
em[1] = 0x02;
em.set(ps, 2);
em.set(message, ps.length + 3);
const emBigInt = u8ArrayToBigInt(em);
const c = modPow(emBigInt, this._eBigInt, this._nBigInt);
return bigIntToU8Array(c, this._keyBytes);
}
async decrypt(_algorithm, message) {
if (message.length !== this._keyBytes) {
return null;
}
const msgBigInt = u8ArrayToBigInt(message);
const emBigInt = modPow(msgBigInt, this._dBigInt, this._nBigInt);
const em = bigIntToU8Array(emBigInt, this._keyBytes);
if (em[0] !== 0x00 || em[1] !== 0x02) {
return null;
}
let i = 2;
for (; i < em.length; i++) {
if (em[i] === 0x00) {
break;
}
}
if (i === em.length) {
return null;
}
return em.slice(i + 1, em.length);
}
async exportKey() {
if (!this._extractable) {
throw new Error("key is not extractable");
}
return { n: this._n, e: this._e, d: this._d };
}
}

@ -0,0 +1,27 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
export default class CopyRectDecoder {
decodeRect(x, y, width, height, sock, display, depth) {
if (sock.rQwait("COPYRECT", 4)) {
return false;
}
let deltaX = sock.rQshift16();
let deltaY = sock.rQshift16();
if ((width === 0) || (height === 0)) {
return true;
}
display.copyImage(deltaX, deltaY, x, y, width, height);
return true;
}
}

@ -0,0 +1,321 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2024 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
import * as Log from '../util/logging.js';
export class H264Parser {
constructor(data) {
this._data = data;
this._index = 0;
this.profileIdc = null;
this.constraintSet = null;
this.levelIdc = null;
}
_getStartSequenceLen(index) {
let data = this._data;
if (data[index + 0] == 0 && data[index + 1] == 0 && data[index + 2] == 0 && data[index + 3] == 1) {
return 4;
}
if (data[index + 0] == 0 && data[index + 1] == 0 && data[index + 2] == 1) {
return 3;
}
return 0;
}
_indexOfNextNalUnit(index) {
let data = this._data;
for (let i = index; i < data.length; ++i) {
if (this._getStartSequenceLen(i) != 0) {
return i;
}
}
return -1;
}
_parseSps(index) {
this.profileIdc = this._data[index];
this.constraintSet = this._data[index + 1];
this.levelIdc = this._data[index + 2];
}
_parseNalUnit(index) {
const firstByte = this._data[index];
if (firstByte & 0x80) {
throw new Error('H264 parsing sanity check failed, forbidden zero bit is set');
}
const unitType = firstByte & 0x1f;
switch (unitType) {
case 1: // coded slice, non-idr
return { slice: true };
case 5: // coded slice, idr
return { slice: true, key: true };
case 6: // sei
return {};
case 7: // sps
this._parseSps(index + 1);
return {};
case 8: // pps
return {};
default:
Log.Warn("Unhandled unit type: ", unitType);
break;
}
return {};
}
parse() {
const startIndex = this._index;
let isKey = false;
while (this._index < this._data.length) {
const startSequenceLen = this._getStartSequenceLen(this._index);
if (startSequenceLen == 0) {
throw new Error('Invalid start sequence in bit stream');
}
const { slice, key } = this._parseNalUnit(this._index + startSequenceLen);
let nextIndex = this._indexOfNextNalUnit(this._index + startSequenceLen);
if (nextIndex == -1) {
this._index = this._data.length;
} else {
this._index = nextIndex;
}
if (key) {
isKey = true;
}
if (slice) {
break;
}
}
if (startIndex === this._index) {
return null;
}
return {
frame: this._data.subarray(startIndex, this._index),
key: isKey,
};
}
}
export class H264Context {
constructor(width, height) {
this.lastUsed = 0;
this._width = width;
this._height = height;
this._profileIdc = null;
this._constraintSet = null;
this._levelIdc = null;
this._decoder = null;
this._pendingFrames = [];
}
_handleFrame(frame) {
let pending = this._pendingFrames.shift();
if (pending === undefined) {
throw new Error("Pending frame queue empty when receiving frame from decoder");
}
if (pending.timestamp != frame.timestamp) {
throw new Error("Video frame timestamp mismatch. Expected " +
frame.timestamp + " but but got " + pending.timestamp);
}
pending.frame = frame;
pending.ready = true;
pending.resolve();
if (!pending.keep) {
frame.close();
}
}
_handleError(e) {
throw new Error("Failed to decode frame: " + e.message);
}
_configureDecoder(profileIdc, constraintSet, levelIdc) {
if (this._decoder === null || this._decoder.state === 'closed') {
this._decoder = new VideoDecoder({
output: frame => this._handleFrame(frame),
error: e => this._handleError(e),
});
}
const codec = 'avc1.' +
profileIdc.toString(16).padStart(2, '0') +
constraintSet.toString(16).padStart(2, '0') +
levelIdc.toString(16).padStart(2, '0');
this._decoder.configure({
codec: codec,
codedWidth: this._width,
codedHeight: this._height,
optimizeForLatency: true,
});
}
_preparePendingFrame(timestamp) {
let pending = {
timestamp: timestamp,
promise: null,
resolve: null,
frame: null,
ready: false,
keep: false,
};
pending.promise = new Promise((resolve) => {
pending.resolve = resolve;
});
this._pendingFrames.push(pending);
return pending;
}
decode(payload) {
let parser = new H264Parser(payload);
let result = null;
// Ideally, this timestamp should come from the server, but we'll just
// approximate it instead.
let timestamp = Math.round(window.performance.now() * 1e3);
while (true) {
let encodedFrame = parser.parse();
if (encodedFrame === null) {
break;
}
if (parser.profileIdc !== null) {
self._profileIdc = parser.profileIdc;
self._constraintSet = parser.constraintSet;
self._levelIdc = parser.levelIdc;
}
if (this._decoder === null || this._decoder.state !== 'configured') {
if (!encodedFrame.key) {
Log.Warn("Missing key frame. Can't decode until one arrives");
continue;
}
if (self._profileIdc === null) {
Log.Warn('Cannot config decoder. Have not received SPS and PPS yet.');
continue;
}
this._configureDecoder(self._profileIdc, self._constraintSet,
self._levelIdc);
}
result = this._preparePendingFrame(timestamp);
const chunk = new EncodedVideoChunk({
timestamp: timestamp,
type: encodedFrame.key ? 'key' : 'delta',
data: encodedFrame.frame,
});
try {
this._decoder.decode(chunk);
} catch (e) {
Log.Warn("Failed to decode:", e);
}
}
// We only keep last frame of each payload
if (result !== null) {
result.keep = true;
}
return result;
}
}
export default class H264Decoder {
constructor() {
this._tick = 0;
this._contexts = {};
}
_contextId(x, y, width, height) {
return [x, y, width, height].join(',');
}
_findOldestContextId() {
let oldestTick = Number.MAX_VALUE;
let oldestKey = undefined;
for (const [key, value] of Object.entries(this._contexts)) {
if (value.lastUsed < oldestTick) {
oldestTick = value.lastUsed;
oldestKey = key;
}
}
return oldestKey;
}
_createContext(x, y, width, height) {
const maxContexts = 64;
if (Object.keys(this._contexts).length >= maxContexts) {
let oldestContextId = this._findOldestContextId();
delete this._contexts[oldestContextId];
}
let context = new H264Context(width, height);
this._contexts[this._contextId(x, y, width, height)] = context;
return context;
}
_getContext(x, y, width, height) {
let context = this._contexts[this._contextId(x, y, width, height)];
return context !== undefined ? context : this._createContext(x, y, width, height);
}
_resetContext(x, y, width, height) {
delete this._contexts[this._contextId(x, y, width, height)];
}
_resetAllContexts() {
this._contexts = {};
}
decodeRect(x, y, width, height, sock, display, depth) {
const resetContextFlag = 1;
const resetAllContextsFlag = 2;
if (sock.rQwait("h264 header", 8)) {
return false;
}
const length = sock.rQshift32();
const flags = sock.rQshift32();
if (sock.rQwait("h264 payload", length, 8)) {
return false;
}
if (flags & resetAllContextsFlag) {
this._resetAllContexts();
} else if (flags & resetContextFlag) {
this._resetContext(x, y, width, height);
}
let context = this._getContext(x, y, width, height);
context.lastUsed = this._tick++;
if (length !== 0) {
let payload = sock.rQshiftBytes(length, false);
let frame = context.decode(payload);
if (frame !== null) {
display.videoFrame(x, y, width, height, frame);
}
}
return true;
}
}

@ -0,0 +1,181 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
import * as Log from '../util/logging.js';
export default class HextileDecoder {
constructor() {
this._tiles = 0;
this._lastsubencoding = 0;
this._tileBuffer = new Uint8Array(16 * 16 * 4);
}
decodeRect(x, y, width, height, sock, display, depth) {
if (this._tiles === 0) {
this._tilesX = Math.ceil(width / 16);
this._tilesY = Math.ceil(height / 16);
this._totalTiles = this._tilesX * this._tilesY;
this._tiles = this._totalTiles;
}
while (this._tiles > 0) {
let bytes = 1;
if (sock.rQwait("HEXTILE", bytes)) {
return false;
}
let subencoding = sock.rQpeek8();
if (subencoding > 30) { // Raw
throw new Error("Illegal hextile subencoding (subencoding: " +
subencoding + ")");
}
const currTile = this._totalTiles - this._tiles;
const tileX = currTile % this._tilesX;
const tileY = Math.floor(currTile / this._tilesX);
const tx = x + tileX * 16;
const ty = y + tileY * 16;
const tw = Math.min(16, (x + width) - tx);
const th = Math.min(16, (y + height) - ty);
// Figure out how much we are expecting
if (subencoding & 0x01) { // Raw
bytes += tw * th * 4;
} else {
if (subencoding & 0x02) { // Background
bytes += 4;
}
if (subencoding & 0x04) { // Foreground
bytes += 4;
}
if (subencoding & 0x08) { // AnySubrects
bytes++; // Since we aren't shifting it off
if (sock.rQwait("HEXTILE", bytes)) {
return false;
}
let subrects = sock.rQpeekBytes(bytes).at(-1);
if (subencoding & 0x10) { // SubrectsColoured
bytes += subrects * (4 + 2);
} else {
bytes += subrects * 2;
}
}
}
if (sock.rQwait("HEXTILE", bytes)) {
return false;
}
// We know the encoding and have a whole tile
sock.rQshift8();
if (subencoding === 0) {
if (this._lastsubencoding & 0x01) {
// Weird: ignore blanks are RAW
Log.Debug(" Ignoring blank after RAW");
} else {
display.fillRect(tx, ty, tw, th, this._background);
}
} else if (subencoding & 0x01) { // Raw
let pixels = tw * th;
let data = sock.rQshiftBytes(pixels * 4, false);
// Max sure the image is fully opaque
for (let i = 0;i < pixels;i++) {
data[i * 4 + 3] = 255;
}
display.blitImage(tx, ty, tw, th, data, 0);
} else {
if (subencoding & 0x02) { // Background
this._background = new Uint8Array(sock.rQshiftBytes(4));
}
if (subencoding & 0x04) { // Foreground
this._foreground = new Uint8Array(sock.rQshiftBytes(4));
}
this._startTile(tx, ty, tw, th, this._background);
if (subencoding & 0x08) { // AnySubrects
let subrects = sock.rQshift8();
for (let s = 0; s < subrects; s++) {
let color;
if (subencoding & 0x10) { // SubrectsColoured
color = sock.rQshiftBytes(4);
} else {
color = this._foreground;
}
const xy = sock.rQshift8();
const sx = (xy >> 4);
const sy = (xy & 0x0f);
const wh = sock.rQshift8();
const sw = (wh >> 4) + 1;
const sh = (wh & 0x0f) + 1;
this._subTile(sx, sy, sw, sh, color);
}
}
this._finishTile(display);
}
this._lastsubencoding = subencoding;
this._tiles--;
}
return true;
}
// start updating a tile
_startTile(x, y, width, height, color) {
this._tileX = x;
this._tileY = y;
this._tileW = width;
this._tileH = height;
const red = color[0];
const green = color[1];
const blue = color[2];
const data = this._tileBuffer;
for (let i = 0; i < width * height * 4; i += 4) {
data[i] = red;
data[i + 1] = green;
data[i + 2] = blue;
data[i + 3] = 255;
}
}
// update sub-rectangle of the current tile
_subTile(x, y, w, h, color) {
const red = color[0];
const green = color[1];
const blue = color[2];
const xend = x + w;
const yend = y + h;
const data = this._tileBuffer;
const width = this._tileW;
for (let j = y; j < yend; j++) {
for (let i = x; i < xend; i++) {
const p = (i + (j * width)) * 4;
data[p] = red;
data[p + 1] = green;
data[p + 2] = blue;
data[p + 3] = 255;
}
}
}
// draw the current tile to the screen
_finishTile(display) {
display.blitImage(this._tileX, this._tileY,
this._tileW, this._tileH,
this._tileBuffer, 0);
}
}

@ -0,0 +1,161 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
export default class JPEGDecoder {
constructor() {
// RealVNC will reuse the quantization tables
// and Huffman tables, so we need to cache them.
this._cachedQuantTables = [];
this._cachedHuffmanTables = [];
this._segments = [];
}
decodeRect(x, y, width, height, sock, display, depth) {
// A rect of JPEG encodings is simply a JPEG file
while (true) {
let segment = this._readSegment(sock);
if (segment === null) {
return false;
}
this._segments.push(segment);
// End of image?
if (segment[1] === 0xD9) {
break;
}
}
let huffmanTables = [];
let quantTables = [];
for (let segment of this._segments) {
let type = segment[1];
if (type === 0xC4) {
// Huffman tables
huffmanTables.push(segment);
} else if (type === 0xDB) {
// Quantization tables
quantTables.push(segment);
}
}
const sofIndex = this._segments.findIndex(
x => x[1] == 0xC0 || x[1] == 0xC2
);
if (sofIndex == -1) {
throw new Error("Illegal JPEG image without SOF");
}
if (quantTables.length === 0) {
this._segments.splice(sofIndex+1, 0,
...this._cachedQuantTables);
}
if (huffmanTables.length === 0) {
this._segments.splice(sofIndex+1, 0,
...this._cachedHuffmanTables);
}
let length = 0;
for (let segment of this._segments) {
length += segment.length;
}
let data = new Uint8Array(length);
length = 0;
for (let segment of this._segments) {
data.set(segment, length);
length += segment.length;
}
display.imageRect(x, y, width, height, "image/jpeg", data);
if (huffmanTables.length !== 0) {
this._cachedHuffmanTables = huffmanTables;
}
if (quantTables.length !== 0) {
this._cachedQuantTables = quantTables;
}
this._segments = [];
return true;
}
_readSegment(sock) {
if (sock.rQwait("JPEG", 2)) {
return null;
}
let marker = sock.rQshift8();
if (marker != 0xFF) {
throw new Error("Illegal JPEG marker received (byte: " +
marker + ")");
}
let type = sock.rQshift8();
if (type >= 0xD0 && type <= 0xD9 || type == 0x01) {
// No length after marker
return new Uint8Array([marker, type]);
}
if (sock.rQwait("JPEG", 2, 2)) {
return null;
}
let length = sock.rQshift16();
if (length < 2) {
throw new Error("Illegal JPEG length received (length: " +
length + ")");
}
if (sock.rQwait("JPEG", length-2, 4)) {
return null;
}
let extra = 0;
if (type === 0xDA) {
// start of scan
if (sock.rQwait("JPEG", length-2 + 2, 4)) {
return null;
}
let len = sock.rQlen();
let data = sock.rQpeekBytes(len, false);
while (true) {
let idx = data.indexOf(0xFF, length-2+extra);
if (idx === -1) {
sock.rQwait("JPEG", Infinity, 4);
return null;
}
if (idx === len-1) {
sock.rQwait("JPEG", Infinity, 4);
return null;
}
if (data.at(idx+1) === 0x00 ||
(data.at(idx+1) >= 0xD0 && data.at(idx+1) <= 0xD7)) {
extra = idx+2 - (length-2);
continue;
}
extra = idx - (length-2);
break;
}
}
let segment = new Uint8Array(2 + length + extra);
segment[0] = marker;
segment[1] = type;
segment[2] = length >> 8;
segment[3] = length;
segment.set(sock.rQshiftBytes(length-2+extra, false), 4);
return segment;
}
}

@ -0,0 +1,59 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
export default class RawDecoder {
constructor() {
this._lines = 0;
}
decodeRect(x, y, width, height, sock, display, depth) {
if ((width === 0) || (height === 0)) {
return true;
}
if (this._lines === 0) {
this._lines = height;
}
const pixelSize = depth == 8 ? 1 : 4;
const bytesPerLine = width * pixelSize;
while (this._lines > 0) {
if (sock.rQwait("RAW", bytesPerLine)) {
return false;
}
const curY = y + (height - this._lines);
let data = sock.rQshiftBytes(bytesPerLine, false);
// Convert data if needed
if (depth == 8) {
const newdata = new Uint8Array(width * 4);
for (let i = 0; i < width; i++) {
newdata[i * 4 + 0] = ((data[i] >> 0) & 0x3) * 255 / 3;
newdata[i * 4 + 1] = ((data[i] >> 2) & 0x3) * 255 / 3;
newdata[i * 4 + 2] = ((data[i] >> 4) & 0x3) * 255 / 3;
newdata[i * 4 + 3] = 255;
}
data = newdata;
}
// Max sure the image is fully opaque
for (let i = 0; i < width; i++) {
data[i * 4 + 3] = 255;
}
display.blitImage(x, curY, width, 1, data, 0);
this._lines--;
}
return true;
}
}

@ -0,0 +1,44 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
export default class RREDecoder {
constructor() {
this._subrects = 0;
}
decodeRect(x, y, width, height, sock, display, depth) {
if (this._subrects === 0) {
if (sock.rQwait("RRE", 4 + 4)) {
return false;
}
this._subrects = sock.rQshift32();
let color = sock.rQshiftBytes(4); // Background
display.fillRect(x, y, width, height, color);
}
while (this._subrects > 0) {
if (sock.rQwait("RRE", 4 + 8)) {
return false;
}
let color = sock.rQshiftBytes(4);
let sx = sock.rQshift16();
let sy = sock.rQshift16();
let swidth = sock.rQshift16();
let sheight = sock.rQshift16();
display.fillRect(x + sx, y + sy, swidth, sheight, color);
this._subrects--;
}
return true;
}
}

@ -0,0 +1,393 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
import * as Log from '../util/logging.js';
import Inflator from "../inflator.js";
export default class TightDecoder {
constructor() {
this._ctl = null;
this._filter = null;
this._numColors = 0;
this._palette = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
this._len = 0;
this._zlibs = [];
for (let i = 0; i < 4; i++) {
this._zlibs[i] = new Inflator();
}
}
decodeRect(x, y, width, height, sock, display, depth) {
if (this._ctl === null) {
if (sock.rQwait("TIGHT compression-control", 1)) {
return false;
}
this._ctl = sock.rQshift8();
// Reset streams if the server requests it
for (let i = 0; i < 4; i++) {
if ((this._ctl >> i) & 1) {
this._zlibs[i].reset();
Log.Info("Reset zlib stream " + i);
}
}
// Figure out filter
this._ctl = this._ctl >> 4;
}
let ret;
if (this._ctl === 0x08) {
ret = this._fillRect(x, y, width, height,
sock, display, depth);
} else if (this._ctl === 0x09) {
ret = this._jpegRect(x, y, width, height,
sock, display, depth);
} else if (this._ctl === 0x0A) {
ret = this._pngRect(x, y, width, height,
sock, display, depth);
} else if ((this._ctl & 0x08) == 0) {
ret = this._basicRect(this._ctl, x, y, width, height,
sock, display, depth);
} else {
throw new Error("Illegal tight compression received (ctl: " +
this._ctl + ")");
}
if (ret) {
this._ctl = null;
}
return ret;
}
_fillRect(x, y, width, height, sock, display, depth) {
if (sock.rQwait("TIGHT", 3)) {
return false;
}
let pixel = sock.rQshiftBytes(3);
display.fillRect(x, y, width, height, pixel, false);
return true;
}
_jpegRect(x, y, width, height, sock, display, depth) {
let data = this._readData(sock);
if (data === null) {
return false;
}
display.imageRect(x, y, width, height, "image/jpeg", data);
return true;
}
_pngRect(x, y, width, height, sock, display, depth) {
throw new Error("PNG received in standard Tight rect");
}
_basicRect(ctl, x, y, width, height, sock, display, depth) {
if (this._filter === null) {
if (ctl & 0x4) {
if (sock.rQwait("TIGHT", 1)) {
return false;
}
this._filter = sock.rQshift8();
} else {
// Implicit CopyFilter
this._filter = 0;
}
}
let streamId = ctl & 0x3;
let ret;
switch (this._filter) {
case 0: // CopyFilter
ret = this._copyFilter(streamId, x, y, width, height,
sock, display, depth);
break;
case 1: // PaletteFilter
ret = this._paletteFilter(streamId, x, y, width, height,
sock, display, depth);
break;
case 2: // GradientFilter
ret = this._gradientFilter(streamId, x, y, width, height,
sock, display, depth);
break;
default:
throw new Error("Illegal tight filter received (ctl: " +
this._filter + ")");
}
if (ret) {
this._filter = null;
}
return ret;
}
_copyFilter(streamId, x, y, width, height, sock, display, depth) {
const uncompressedSize = width * height * 3;
let data;
if (uncompressedSize === 0) {
return true;
}
if (uncompressedSize < 12) {
if (sock.rQwait("TIGHT", uncompressedSize)) {
return false;
}
data = sock.rQshiftBytes(uncompressedSize);
} else {
data = this._readData(sock);
if (data === null) {
return false;
}
this._zlibs[streamId].setInput(data);
data = this._zlibs[streamId].inflate(uncompressedSize);
this._zlibs[streamId].setInput(null);
}
let rgbx = new Uint8Array(width * height * 4);
for (let i = 0, j = 0; i < width * height * 4; i += 4, j += 3) {
rgbx[i] = data[j];
rgbx[i + 1] = data[j + 1];
rgbx[i + 2] = data[j + 2];
rgbx[i + 3] = 255; // Alpha
}
display.blitImage(x, y, width, height, rgbx, 0, false);
return true;
}
_paletteFilter(streamId, x, y, width, height, sock, display, depth) {
if (this._numColors === 0) {
if (sock.rQwait("TIGHT palette", 1)) {
return false;
}
const numColors = sock.rQpeek8() + 1;
const paletteSize = numColors * 3;
if (sock.rQwait("TIGHT palette", 1 + paletteSize)) {
return false;
}
this._numColors = numColors;
sock.rQskipBytes(1);
sock.rQshiftTo(this._palette, paletteSize);
}
const bpp = (this._numColors <= 2) ? 1 : 8;
const rowSize = Math.floor((width * bpp + 7) / 8);
const uncompressedSize = rowSize * height;
let data;
if (uncompressedSize === 0) {
return true;
}
if (uncompressedSize < 12) {
if (sock.rQwait("TIGHT", uncompressedSize)) {
return false;
}
data = sock.rQshiftBytes(uncompressedSize);
} else {
data = this._readData(sock);
if (data === null) {
return false;
}
this._zlibs[streamId].setInput(data);
data = this._zlibs[streamId].inflate(uncompressedSize);
this._zlibs[streamId].setInput(null);
}
// Convert indexed (palette based) image data to RGB
if (this._numColors == 2) {
this._monoRect(x, y, width, height, data, this._palette, display);
} else {
this._paletteRect(x, y, width, height, data, this._palette, display);
}
this._numColors = 0;
return true;
}
_monoRect(x, y, width, height, data, palette, display) {
// Convert indexed (palette based) image data to RGB
// TODO: reduce number of calculations inside loop
const dest = this._getScratchBuffer(width * height * 4);
const w = Math.floor((width + 7) / 8);
const w1 = Math.floor(width / 8);
for (let y = 0; y < height; y++) {
let dp, sp, x;
for (x = 0; x < w1; x++) {
for (let b = 7; b >= 0; b--) {
dp = (y * width + x * 8 + 7 - b) * 4;
sp = (data[y * w + x] >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
dest[dp + 3] = 255;
}
}
for (let b = 7; b >= 8 - width % 8; b--) {
dp = (y * width + x * 8 + 7 - b) * 4;
sp = (data[y * w + x] >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
dest[dp + 3] = 255;
}
}
display.blitImage(x, y, width, height, dest, 0, false);
}
_paletteRect(x, y, width, height, data, palette, display) {
// Convert indexed (palette based) image data to RGB
const dest = this._getScratchBuffer(width * height * 4);
const total = width * height * 4;
for (let i = 0, j = 0; i < total; i += 4, j++) {
const sp = data[j] * 3;
dest[i] = palette[sp];
dest[i + 1] = palette[sp + 1];
dest[i + 2] = palette[sp + 2];
dest[i + 3] = 255;
}
display.blitImage(x, y, width, height, dest, 0, false);
}
_gradientFilter(streamId, x, y, width, height, sock, display, depth) {
// assume the TPIXEL is 3 bytes long
const uncompressedSize = width * height * 3;
let data;
if (uncompressedSize === 0) {
return true;
}
if (uncompressedSize < 12) {
if (sock.rQwait("TIGHT", uncompressedSize)) {
return false;
}
data = sock.rQshiftBytes(uncompressedSize);
} else {
data = this._readData(sock);
if (data === null) {
return false;
}
this._zlibs[streamId].setInput(data);
data = this._zlibs[streamId].inflate(uncompressedSize);
this._zlibs[streamId].setInput(null);
}
let rgbx = new Uint8Array(4 * width * height);
let rgbxIndex = 0, dataIndex = 0;
let left = new Uint8Array(3);
for (let x = 0; x < width; x++) {
for (let c = 0; c < 3; c++) {
const prediction = left[c];
const value = data[dataIndex++] + prediction;
rgbx[rgbxIndex++] = value;
left[c] = value;
}
rgbx[rgbxIndex++] = 255;
}
let upperIndex = 0;
let upper = new Uint8Array(3),
upperleft = new Uint8Array(3);
for (let y = 1; y < height; y++) {
left.fill(0);
upperleft.fill(0);
for (let x = 0; x < width; x++) {
for (let c = 0; c < 3; c++) {
upper[c] = rgbx[upperIndex++];
let prediction = left[c] + upper[c] - upperleft[c];
if (prediction < 0) {
prediction = 0;
} else if (prediction > 255) {
prediction = 255;
}
const value = data[dataIndex++] + prediction;
rgbx[rgbxIndex++] = value;
upperleft[c] = upper[c];
left[c] = value;
}
rgbx[rgbxIndex++] = 255;
upperIndex++;
}
}
display.blitImage(x, y, width, height, rgbx, 0, false);
return true;
}
_readData(sock) {
if (this._len === 0) {
if (sock.rQwait("TIGHT", 3)) {
return null;
}
let byte;
byte = sock.rQshift8();
this._len = byte & 0x7f;
if (byte & 0x80) {
byte = sock.rQshift8();
this._len |= (byte & 0x7f) << 7;
if (byte & 0x80) {
byte = sock.rQshift8();
this._len |= byte << 14;
}
}
}
if (sock.rQwait("TIGHT", this._len)) {
return null;
}
let data = sock.rQshiftBytes(this._len, false);
this._len = 0;
return data;
}
_getScratchBuffer(size) {
if (!this._scratchBuffer || (this._scratchBuffer.length < size)) {
this._scratchBuffer = new Uint8Array(size);
}
return this._scratchBuffer;
}
}

@ -0,0 +1,27 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
import TightDecoder from './tight.js';
export default class TightPNGDecoder extends TightDecoder {
_pngRect(x, y, width, height, sock, display, depth) {
let data = this._readData(sock);
if (data === null) {
return false;
}
display.imageRect(x, y, width, height, "image/png", data);
return true;
}
_basicRect(ctl, x, y, width, height, sock, display, depth) {
throw new Error("BasicCompression received in TightPNG rect");
}
}

@ -0,0 +1,51 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2024 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
import Inflator from "../inflator.js";
export default class ZlibDecoder {
constructor() {
this._zlib = new Inflator();
this._length = 0;
}
decodeRect(x, y, width, height, sock, display, depth) {
if ((width === 0) || (height === 0)) {
return true;
}
if (this._length === 0) {
if (sock.rQwait("ZLIB", 4)) {
return false;
}
this._length = sock.rQshift32();
}
if (sock.rQwait("ZLIB", this._length)) {
return false;
}
let data = new Uint8Array(sock.rQshiftBytes(this._length, false));
this._length = 0;
this._zlib.setInput(data);
data = this._zlib.inflate(width * height * 4);
this._zlib.setInput(null);
// Max sure the image is fully opaque
for (let i = 0; i < width * height; i++) {
data[i * 4 + 3] = 255;
}
display.blitImage(x, y, width, height, data, 0);
return true;
}
}

@ -0,0 +1,185 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2021 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
import Inflate from "../inflator.js";
const ZRLE_TILE_WIDTH = 64;
const ZRLE_TILE_HEIGHT = 64;
export default class ZRLEDecoder {
constructor() {
this._length = 0;
this._inflator = new Inflate();
this._pixelBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4);
this._tileBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4);
}
decodeRect(x, y, width, height, sock, display, depth) {
if (this._length === 0) {
if (sock.rQwait("ZLib data length", 4)) {
return false;
}
this._length = sock.rQshift32();
}
if (sock.rQwait("Zlib data", this._length)) {
return false;
}
const data = sock.rQshiftBytes(this._length, false);
this._inflator.setInput(data);
for (let ty = y; ty < y + height; ty += ZRLE_TILE_HEIGHT) {
let th = Math.min(ZRLE_TILE_HEIGHT, y + height - ty);
for (let tx = x; tx < x + width; tx += ZRLE_TILE_WIDTH) {
let tw = Math.min(ZRLE_TILE_WIDTH, x + width - tx);
const tileSize = tw * th;
const subencoding = this._inflator.inflate(1)[0];
if (subencoding === 0) {
// raw data
const data = this._readPixels(tileSize);
display.blitImage(tx, ty, tw, th, data, 0, false);
} else if (subencoding === 1) {
// solid
const background = this._readPixels(1);
display.fillRect(tx, ty, tw, th, [background[0], background[1], background[2]]);
} else if (subencoding >= 2 && subencoding <= 16) {
const data = this._decodePaletteTile(subencoding, tileSize, tw, th);
display.blitImage(tx, ty, tw, th, data, 0, false);
} else if (subencoding === 128) {
const data = this._decodeRLETile(tileSize);
display.blitImage(tx, ty, tw, th, data, 0, false);
} else if (subencoding >= 130 && subencoding <= 255) {
const data = this._decodeRLEPaletteTile(subencoding - 128, tileSize);
display.blitImage(tx, ty, tw, th, data, 0, false);
} else {
throw new Error('Unknown subencoding: ' + subencoding);
}
}
}
this._length = 0;
return true;
}
_getBitsPerPixelInPalette(paletteSize) {
if (paletteSize <= 2) {
return 1;
} else if (paletteSize <= 4) {
return 2;
} else if (paletteSize <= 16) {
return 4;
}
}
_readPixels(pixels) {
let data = this._pixelBuffer;
const buffer = this._inflator.inflate(3*pixels);
for (let i = 0, j = 0; i < pixels*4; i += 4, j += 3) {
data[i] = buffer[j];
data[i + 1] = buffer[j + 1];
data[i + 2] = buffer[j + 2];
data[i + 3] = 255; // Add the Alpha
}
return data;
}
_decodePaletteTile(paletteSize, tileSize, tilew, tileh) {
const data = this._tileBuffer;
const palette = this._readPixels(paletteSize);
const bitsPerPixel = this._getBitsPerPixelInPalette(paletteSize);
const mask = (1 << bitsPerPixel) - 1;
let offset = 0;
let encoded = this._inflator.inflate(1)[0];
for (let y=0; y<tileh; y++) {
let shift = 8-bitsPerPixel;
for (let x=0; x<tilew; x++) {
if (shift<0) {
shift=8-bitsPerPixel;
encoded = this._inflator.inflate(1)[0];
}
let indexInPalette = (encoded>>shift) & mask;
data[offset] = palette[indexInPalette * 4];
data[offset + 1] = palette[indexInPalette * 4 + 1];
data[offset + 2] = palette[indexInPalette * 4 + 2];
data[offset + 3] = palette[indexInPalette * 4 + 3];
offset += 4;
shift-=bitsPerPixel;
}
if (shift<8-bitsPerPixel && y<tileh-1) {
encoded = this._inflator.inflate(1)[0];
}
}
return data;
}
_decodeRLETile(tileSize) {
const data = this._tileBuffer;
let i = 0;
while (i < tileSize) {
const pixel = this._readPixels(1);
const length = this._readRLELength();
for (let j = 0; j < length; j++) {
data[i * 4] = pixel[0];
data[i * 4 + 1] = pixel[1];
data[i * 4 + 2] = pixel[2];
data[i * 4 + 3] = pixel[3];
i++;
}
}
return data;
}
_decodeRLEPaletteTile(paletteSize, tileSize) {
const data = this._tileBuffer;
// palette
const palette = this._readPixels(paletteSize);
let offset = 0;
while (offset < tileSize) {
let indexInPalette = this._inflator.inflate(1)[0];
let length = 1;
if (indexInPalette >= 128) {
indexInPalette -= 128;
length = this._readRLELength();
}
if (indexInPalette > paletteSize) {
throw new Error('Too big index in palette: ' + indexInPalette + ', palette size: ' + paletteSize);
}
if (offset + length > tileSize) {
throw new Error('Too big rle length in palette mode: ' + length + ', allowed length is: ' + (tileSize - offset));
}
for (let j = 0; j < length; j++) {
data[offset * 4] = palette[indexInPalette * 4];
data[offset * 4 + 1] = palette[indexInPalette * 4 + 1];
data[offset * 4 + 2] = palette[indexInPalette * 4 + 2];
data[offset * 4 + 3] = palette[indexInPalette * 4 + 3];
offset++;
}
}
return data;
}
_readRLELength() {
let length = 0;
let current = 0;
do {
current = this._inflator.inflate(1)[0];
length += current;
} while (current === 255);
return length + 1;
}
}

@ -0,0 +1,84 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2020 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js";
import { Z_FULL_FLUSH, Z_DEFAULT_COMPRESSION } from "../vendor/pako/lib/zlib/deflate.js";
import ZStream from "../vendor/pako/lib/zlib/zstream.js";
export default class Deflator {
constructor() {
this.strm = new ZStream();
this.chunkSize = 1024 * 10 * 10;
this.outputBuffer = new Uint8Array(this.chunkSize);
deflateInit(this.strm, Z_DEFAULT_COMPRESSION);
}
deflate(inData) {
/* eslint-disable camelcase */
this.strm.input = inData;
this.strm.avail_in = this.strm.input.length;
this.strm.next_in = 0;
this.strm.output = this.outputBuffer;
this.strm.avail_out = this.chunkSize;
this.strm.next_out = 0;
/* eslint-enable camelcase */
let lastRet = deflate(this.strm, Z_FULL_FLUSH);
let outData = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
if (lastRet < 0) {
throw new Error("zlib deflate failed");
}
if (this.strm.avail_in > 0) {
// Read chunks until done
let chunks = [outData];
let totalLen = outData.length;
do {
/* eslint-disable camelcase */
this.strm.output = new Uint8Array(this.chunkSize);
this.strm.next_out = 0;
this.strm.avail_out = this.chunkSize;
/* eslint-enable camelcase */
lastRet = deflate(this.strm, Z_FULL_FLUSH);
if (lastRet < 0) {
throw new Error("zlib deflate failed");
}
let chunk = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
totalLen += chunk.length;
chunks.push(chunk);
} while (this.strm.avail_in > 0);
// Combine chunks into a single data
let newData = new Uint8Array(totalLen);
let offset = 0;
for (let i = 0; i < chunks.length; i++) {
newData.set(chunks[i], offset);
offset += chunks[i].length;
}
outData = newData;
}
/* eslint-disable camelcase */
this.strm.input = null;
this.strm.avail_in = 0;
this.strm.next_in = 0;
/* eslint-enable camelcase */
return outData;
}
}

@ -0,0 +1,578 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
import * as Log from './util/logging.js';
import Base64 from "./base64.js";
import { toSigned32bit } from './util/int.js';
export default class Display {
constructor(target) {
this._drawCtx = null;
this._renderQ = []; // queue drawing actions for in-oder rendering
this._flushPromise = null;
// the full frame buffer (logical canvas) size
this._fbWidth = 0;
this._fbHeight = 0;
this._prevDrawStyle = "";
Log.Debug(">> Display.constructor");
// The visible canvas
this._target = target;
if (!this._target) {
throw new Error("Target must be set");
}
if (typeof this._target === 'string') {
throw new Error('target must be a DOM element');
}
if (!this._target.getContext) {
throw new Error("no getContext method");
}
this._targetCtx = this._target.getContext('2d');
// the visible canvas viewport (i.e. what actually gets seen)
this._viewportLoc = { 'x': 0, 'y': 0, 'w': this._target.width, 'h': this._target.height };
// The hidden canvas, where we do the actual rendering
this._backbuffer = document.createElement('canvas');
this._drawCtx = this._backbuffer.getContext('2d');
this._damageBounds = { left: 0, top: 0,
right: this._backbuffer.width,
bottom: this._backbuffer.height };
Log.Debug("User Agent: " + navigator.userAgent);
Log.Debug("<< Display.constructor");
// ===== PROPERTIES =====
this._scale = 1.0;
this._clipViewport = false;
}
// ===== PROPERTIES =====
get scale() { return this._scale; }
set scale(scale) {
this._rescale(scale);
}
get clipViewport() { return this._clipViewport; }
set clipViewport(viewport) {
this._clipViewport = viewport;
// May need to readjust the viewport dimensions
const vp = this._viewportLoc;
this.viewportChangeSize(vp.w, vp.h);
this.viewportChangePos(0, 0);
}
get width() {
return this._fbWidth;
}
get height() {
return this._fbHeight;
}
// ===== PUBLIC METHODS =====
viewportChangePos(deltaX, deltaY) {
const vp = this._viewportLoc;
deltaX = Math.floor(deltaX);
deltaY = Math.floor(deltaY);
if (!this._clipViewport) {
deltaX = -vp.w; // clamped later of out of bounds
deltaY = -vp.h;
}
const vx2 = vp.x + vp.w - 1;
const vy2 = vp.y + vp.h - 1;
// Position change
if (deltaX < 0 && vp.x + deltaX < 0) {
deltaX = -vp.x;
}
if (vx2 + deltaX >= this._fbWidth) {
deltaX -= vx2 + deltaX - this._fbWidth + 1;
}
if (vp.y + deltaY < 0) {
deltaY = -vp.y;
}
if (vy2 + deltaY >= this._fbHeight) {
deltaY -= (vy2 + deltaY - this._fbHeight + 1);
}
if (deltaX === 0 && deltaY === 0) {
return;
}
Log.Debug("viewportChange deltaX: " + deltaX + ", deltaY: " + deltaY);
vp.x += deltaX;
vp.y += deltaY;
this._damage(vp.x, vp.y, vp.w, vp.h);
this.flip();
}
viewportChangeSize(width, height) {
if (!this._clipViewport ||
typeof(width) === "undefined" ||
typeof(height) === "undefined") {
Log.Debug("Setting viewport to full display region");
width = this._fbWidth;
height = this._fbHeight;
}
width = Math.floor(width);
height = Math.floor(height);
if (width > this._fbWidth) {
width = this._fbWidth;
}
if (height > this._fbHeight) {
height = this._fbHeight;
}
const vp = this._viewportLoc;
if (vp.w !== width || vp.h !== height) {
vp.w = width;
vp.h = height;
const canvas = this._target;
canvas.width = width;
canvas.height = height;
// The position might need to be updated if we've grown
this.viewportChangePos(0, 0);
this._damage(vp.x, vp.y, vp.w, vp.h);
this.flip();
// Update the visible size of the target canvas
this._rescale(this._scale);
}
}
absX(x) {
if (this._scale === 0) {
return 0;
}
return toSigned32bit(x / this._scale + this._viewportLoc.x);
}
absY(y) {
if (this._scale === 0) {
return 0;
}
return toSigned32bit(y / this._scale + this._viewportLoc.y);
}
resize(width, height) {
this._prevDrawStyle = "";
this._fbWidth = width;
this._fbHeight = height;
const canvas = this._backbuffer;
if (canvas.width !== width || canvas.height !== height) {
// We have to save the canvas data since changing the size will clear it
let saveImg = null;
if (canvas.width > 0 && canvas.height > 0) {
saveImg = this._drawCtx.getImageData(0, 0, canvas.width, canvas.height);
}
if (canvas.width !== width) {
canvas.width = width;
}
if (canvas.height !== height) {
canvas.height = height;
}
if (saveImg) {
this._drawCtx.putImageData(saveImg, 0, 0);
}
}
// Readjust the viewport as it may be incorrectly sized
// and positioned
const vp = this._viewportLoc;
this.viewportChangeSize(vp.w, vp.h);
this.viewportChangePos(0, 0);
}
getImageData() {
return this._drawCtx.getImageData(0, 0, this.width, this.height);
}
toDataURL(type, encoderOptions) {
return this._backbuffer.toDataURL(type, encoderOptions);
}
toBlob(callback, type, quality) {
return this._backbuffer.toBlob(callback, type, quality);
}
// Track what parts of the visible canvas that need updating
_damage(x, y, w, h) {
if (x < this._damageBounds.left) {
this._damageBounds.left = x;
}
if (y < this._damageBounds.top) {
this._damageBounds.top = y;
}
if ((x + w) > this._damageBounds.right) {
this._damageBounds.right = x + w;
}
if ((y + h) > this._damageBounds.bottom) {
this._damageBounds.bottom = y + h;
}
}
// Update the visible canvas with the contents of the
// rendering canvas
flip(fromQueue) {
if (this._renderQ.length !== 0 && !fromQueue) {
this._renderQPush({
'type': 'flip'
});
} else {
let x = this._damageBounds.left;
let y = this._damageBounds.top;
let w = this._damageBounds.right - x;
let h = this._damageBounds.bottom - y;
let vx = x - this._viewportLoc.x;
let vy = y - this._viewportLoc.y;
if (vx < 0) {
w += vx;
x -= vx;
vx = 0;
}
if (vy < 0) {
h += vy;
y -= vy;
vy = 0;
}
if ((vx + w) > this._viewportLoc.w) {
w = this._viewportLoc.w - vx;
}
if ((vy + h) > this._viewportLoc.h) {
h = this._viewportLoc.h - vy;
}
if ((w > 0) && (h > 0)) {
// FIXME: We may need to disable image smoothing here
// as well (see copyImage()), but we haven't
// noticed any problem yet.
this._targetCtx.drawImage(this._backbuffer,
x, y, w, h,
vx, vy, w, h);
}
this._damageBounds.left = this._damageBounds.top = 65535;
this._damageBounds.right = this._damageBounds.bottom = 0;
}
}
pending() {
return this._renderQ.length > 0;
}
flush() {
if (this._renderQ.length === 0) {
return Promise.resolve();
} else {
if (this._flushPromise === null) {
this._flushPromise = new Promise((resolve) => {
this._flushResolve = resolve;
});
}
return this._flushPromise;
}
}
fillRect(x, y, width, height, color, fromQueue) {
if (this._renderQ.length !== 0 && !fromQueue) {
this._renderQPush({
'type': 'fill',
'x': x,
'y': y,
'width': width,
'height': height,
'color': color
});
} else {
this._setFillColor(color);
this._drawCtx.fillRect(x, y, width, height);
this._damage(x, y, width, height);
}
}
copyImage(oldX, oldY, newX, newY, w, h, fromQueue) {
if (this._renderQ.length !== 0 && !fromQueue) {
this._renderQPush({
'type': 'copy',
'oldX': oldX,
'oldY': oldY,
'x': newX,
'y': newY,
'width': w,
'height': h,
});
} else {
// Due to this bug among others [1] we need to disable the image-smoothing to
// avoid getting a blur effect when copying data.
//
// 1. https://bugzilla.mozilla.org/show_bug.cgi?id=1194719
//
// We need to set these every time since all properties are reset
// when the the size is changed
this._drawCtx.mozImageSmoothingEnabled = false;
this._drawCtx.webkitImageSmoothingEnabled = false;
this._drawCtx.msImageSmoothingEnabled = false;
this._drawCtx.imageSmoothingEnabled = false;
this._drawCtx.drawImage(this._backbuffer,
oldX, oldY, w, h,
newX, newY, w, h);
this._damage(newX, newY, w, h);
}
}
imageRect(x, y, width, height, mime, arr) {
/* The internal logic cannot handle empty images, so bail early */
if ((width === 0) || (height === 0)) {
return;
}
const img = new Image();
img.src = "data: " + mime + ";base64," + Base64.encode(arr);
this._renderQPush({
'type': 'img',
'img': img,
'x': x,
'y': y,
'width': width,
'height': height
});
}
videoFrame(x, y, width, height, frame) {
this._renderQPush({
'type': 'frame',
'frame': frame,
'x': x,
'y': y,
'width': width,
'height': height
});
}
blitImage(x, y, width, height, arr, offset, fromQueue) {
if (this._renderQ.length !== 0 && !fromQueue) {
// NB(directxman12): it's technically more performant here to use preallocated arrays,
// but it's a lot of extra work for not a lot of payoff -- if we're using the render queue,
// this probably isn't getting called *nearly* as much
const newArr = new Uint8Array(width * height * 4);
newArr.set(new Uint8Array(arr.buffer, 0, newArr.length));
this._renderQPush({
'type': 'blit',
'data': newArr,
'x': x,
'y': y,
'width': width,
'height': height,
});
} else {
// NB(directxman12): arr must be an Type Array view
let data = new Uint8ClampedArray(arr.buffer,
arr.byteOffset + offset,
width * height * 4);
let img = new ImageData(data, width, height);
this._drawCtx.putImageData(img, x, y);
this._damage(x, y, width, height);
}
}
drawImage(img, ...args) {
this._drawCtx.drawImage(img, ...args);
if (args.length <= 4) {
const [x, y] = args;
this._damage(x, y, img.width, img.height);
} else {
const [,, sw, sh, dx, dy] = args;
this._damage(dx, dy, sw, sh);
}
}
autoscale(containerWidth, containerHeight) {
let scaleRatio;
if (containerWidth === 0 || containerHeight === 0) {
scaleRatio = 0;
} else {
const vp = this._viewportLoc;
const targetAspectRatio = containerWidth / containerHeight;
const fbAspectRatio = vp.w / vp.h;
if (fbAspectRatio >= targetAspectRatio) {
scaleRatio = containerWidth / vp.w;
} else {
scaleRatio = containerHeight / vp.h;
}
}
this._rescale(scaleRatio);
}
// ===== PRIVATE METHODS =====
_rescale(factor) {
this._scale = factor;
const vp = this._viewportLoc;
// NB(directxman12): If you set the width directly, or set the
// style width to a number, the canvas is cleared.
// However, if you set the style width to a string
// ('NNNpx'), the canvas is scaled without clearing.
const width = factor * vp.w + 'px';
const height = factor * vp.h + 'px';
if ((this._target.style.width !== width) ||
(this._target.style.height !== height)) {
this._target.style.width = width;
this._target.style.height = height;
}
}
_setFillColor(color) {
const newStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
if (newStyle !== this._prevDrawStyle) {
this._drawCtx.fillStyle = newStyle;
this._prevDrawStyle = newStyle;
}
}
_renderQPush(action) {
this._renderQ.push(action);
if (this._renderQ.length === 1) {
// If this can be rendered immediately it will be, otherwise
// the scanner will wait for the relevant event
this._scanRenderQ();
}
}
_resumeRenderQ() {
// "this" is the object that is ready, not the
// display object
this.removeEventListener('load', this._noVNCDisplay._resumeRenderQ);
this._noVNCDisplay._scanRenderQ();
}
_scanRenderQ() {
let ready = true;
while (ready && this._renderQ.length > 0) {
const a = this._renderQ[0];
switch (a.type) {
case 'flip':
this.flip(true);
break;
case 'copy':
this.copyImage(a.oldX, a.oldY, a.x, a.y, a.width, a.height, true);
break;
case 'fill':
this.fillRect(a.x, a.y, a.width, a.height, a.color, true);
break;
case 'blit':
this.blitImage(a.x, a.y, a.width, a.height, a.data, 0, true);
break;
case 'img':
if (a.img.complete) {
if (a.img.width !== a.width || a.img.height !== a.height) {
Log.Error("Decoded image has incorrect dimensions. Got " +
a.img.width + "x" + a.img.height + ". Expected " +
a.width + "x" + a.height + ".");
return;
}
this.drawImage(a.img, a.x, a.y);
// This helps the browser free the memory right
// away, rather than ballooning
a.img.src = "";
} else {
a.img._noVNCDisplay = this;
a.img.addEventListener('load', this._resumeRenderQ);
// We need to wait for this image to 'load'
// to keep things in-order
ready = false;
}
break;
case 'frame':
if (a.frame.ready) {
// The encoded frame may be larger than the rect due to
// limitations of the encoder, so we need to crop the
// frame.
let frame = a.frame.frame;
if (frame.codedWidth < a.width || frame.codedHeight < a.height) {
Log.Warn("Decoded video frame does not cover its full rectangle area. Expecting at least " +
a.width + "x" + a.height + " but got " +
frame.codedWidth + "x" + frame.codedHeight);
}
const sx = 0;
const sy = 0;
const sw = a.width;
const sh = a.height;
const dx = a.x;
const dy = a.y;
const dw = sw;
const dh = sh;
this.drawImage(frame, sx, sy, sw, sh, dx, dy, dw, dh);
frame.close();
} else {
let display = this;
a.frame.promise.then(() => {
display._scanRenderQ();
});
ready = false;
}
break;
}
if (ready) {
this._renderQ.shift();
}
}
if (this._renderQ.length === 0 &&
this._flushPromise !== null) {
this._flushResolve();
this._flushPromise = null;
this._flushResolve = null;
}
}
}

@ -0,0 +1,54 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
export const encodings = {
encodingRaw: 0,
encodingCopyRect: 1,
encodingRRE: 2,
encodingHextile: 5,
encodingZlib: 6,
encodingTight: 7,
encodingZRLE: 16,
encodingTightPNG: -260,
encodingJPEG: 21,
encodingH264: 50,
pseudoEncodingQualityLevel9: -23,
pseudoEncodingQualityLevel0: -32,
pseudoEncodingDesktopSize: -223,
pseudoEncodingLastRect: -224,
pseudoEncodingCursor: -239,
pseudoEncodingQEMUExtendedKeyEvent: -258,
pseudoEncodingQEMULedEvent: -261,
pseudoEncodingDesktopName: -307,
pseudoEncodingExtendedDesktopSize: -308,
pseudoEncodingXvp: -309,
pseudoEncodingFence: -312,
pseudoEncodingContinuousUpdates: -313,
pseudoEncodingExtendedMouseButtons: -316,
pseudoEncodingCompressLevel9: -247,
pseudoEncodingCompressLevel0: -256,
pseudoEncodingVMwareCursor: 0x574d5664,
pseudoEncodingExtendedClipboard: 0xc0a1e5ce
};
export function encodingName(num) {
switch (num) {
case encodings.encodingRaw: return "Raw";
case encodings.encodingCopyRect: return "CopyRect";
case encodings.encodingRRE: return "RRE";
case encodings.encodingHextile: return "Hextile";
case encodings.encodingZlib: return "Zlib";
case encodings.encodingTight: return "Tight";
case encodings.encodingZRLE: return "ZRLE";
case encodings.encodingTightPNG: return "TightPNG";
case encodings.encodingJPEG: return "JPEG";
case encodings.encodingH264: return "H.264";
default: return "[unknown encoding " + num + "]";
}
}

@ -0,0 +1,65 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2020 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
import { inflateInit, inflate, inflateReset } from "../vendor/pako/lib/zlib/inflate.js";
import ZStream from "../vendor/pako/lib/zlib/zstream.js";
export default class Inflate {
constructor() {
this.strm = new ZStream();
this.chunkSize = 1024 * 10 * 10;
this.strm.output = new Uint8Array(this.chunkSize);
inflateInit(this.strm);
}
setInput(data) {
if (!data) {
//FIXME: flush remaining data.
/* eslint-disable camelcase */
this.strm.input = null;
this.strm.avail_in = 0;
this.strm.next_in = 0;
} else {
this.strm.input = data;
this.strm.avail_in = this.strm.input.length;
this.strm.next_in = 0;
/* eslint-enable camelcase */
}
}
inflate(expected) {
// resize our output buffer if it's too small
// (we could just use multiple chunks, but that would cause an extra
// allocation each time to flatten the chunks)
if (expected > this.chunkSize) {
this.chunkSize = expected;
this.strm.output = new Uint8Array(this.chunkSize);
}
/* eslint-disable camelcase */
this.strm.next_out = 0;
this.strm.avail_out = expected;
/* eslint-enable camelcase */
let ret = inflate(this.strm, 0); // Flush argument not used.
if (ret < 0) {
throw new Error("zlib inflate failed");
}
if (this.strm.next_out != expected) {
throw new Error("Incomplete zlib block");
}
return new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
}
reset() {
inflateReset(this.strm);
}
}

@ -0,0 +1,311 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2018 The noVNC authors
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
*/
import KeyTable from "./keysym.js";
/*
* Mapping between HTML key values and VNC/X11 keysyms for "special"
* keys that cannot be handled via their Unicode codepoint.
*
* See https://www.w3.org/TR/uievents-key/ for possible values.
*/
const DOMKeyTable = {};
function addStandard(key, standard) {
if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\"");
DOMKeyTable[key] = [standard, standard, standard, standard];
}
function addLeftRight(key, left, right) {
if (left === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
if (right === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\"");
DOMKeyTable[key] = [left, left, right, left];
}
function addNumpad(key, standard, numpad) {
if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
if (numpad === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\"");
DOMKeyTable[key] = [standard, standard, standard, numpad];
}
// 3.2. Modifier Keys
addLeftRight("Alt", KeyTable.XK_Alt_L, KeyTable.XK_Alt_R);
addStandard("AltGraph", KeyTable.XK_ISO_Level3_Shift);
addStandard("CapsLock", KeyTable.XK_Caps_Lock);
addLeftRight("Control", KeyTable.XK_Control_L, KeyTable.XK_Control_R);
// - Fn
// - FnLock
addLeftRight("Meta", KeyTable.XK_Super_L, KeyTable.XK_Super_R);
addStandard("NumLock", KeyTable.XK_Num_Lock);
addStandard("ScrollLock", KeyTable.XK_Scroll_Lock);
addLeftRight("Shift", KeyTable.XK_Shift_L, KeyTable.XK_Shift_R);
// - Symbol
// - SymbolLock
// - Hyper
// - Super
// 3.3. Whitespace Keys
addNumpad("Enter", KeyTable.XK_Return, KeyTable.XK_KP_Enter);
addStandard("Tab", KeyTable.XK_Tab);
addNumpad(" ", KeyTable.XK_space, KeyTable.XK_KP_Space);
// 3.4. Navigation Keys
addNumpad("ArrowDown", KeyTable.XK_Down, KeyTable.XK_KP_Down);
addNumpad("ArrowLeft", KeyTable.XK_Left, KeyTable.XK_KP_Left);
addNumpad("ArrowRight", KeyTable.XK_Right, KeyTable.XK_KP_Right);
addNumpad("ArrowUp", KeyTable.XK_Up, KeyTable.XK_KP_Up);
addNumpad("End", KeyTable.XK_End, KeyTable.XK_KP_End);
addNumpad("Home", KeyTable.XK_Home, KeyTable.XK_KP_Home);
addNumpad("PageDown", KeyTable.XK_Next, KeyTable.XK_KP_Next);
addNumpad("PageUp", KeyTable.XK_Prior, KeyTable.XK_KP_Prior);
// 3.5. Editing Keys
addStandard("Backspace", KeyTable.XK_BackSpace);
// Browsers send "Clear" for the numpad 5 without NumLock because
// Windows uses VK_Clear for that key. But Unix expects KP_Begin for
// that scenario.
addNumpad("Clear", KeyTable.XK_Clear, KeyTable.XK_KP_Begin);
addStandard("Copy", KeyTable.XF86XK_Copy);
// - CrSel
addStandard("Cut", KeyTable.XF86XK_Cut);
addNumpad("Delete", KeyTable.XK_Delete, KeyTable.XK_KP_Delete);
// - EraseEof
// - ExSel
addNumpad("Insert", KeyTable.XK_Insert, KeyTable.XK_KP_Insert);
addStandard("Paste", KeyTable.XF86XK_Paste);
addStandard("Redo", KeyTable.XK_Redo);
addStandard("Undo", KeyTable.XK_Undo);
// 3.6. UI Keys
// - Accept
// - Again (could just be XK_Redo)
// - Attn
addStandard("Cancel", KeyTable.XK_Cancel);
addStandard("ContextMenu", KeyTable.XK_Menu);
addStandard("Escape", KeyTable.XK_Escape);
addStandard("Execute", KeyTable.XK_Execute);
addStandard("Find", KeyTable.XK_Find);
addStandard("Help", KeyTable.XK_Help);
addStandard("Pause", KeyTable.XK_Pause);
// - Play
// - Props
addStandard("Select", KeyTable.XK_Select);
addStandard("ZoomIn", KeyTable.XF86XK_ZoomIn);
addStandard("ZoomOut", KeyTable.XF86XK_ZoomOut);
// 3.7. Device Keys
addStandard("BrightnessDown", KeyTable.XF86XK_MonBrightnessDown);
addStandard("BrightnessUp", KeyTable.XF86XK_MonBrightnessUp);
addStandard("Eject", KeyTable.XF86XK_Eject);
addStandard("LogOff", KeyTable.XF86XK_LogOff);
addStandard("Power", KeyTable.XF86XK_PowerOff);
addStandard("PowerOff", KeyTable.XF86XK_PowerDown);
addStandard("PrintScreen", KeyTable.XK_Print);
addStandard("Hibernate", KeyTable.XF86XK_Hibernate);
addStandard("Standby", KeyTable.XF86XK_Standby);
addStandard("WakeUp", KeyTable.XF86XK_WakeUp);
// 3.8. IME and Composition Keys
addStandard("AllCandidates", KeyTable.XK_MultipleCandidate);
addStandard("Alphanumeric", KeyTable.XK_Eisu_toggle);
addStandard("CodeInput", KeyTable.XK_Codeinput);
addStandard("Compose", KeyTable.XK_Multi_key);
addStandard("Convert", KeyTable.XK_Henkan);
// - Dead
// - FinalMode
addStandard("GroupFirst", KeyTable.XK_ISO_First_Group);
addStandard("GroupLast", KeyTable.XK_ISO_Last_Group);
addStandard("GroupNext", KeyTable.XK_ISO_Next_Group);
addStandard("GroupPrevious", KeyTable.XK_ISO_Prev_Group);
// - ModeChange (XK_Mode_switch is often used for AltGr)
// - NextCandidate
addStandard("NonConvert", KeyTable.XK_Muhenkan);
addStandard("PreviousCandidate", KeyTable.XK_PreviousCandidate);
// - Process
addStandard("SingleCandidate", KeyTable.XK_SingleCandidate);
addStandard("HangulMode", KeyTable.XK_Hangul);
addStandard("HanjaMode", KeyTable.XK_Hangul_Hanja);
addStandard("JunjaMode", KeyTable.XK_Hangul_Jeonja);
addStandard("Eisu", KeyTable.XK_Eisu_toggle);
addStandard("Hankaku", KeyTable.XK_Hankaku);
addStandard("Hiragana", KeyTable.XK_Hiragana);
addStandard("HiraganaKatakana", KeyTable.XK_Hiragana_Katakana);
addStandard("KanaMode", KeyTable.XK_Kana_Shift); // could also be _Kana_Lock
addStandard("KanjiMode", KeyTable.XK_Kanji);
addStandard("Katakana", KeyTable.XK_Katakana);
addStandard("Romaji", KeyTable.XK_Romaji);
addStandard("Zenkaku", KeyTable.XK_Zenkaku);
addStandard("ZenkakuHankaku", KeyTable.XK_Zenkaku_Hankaku);
// 3.9. General-Purpose Function Keys
addStandard("F1", KeyTable.XK_F1);
addStandard("F2", KeyTable.XK_F2);
addStandard("F3", KeyTable.XK_F3);
addStandard("F4", KeyTable.XK_F4);
addStandard("F5", KeyTable.XK_F5);
addStandard("F6", KeyTable.XK_F6);
addStandard("F7", KeyTable.XK_F7);
addStandard("F8", KeyTable.XK_F8);
addStandard("F9", KeyTable.XK_F9);
addStandard("F10", KeyTable.XK_F10);
addStandard("F11", KeyTable.XK_F11);
addStandard("F12", KeyTable.XK_F12);
addStandard("F13", KeyTable.XK_F13);
addStandard("F14", KeyTable.XK_F14);
addStandard("F15", KeyTable.XK_F15);
addStandard("F16", KeyTable.XK_F16);
addStandard("F17", KeyTable.XK_F17);
addStandard("F18", KeyTable.XK_F18);
addStandard("F19", KeyTable.XK_F19);
addStandard("F20", KeyTable.XK_F20);
addStandard("F21", KeyTable.XK_F21);
addStandard("F22", KeyTable.XK_F22);
addStandard("F23", KeyTable.XK_F23);
addStandard("F24", KeyTable.XK_F24);
addStandard("F25", KeyTable.XK_F25);
addStandard("F26", KeyTable.XK_F26);
addStandard("F27", KeyTable.XK_F27);
addStandard("F28", KeyTable.XK_F28);
addStandard("F29", KeyTable.XK_F29);
addStandard("F30", KeyTable.XK_F30);
addStandard("F31", KeyTable.XK_F31);
addStandard("F32", KeyTable.XK_F32);
addStandard("F33", KeyTable.XK_F33);
addStandard("F34", KeyTable.XK_F34);
addStandard("F35", KeyTable.XK_F35);
// - Soft1...
// 3.10. Multimedia Keys
// - ChannelDown
// - ChannelUp
addStandard("Close", KeyTable.XF86XK_Close);
addStandard("MailForward", KeyTable.XF86XK_MailForward);
addStandard("MailReply", KeyTable.XF86XK_Reply);
addStandard("MailSend", KeyTable.XF86XK_Send);
// - MediaClose
addStandard("MediaFastForward", KeyTable.XF86XK_AudioForward);
addStandard("MediaPause", KeyTable.XF86XK_AudioPause);
addStandard("MediaPlay", KeyTable.XF86XK_AudioPlay);
// - MediaPlayPause
addStandard("MediaRecord", KeyTable.XF86XK_AudioRecord);
addStandard("MediaRewind", KeyTable.XF86XK_AudioRewind);
addStandard("MediaStop", KeyTable.XF86XK_AudioStop);
addStandard("MediaTrackNext", KeyTable.XF86XK_AudioNext);
addStandard("MediaTrackPrevious", KeyTable.XF86XK_AudioPrev);
addStandard("New", KeyTable.XF86XK_New);
addStandard("Open", KeyTable.XF86XK_Open);
addStandard("Print", KeyTable.XK_Print);
addStandard("Save", KeyTable.XF86XK_Save);
addStandard("SpellCheck", KeyTable.XF86XK_Spell);
// 3.11. Multimedia Numpad Keys
// - Key11
// - Key12
// 3.12. Audio Keys
// - AudioBalanceLeft
// - AudioBalanceRight
// - AudioBassBoostDown
// - AudioBassBoostToggle
// - AudioBassBoostUp
// - AudioFaderFront
// - AudioFaderRear
// - AudioSurroundModeNext
// - AudioTrebleDown
// - AudioTrebleUp
addStandard("AudioVolumeDown", KeyTable.XF86XK_AudioLowerVolume);
addStandard("AudioVolumeUp", KeyTable.XF86XK_AudioRaiseVolume);
addStandard("AudioVolumeMute", KeyTable.XF86XK_AudioMute);
// - MicrophoneToggle
// - MicrophoneVolumeDown
// - MicrophoneVolumeUp
addStandard("MicrophoneVolumeMute", KeyTable.XF86XK_AudioMicMute);
// 3.13. Speech Keys
// - SpeechCorrectionList
// - SpeechInputToggle
// 3.14. Application Keys
addStandard("LaunchApplication1", KeyTable.XF86XK_MyComputer);
addStandard("LaunchApplication2", KeyTable.XF86XK_Calculator);
addStandard("LaunchCalendar", KeyTable.XF86XK_Calendar);
// - LaunchContacts
addStandard("LaunchMail", KeyTable.XF86XK_Mail);
addStandard("LaunchMediaPlayer", KeyTable.XF86XK_AudioMedia);
addStandard("LaunchMusicPlayer", KeyTable.XF86XK_Music);
addStandard("LaunchPhone", KeyTable.XF86XK_Phone);
addStandard("LaunchScreenSaver", KeyTable.XF86XK_ScreenSaver);
addStandard("LaunchSpreadsheet", KeyTable.XF86XK_Excel);
addStandard("LaunchWebBrowser", KeyTable.XF86XK_WWW);
addStandard("LaunchWebCam", KeyTable.XF86XK_WebCam);
addStandard("LaunchWordProcessor", KeyTable.XF86XK_Word);
// 3.15. Browser Keys
addStandard("BrowserBack", KeyTable.XF86XK_Back);
addStandard("BrowserFavorites", KeyTable.XF86XK_Favorites);
addStandard("BrowserForward", KeyTable.XF86XK_Forward);
addStandard("BrowserHome", KeyTable.XF86XK_HomePage);
addStandard("BrowserRefresh", KeyTable.XF86XK_Refresh);
addStandard("BrowserSearch", KeyTable.XF86XK_Search);
addStandard("BrowserStop", KeyTable.XF86XK_Stop);
// 3.16. Mobile Phone Keys
// - A whole bunch...
// 3.17. TV Keys
// - A whole bunch...
// 3.18. Media Controller Keys
// - A whole bunch...
addStandard("Dimmer", KeyTable.XF86XK_BrightnessAdjust);
addStandard("MediaAudioTrack", KeyTable.XF86XK_AudioCycleTrack);
addStandard("RandomToggle", KeyTable.XF86XK_AudioRandomPlay);
addStandard("SplitScreenToggle", KeyTable.XF86XK_SplitScreen);
addStandard("Subtitle", KeyTable.XF86XK_Subtitle);
addStandard("VideoModeNext", KeyTable.XF86XK_Next_VMode);
// Extra: Numpad
addNumpad("=", KeyTable.XK_equal, KeyTable.XK_KP_Equal);
addNumpad("+", KeyTable.XK_plus, KeyTable.XK_KP_Add);
addNumpad("-", KeyTable.XK_minus, KeyTable.XK_KP_Subtract);
addNumpad("*", KeyTable.XK_asterisk, KeyTable.XK_KP_Multiply);
addNumpad("/", KeyTable.XK_slash, KeyTable.XK_KP_Divide);
addNumpad(".", KeyTable.XK_period, KeyTable.XK_KP_Decimal);
addNumpad(",", KeyTable.XK_comma, KeyTable.XK_KP_Separator);
addNumpad("0", KeyTable.XK_0, KeyTable.XK_KP_0);
addNumpad("1", KeyTable.XK_1, KeyTable.XK_KP_1);
addNumpad("2", KeyTable.XK_2, KeyTable.XK_KP_2);
addNumpad("3", KeyTable.XK_3, KeyTable.XK_KP_3);
addNumpad("4", KeyTable.XK_4, KeyTable.XK_KP_4);
addNumpad("5", KeyTable.XK_5, KeyTable.XK_KP_5);
addNumpad("6", KeyTable.XK_6, KeyTable.XK_KP_6);
addNumpad("7", KeyTable.XK_7, KeyTable.XK_KP_7);
addNumpad("8", KeyTable.XK_8, KeyTable.XK_KP_8);
addNumpad("9", KeyTable.XK_9, KeyTable.XK_KP_9);
export default DOMKeyTable;

@ -0,0 +1,129 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2018 The noVNC authors
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
*/
/*
* Fallback mapping between HTML key codes (physical keys) and
* HTML key values. This only works for keys that don't vary
* between layouts. We also omit those who manage fine by mapping the
* Unicode representation.
*
* See https://www.w3.org/TR/uievents-code/ for possible codes.
* See https://www.w3.org/TR/uievents-key/ for possible values.
*/
/* eslint-disable key-spacing */
export default {
// 3.1.1.1. Writing System Keys
'Backspace': 'Backspace',
// 3.1.1.2. Functional Keys
'AltLeft': 'Alt',
'AltRight': 'Alt', // This could also be 'AltGraph'
'CapsLock': 'CapsLock',
'ContextMenu': 'ContextMenu',
'ControlLeft': 'Control',
'ControlRight': 'Control',
'Enter': 'Enter',
'MetaLeft': 'Meta',
'MetaRight': 'Meta',
'ShiftLeft': 'Shift',
'ShiftRight': 'Shift',
'Tab': 'Tab',
// FIXME: Japanese/Korean keys
// 3.1.2. Control Pad Section
'Delete': 'Delete',
'End': 'End',
'Help': 'Help',
'Home': 'Home',
'Insert': 'Insert',
'PageDown': 'PageDown',
'PageUp': 'PageUp',
// 3.1.3. Arrow Pad Section
'ArrowDown': 'ArrowDown',
'ArrowLeft': 'ArrowLeft',
'ArrowRight': 'ArrowRight',
'ArrowUp': 'ArrowUp',
// 3.1.4. Numpad Section
'NumLock': 'NumLock',
'NumpadBackspace': 'Backspace',
'NumpadClear': 'Clear',
// 3.1.5. Function Section
'Escape': 'Escape',
'F1': 'F1',
'F2': 'F2',
'F3': 'F3',
'F4': 'F4',
'F5': 'F5',
'F6': 'F6',
'F7': 'F7',
'F8': 'F8',
'F9': 'F9',
'F10': 'F10',
'F11': 'F11',
'F12': 'F12',
'F13': 'F13',
'F14': 'F14',
'F15': 'F15',
'F16': 'F16',
'F17': 'F17',
'F18': 'F18',
'F19': 'F19',
'F20': 'F20',
'F21': 'F21',
'F22': 'F22',
'F23': 'F23',
'F24': 'F24',
'F25': 'F25',
'F26': 'F26',
'F27': 'F27',
'F28': 'F28',
'F29': 'F29',
'F30': 'F30',
'F31': 'F31',
'F32': 'F32',
'F33': 'F33',
'F34': 'F34',
'F35': 'F35',
'PrintScreen': 'PrintScreen',
'ScrollLock': 'ScrollLock',
'Pause': 'Pause',
// 3.1.6. Media Keys
'BrowserBack': 'BrowserBack',
'BrowserFavorites': 'BrowserFavorites',
'BrowserForward': 'BrowserForward',
'BrowserHome': 'BrowserHome',
'BrowserRefresh': 'BrowserRefresh',
'BrowserSearch': 'BrowserSearch',
'BrowserStop': 'BrowserStop',
'Eject': 'Eject',
'LaunchApp1': 'LaunchMyComputer',
'LaunchApp2': 'LaunchCalendar',
'LaunchMail': 'LaunchMail',
'MediaPlayPause': 'MediaPlay',
'MediaStop': 'MediaStop',
'MediaTrackNext': 'MediaTrackNext',
'MediaTrackPrevious': 'MediaTrackPrevious',
'Power': 'Power',
'Sleep': 'Sleep',
'AudioVolumeDown': 'AudioVolumeDown',
'AudioVolumeMute': 'AudioVolumeMute',
'AudioVolumeUp': 'AudioVolumeUp',
'WakeUp': 'WakeUp',
};

@ -0,0 +1,567 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2020 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
*/
const GH_NOGESTURE = 0;
const GH_ONETAP = 1;
const GH_TWOTAP = 2;
const GH_THREETAP = 4;
const GH_DRAG = 8;
const GH_LONGPRESS = 16;
const GH_TWODRAG = 32;
const GH_PINCH = 64;
const GH_INITSTATE = 127;
const GH_MOVE_THRESHOLD = 50;
const GH_ANGLE_THRESHOLD = 90; // Degrees
// Timeout when waiting for gestures (ms)
const GH_MULTITOUCH_TIMEOUT = 250;
// Maximum time between press and release for a tap (ms)
const GH_TAP_TIMEOUT = 1000;
// Timeout when waiting for longpress (ms)
const GH_LONGPRESS_TIMEOUT = 1000;
// Timeout when waiting to decide between PINCH and TWODRAG (ms)
const GH_TWOTOUCH_TIMEOUT = 50;
export default class GestureHandler {
constructor() {
this._target = null;
this._state = GH_INITSTATE;
this._tracked = [];
this._ignored = [];
this._waitingRelease = false;
this._releaseStart = 0.0;
this._longpressTimeoutId = null;
this._twoTouchTimeoutId = null;
this._boundEventHandler = this._eventHandler.bind(this);
}
attach(target) {
this.detach();
this._target = target;
this._target.addEventListener('touchstart',
this._boundEventHandler);
this._target.addEventListener('touchmove',
this._boundEventHandler);
this._target.addEventListener('touchend',
this._boundEventHandler);
this._target.addEventListener('touchcancel',
this._boundEventHandler);
}
detach() {
if (!this._target) {
return;
}
this._stopLongpressTimeout();
this._stopTwoTouchTimeout();
this._target.removeEventListener('touchstart',
this._boundEventHandler);
this._target.removeEventListener('touchmove',
this._boundEventHandler);
this._target.removeEventListener('touchend',
this._boundEventHandler);
this._target.removeEventListener('touchcancel',
this._boundEventHandler);
this._target = null;
}
_eventHandler(e) {
let fn;
e.stopPropagation();
e.preventDefault();
switch (e.type) {
case 'touchstart':
fn = this._touchStart;
break;
case 'touchmove':
fn = this._touchMove;
break;
case 'touchend':
case 'touchcancel':
fn = this._touchEnd;
break;
}
for (let i = 0; i < e.changedTouches.length; i++) {
let touch = e.changedTouches[i];
fn.call(this, touch.identifier, touch.clientX, touch.clientY);
}
}
_touchStart(id, x, y) {
// Ignore any new touches if there is already an active gesture,
// or we're in a cleanup state
if (this._hasDetectedGesture() || (this._state === GH_NOGESTURE)) {
this._ignored.push(id);
return;
}
// Did it take too long between touches that we should no longer
// consider this a single gesture?
if ((this._tracked.length > 0) &&
((Date.now() - this._tracked[0].started) > GH_MULTITOUCH_TIMEOUT)) {
this._state = GH_NOGESTURE;
this._ignored.push(id);
return;
}
// If we're waiting for fingers to release then we should no longer
// recognize new touches
if (this._waitingRelease) {
this._state = GH_NOGESTURE;
this._ignored.push(id);
return;
}
this._tracked.push({
id: id,
started: Date.now(),
active: true,
firstX: x,
firstY: y,
lastX: x,
lastY: y,
angle: 0
});
switch (this._tracked.length) {
case 1:
this._startLongpressTimeout();
break;
case 2:
this._state &= ~(GH_ONETAP | GH_DRAG | GH_LONGPRESS);
this._stopLongpressTimeout();
break;
case 3:
this._state &= ~(GH_TWOTAP | GH_TWODRAG | GH_PINCH);
break;
default:
this._state = GH_NOGESTURE;
}
}
_touchMove(id, x, y) {
let touch = this._tracked.find(t => t.id === id);
// If this is an update for a touch we're not tracking, ignore it
if (touch === undefined) {
return;
}
// Update the touches last position with the event coordinates
touch.lastX = x;
touch.lastY = y;
let deltaX = x - touch.firstX;
let deltaY = y - touch.firstY;
// Update angle when the touch has moved
if ((touch.firstX !== touch.lastX) ||
(touch.firstY !== touch.lastY)) {
touch.angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
}
if (!this._hasDetectedGesture()) {
// Ignore moves smaller than the minimum threshold
if (Math.hypot(deltaX, deltaY) < GH_MOVE_THRESHOLD) {
return;
}
// Can't be a tap or long press as we've seen movement
this._state &= ~(GH_ONETAP | GH_TWOTAP | GH_THREETAP | GH_LONGPRESS);
this._stopLongpressTimeout();
if (this._tracked.length !== 1) {
this._state &= ~(GH_DRAG);
}
if (this._tracked.length !== 2) {
this._state &= ~(GH_TWODRAG | GH_PINCH);
}
// We need to figure out which of our different two touch gestures
// this might be
if (this._tracked.length === 2) {
// The other touch is the one where the id doesn't match
let prevTouch = this._tracked.find(t => t.id !== id);
// How far the previous touch point has moved since start
let prevDeltaMove = Math.hypot(prevTouch.firstX - prevTouch.lastX,
prevTouch.firstY - prevTouch.lastY);
// We know that the current touch moved far enough,
// but unless both touches moved further than their
// threshold we don't want to disqualify any gestures
if (prevDeltaMove > GH_MOVE_THRESHOLD) {
// The angle difference between the direction of the touch points
let deltaAngle = Math.abs(touch.angle - prevTouch.angle);
deltaAngle = Math.abs(((deltaAngle + 180) % 360) - 180);
// PINCH or TWODRAG can be eliminated depending on the angle
if (deltaAngle > GH_ANGLE_THRESHOLD) {
this._state &= ~GH_TWODRAG;
} else {
this._state &= ~GH_PINCH;
}
if (this._isTwoTouchTimeoutRunning()) {
this._stopTwoTouchTimeout();
}
} else if (!this._isTwoTouchTimeoutRunning()) {
// We can't determine the gesture right now, let's
// wait and see if more events are on their way
this._startTwoTouchTimeout();
}
}
if (!this._hasDetectedGesture()) {
return;
}
this._pushEvent('gesturestart');
}
this._pushEvent('gesturemove');
}
_touchEnd(id, x, y) {
// Check if this is an ignored touch
if (this._ignored.indexOf(id) !== -1) {
// Remove this touch from ignored
this._ignored.splice(this._ignored.indexOf(id), 1);
// And reset the state if there are no more touches
if ((this._ignored.length === 0) &&
(this._tracked.length === 0)) {
this._state = GH_INITSTATE;
this._waitingRelease = false;
}
return;
}
// We got a touchend before the timer triggered,
// this cannot result in a gesture anymore.
if (!this._hasDetectedGesture() &&
this._isTwoTouchTimeoutRunning()) {
this._stopTwoTouchTimeout();
this._state = GH_NOGESTURE;
}
// Some gestures don't trigger until a touch is released
if (!this._hasDetectedGesture()) {
// Can't be a gesture that relies on movement
this._state &= ~(GH_DRAG | GH_TWODRAG | GH_PINCH);
// Or something that relies on more time
this._state &= ~GH_LONGPRESS;
this._stopLongpressTimeout();
if (!this._waitingRelease) {
this._releaseStart = Date.now();
this._waitingRelease = true;
// Can't be a tap that requires more touches than we current have
switch (this._tracked.length) {
case 1:
this._state &= ~(GH_TWOTAP | GH_THREETAP);
break;
case 2:
this._state &= ~(GH_ONETAP | GH_THREETAP);
break;
}
}
}
// Waiting for all touches to release? (i.e. some tap)
if (this._waitingRelease) {
// Were all touches released at roughly the same time?
if ((Date.now() - this._releaseStart) > GH_MULTITOUCH_TIMEOUT) {
this._state = GH_NOGESTURE;
}
// Did too long time pass between press and release?
if (this._tracked.some(t => (Date.now() - t.started) > GH_TAP_TIMEOUT)) {
this._state = GH_NOGESTURE;
}
let touch = this._tracked.find(t => t.id === id);
touch.active = false;
// Are we still waiting for more releases?
if (this._hasDetectedGesture()) {
this._pushEvent('gesturestart');
} else {
// Have we reached a dead end?
if (this._state !== GH_NOGESTURE) {
return;
}
}
}
if (this._hasDetectedGesture()) {
this._pushEvent('gestureend');
}
// Ignore any remaining touches until they are ended
for (let i = 0; i < this._tracked.length; i++) {
if (this._tracked[i].active) {
this._ignored.push(this._tracked[i].id);
}
}
this._tracked = [];
this._state = GH_NOGESTURE;
// Remove this touch from ignored if it's in there
if (this._ignored.indexOf(id) !== -1) {
this._ignored.splice(this._ignored.indexOf(id), 1);
}
// We reset the state if ignored is empty
if ((this._ignored.length === 0)) {
this._state = GH_INITSTATE;
this._waitingRelease = false;
}
}
_hasDetectedGesture() {
if (this._state === GH_NOGESTURE) {
return false;
}
// Check to see if the bitmask value is a power of 2
// (i.e. only one bit set). If it is, we have a state.
if (this._state & (this._state - 1)) {
return false;
}
// For taps we also need to have all touches released
// before we've fully detected the gesture
if (this._state & (GH_ONETAP | GH_TWOTAP | GH_THREETAP)) {
if (this._tracked.some(t => t.active)) {
return false;
}
}
return true;
}
_startLongpressTimeout() {
this._stopLongpressTimeout();
this._longpressTimeoutId = setTimeout(() => this._longpressTimeout(),
GH_LONGPRESS_TIMEOUT);
}
_stopLongpressTimeout() {
clearTimeout(this._longpressTimeoutId);
this._longpressTimeoutId = null;
}
_longpressTimeout() {
if (this._hasDetectedGesture()) {
throw new Error("A longpress gesture failed, conflict with a different gesture");
}
this._state = GH_LONGPRESS;
this._pushEvent('gesturestart');
}
_startTwoTouchTimeout() {
this._stopTwoTouchTimeout();
this._twoTouchTimeoutId = setTimeout(() => this._twoTouchTimeout(),
GH_TWOTOUCH_TIMEOUT);
}
_stopTwoTouchTimeout() {
clearTimeout(this._twoTouchTimeoutId);
this._twoTouchTimeoutId = null;
}
_isTwoTouchTimeoutRunning() {
return this._twoTouchTimeoutId !== null;
}
_twoTouchTimeout() {
if (this._tracked.length === 0) {
throw new Error("A pinch or two drag gesture failed, no tracked touches");
}
// How far each touch point has moved since start
let avgM = this._getAverageMovement();
let avgMoveH = Math.abs(avgM.x);
let avgMoveV = Math.abs(avgM.y);
// The difference in the distance between where
// the touch points started and where they are now
let avgD = this._getAverageDistance();
let deltaTouchDistance = Math.abs(Math.hypot(avgD.first.x, avgD.first.y) -
Math.hypot(avgD.last.x, avgD.last.y));
if ((avgMoveV < deltaTouchDistance) &&
(avgMoveH < deltaTouchDistance)) {
this._state = GH_PINCH;
} else {
this._state = GH_TWODRAG;
}
this._pushEvent('gesturestart');
this._pushEvent('gesturemove');
}
_pushEvent(type) {
let detail = { type: this._stateToGesture(this._state) };
// For most gesture events the current (average) position is the
// most useful
let avg = this._getPosition();
let pos = avg.last;
// However we have a slight distance to detect gestures, so for the
// first gesture event we want to use the first positions we saw
if (type === 'gesturestart') {
pos = avg.first;
}
// For these gestures, we always want the event coordinates
// to be where the gesture began, not the current touch location.
switch (this._state) {
case GH_TWODRAG:
case GH_PINCH:
pos = avg.first;
break;
}
detail['clientX'] = pos.x;
detail['clientY'] = pos.y;
// FIXME: other coordinates?
// Some gestures also have a magnitude
if (this._state === GH_PINCH) {
let distance = this._getAverageDistance();
if (type === 'gesturestart') {
detail['magnitudeX'] = distance.first.x;
detail['magnitudeY'] = distance.first.y;
} else {
detail['magnitudeX'] = distance.last.x;
detail['magnitudeY'] = distance.last.y;
}
} else if (this._state === GH_TWODRAG) {
if (type === 'gesturestart') {
detail['magnitudeX'] = 0.0;
detail['magnitudeY'] = 0.0;
} else {
let movement = this._getAverageMovement();
detail['magnitudeX'] = movement.x;
detail['magnitudeY'] = movement.y;
}
}
let gev = new CustomEvent(type, { detail: detail });
this._target.dispatchEvent(gev);
}
_stateToGesture(state) {
switch (state) {
case GH_ONETAP:
return 'onetap';
case GH_TWOTAP:
return 'twotap';
case GH_THREETAP:
return 'threetap';
case GH_DRAG:
return 'drag';
case GH_LONGPRESS:
return 'longpress';
case GH_TWODRAG:
return 'twodrag';
case GH_PINCH:
return 'pinch';
}
throw new Error("Unknown gesture state: " + state);
}
_getPosition() {
if (this._tracked.length === 0) {
throw new Error("Failed to get gesture position, no tracked touches");
}
let size = this._tracked.length;
let fx = 0, fy = 0, lx = 0, ly = 0;
for (let i = 0; i < this._tracked.length; i++) {
fx += this._tracked[i].firstX;
fy += this._tracked[i].firstY;
lx += this._tracked[i].lastX;
ly += this._tracked[i].lastY;
}
return { first: { x: fx / size,
y: fy / size },
last: { x: lx / size,
y: ly / size } };
}
_getAverageMovement() {
if (this._tracked.length === 0) {
throw new Error("Failed to get gesture movement, no tracked touches");
}
let totalH, totalV;
totalH = totalV = 0;
let size = this._tracked.length;
for (let i = 0; i < this._tracked.length; i++) {
totalH += this._tracked[i].lastX - this._tracked[i].firstX;
totalV += this._tracked[i].lastY - this._tracked[i].firstY;
}
return { x: totalH / size,
y: totalV / size };
}
_getAverageDistance() {
if (this._tracked.length === 0) {
throw new Error("Failed to get gesture distance, no tracked touches");
}
// Distance between the first and last tracked touches
let first = this._tracked[0];
let last = this._tracked[this._tracked.length - 1];
let fdx = Math.abs(last.firstX - first.firstX);
let fdy = Math.abs(last.firstY - first.firstY);
let ldx = Math.abs(last.lastX - first.lastX);
let ldy = Math.abs(last.lastY - first.lastY);
return { first: { x: fdx, y: fdy },
last: { x: ldx, y: ldy } };
}
}

@ -0,0 +1,294 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
*/
import * as Log from '../util/logging.js';
import { stopEvent } from '../util/events.js';
import * as KeyboardUtil from "./util.js";
import KeyTable from "./keysym.js";
import * as browser from "../util/browser.js";
//
// Keyboard event handler
//
export default class Keyboard {
constructor(target) {
this._target = target || null;
this._keyDownList = {}; // List of depressed keys
// (even if they are happy)
this._altGrArmed = false; // Windows AltGr detection
// keep these here so we can refer to them later
this._eventHandlers = {
'keyup': this._handleKeyUp.bind(this),
'keydown': this._handleKeyDown.bind(this),
'blur': this._allKeysUp.bind(this),
};
// ===== EVENT HANDLERS =====
this.onkeyevent = () => {}; // Handler for key press/release
}
// ===== PRIVATE METHODS =====
_sendKeyEvent(keysym, code, down, numlock = null, capslock = null) {
if (down) {
this._keyDownList[code] = keysym;
} else {
// Do we really think this key is down?
if (!(code in this._keyDownList)) {
return;
}
delete this._keyDownList[code];
}
Log.Debug("onkeyevent " + (down ? "down" : "up") +
", keysym: " + keysym, ", code: " + code +
", numlock: " + numlock + ", capslock: " + capslock);
this.onkeyevent(keysym, code, down, numlock, capslock);
}
_getKeyCode(e) {
const code = KeyboardUtil.getKeycode(e);
if (code !== 'Unidentified') {
return code;
}
// Unstable, but we don't have anything else to go on
if (e.keyCode) {
// 229 is used for composition events
if (e.keyCode !== 229) {
return 'Platform' + e.keyCode;
}
}
// A precursor to the final DOM3 standard. Unfortunately it
// is not layout independent, so it is as bad as using keyCode
if (e.keyIdentifier) {
// Non-character key?
if (e.keyIdentifier.substr(0, 2) !== 'U+') {
return e.keyIdentifier;
}
const codepoint = parseInt(e.keyIdentifier.substr(2), 16);
const char = String.fromCharCode(codepoint).toUpperCase();
return 'Platform' + char.charCodeAt();
}
return 'Unidentified';
}
_handleKeyDown(e) {
const code = this._getKeyCode(e);
let keysym = KeyboardUtil.getKeysym(e);
let numlock = e.getModifierState('NumLock');
let capslock = e.getModifierState('CapsLock');
// getModifierState for NumLock is not supported on mac and ios and always returns false.
// Set to null to indicate unknown/unsupported instead.
if (browser.isMac() || browser.isIOS()) {
numlock = null;
}
// Windows doesn't have a proper AltGr, but handles it using
// fake Ctrl+Alt. However the remote end might not be Windows,
// so we need to merge those in to a single AltGr event. We
// detect this case by seeing the two key events directly after
// each other with a very short time between them (<50ms).
if (this._altGrArmed) {
this._altGrArmed = false;
clearTimeout(this._altGrTimeout);
if ((code === "AltRight") &&
((e.timeStamp - this._altGrCtrlTime) < 50)) {
// FIXME: We fail to detect this if either Ctrl key is
// first manually pressed as Windows then no
// longer sends the fake Ctrl down event. It
// does however happily send real Ctrl events
// even when AltGr is already down. Some
// browsers detect this for us though and set the
// key to "AltGraph".
keysym = KeyTable.XK_ISO_Level3_Shift;
} else {
this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true, numlock, capslock);
}
}
// We cannot handle keys we cannot track, but we also need
// to deal with virtual keyboards which omit key info
if (code === 'Unidentified') {
if (keysym) {
// If it's a virtual keyboard then it should be
// sufficient to just send press and release right
// after each other
this._sendKeyEvent(keysym, code, true, numlock, capslock);
this._sendKeyEvent(keysym, code, false, numlock, capslock);
}
stopEvent(e);
return;
}
// Alt behaves more like AltGraph on macOS, so shuffle the
// keys around a bit to make things more sane for the remote
// server. This method is used by RealVNC and TigerVNC (and
// possibly others).
if (browser.isMac() || browser.isIOS()) {
switch (keysym) {
case KeyTable.XK_Super_L:
keysym = KeyTable.XK_Alt_L;
break;
case KeyTable.XK_Super_R:
keysym = KeyTable.XK_Super_L;
break;
case KeyTable.XK_Alt_L:
keysym = KeyTable.XK_Mode_switch;
break;
case KeyTable.XK_Alt_R:
keysym = KeyTable.XK_ISO_Level3_Shift;
break;
}
}
// Is this key already pressed? If so, then we must use the
// same keysym or we'll confuse the server
if (code in this._keyDownList) {
keysym = this._keyDownList[code];
}
// macOS doesn't send proper key releases if a key is pressed
// while meta is held down
if ((browser.isMac() || browser.isIOS()) &&
(e.metaKey && code !== 'MetaLeft' && code !== 'MetaRight')) {
this._sendKeyEvent(keysym, code, true, numlock, capslock);
this._sendKeyEvent(keysym, code, false, numlock, capslock);
stopEvent(e);
return;
}
// macOS doesn't send proper key events for modifiers, only
// state change events. That gets extra confusing for CapsLock
// which toggles on each press, but not on release. So pretend
// it was a quick press and release of the button.
if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) {
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true, numlock, capslock);
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false, numlock, capslock);
stopEvent(e);
return;
}
// Windows doesn't send proper key releases for a bunch of
// Japanese IM keys so we have to fake the release right away
const jpBadKeys = [ KeyTable.XK_Zenkaku_Hankaku,
KeyTable.XK_Eisu_toggle,
KeyTable.XK_Katakana,
KeyTable.XK_Hiragana,
KeyTable.XK_Romaji ];
if (browser.isWindows() && jpBadKeys.includes(keysym)) {
this._sendKeyEvent(keysym, code, true, numlock, capslock);
this._sendKeyEvent(keysym, code, false, numlock, capslock);
stopEvent(e);
return;
}
stopEvent(e);
// Possible start of AltGr sequence? (see above)
if ((code === "ControlLeft") && browser.isWindows() &&
!("ControlLeft" in this._keyDownList)) {
this._altGrArmed = true;
this._altGrTimeout = setTimeout(this._interruptAltGrSequence.bind(this), 100);
this._altGrCtrlTime = e.timeStamp;
return;
}
this._sendKeyEvent(keysym, code, true, numlock, capslock);
}
_handleKeyUp(e) {
stopEvent(e);
const code = this._getKeyCode(e);
// We can't get a release in the middle of an AltGr sequence, so
// abort that detection
this._interruptAltGrSequence();
// See comment in _handleKeyDown()
if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) {
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true);
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false);
return;
}
this._sendKeyEvent(this._keyDownList[code], code, false);
// Windows has a rather nasty bug where it won't send key
// release events for a Shift button if the other Shift is still
// pressed
if (browser.isWindows() && ((code === 'ShiftLeft') ||
(code === 'ShiftRight'))) {
if ('ShiftRight' in this._keyDownList) {
this._sendKeyEvent(this._keyDownList['ShiftRight'],
'ShiftRight', false);
}
if ('ShiftLeft' in this._keyDownList) {
this._sendKeyEvent(this._keyDownList['ShiftLeft'],
'ShiftLeft', false);
}
}
}
_interruptAltGrSequence() {
if (this._altGrArmed) {
this._altGrArmed = false;
clearTimeout(this._altGrTimeout);
this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
}
}
_allKeysUp() {
Log.Debug(">> Keyboard.allKeysUp");
// Prevent control key being processed after losing focus.
this._interruptAltGrSequence();
for (let code in this._keyDownList) {
this._sendKeyEvent(this._keyDownList[code], code, false);
}
Log.Debug("<< Keyboard.allKeysUp");
}
// ===== PUBLIC METHODS =====
grab() {
//Log.Debug(">> Keyboard.grab");
this._target.addEventListener('keydown', this._eventHandlers.keydown);
this._target.addEventListener('keyup', this._eventHandlers.keyup);
// Release (key up) if window loses focus
window.addEventListener('blur', this._eventHandlers.blur);
//Log.Debug("<< Keyboard.grab");
}
ungrab() {
//Log.Debug(">> Keyboard.ungrab");
this._target.removeEventListener('keydown', this._eventHandlers.keydown);
this._target.removeEventListener('keyup', this._eventHandlers.keyup);
window.removeEventListener('blur', this._eventHandlers.blur);
// Release (key up) all keys that are in a down state
this._allKeysUp();
//Log.Debug(">> Keyboard.ungrab");
}
}

@ -0,0 +1,616 @@
/* eslint-disable key-spacing */
export default {
XK_VoidSymbol: 0xffffff, /* Void symbol */
XK_BackSpace: 0xff08, /* Back space, back char */
XK_Tab: 0xff09,
XK_Linefeed: 0xff0a, /* Linefeed, LF */
XK_Clear: 0xff0b,
XK_Return: 0xff0d, /* Return, enter */
XK_Pause: 0xff13, /* Pause, hold */
XK_Scroll_Lock: 0xff14,
XK_Sys_Req: 0xff15,
XK_Escape: 0xff1b,
XK_Delete: 0xffff, /* Delete, rubout */
/* International & multi-key character composition */
XK_Multi_key: 0xff20, /* Multi-key character compose */
XK_Codeinput: 0xff37,
XK_SingleCandidate: 0xff3c,
XK_MultipleCandidate: 0xff3d,
XK_PreviousCandidate: 0xff3e,
/* Japanese keyboard support */
XK_Kanji: 0xff21, /* Kanji, Kanji convert */
XK_Muhenkan: 0xff22, /* Cancel Conversion */
XK_Henkan_Mode: 0xff23, /* Start/Stop Conversion */
XK_Henkan: 0xff23, /* Alias for Henkan_Mode */
XK_Romaji: 0xff24, /* to Romaji */
XK_Hiragana: 0xff25, /* to Hiragana */
XK_Katakana: 0xff26, /* to Katakana */
XK_Hiragana_Katakana: 0xff27, /* Hiragana/Katakana toggle */
XK_Zenkaku: 0xff28, /* to Zenkaku */
XK_Hankaku: 0xff29, /* to Hankaku */
XK_Zenkaku_Hankaku: 0xff2a, /* Zenkaku/Hankaku toggle */
XK_Touroku: 0xff2b, /* Add to Dictionary */
XK_Massyo: 0xff2c, /* Delete from Dictionary */
XK_Kana_Lock: 0xff2d, /* Kana Lock */
XK_Kana_Shift: 0xff2e, /* Kana Shift */
XK_Eisu_Shift: 0xff2f, /* Alphanumeric Shift */
XK_Eisu_toggle: 0xff30, /* Alphanumeric toggle */
XK_Kanji_Bangou: 0xff37, /* Codeinput */
XK_Zen_Koho: 0xff3d, /* Multiple/All Candidate(s) */
XK_Mae_Koho: 0xff3e, /* Previous Candidate */
/* Cursor control & motion */
XK_Home: 0xff50,
XK_Left: 0xff51, /* Move left, left arrow */
XK_Up: 0xff52, /* Move up, up arrow */
XK_Right: 0xff53, /* Move right, right arrow */
XK_Down: 0xff54, /* Move down, down arrow */
XK_Prior: 0xff55, /* Prior, previous */
XK_Page_Up: 0xff55,
XK_Next: 0xff56, /* Next */
XK_Page_Down: 0xff56,
XK_End: 0xff57, /* EOL */
XK_Begin: 0xff58, /* BOL */
/* Misc functions */
XK_Select: 0xff60, /* Select, mark */
XK_Print: 0xff61,
XK_Execute: 0xff62, /* Execute, run, do */
XK_Insert: 0xff63, /* Insert, insert here */
XK_Undo: 0xff65,
XK_Redo: 0xff66, /* Redo, again */
XK_Menu: 0xff67,
XK_Find: 0xff68, /* Find, search */
XK_Cancel: 0xff69, /* Cancel, stop, abort, exit */
XK_Help: 0xff6a, /* Help */
XK_Break: 0xff6b,
XK_Mode_switch: 0xff7e, /* Character set switch */
XK_script_switch: 0xff7e, /* Alias for mode_switch */
XK_Num_Lock: 0xff7f,
/* Keypad functions, keypad numbers cleverly chosen to map to ASCII */
XK_KP_Space: 0xff80, /* Space */
XK_KP_Tab: 0xff89,
XK_KP_Enter: 0xff8d, /* Enter */
XK_KP_F1: 0xff91, /* PF1, KP_A, ... */
XK_KP_F2: 0xff92,
XK_KP_F3: 0xff93,
XK_KP_F4: 0xff94,
XK_KP_Home: 0xff95,
XK_KP_Left: 0xff96,
XK_KP_Up: 0xff97,
XK_KP_Right: 0xff98,
XK_KP_Down: 0xff99,
XK_KP_Prior: 0xff9a,
XK_KP_Page_Up: 0xff9a,
XK_KP_Next: 0xff9b,
XK_KP_Page_Down: 0xff9b,
XK_KP_End: 0xff9c,
XK_KP_Begin: 0xff9d,
XK_KP_Insert: 0xff9e,
XK_KP_Delete: 0xff9f,
XK_KP_Equal: 0xffbd, /* Equals */
XK_KP_Multiply: 0xffaa,
XK_KP_Add: 0xffab,
XK_KP_Separator: 0xffac, /* Separator, often comma */
XK_KP_Subtract: 0xffad,
XK_KP_Decimal: 0xffae,
XK_KP_Divide: 0xffaf,
XK_KP_0: 0xffb0,
XK_KP_1: 0xffb1,
XK_KP_2: 0xffb2,
XK_KP_3: 0xffb3,
XK_KP_4: 0xffb4,
XK_KP_5: 0xffb5,
XK_KP_6: 0xffb6,
XK_KP_7: 0xffb7,
XK_KP_8: 0xffb8,
XK_KP_9: 0xffb9,
/*
* Auxiliary functions; note the duplicate definitions for left and right
* function keys; Sun keyboards and a few other manufacturers have such
* function key groups on the left and/or right sides of the keyboard.
* We've not found a keyboard with more than 35 function keys total.
*/
XK_F1: 0xffbe,
XK_F2: 0xffbf,
XK_F3: 0xffc0,
XK_F4: 0xffc1,
XK_F5: 0xffc2,
XK_F6: 0xffc3,
XK_F7: 0xffc4,
XK_F8: 0xffc5,
XK_F9: 0xffc6,
XK_F10: 0xffc7,
XK_F11: 0xffc8,
XK_L1: 0xffc8,
XK_F12: 0xffc9,
XK_L2: 0xffc9,
XK_F13: 0xffca,
XK_L3: 0xffca,
XK_F14: 0xffcb,
XK_L4: 0xffcb,
XK_F15: 0xffcc,
XK_L5: 0xffcc,
XK_F16: 0xffcd,
XK_L6: 0xffcd,
XK_F17: 0xffce,
XK_L7: 0xffce,
XK_F18: 0xffcf,
XK_L8: 0xffcf,
XK_F19: 0xffd0,
XK_L9: 0xffd0,
XK_F20: 0xffd1,
XK_L10: 0xffd1,
XK_F21: 0xffd2,
XK_R1: 0xffd2,
XK_F22: 0xffd3,
XK_R2: 0xffd3,
XK_F23: 0xffd4,
XK_R3: 0xffd4,
XK_F24: 0xffd5,
XK_R4: 0xffd5,
XK_F25: 0xffd6,
XK_R5: 0xffd6,
XK_F26: 0xffd7,
XK_R6: 0xffd7,
XK_F27: 0xffd8,
XK_R7: 0xffd8,
XK_F28: 0xffd9,
XK_R8: 0xffd9,
XK_F29: 0xffda,
XK_R9: 0xffda,
XK_F30: 0xffdb,
XK_R10: 0xffdb,
XK_F31: 0xffdc,
XK_R11: 0xffdc,
XK_F32: 0xffdd,
XK_R12: 0xffdd,
XK_F33: 0xffde,
XK_R13: 0xffde,
XK_F34: 0xffdf,
XK_R14: 0xffdf,
XK_F35: 0xffe0,
XK_R15: 0xffe0,
/* Modifiers */
XK_Shift_L: 0xffe1, /* Left shift */
XK_Shift_R: 0xffe2, /* Right shift */
XK_Control_L: 0xffe3, /* Left control */
XK_Control_R: 0xffe4, /* Right control */
XK_Caps_Lock: 0xffe5, /* Caps lock */
XK_Shift_Lock: 0xffe6, /* Shift lock */
XK_Meta_L: 0xffe7, /* Left meta */
XK_Meta_R: 0xffe8, /* Right meta */
XK_Alt_L: 0xffe9, /* Left alt */
XK_Alt_R: 0xffea, /* Right alt */
XK_Super_L: 0xffeb, /* Left super */
XK_Super_R: 0xffec, /* Right super */
XK_Hyper_L: 0xffed, /* Left hyper */
XK_Hyper_R: 0xffee, /* Right hyper */
/*
* Keyboard (XKB) Extension function and modifier keys
* (from Appendix C of "The X Keyboard Extension: Protocol Specification")
* Byte 3 = 0xfe
*/
XK_ISO_Level3_Shift: 0xfe03, /* AltGr */
XK_ISO_Next_Group: 0xfe08,
XK_ISO_Prev_Group: 0xfe0a,
XK_ISO_First_Group: 0xfe0c,
XK_ISO_Last_Group: 0xfe0e,
/*
* Latin 1
* (ISO/IEC 8859-1: Unicode U+0020..U+00FF)
* Byte 3: 0
*/
XK_space: 0x0020, /* U+0020 SPACE */
XK_exclam: 0x0021, /* U+0021 EXCLAMATION MARK */
XK_quotedbl: 0x0022, /* U+0022 QUOTATION MARK */
XK_numbersign: 0x0023, /* U+0023 NUMBER SIGN */
XK_dollar: 0x0024, /* U+0024 DOLLAR SIGN */
XK_percent: 0x0025, /* U+0025 PERCENT SIGN */
XK_ampersand: 0x0026, /* U+0026 AMPERSAND */
XK_apostrophe: 0x0027, /* U+0027 APOSTROPHE */
XK_quoteright: 0x0027, /* deprecated */
XK_parenleft: 0x0028, /* U+0028 LEFT PARENTHESIS */
XK_parenright: 0x0029, /* U+0029 RIGHT PARENTHESIS */
XK_asterisk: 0x002a, /* U+002A ASTERISK */
XK_plus: 0x002b, /* U+002B PLUS SIGN */
XK_comma: 0x002c, /* U+002C COMMA */
XK_minus: 0x002d, /* U+002D HYPHEN-MINUS */
XK_period: 0x002e, /* U+002E FULL STOP */
XK_slash: 0x002f, /* U+002F SOLIDUS */
XK_0: 0x0030, /* U+0030 DIGIT ZERO */
XK_1: 0x0031, /* U+0031 DIGIT ONE */
XK_2: 0x0032, /* U+0032 DIGIT TWO */
XK_3: 0x0033, /* U+0033 DIGIT THREE */
XK_4: 0x0034, /* U+0034 DIGIT FOUR */
XK_5: 0x0035, /* U+0035 DIGIT FIVE */
XK_6: 0x0036, /* U+0036 DIGIT SIX */
XK_7: 0x0037, /* U+0037 DIGIT SEVEN */
XK_8: 0x0038, /* U+0038 DIGIT EIGHT */
XK_9: 0x0039, /* U+0039 DIGIT NINE */
XK_colon: 0x003a, /* U+003A COLON */
XK_semicolon: 0x003b, /* U+003B SEMICOLON */
XK_less: 0x003c, /* U+003C LESS-THAN SIGN */
XK_equal: 0x003d, /* U+003D EQUALS SIGN */
XK_greater: 0x003e, /* U+003E GREATER-THAN SIGN */
XK_question: 0x003f, /* U+003F QUESTION MARK */
XK_at: 0x0040, /* U+0040 COMMERCIAL AT */
XK_A: 0x0041, /* U+0041 LATIN CAPITAL LETTER A */
XK_B: 0x0042, /* U+0042 LATIN CAPITAL LETTER B */
XK_C: 0x0043, /* U+0043 LATIN CAPITAL LETTER C */
XK_D: 0x0044, /* U+0044 LATIN CAPITAL LETTER D */
XK_E: 0x0045, /* U+0045 LATIN CAPITAL LETTER E */
XK_F: 0x0046, /* U+0046 LATIN CAPITAL LETTER F */
XK_G: 0x0047, /* U+0047 LATIN CAPITAL LETTER G */
XK_H: 0x0048, /* U+0048 LATIN CAPITAL LETTER H */
XK_I: 0x0049, /* U+0049 LATIN CAPITAL LETTER I */
XK_J: 0x004a, /* U+004A LATIN CAPITAL LETTER J */
XK_K: 0x004b, /* U+004B LATIN CAPITAL LETTER K */
XK_L: 0x004c, /* U+004C LATIN CAPITAL LETTER L */
XK_M: 0x004d, /* U+004D LATIN CAPITAL LETTER M */
XK_N: 0x004e, /* U+004E LATIN CAPITAL LETTER N */
XK_O: 0x004f, /* U+004F LATIN CAPITAL LETTER O */
XK_P: 0x0050, /* U+0050 LATIN CAPITAL LETTER P */
XK_Q: 0x0051, /* U+0051 LATIN CAPITAL LETTER Q */
XK_R: 0x0052, /* U+0052 LATIN CAPITAL LETTER R */
XK_S: 0x0053, /* U+0053 LATIN CAPITAL LETTER S */
XK_T: 0x0054, /* U+0054 LATIN CAPITAL LETTER T */
XK_U: 0x0055, /* U+0055 LATIN CAPITAL LETTER U */
XK_V: 0x0056, /* U+0056 LATIN CAPITAL LETTER V */
XK_W: 0x0057, /* U+0057 LATIN CAPITAL LETTER W */
XK_X: 0x0058, /* U+0058 LATIN CAPITAL LETTER X */
XK_Y: 0x0059, /* U+0059 LATIN CAPITAL LETTER Y */
XK_Z: 0x005a, /* U+005A LATIN CAPITAL LETTER Z */
XK_bracketleft: 0x005b, /* U+005B LEFT SQUARE BRACKET */
XK_backslash: 0x005c, /* U+005C REVERSE SOLIDUS */
XK_bracketright: 0x005d, /* U+005D RIGHT SQUARE BRACKET */
XK_asciicircum: 0x005e, /* U+005E CIRCUMFLEX ACCENT */
XK_underscore: 0x005f, /* U+005F LOW LINE */
XK_grave: 0x0060, /* U+0060 GRAVE ACCENT */
XK_quoteleft: 0x0060, /* deprecated */
XK_a: 0x0061, /* U+0061 LATIN SMALL LETTER A */
XK_b: 0x0062, /* U+0062 LATIN SMALL LETTER B */
XK_c: 0x0063, /* U+0063 LATIN SMALL LETTER C */
XK_d: 0x0064, /* U+0064 LATIN SMALL LETTER D */
XK_e: 0x0065, /* U+0065 LATIN SMALL LETTER E */
XK_f: 0x0066, /* U+0066 LATIN SMALL LETTER F */
XK_g: 0x0067, /* U+0067 LATIN SMALL LETTER G */
XK_h: 0x0068, /* U+0068 LATIN SMALL LETTER H */
XK_i: 0x0069, /* U+0069 LATIN SMALL LETTER I */
XK_j: 0x006a, /* U+006A LATIN SMALL LETTER J */
XK_k: 0x006b, /* U+006B LATIN SMALL LETTER K */
XK_l: 0x006c, /* U+006C LATIN SMALL LETTER L */
XK_m: 0x006d, /* U+006D LATIN SMALL LETTER M */
XK_n: 0x006e, /* U+006E LATIN SMALL LETTER N */
XK_o: 0x006f, /* U+006F LATIN SMALL LETTER O */
XK_p: 0x0070, /* U+0070 LATIN SMALL LETTER P */
XK_q: 0x0071, /* U+0071 LATIN SMALL LETTER Q */
XK_r: 0x0072, /* U+0072 LATIN SMALL LETTER R */
XK_s: 0x0073, /* U+0073 LATIN SMALL LETTER S */
XK_t: 0x0074, /* U+0074 LATIN SMALL LETTER T */
XK_u: 0x0075, /* U+0075 LATIN SMALL LETTER U */
XK_v: 0x0076, /* U+0076 LATIN SMALL LETTER V */
XK_w: 0x0077, /* U+0077 LATIN SMALL LETTER W */
XK_x: 0x0078, /* U+0078 LATIN SMALL LETTER X */
XK_y: 0x0079, /* U+0079 LATIN SMALL LETTER Y */
XK_z: 0x007a, /* U+007A LATIN SMALL LETTER Z */
XK_braceleft: 0x007b, /* U+007B LEFT CURLY BRACKET */
XK_bar: 0x007c, /* U+007C VERTICAL LINE */
XK_braceright: 0x007d, /* U+007D RIGHT CURLY BRACKET */
XK_asciitilde: 0x007e, /* U+007E TILDE */
XK_nobreakspace: 0x00a0, /* U+00A0 NO-BREAK SPACE */
XK_exclamdown: 0x00a1, /* U+00A1 INVERTED EXCLAMATION MARK */
XK_cent: 0x00a2, /* U+00A2 CENT SIGN */
XK_sterling: 0x00a3, /* U+00A3 POUND SIGN */
XK_currency: 0x00a4, /* U+00A4 CURRENCY SIGN */
XK_yen: 0x00a5, /* U+00A5 YEN SIGN */
XK_brokenbar: 0x00a6, /* U+00A6 BROKEN BAR */
XK_section: 0x00a7, /* U+00A7 SECTION SIGN */
XK_diaeresis: 0x00a8, /* U+00A8 DIAERESIS */
XK_copyright: 0x00a9, /* U+00A9 COPYRIGHT SIGN */
XK_ordfeminine: 0x00aa, /* U+00AA FEMININE ORDINAL INDICATOR */
XK_guillemotleft: 0x00ab, /* U+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */
XK_notsign: 0x00ac, /* U+00AC NOT SIGN */
XK_hyphen: 0x00ad, /* U+00AD SOFT HYPHEN */
XK_registered: 0x00ae, /* U+00AE REGISTERED SIGN */
XK_macron: 0x00af, /* U+00AF MACRON */
XK_degree: 0x00b0, /* U+00B0 DEGREE SIGN */
XK_plusminus: 0x00b1, /* U+00B1 PLUS-MINUS SIGN */
XK_twosuperior: 0x00b2, /* U+00B2 SUPERSCRIPT TWO */
XK_threesuperior: 0x00b3, /* U+00B3 SUPERSCRIPT THREE */
XK_acute: 0x00b4, /* U+00B4 ACUTE ACCENT */
XK_mu: 0x00b5, /* U+00B5 MICRO SIGN */
XK_paragraph: 0x00b6, /* U+00B6 PILCROW SIGN */
XK_periodcentered: 0x00b7, /* U+00B7 MIDDLE DOT */
XK_cedilla: 0x00b8, /* U+00B8 CEDILLA */
XK_onesuperior: 0x00b9, /* U+00B9 SUPERSCRIPT ONE */
XK_masculine: 0x00ba, /* U+00BA MASCULINE ORDINAL INDICATOR */
XK_guillemotright: 0x00bb, /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */
XK_onequarter: 0x00bc, /* U+00BC VULGAR FRACTION ONE QUARTER */
XK_onehalf: 0x00bd, /* U+00BD VULGAR FRACTION ONE HALF */
XK_threequarters: 0x00be, /* U+00BE VULGAR FRACTION THREE QUARTERS */
XK_questiondown: 0x00bf, /* U+00BF INVERTED QUESTION MARK */
XK_Agrave: 0x00c0, /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */
XK_Aacute: 0x00c1, /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */
XK_Acircumflex: 0x00c2, /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */
XK_Atilde: 0x00c3, /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */
XK_Adiaeresis: 0x00c4, /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS */
XK_Aring: 0x00c5, /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */
XK_AE: 0x00c6, /* U+00C6 LATIN CAPITAL LETTER AE */
XK_Ccedilla: 0x00c7, /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */
XK_Egrave: 0x00c8, /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */
XK_Eacute: 0x00c9, /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */
XK_Ecircumflex: 0x00ca, /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */
XK_Ediaeresis: 0x00cb, /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS */
XK_Igrave: 0x00cc, /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */
XK_Iacute: 0x00cd, /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */
XK_Icircumflex: 0x00ce, /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */
XK_Idiaeresis: 0x00cf, /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS */
XK_ETH: 0x00d0, /* U+00D0 LATIN CAPITAL LETTER ETH */
XK_Eth: 0x00d0, /* deprecated */
XK_Ntilde: 0x00d1, /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */
XK_Ograve: 0x00d2, /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */
XK_Oacute: 0x00d3, /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */
XK_Ocircumflex: 0x00d4, /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */
XK_Otilde: 0x00d5, /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */
XK_Odiaeresis: 0x00d6, /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS */
XK_multiply: 0x00d7, /* U+00D7 MULTIPLICATION SIGN */
XK_Oslash: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */
XK_Ooblique: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */
XK_Ugrave: 0x00d9, /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */
XK_Uacute: 0x00da, /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */
XK_Ucircumflex: 0x00db, /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */
XK_Udiaeresis: 0x00dc, /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS */
XK_Yacute: 0x00dd, /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */
XK_THORN: 0x00de, /* U+00DE LATIN CAPITAL LETTER THORN */
XK_Thorn: 0x00de, /* deprecated */
XK_ssharp: 0x00df, /* U+00DF LATIN SMALL LETTER SHARP S */
XK_agrave: 0x00e0, /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */
XK_aacute: 0x00e1, /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */
XK_acircumflex: 0x00e2, /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX */
XK_atilde: 0x00e3, /* U+00E3 LATIN SMALL LETTER A WITH TILDE */
XK_adiaeresis: 0x00e4, /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */
XK_aring: 0x00e5, /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */
XK_ae: 0x00e6, /* U+00E6 LATIN SMALL LETTER AE */
XK_ccedilla: 0x00e7, /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */
XK_egrave: 0x00e8, /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */
XK_eacute: 0x00e9, /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */
XK_ecircumflex: 0x00ea, /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX */
XK_ediaeresis: 0x00eb, /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */
XK_igrave: 0x00ec, /* U+00EC LATIN SMALL LETTER I WITH GRAVE */
XK_iacute: 0x00ed, /* U+00ED LATIN SMALL LETTER I WITH ACUTE */
XK_icircumflex: 0x00ee, /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX */
XK_idiaeresis: 0x00ef, /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */
XK_eth: 0x00f0, /* U+00F0 LATIN SMALL LETTER ETH */
XK_ntilde: 0x00f1, /* U+00F1 LATIN SMALL LETTER N WITH TILDE */
XK_ograve: 0x00f2, /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */
XK_oacute: 0x00f3, /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */
XK_ocircumflex: 0x00f4, /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX */
XK_otilde: 0x00f5, /* U+00F5 LATIN SMALL LETTER O WITH TILDE */
XK_odiaeresis: 0x00f6, /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */
XK_division: 0x00f7, /* U+00F7 DIVISION SIGN */
XK_oslash: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */
XK_ooblique: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */
XK_ugrave: 0x00f9, /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */
XK_uacute: 0x00fa, /* U+00FA LATIN SMALL LETTER U WITH ACUTE */
XK_ucircumflex: 0x00fb, /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX */
XK_udiaeresis: 0x00fc, /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */
XK_yacute: 0x00fd, /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */
XK_thorn: 0x00fe, /* U+00FE LATIN SMALL LETTER THORN */
XK_ydiaeresis: 0x00ff, /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */
/*
* Korean
* Byte 3 = 0x0e
*/
XK_Hangul: 0xff31, /* Hangul start/stop(toggle) */
XK_Hangul_Hanja: 0xff34, /* Start Hangul->Hanja Conversion */
XK_Hangul_Jeonja: 0xff38, /* Jeonja mode */
/*
* XFree86 vendor specific keysyms.
*
* The XFree86 keysym range is 0x10080001 - 0x1008FFFF.
*/
XF86XK_ModeLock: 0x1008FF01,
XF86XK_MonBrightnessUp: 0x1008FF02,
XF86XK_MonBrightnessDown: 0x1008FF03,
XF86XK_KbdLightOnOff: 0x1008FF04,
XF86XK_KbdBrightnessUp: 0x1008FF05,
XF86XK_KbdBrightnessDown: 0x1008FF06,
XF86XK_Standby: 0x1008FF10,
XF86XK_AudioLowerVolume: 0x1008FF11,
XF86XK_AudioMute: 0x1008FF12,
XF86XK_AudioRaiseVolume: 0x1008FF13,
XF86XK_AudioPlay: 0x1008FF14,
XF86XK_AudioStop: 0x1008FF15,
XF86XK_AudioPrev: 0x1008FF16,
XF86XK_AudioNext: 0x1008FF17,
XF86XK_HomePage: 0x1008FF18,
XF86XK_Mail: 0x1008FF19,
XF86XK_Start: 0x1008FF1A,
XF86XK_Search: 0x1008FF1B,
XF86XK_AudioRecord: 0x1008FF1C,
XF86XK_Calculator: 0x1008FF1D,
XF86XK_Memo: 0x1008FF1E,
XF86XK_ToDoList: 0x1008FF1F,
XF86XK_Calendar: 0x1008FF20,
XF86XK_PowerDown: 0x1008FF21,
XF86XK_ContrastAdjust: 0x1008FF22,
XF86XK_RockerUp: 0x1008FF23,
XF86XK_RockerDown: 0x1008FF24,
XF86XK_RockerEnter: 0x1008FF25,
XF86XK_Back: 0x1008FF26,
XF86XK_Forward: 0x1008FF27,
XF86XK_Stop: 0x1008FF28,
XF86XK_Refresh: 0x1008FF29,
XF86XK_PowerOff: 0x1008FF2A,
XF86XK_WakeUp: 0x1008FF2B,
XF86XK_Eject: 0x1008FF2C,
XF86XK_ScreenSaver: 0x1008FF2D,
XF86XK_WWW: 0x1008FF2E,
XF86XK_Sleep: 0x1008FF2F,
XF86XK_Favorites: 0x1008FF30,
XF86XK_AudioPause: 0x1008FF31,
XF86XK_AudioMedia: 0x1008FF32,
XF86XK_MyComputer: 0x1008FF33,
XF86XK_VendorHome: 0x1008FF34,
XF86XK_LightBulb: 0x1008FF35,
XF86XK_Shop: 0x1008FF36,
XF86XK_History: 0x1008FF37,
XF86XK_OpenURL: 0x1008FF38,
XF86XK_AddFavorite: 0x1008FF39,
XF86XK_HotLinks: 0x1008FF3A,
XF86XK_BrightnessAdjust: 0x1008FF3B,
XF86XK_Finance: 0x1008FF3C,
XF86XK_Community: 0x1008FF3D,
XF86XK_AudioRewind: 0x1008FF3E,
XF86XK_BackForward: 0x1008FF3F,
XF86XK_Launch0: 0x1008FF40,
XF86XK_Launch1: 0x1008FF41,
XF86XK_Launch2: 0x1008FF42,
XF86XK_Launch3: 0x1008FF43,
XF86XK_Launch4: 0x1008FF44,
XF86XK_Launch5: 0x1008FF45,
XF86XK_Launch6: 0x1008FF46,
XF86XK_Launch7: 0x1008FF47,
XF86XK_Launch8: 0x1008FF48,
XF86XK_Launch9: 0x1008FF49,
XF86XK_LaunchA: 0x1008FF4A,
XF86XK_LaunchB: 0x1008FF4B,
XF86XK_LaunchC: 0x1008FF4C,
XF86XK_LaunchD: 0x1008FF4D,
XF86XK_LaunchE: 0x1008FF4E,
XF86XK_LaunchF: 0x1008FF4F,
XF86XK_ApplicationLeft: 0x1008FF50,
XF86XK_ApplicationRight: 0x1008FF51,
XF86XK_Book: 0x1008FF52,
XF86XK_CD: 0x1008FF53,
XF86XK_Calculater: 0x1008FF54,
XF86XK_Clear: 0x1008FF55,
XF86XK_Close: 0x1008FF56,
XF86XK_Copy: 0x1008FF57,
XF86XK_Cut: 0x1008FF58,
XF86XK_Display: 0x1008FF59,
XF86XK_DOS: 0x1008FF5A,
XF86XK_Documents: 0x1008FF5B,
XF86XK_Excel: 0x1008FF5C,
XF86XK_Explorer: 0x1008FF5D,
XF86XK_Game: 0x1008FF5E,
XF86XK_Go: 0x1008FF5F,
XF86XK_iTouch: 0x1008FF60,
XF86XK_LogOff: 0x1008FF61,
XF86XK_Market: 0x1008FF62,
XF86XK_Meeting: 0x1008FF63,
XF86XK_MenuKB: 0x1008FF65,
XF86XK_MenuPB: 0x1008FF66,
XF86XK_MySites: 0x1008FF67,
XF86XK_New: 0x1008FF68,
XF86XK_News: 0x1008FF69,
XF86XK_OfficeHome: 0x1008FF6A,
XF86XK_Open: 0x1008FF6B,
XF86XK_Option: 0x1008FF6C,
XF86XK_Paste: 0x1008FF6D,
XF86XK_Phone: 0x1008FF6E,
XF86XK_Q: 0x1008FF70,
XF86XK_Reply: 0x1008FF72,
XF86XK_Reload: 0x1008FF73,
XF86XK_RotateWindows: 0x1008FF74,
XF86XK_RotationPB: 0x1008FF75,
XF86XK_RotationKB: 0x1008FF76,
XF86XK_Save: 0x1008FF77,
XF86XK_ScrollUp: 0x1008FF78,
XF86XK_ScrollDown: 0x1008FF79,
XF86XK_ScrollClick: 0x1008FF7A,
XF86XK_Send: 0x1008FF7B,
XF86XK_Spell: 0x1008FF7C,
XF86XK_SplitScreen: 0x1008FF7D,
XF86XK_Support: 0x1008FF7E,
XF86XK_TaskPane: 0x1008FF7F,
XF86XK_Terminal: 0x1008FF80,
XF86XK_Tools: 0x1008FF81,
XF86XK_Travel: 0x1008FF82,
XF86XK_UserPB: 0x1008FF84,
XF86XK_User1KB: 0x1008FF85,
XF86XK_User2KB: 0x1008FF86,
XF86XK_Video: 0x1008FF87,
XF86XK_WheelButton: 0x1008FF88,
XF86XK_Word: 0x1008FF89,
XF86XK_Xfer: 0x1008FF8A,
XF86XK_ZoomIn: 0x1008FF8B,
XF86XK_ZoomOut: 0x1008FF8C,
XF86XK_Away: 0x1008FF8D,
XF86XK_Messenger: 0x1008FF8E,
XF86XK_WebCam: 0x1008FF8F,
XF86XK_MailForward: 0x1008FF90,
XF86XK_Pictures: 0x1008FF91,
XF86XK_Music: 0x1008FF92,
XF86XK_Battery: 0x1008FF93,
XF86XK_Bluetooth: 0x1008FF94,
XF86XK_WLAN: 0x1008FF95,
XF86XK_UWB: 0x1008FF96,
XF86XK_AudioForward: 0x1008FF97,
XF86XK_AudioRepeat: 0x1008FF98,
XF86XK_AudioRandomPlay: 0x1008FF99,
XF86XK_Subtitle: 0x1008FF9A,
XF86XK_AudioCycleTrack: 0x1008FF9B,
XF86XK_CycleAngle: 0x1008FF9C,
XF86XK_FrameBack: 0x1008FF9D,
XF86XK_FrameForward: 0x1008FF9E,
XF86XK_Time: 0x1008FF9F,
XF86XK_Select: 0x1008FFA0,
XF86XK_View: 0x1008FFA1,
XF86XK_TopMenu: 0x1008FFA2,
XF86XK_Red: 0x1008FFA3,
XF86XK_Green: 0x1008FFA4,
XF86XK_Yellow: 0x1008FFA5,
XF86XK_Blue: 0x1008FFA6,
XF86XK_Suspend: 0x1008FFA7,
XF86XK_Hibernate: 0x1008FFA8,
XF86XK_TouchpadToggle: 0x1008FFA9,
XF86XK_TouchpadOn: 0x1008FFB0,
XF86XK_TouchpadOff: 0x1008FFB1,
XF86XK_AudioMicMute: 0x1008FFB2,
XF86XK_Switch_VT_1: 0x1008FE01,
XF86XK_Switch_VT_2: 0x1008FE02,
XF86XK_Switch_VT_3: 0x1008FE03,
XF86XK_Switch_VT_4: 0x1008FE04,
XF86XK_Switch_VT_5: 0x1008FE05,
XF86XK_Switch_VT_6: 0x1008FE06,
XF86XK_Switch_VT_7: 0x1008FE07,
XF86XK_Switch_VT_8: 0x1008FE08,
XF86XK_Switch_VT_9: 0x1008FE09,
XF86XK_Switch_VT_10: 0x1008FE0A,
XF86XK_Switch_VT_11: 0x1008FE0B,
XF86XK_Switch_VT_12: 0x1008FE0C,
XF86XK_Ungrab: 0x1008FE20,
XF86XK_ClearGrab: 0x1008FE21,
XF86XK_Next_VMode: 0x1008FE22,
XF86XK_Prev_VMode: 0x1008FE23,
XF86XK_LogWindowTree: 0x1008FE24,
XF86XK_LogGrabInfo: 0x1008FE25,
};

@ -0,0 +1,688 @@
/*
* Mapping from Unicode codepoints to X11/RFB keysyms
*
* This file was automatically generated from keysymdef.h
* DO NOT EDIT!
*/
/* Functions at the bottom */
const codepoints = {
0x0100: 0x03c0, // XK_Amacron
0x0101: 0x03e0, // XK_amacron
0x0102: 0x01c3, // XK_Abreve
0x0103: 0x01e3, // XK_abreve
0x0104: 0x01a1, // XK_Aogonek
0x0105: 0x01b1, // XK_aogonek
0x0106: 0x01c6, // XK_Cacute
0x0107: 0x01e6, // XK_cacute
0x0108: 0x02c6, // XK_Ccircumflex
0x0109: 0x02e6, // XK_ccircumflex
0x010a: 0x02c5, // XK_Cabovedot
0x010b: 0x02e5, // XK_cabovedot
0x010c: 0x01c8, // XK_Ccaron
0x010d: 0x01e8, // XK_ccaron
0x010e: 0x01cf, // XK_Dcaron
0x010f: 0x01ef, // XK_dcaron
0x0110: 0x01d0, // XK_Dstroke
0x0111: 0x01f0, // XK_dstroke
0x0112: 0x03aa, // XK_Emacron
0x0113: 0x03ba, // XK_emacron
0x0116: 0x03cc, // XK_Eabovedot
0x0117: 0x03ec, // XK_eabovedot
0x0118: 0x01ca, // XK_Eogonek
0x0119: 0x01ea, // XK_eogonek
0x011a: 0x01cc, // XK_Ecaron
0x011b: 0x01ec, // XK_ecaron
0x011c: 0x02d8, // XK_Gcircumflex
0x011d: 0x02f8, // XK_gcircumflex
0x011e: 0x02ab, // XK_Gbreve
0x011f: 0x02bb, // XK_gbreve
0x0120: 0x02d5, // XK_Gabovedot
0x0121: 0x02f5, // XK_gabovedot
0x0122: 0x03ab, // XK_Gcedilla
0x0123: 0x03bb, // XK_gcedilla
0x0124: 0x02a6, // XK_Hcircumflex
0x0125: 0x02b6, // XK_hcircumflex
0x0126: 0x02a1, // XK_Hstroke
0x0127: 0x02b1, // XK_hstroke
0x0128: 0x03a5, // XK_Itilde
0x0129: 0x03b5, // XK_itilde
0x012a: 0x03cf, // XK_Imacron
0x012b: 0x03ef, // XK_imacron
0x012e: 0x03c7, // XK_Iogonek
0x012f: 0x03e7, // XK_iogonek
0x0130: 0x02a9, // XK_Iabovedot
0x0131: 0x02b9, // XK_idotless
0x0134: 0x02ac, // XK_Jcircumflex
0x0135: 0x02bc, // XK_jcircumflex
0x0136: 0x03d3, // XK_Kcedilla
0x0137: 0x03f3, // XK_kcedilla
0x0138: 0x03a2, // XK_kra
0x0139: 0x01c5, // XK_Lacute
0x013a: 0x01e5, // XK_lacute
0x013b: 0x03a6, // XK_Lcedilla
0x013c: 0x03b6, // XK_lcedilla
0x013d: 0x01a5, // XK_Lcaron
0x013e: 0x01b5, // XK_lcaron
0x0141: 0x01a3, // XK_Lstroke
0x0142: 0x01b3, // XK_lstroke
0x0143: 0x01d1, // XK_Nacute
0x0144: 0x01f1, // XK_nacute
0x0145: 0x03d1, // XK_Ncedilla
0x0146: 0x03f1, // XK_ncedilla
0x0147: 0x01d2, // XK_Ncaron
0x0148: 0x01f2, // XK_ncaron
0x014a: 0x03bd, // XK_ENG
0x014b: 0x03bf, // XK_eng
0x014c: 0x03d2, // XK_Omacron
0x014d: 0x03f2, // XK_omacron
0x0150: 0x01d5, // XK_Odoubleacute
0x0151: 0x01f5, // XK_odoubleacute
0x0152: 0x13bc, // XK_OE
0x0153: 0x13bd, // XK_oe
0x0154: 0x01c0, // XK_Racute
0x0155: 0x01e0, // XK_racute
0x0156: 0x03a3, // XK_Rcedilla
0x0157: 0x03b3, // XK_rcedilla
0x0158: 0x01d8, // XK_Rcaron
0x0159: 0x01f8, // XK_rcaron
0x015a: 0x01a6, // XK_Sacute
0x015b: 0x01b6, // XK_sacute
0x015c: 0x02de, // XK_Scircumflex
0x015d: 0x02fe, // XK_scircumflex
0x015e: 0x01aa, // XK_Scedilla
0x015f: 0x01ba, // XK_scedilla
0x0160: 0x01a9, // XK_Scaron
0x0161: 0x01b9, // XK_scaron
0x0162: 0x01de, // XK_Tcedilla
0x0163: 0x01fe, // XK_tcedilla
0x0164: 0x01ab, // XK_Tcaron
0x0165: 0x01bb, // XK_tcaron
0x0166: 0x03ac, // XK_Tslash
0x0167: 0x03bc, // XK_tslash
0x0168: 0x03dd, // XK_Utilde
0x0169: 0x03fd, // XK_utilde
0x016a: 0x03de, // XK_Umacron
0x016b: 0x03fe, // XK_umacron
0x016c: 0x02dd, // XK_Ubreve
0x016d: 0x02fd, // XK_ubreve
0x016e: 0x01d9, // XK_Uring
0x016f: 0x01f9, // XK_uring
0x0170: 0x01db, // XK_Udoubleacute
0x0171: 0x01fb, // XK_udoubleacute
0x0172: 0x03d9, // XK_Uogonek
0x0173: 0x03f9, // XK_uogonek
0x0178: 0x13be, // XK_Ydiaeresis
0x0179: 0x01ac, // XK_Zacute
0x017a: 0x01bc, // XK_zacute
0x017b: 0x01af, // XK_Zabovedot
0x017c: 0x01bf, // XK_zabovedot
0x017d: 0x01ae, // XK_Zcaron
0x017e: 0x01be, // XK_zcaron
0x0192: 0x08f6, // XK_function
0x01d2: 0x10001d1, // XK_Ocaron
0x02c7: 0x01b7, // XK_caron
0x02d8: 0x01a2, // XK_breve
0x02d9: 0x01ff, // XK_abovedot
0x02db: 0x01b2, // XK_ogonek
0x02dd: 0x01bd, // XK_doubleacute
0x0385: 0x07ae, // XK_Greek_accentdieresis
0x0386: 0x07a1, // XK_Greek_ALPHAaccent
0x0388: 0x07a2, // XK_Greek_EPSILONaccent
0x0389: 0x07a3, // XK_Greek_ETAaccent
0x038a: 0x07a4, // XK_Greek_IOTAaccent
0x038c: 0x07a7, // XK_Greek_OMICRONaccent
0x038e: 0x07a8, // XK_Greek_UPSILONaccent
0x038f: 0x07ab, // XK_Greek_OMEGAaccent
0x0390: 0x07b6, // XK_Greek_iotaaccentdieresis
0x0391: 0x07c1, // XK_Greek_ALPHA
0x0392: 0x07c2, // XK_Greek_BETA
0x0393: 0x07c3, // XK_Greek_GAMMA
0x0394: 0x07c4, // XK_Greek_DELTA
0x0395: 0x07c5, // XK_Greek_EPSILON
0x0396: 0x07c6, // XK_Greek_ZETA
0x0397: 0x07c7, // XK_Greek_ETA
0x0398: 0x07c8, // XK_Greek_THETA
0x0399: 0x07c9, // XK_Greek_IOTA
0x039a: 0x07ca, // XK_Greek_KAPPA
0x039b: 0x07cb, // XK_Greek_LAMDA
0x039c: 0x07cc, // XK_Greek_MU
0x039d: 0x07cd, // XK_Greek_NU
0x039e: 0x07ce, // XK_Greek_XI
0x039f: 0x07cf, // XK_Greek_OMICRON
0x03a0: 0x07d0, // XK_Greek_PI
0x03a1: 0x07d1, // XK_Greek_RHO
0x03a3: 0x07d2, // XK_Greek_SIGMA
0x03a4: 0x07d4, // XK_Greek_TAU
0x03a5: 0x07d5, // XK_Greek_UPSILON
0x03a6: 0x07d6, // XK_Greek_PHI
0x03a7: 0x07d7, // XK_Greek_CHI
0x03a8: 0x07d8, // XK_Greek_PSI
0x03a9: 0x07d9, // XK_Greek_OMEGA
0x03aa: 0x07a5, // XK_Greek_IOTAdieresis
0x03ab: 0x07a9, // XK_Greek_UPSILONdieresis
0x03ac: 0x07b1, // XK_Greek_alphaaccent
0x03ad: 0x07b2, // XK_Greek_epsilonaccent
0x03ae: 0x07b3, // XK_Greek_etaaccent
0x03af: 0x07b4, // XK_Greek_iotaaccent
0x03b0: 0x07ba, // XK_Greek_upsilonaccentdieresis
0x03b1: 0x07e1, // XK_Greek_alpha
0x03b2: 0x07e2, // XK_Greek_beta
0x03b3: 0x07e3, // XK_Greek_gamma
0x03b4: 0x07e4, // XK_Greek_delta
0x03b5: 0x07e5, // XK_Greek_epsilon
0x03b6: 0x07e6, // XK_Greek_zeta
0x03b7: 0x07e7, // XK_Greek_eta
0x03b8: 0x07e8, // XK_Greek_theta
0x03b9: 0x07e9, // XK_Greek_iota
0x03ba: 0x07ea, // XK_Greek_kappa
0x03bb: 0x07eb, // XK_Greek_lamda
0x03bc: 0x07ec, // XK_Greek_mu
0x03bd: 0x07ed, // XK_Greek_nu
0x03be: 0x07ee, // XK_Greek_xi
0x03bf: 0x07ef, // XK_Greek_omicron
0x03c0: 0x07f0, // XK_Greek_pi
0x03c1: 0x07f1, // XK_Greek_rho
0x03c2: 0x07f3, // XK_Greek_finalsmallsigma
0x03c3: 0x07f2, // XK_Greek_sigma
0x03c4: 0x07f4, // XK_Greek_tau
0x03c5: 0x07f5, // XK_Greek_upsilon
0x03c6: 0x07f6, // XK_Greek_phi
0x03c7: 0x07f7, // XK_Greek_chi
0x03c8: 0x07f8, // XK_Greek_psi
0x03c9: 0x07f9, // XK_Greek_omega
0x03ca: 0x07b5, // XK_Greek_iotadieresis
0x03cb: 0x07b9, // XK_Greek_upsilondieresis
0x03cc: 0x07b7, // XK_Greek_omicronaccent
0x03cd: 0x07b8, // XK_Greek_upsilonaccent
0x03ce: 0x07bb, // XK_Greek_omegaaccent
0x0401: 0x06b3, // XK_Cyrillic_IO
0x0402: 0x06b1, // XK_Serbian_DJE
0x0403: 0x06b2, // XK_Macedonia_GJE
0x0404: 0x06b4, // XK_Ukrainian_IE
0x0405: 0x06b5, // XK_Macedonia_DSE
0x0406: 0x06b6, // XK_Ukrainian_I
0x0407: 0x06b7, // XK_Ukrainian_YI
0x0408: 0x06b8, // XK_Cyrillic_JE
0x0409: 0x06b9, // XK_Cyrillic_LJE
0x040a: 0x06ba, // XK_Cyrillic_NJE
0x040b: 0x06bb, // XK_Serbian_TSHE
0x040c: 0x06bc, // XK_Macedonia_KJE
0x040e: 0x06be, // XK_Byelorussian_SHORTU
0x040f: 0x06bf, // XK_Cyrillic_DZHE
0x0410: 0x06e1, // XK_Cyrillic_A
0x0411: 0x06e2, // XK_Cyrillic_BE
0x0412: 0x06f7, // XK_Cyrillic_VE
0x0413: 0x06e7, // XK_Cyrillic_GHE
0x0414: 0x06e4, // XK_Cyrillic_DE
0x0415: 0x06e5, // XK_Cyrillic_IE
0x0416: 0x06f6, // XK_Cyrillic_ZHE
0x0417: 0x06fa, // XK_Cyrillic_ZE
0x0418: 0x06e9, // XK_Cyrillic_I
0x0419: 0x06ea, // XK_Cyrillic_SHORTI
0x041a: 0x06eb, // XK_Cyrillic_KA
0x041b: 0x06ec, // XK_Cyrillic_EL
0x041c: 0x06ed, // XK_Cyrillic_EM
0x041d: 0x06ee, // XK_Cyrillic_EN
0x041e: 0x06ef, // XK_Cyrillic_O
0x041f: 0x06f0, // XK_Cyrillic_PE
0x0420: 0x06f2, // XK_Cyrillic_ER
0x0421: 0x06f3, // XK_Cyrillic_ES
0x0422: 0x06f4, // XK_Cyrillic_TE
0x0423: 0x06f5, // XK_Cyrillic_U
0x0424: 0x06e6, // XK_Cyrillic_EF
0x0425: 0x06e8, // XK_Cyrillic_HA
0x0426: 0x06e3, // XK_Cyrillic_TSE
0x0427: 0x06fe, // XK_Cyrillic_CHE
0x0428: 0x06fb, // XK_Cyrillic_SHA
0x0429: 0x06fd, // XK_Cyrillic_SHCHA
0x042a: 0x06ff, // XK_Cyrillic_HARDSIGN
0x042b: 0x06f9, // XK_Cyrillic_YERU
0x042c: 0x06f8, // XK_Cyrillic_SOFTSIGN
0x042d: 0x06fc, // XK_Cyrillic_E
0x042e: 0x06e0, // XK_Cyrillic_YU
0x042f: 0x06f1, // XK_Cyrillic_YA
0x0430: 0x06c1, // XK_Cyrillic_a
0x0431: 0x06c2, // XK_Cyrillic_be
0x0432: 0x06d7, // XK_Cyrillic_ve
0x0433: 0x06c7, // XK_Cyrillic_ghe
0x0434: 0x06c4, // XK_Cyrillic_de
0x0435: 0x06c5, // XK_Cyrillic_ie
0x0436: 0x06d6, // XK_Cyrillic_zhe
0x0437: 0x06da, // XK_Cyrillic_ze
0x0438: 0x06c9, // XK_Cyrillic_i
0x0439: 0x06ca, // XK_Cyrillic_shorti
0x043a: 0x06cb, // XK_Cyrillic_ka
0x043b: 0x06cc, // XK_Cyrillic_el
0x043c: 0x06cd, // XK_Cyrillic_em
0x043d: 0x06ce, // XK_Cyrillic_en
0x043e: 0x06cf, // XK_Cyrillic_o
0x043f: 0x06d0, // XK_Cyrillic_pe
0x0440: 0x06d2, // XK_Cyrillic_er
0x0441: 0x06d3, // XK_Cyrillic_es
0x0442: 0x06d4, // XK_Cyrillic_te
0x0443: 0x06d5, // XK_Cyrillic_u
0x0444: 0x06c6, // XK_Cyrillic_ef
0x0445: 0x06c8, // XK_Cyrillic_ha
0x0446: 0x06c3, // XK_Cyrillic_tse
0x0447: 0x06de, // XK_Cyrillic_che
0x0448: 0x06db, // XK_Cyrillic_sha
0x0449: 0x06dd, // XK_Cyrillic_shcha
0x044a: 0x06df, // XK_Cyrillic_hardsign
0x044b: 0x06d9, // XK_Cyrillic_yeru
0x044c: 0x06d8, // XK_Cyrillic_softsign
0x044d: 0x06dc, // XK_Cyrillic_e
0x044e: 0x06c0, // XK_Cyrillic_yu
0x044f: 0x06d1, // XK_Cyrillic_ya
0x0451: 0x06a3, // XK_Cyrillic_io
0x0452: 0x06a1, // XK_Serbian_dje
0x0453: 0x06a2, // XK_Macedonia_gje
0x0454: 0x06a4, // XK_Ukrainian_ie
0x0455: 0x06a5, // XK_Macedonia_dse
0x0456: 0x06a6, // XK_Ukrainian_i
0x0457: 0x06a7, // XK_Ukrainian_yi
0x0458: 0x06a8, // XK_Cyrillic_je
0x0459: 0x06a9, // XK_Cyrillic_lje
0x045a: 0x06aa, // XK_Cyrillic_nje
0x045b: 0x06ab, // XK_Serbian_tshe
0x045c: 0x06ac, // XK_Macedonia_kje
0x045e: 0x06ae, // XK_Byelorussian_shortu
0x045f: 0x06af, // XK_Cyrillic_dzhe
0x0490: 0x06bd, // XK_Ukrainian_GHE_WITH_UPTURN
0x0491: 0x06ad, // XK_Ukrainian_ghe_with_upturn
0x05d0: 0x0ce0, // XK_hebrew_aleph
0x05d1: 0x0ce1, // XK_hebrew_bet
0x05d2: 0x0ce2, // XK_hebrew_gimel
0x05d3: 0x0ce3, // XK_hebrew_dalet
0x05d4: 0x0ce4, // XK_hebrew_he
0x05d5: 0x0ce5, // XK_hebrew_waw
0x05d6: 0x0ce6, // XK_hebrew_zain
0x05d7: 0x0ce7, // XK_hebrew_chet
0x05d8: 0x0ce8, // XK_hebrew_tet
0x05d9: 0x0ce9, // XK_hebrew_yod
0x05da: 0x0cea, // XK_hebrew_finalkaph
0x05db: 0x0ceb, // XK_hebrew_kaph
0x05dc: 0x0cec, // XK_hebrew_lamed
0x05dd: 0x0ced, // XK_hebrew_finalmem
0x05de: 0x0cee, // XK_hebrew_mem
0x05df: 0x0cef, // XK_hebrew_finalnun
0x05e0: 0x0cf0, // XK_hebrew_nun
0x05e1: 0x0cf1, // XK_hebrew_samech
0x05e2: 0x0cf2, // XK_hebrew_ayin
0x05e3: 0x0cf3, // XK_hebrew_finalpe
0x05e4: 0x0cf4, // XK_hebrew_pe
0x05e5: 0x0cf5, // XK_hebrew_finalzade
0x05e6: 0x0cf6, // XK_hebrew_zade
0x05e7: 0x0cf7, // XK_hebrew_qoph
0x05e8: 0x0cf8, // XK_hebrew_resh
0x05e9: 0x0cf9, // XK_hebrew_shin
0x05ea: 0x0cfa, // XK_hebrew_taw
0x060c: 0x05ac, // XK_Arabic_comma
0x061b: 0x05bb, // XK_Arabic_semicolon
0x061f: 0x05bf, // XK_Arabic_question_mark
0x0621: 0x05c1, // XK_Arabic_hamza
0x0622: 0x05c2, // XK_Arabic_maddaonalef
0x0623: 0x05c3, // XK_Arabic_hamzaonalef
0x0624: 0x05c4, // XK_Arabic_hamzaonwaw
0x0625: 0x05c5, // XK_Arabic_hamzaunderalef
0x0626: 0x05c6, // XK_Arabic_hamzaonyeh
0x0627: 0x05c7, // XK_Arabic_alef
0x0628: 0x05c8, // XK_Arabic_beh
0x0629: 0x05c9, // XK_Arabic_tehmarbuta
0x062a: 0x05ca, // XK_Arabic_teh
0x062b: 0x05cb, // XK_Arabic_theh
0x062c: 0x05cc, // XK_Arabic_jeem
0x062d: 0x05cd, // XK_Arabic_hah
0x062e: 0x05ce, // XK_Arabic_khah
0x062f: 0x05cf, // XK_Arabic_dal
0x0630: 0x05d0, // XK_Arabic_thal
0x0631: 0x05d1, // XK_Arabic_ra
0x0632: 0x05d2, // XK_Arabic_zain
0x0633: 0x05d3, // XK_Arabic_seen
0x0634: 0x05d4, // XK_Arabic_sheen
0x0635: 0x05d5, // XK_Arabic_sad
0x0636: 0x05d6, // XK_Arabic_dad
0x0637: 0x05d7, // XK_Arabic_tah
0x0638: 0x05d8, // XK_Arabic_zah
0x0639: 0x05d9, // XK_Arabic_ain
0x063a: 0x05da, // XK_Arabic_ghain
0x0640: 0x05e0, // XK_Arabic_tatweel
0x0641: 0x05e1, // XK_Arabic_feh
0x0642: 0x05e2, // XK_Arabic_qaf
0x0643: 0x05e3, // XK_Arabic_kaf
0x0644: 0x05e4, // XK_Arabic_lam
0x0645: 0x05e5, // XK_Arabic_meem
0x0646: 0x05e6, // XK_Arabic_noon
0x0647: 0x05e7, // XK_Arabic_ha
0x0648: 0x05e8, // XK_Arabic_waw
0x0649: 0x05e9, // XK_Arabic_alefmaksura
0x064a: 0x05ea, // XK_Arabic_yeh
0x064b: 0x05eb, // XK_Arabic_fathatan
0x064c: 0x05ec, // XK_Arabic_dammatan
0x064d: 0x05ed, // XK_Arabic_kasratan
0x064e: 0x05ee, // XK_Arabic_fatha
0x064f: 0x05ef, // XK_Arabic_damma
0x0650: 0x05f0, // XK_Arabic_kasra
0x0651: 0x05f1, // XK_Arabic_shadda
0x0652: 0x05f2, // XK_Arabic_sukun
0x0e01: 0x0da1, // XK_Thai_kokai
0x0e02: 0x0da2, // XK_Thai_khokhai
0x0e03: 0x0da3, // XK_Thai_khokhuat
0x0e04: 0x0da4, // XK_Thai_khokhwai
0x0e05: 0x0da5, // XK_Thai_khokhon
0x0e06: 0x0da6, // XK_Thai_khorakhang
0x0e07: 0x0da7, // XK_Thai_ngongu
0x0e08: 0x0da8, // XK_Thai_chochan
0x0e09: 0x0da9, // XK_Thai_choching
0x0e0a: 0x0daa, // XK_Thai_chochang
0x0e0b: 0x0dab, // XK_Thai_soso
0x0e0c: 0x0dac, // XK_Thai_chochoe
0x0e0d: 0x0dad, // XK_Thai_yoying
0x0e0e: 0x0dae, // XK_Thai_dochada
0x0e0f: 0x0daf, // XK_Thai_topatak
0x0e10: 0x0db0, // XK_Thai_thothan
0x0e11: 0x0db1, // XK_Thai_thonangmontho
0x0e12: 0x0db2, // XK_Thai_thophuthao
0x0e13: 0x0db3, // XK_Thai_nonen
0x0e14: 0x0db4, // XK_Thai_dodek
0x0e15: 0x0db5, // XK_Thai_totao
0x0e16: 0x0db6, // XK_Thai_thothung
0x0e17: 0x0db7, // XK_Thai_thothahan
0x0e18: 0x0db8, // XK_Thai_thothong
0x0e19: 0x0db9, // XK_Thai_nonu
0x0e1a: 0x0dba, // XK_Thai_bobaimai
0x0e1b: 0x0dbb, // XK_Thai_popla
0x0e1c: 0x0dbc, // XK_Thai_phophung
0x0e1d: 0x0dbd, // XK_Thai_fofa
0x0e1e: 0x0dbe, // XK_Thai_phophan
0x0e1f: 0x0dbf, // XK_Thai_fofan
0x0e20: 0x0dc0, // XK_Thai_phosamphao
0x0e21: 0x0dc1, // XK_Thai_moma
0x0e22: 0x0dc2, // XK_Thai_yoyak
0x0e23: 0x0dc3, // XK_Thai_rorua
0x0e24: 0x0dc4, // XK_Thai_ru
0x0e25: 0x0dc5, // XK_Thai_loling
0x0e26: 0x0dc6, // XK_Thai_lu
0x0e27: 0x0dc7, // XK_Thai_wowaen
0x0e28: 0x0dc8, // XK_Thai_sosala
0x0e29: 0x0dc9, // XK_Thai_sorusi
0x0e2a: 0x0dca, // XK_Thai_sosua
0x0e2b: 0x0dcb, // XK_Thai_hohip
0x0e2c: 0x0dcc, // XK_Thai_lochula
0x0e2d: 0x0dcd, // XK_Thai_oang
0x0e2e: 0x0dce, // XK_Thai_honokhuk
0x0e2f: 0x0dcf, // XK_Thai_paiyannoi
0x0e30: 0x0dd0, // XK_Thai_saraa
0x0e31: 0x0dd1, // XK_Thai_maihanakat
0x0e32: 0x0dd2, // XK_Thai_saraaa
0x0e33: 0x0dd3, // XK_Thai_saraam
0x0e34: 0x0dd4, // XK_Thai_sarai
0x0e35: 0x0dd5, // XK_Thai_saraii
0x0e36: 0x0dd6, // XK_Thai_saraue
0x0e37: 0x0dd7, // XK_Thai_sarauee
0x0e38: 0x0dd8, // XK_Thai_sarau
0x0e39: 0x0dd9, // XK_Thai_sarauu
0x0e3a: 0x0dda, // XK_Thai_phinthu
0x0e3f: 0x0ddf, // XK_Thai_baht
0x0e40: 0x0de0, // XK_Thai_sarae
0x0e41: 0x0de1, // XK_Thai_saraae
0x0e42: 0x0de2, // XK_Thai_sarao
0x0e43: 0x0de3, // XK_Thai_saraaimaimuan
0x0e44: 0x0de4, // XK_Thai_saraaimaimalai
0x0e45: 0x0de5, // XK_Thai_lakkhangyao
0x0e46: 0x0de6, // XK_Thai_maiyamok
0x0e47: 0x0de7, // XK_Thai_maitaikhu
0x0e48: 0x0de8, // XK_Thai_maiek
0x0e49: 0x0de9, // XK_Thai_maitho
0x0e4a: 0x0dea, // XK_Thai_maitri
0x0e4b: 0x0deb, // XK_Thai_maichattawa
0x0e4c: 0x0dec, // XK_Thai_thanthakhat
0x0e4d: 0x0ded, // XK_Thai_nikhahit
0x0e50: 0x0df0, // XK_Thai_leksun
0x0e51: 0x0df1, // XK_Thai_leknung
0x0e52: 0x0df2, // XK_Thai_leksong
0x0e53: 0x0df3, // XK_Thai_leksam
0x0e54: 0x0df4, // XK_Thai_leksi
0x0e55: 0x0df5, // XK_Thai_lekha
0x0e56: 0x0df6, // XK_Thai_lekhok
0x0e57: 0x0df7, // XK_Thai_lekchet
0x0e58: 0x0df8, // XK_Thai_lekpaet
0x0e59: 0x0df9, // XK_Thai_lekkao
0x2002: 0x0aa2, // XK_enspace
0x2003: 0x0aa1, // XK_emspace
0x2004: 0x0aa3, // XK_em3space
0x2005: 0x0aa4, // XK_em4space
0x2007: 0x0aa5, // XK_digitspace
0x2008: 0x0aa6, // XK_punctspace
0x2009: 0x0aa7, // XK_thinspace
0x200a: 0x0aa8, // XK_hairspace
0x2012: 0x0abb, // XK_figdash
0x2013: 0x0aaa, // XK_endash
0x2014: 0x0aa9, // XK_emdash
0x2015: 0x07af, // XK_Greek_horizbar
0x2017: 0x0cdf, // XK_hebrew_doublelowline
0x2018: 0x0ad0, // XK_leftsinglequotemark
0x2019: 0x0ad1, // XK_rightsinglequotemark
0x201a: 0x0afd, // XK_singlelowquotemark
0x201c: 0x0ad2, // XK_leftdoublequotemark
0x201d: 0x0ad3, // XK_rightdoublequotemark
0x201e: 0x0afe, // XK_doublelowquotemark
0x2020: 0x0af1, // XK_dagger
0x2021: 0x0af2, // XK_doubledagger
0x2022: 0x0ae6, // XK_enfilledcircbullet
0x2025: 0x0aaf, // XK_doubbaselinedot
0x2026: 0x0aae, // XK_ellipsis
0x2030: 0x0ad5, // XK_permille
0x2032: 0x0ad6, // XK_minutes
0x2033: 0x0ad7, // XK_seconds
0x2038: 0x0afc, // XK_caret
0x203e: 0x047e, // XK_overline
0x20a9: 0x0eff, // XK_Korean_Won
0x20ac: 0x20ac, // XK_EuroSign
0x2105: 0x0ab8, // XK_careof
0x2116: 0x06b0, // XK_numerosign
0x2117: 0x0afb, // XK_phonographcopyright
0x211e: 0x0ad4, // XK_prescription
0x2122: 0x0ac9, // XK_trademark
0x2153: 0x0ab0, // XK_onethird
0x2154: 0x0ab1, // XK_twothirds
0x2155: 0x0ab2, // XK_onefifth
0x2156: 0x0ab3, // XK_twofifths
0x2157: 0x0ab4, // XK_threefifths
0x2158: 0x0ab5, // XK_fourfifths
0x2159: 0x0ab6, // XK_onesixth
0x215a: 0x0ab7, // XK_fivesixths
0x215b: 0x0ac3, // XK_oneeighth
0x215c: 0x0ac4, // XK_threeeighths
0x215d: 0x0ac5, // XK_fiveeighths
0x215e: 0x0ac6, // XK_seveneighths
0x2190: 0x08fb, // XK_leftarrow
0x2191: 0x08fc, // XK_uparrow
0x2192: 0x08fd, // XK_rightarrow
0x2193: 0x08fe, // XK_downarrow
0x21d2: 0x08ce, // XK_implies
0x21d4: 0x08cd, // XK_ifonlyif
0x2202: 0x08ef, // XK_partialderivative
0x2207: 0x08c5, // XK_nabla
0x2218: 0x0bca, // XK_jot
0x221a: 0x08d6, // XK_radical
0x221d: 0x08c1, // XK_variation
0x221e: 0x08c2, // XK_infinity
0x2227: 0x08de, // XK_logicaland
0x2228: 0x08df, // XK_logicalor
0x2229: 0x08dc, // XK_intersection
0x222a: 0x08dd, // XK_union
0x222b: 0x08bf, // XK_integral
0x2234: 0x08c0, // XK_therefore
0x223c: 0x08c8, // XK_approximate
0x2243: 0x08c9, // XK_similarequal
0x2245: 0x1002248, // XK_approxeq
0x2260: 0x08bd, // XK_notequal
0x2261: 0x08cf, // XK_identical
0x2264: 0x08bc, // XK_lessthanequal
0x2265: 0x08be, // XK_greaterthanequal
0x2282: 0x08da, // XK_includedin
0x2283: 0x08db, // XK_includes
0x22a2: 0x0bfc, // XK_righttack
0x22a3: 0x0bdc, // XK_lefttack
0x22a4: 0x0bc2, // XK_downtack
0x22a5: 0x0bce, // XK_uptack
0x2308: 0x0bd3, // XK_upstile
0x230a: 0x0bc4, // XK_downstile
0x2315: 0x0afa, // XK_telephonerecorder
0x2320: 0x08a4, // XK_topintegral
0x2321: 0x08a5, // XK_botintegral
0x2395: 0x0bcc, // XK_quad
0x239b: 0x08ab, // XK_topleftparens
0x239d: 0x08ac, // XK_botleftparens
0x239e: 0x08ad, // XK_toprightparens
0x23a0: 0x08ae, // XK_botrightparens
0x23a1: 0x08a7, // XK_topleftsqbracket
0x23a3: 0x08a8, // XK_botleftsqbracket
0x23a4: 0x08a9, // XK_toprightsqbracket
0x23a6: 0x08aa, // XK_botrightsqbracket
0x23a8: 0x08af, // XK_leftmiddlecurlybrace
0x23ac: 0x08b0, // XK_rightmiddlecurlybrace
0x23b7: 0x08a1, // XK_leftradical
0x23ba: 0x09ef, // XK_horizlinescan1
0x23bb: 0x09f0, // XK_horizlinescan3
0x23bc: 0x09f2, // XK_horizlinescan7
0x23bd: 0x09f3, // XK_horizlinescan9
0x2409: 0x09e2, // XK_ht
0x240a: 0x09e5, // XK_lf
0x240b: 0x09e9, // XK_vt
0x240c: 0x09e3, // XK_ff
0x240d: 0x09e4, // XK_cr
0x2423: 0x0aac, // XK_signifblank
0x2424: 0x09e8, // XK_nl
0x2500: 0x08a3, // XK_horizconnector
0x2502: 0x08a6, // XK_vertconnector
0x250c: 0x08a2, // XK_topleftradical
0x2510: 0x09eb, // XK_uprightcorner
0x2514: 0x09ed, // XK_lowleftcorner
0x2518: 0x09ea, // XK_lowrightcorner
0x251c: 0x09f4, // XK_leftt
0x2524: 0x09f5, // XK_rightt
0x252c: 0x09f7, // XK_topt
0x2534: 0x09f6, // XK_bott
0x253c: 0x09ee, // XK_crossinglines
0x2592: 0x09e1, // XK_checkerboard
0x25aa: 0x0ae7, // XK_enfilledsqbullet
0x25ab: 0x0ae1, // XK_enopensquarebullet
0x25ac: 0x0adb, // XK_filledrectbullet
0x25ad: 0x0ae2, // XK_openrectbullet
0x25ae: 0x0adf, // XK_emfilledrect
0x25af: 0x0acf, // XK_emopenrectangle
0x25b2: 0x0ae8, // XK_filledtribulletup
0x25b3: 0x0ae3, // XK_opentribulletup
0x25b6: 0x0add, // XK_filledrighttribullet
0x25b7: 0x0acd, // XK_rightopentriangle
0x25bc: 0x0ae9, // XK_filledtribulletdown
0x25bd: 0x0ae4, // XK_opentribulletdown
0x25c0: 0x0adc, // XK_filledlefttribullet
0x25c1: 0x0acc, // XK_leftopentriangle
0x25c6: 0x09e0, // XK_soliddiamond
0x25cb: 0x0ace, // XK_emopencircle
0x25cf: 0x0ade, // XK_emfilledcircle
0x25e6: 0x0ae0, // XK_enopencircbullet
0x2606: 0x0ae5, // XK_openstar
0x260e: 0x0af9, // XK_telephone
0x2613: 0x0aca, // XK_signaturemark
0x261c: 0x0aea, // XK_leftpointer
0x261e: 0x0aeb, // XK_rightpointer
0x2640: 0x0af8, // XK_femalesymbol
0x2642: 0x0af7, // XK_malesymbol
0x2663: 0x0aec, // XK_club
0x2665: 0x0aee, // XK_heart
0x2666: 0x0aed, // XK_diamond
0x266d: 0x0af6, // XK_musicalflat
0x266f: 0x0af5, // XK_musicalsharp
0x2713: 0x0af3, // XK_checkmark
0x2717: 0x0af4, // XK_ballotcross
0x271d: 0x0ad9, // XK_latincross
0x2720: 0x0af0, // XK_maltesecross
0x27e8: 0x0abc, // XK_leftanglebracket
0x27e9: 0x0abe, // XK_rightanglebracket
0x3001: 0x04a4, // XK_kana_comma
0x3002: 0x04a1, // XK_kana_fullstop
0x300c: 0x04a2, // XK_kana_openingbracket
0x300d: 0x04a3, // XK_kana_closingbracket
0x309b: 0x04de, // XK_voicedsound
0x309c: 0x04df, // XK_semivoicedsound
0x30a1: 0x04a7, // XK_kana_a
0x30a2: 0x04b1, // XK_kana_A
0x30a3: 0x04a8, // XK_kana_i
0x30a4: 0x04b2, // XK_kana_I
0x30a5: 0x04a9, // XK_kana_u
0x30a6: 0x04b3, // XK_kana_U
0x30a7: 0x04aa, // XK_kana_e
0x30a8: 0x04b4, // XK_kana_E
0x30a9: 0x04ab, // XK_kana_o
0x30aa: 0x04b5, // XK_kana_O
0x30ab: 0x04b6, // XK_kana_KA
0x30ad: 0x04b7, // XK_kana_KI
0x30af: 0x04b8, // XK_kana_KU
0x30b1: 0x04b9, // XK_kana_KE
0x30b3: 0x04ba, // XK_kana_KO
0x30b5: 0x04bb, // XK_kana_SA
0x30b7: 0x04bc, // XK_kana_SHI
0x30b9: 0x04bd, // XK_kana_SU
0x30bb: 0x04be, // XK_kana_SE
0x30bd: 0x04bf, // XK_kana_SO
0x30bf: 0x04c0, // XK_kana_TA
0x30c1: 0x04c1, // XK_kana_CHI
0x30c3: 0x04af, // XK_kana_tsu
0x30c4: 0x04c2, // XK_kana_TSU
0x30c6: 0x04c3, // XK_kana_TE
0x30c8: 0x04c4, // XK_kana_TO
0x30ca: 0x04c5, // XK_kana_NA
0x30cb: 0x04c6, // XK_kana_NI
0x30cc: 0x04c7, // XK_kana_NU
0x30cd: 0x04c8, // XK_kana_NE
0x30ce: 0x04c9, // XK_kana_NO
0x30cf: 0x04ca, // XK_kana_HA
0x30d2: 0x04cb, // XK_kana_HI
0x30d5: 0x04cc, // XK_kana_FU
0x30d8: 0x04cd, // XK_kana_HE
0x30db: 0x04ce, // XK_kana_HO
0x30de: 0x04cf, // XK_kana_MA
0x30df: 0x04d0, // XK_kana_MI
0x30e0: 0x04d1, // XK_kana_MU
0x30e1: 0x04d2, // XK_kana_ME
0x30e2: 0x04d3, // XK_kana_MO
0x30e3: 0x04ac, // XK_kana_ya
0x30e4: 0x04d4, // XK_kana_YA
0x30e5: 0x04ad, // XK_kana_yu
0x30e6: 0x04d5, // XK_kana_YU
0x30e7: 0x04ae, // XK_kana_yo
0x30e8: 0x04d6, // XK_kana_YO
0x30e9: 0x04d7, // XK_kana_RA
0x30ea: 0x04d8, // XK_kana_RI
0x30eb: 0x04d9, // XK_kana_RU
0x30ec: 0x04da, // XK_kana_RE
0x30ed: 0x04db, // XK_kana_RO
0x30ef: 0x04dc, // XK_kana_WA
0x30f2: 0x04a6, // XK_kana_WO
0x30f3: 0x04dd, // XK_kana_N
0x30fb: 0x04a5, // XK_kana_conjunctive
0x30fc: 0x04b0, // XK_prolongedsound
};
export default {
lookup(u) {
// Latin-1 is one-to-one mapping
if ((u >= 0x20) && (u <= 0xff)) {
return u;
}
// Lookup table (fairly random)
const keysym = codepoints[u];
if (keysym !== undefined) {
return keysym;
}
// General mapping as final fallback
return 0x01000000 | u;
},
};

@ -0,0 +1,191 @@
import KeyTable from "./keysym.js";
import keysyms from "./keysymdef.js";
import vkeys from "./vkeys.js";
import fixedkeys from "./fixedkeys.js";
import DOMKeyTable from "./domkeytable.js";
import * as browser from "../util/browser.js";
// Get 'KeyboardEvent.code', handling legacy browsers
export function getKeycode(evt) {
// Are we getting proper key identifiers?
// (unfortunately Firefox and Chrome are crappy here and gives
// us an empty string on some platforms, rather than leaving it
// undefined)
if (evt.code) {
// Mozilla isn't fully in sync with the spec yet
switch (evt.code) {
case 'OSLeft': return 'MetaLeft';
case 'OSRight': return 'MetaRight';
}
return evt.code;
}
// The de-facto standard is to use Windows Virtual-Key codes
// in the 'keyCode' field for non-printable characters
if (evt.keyCode in vkeys) {
let code = vkeys[evt.keyCode];
// macOS has messed up this code for some reason
if (browser.isMac() && (code === 'ContextMenu')) {
code = 'MetaRight';
}
// The keyCode doesn't distinguish between left and right
// for the standard modifiers
if (evt.location === 2) {
switch (code) {
case 'ShiftLeft': return 'ShiftRight';
case 'ControlLeft': return 'ControlRight';
case 'AltLeft': return 'AltRight';
}
}
// Nor a bunch of the numpad keys
if (evt.location === 3) {
switch (code) {
case 'Delete': return 'NumpadDecimal';
case 'Insert': return 'Numpad0';
case 'End': return 'Numpad1';
case 'ArrowDown': return 'Numpad2';
case 'PageDown': return 'Numpad3';
case 'ArrowLeft': return 'Numpad4';
case 'ArrowRight': return 'Numpad6';
case 'Home': return 'Numpad7';
case 'ArrowUp': return 'Numpad8';
case 'PageUp': return 'Numpad9';
case 'Enter': return 'NumpadEnter';
}
}
return code;
}
return 'Unidentified';
}
// Get 'KeyboardEvent.key', handling legacy browsers
export function getKey(evt) {
// Are we getting a proper key value?
if ((evt.key !== undefined) && (evt.key !== 'Unidentified')) {
// Mozilla isn't fully in sync with the spec yet
switch (evt.key) {
case 'OS': return 'Meta';
case 'LaunchMyComputer': return 'LaunchApplication1';
case 'LaunchCalculator': return 'LaunchApplication2';
}
// iOS leaks some OS names
switch (evt.key) {
case 'UIKeyInputUpArrow': return 'ArrowUp';
case 'UIKeyInputDownArrow': return 'ArrowDown';
case 'UIKeyInputLeftArrow': return 'ArrowLeft';
case 'UIKeyInputRightArrow': return 'ArrowRight';
case 'UIKeyInputEscape': return 'Escape';
}
// Broken behaviour in Chrome
if ((evt.key === '\x00') && (evt.code === 'NumpadDecimal')) {
return 'Delete';
}
return evt.key;
}
// Try to deduce it based on the physical key
const code = getKeycode(evt);
if (code in fixedkeys) {
return fixedkeys[code];
}
// If that failed, then see if we have a printable character
if (evt.charCode) {
return String.fromCharCode(evt.charCode);
}
// At this point we have nothing left to go on
return 'Unidentified';
}
// Get the most reliable keysym value we can get from a key event
export function getKeysym(evt) {
const key = getKey(evt);
if (key === 'Unidentified') {
return null;
}
// First look up special keys
if (key in DOMKeyTable) {
let location = evt.location;
// Safari screws up location for the right cmd key
if ((key === 'Meta') && (location === 0)) {
location = 2;
}
// And for Clear
if ((key === 'Clear') && (location === 3)) {
let code = getKeycode(evt);
if (code === 'NumLock') {
location = 0;
}
}
if ((location === undefined) || (location > 3)) {
location = 0;
}
// The original Meta key now gets confused with the Windows key
// https://bugs.chromium.org/p/chromium/issues/detail?id=1020141
// https://bugzilla.mozilla.org/show_bug.cgi?id=1232918
if (key === 'Meta') {
let code = getKeycode(evt);
if (code === 'AltLeft') {
return KeyTable.XK_Meta_L;
} else if (code === 'AltRight') {
return KeyTable.XK_Meta_R;
}
}
// macOS has Clear instead of NumLock, but the remote system is
// probably not macOS, so lying here is probably best...
if (key === 'Clear') {
let code = getKeycode(evt);
if (code === 'NumLock') {
return KeyTable.XK_Num_Lock;
}
}
// Windows sends alternating symbols for some keys when using a
// Japanese layout. We have no way of synchronising with the IM
// running on the remote system, so we send some combined keysym
// instead and hope for the best.
if (browser.isWindows()) {
switch (key) {
case 'Zenkaku':
case 'Hankaku':
return KeyTable.XK_Zenkaku_Hankaku;
case 'Romaji':
case 'KanaMode':
return KeyTable.XK_Romaji;
}
}
return DOMKeyTable[key][location];
}
// Now we need to look at the Unicode symbol instead
// Special key? (FIXME: Should have been caught earlier)
if (key.length !== 1) {
return null;
}
const codepoint = key.charCodeAt();
if (codepoint) {
return keysyms.lookup(codepoint);
}
return null;
}

@ -0,0 +1,116 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2018 The noVNC authors
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
*/
/*
* Mapping between Microsoft® Windows® Virtual-Key codes and
* HTML key codes.
*/
export default {
0x08: 'Backspace',
0x09: 'Tab',
0x0a: 'NumpadClear',
0x0d: 'Enter',
0x10: 'ShiftLeft',
0x11: 'ControlLeft',
0x12: 'AltLeft',
0x13: 'Pause',
0x14: 'CapsLock',
0x15: 'Lang1',
0x19: 'Lang2',
0x1b: 'Escape',
0x1c: 'Convert',
0x1d: 'NonConvert',
0x20: 'Space',
0x21: 'PageUp',
0x22: 'PageDown',
0x23: 'End',
0x24: 'Home',
0x25: 'ArrowLeft',
0x26: 'ArrowUp',
0x27: 'ArrowRight',
0x28: 'ArrowDown',
0x29: 'Select',
0x2c: 'PrintScreen',
0x2d: 'Insert',
0x2e: 'Delete',
0x2f: 'Help',
0x30: 'Digit0',
0x31: 'Digit1',
0x32: 'Digit2',
0x33: 'Digit3',
0x34: 'Digit4',
0x35: 'Digit5',
0x36: 'Digit6',
0x37: 'Digit7',
0x38: 'Digit8',
0x39: 'Digit9',
0x5b: 'MetaLeft',
0x5c: 'MetaRight',
0x5d: 'ContextMenu',
0x5f: 'Sleep',
0x60: 'Numpad0',
0x61: 'Numpad1',
0x62: 'Numpad2',
0x63: 'Numpad3',
0x64: 'Numpad4',
0x65: 'Numpad5',
0x66: 'Numpad6',
0x67: 'Numpad7',
0x68: 'Numpad8',
0x69: 'Numpad9',
0x6a: 'NumpadMultiply',
0x6b: 'NumpadAdd',
0x6c: 'NumpadDecimal',
0x6d: 'NumpadSubtract',
0x6e: 'NumpadDecimal', // Duplicate, because buggy on Windows
0x6f: 'NumpadDivide',
0x70: 'F1',
0x71: 'F2',
0x72: 'F3',
0x73: 'F4',
0x74: 'F5',
0x75: 'F6',
0x76: 'F7',
0x77: 'F8',
0x78: 'F9',
0x79: 'F10',
0x7a: 'F11',
0x7b: 'F12',
0x7c: 'F13',
0x7d: 'F14',
0x7e: 'F15',
0x7f: 'F16',
0x80: 'F17',
0x81: 'F18',
0x82: 'F19',
0x83: 'F20',
0x84: 'F21',
0x85: 'F22',
0x86: 'F23',
0x87: 'F24',
0x90: 'NumLock',
0x91: 'ScrollLock',
0xa6: 'BrowserBack',
0xa7: 'BrowserForward',
0xa8: 'BrowserRefresh',
0xa9: 'BrowserStop',
0xaa: 'BrowserSearch',
0xab: 'BrowserFavorites',
0xac: 'BrowserHome',
0xad: 'AudioVolumeMute',
0xae: 'AudioVolumeDown',
0xaf: 'AudioVolumeUp',
0xb0: 'MediaTrackNext',
0xb1: 'MediaTrackPrevious',
0xb2: 'MediaStop',
0xb3: 'MediaPlayPause',
0xb4: 'LaunchMail',
0xb5: 'MediaSelect',
0xb6: 'LaunchApp1',
0xb7: 'LaunchApp2',
0xe1: 'AltRight', // Only when it is AltGraph
};

@ -0,0 +1,173 @@
/*
* This file is auto-generated from keymaps.csv
* Database checksum sha256(76d68c10e97d37fe2ea459e210125ae41796253fb217e900bf2983ade13a7920)
* To re-generate, run:
* keymap-gen code-map --lang=js keymaps.csv html atset1
*/
export default {
"Again": 0xe005, /* html:Again (Again) -> linux:129 (KEY_AGAIN) -> atset1:57349 */
"AltLeft": 0x38, /* html:AltLeft (AltLeft) -> linux:56 (KEY_LEFTALT) -> atset1:56 */
"AltRight": 0xe038, /* html:AltRight (AltRight) -> linux:100 (KEY_RIGHTALT) -> atset1:57400 */
"ArrowDown": 0xe050, /* html:ArrowDown (ArrowDown) -> linux:108 (KEY_DOWN) -> atset1:57424 */
"ArrowLeft": 0xe04b, /* html:ArrowLeft (ArrowLeft) -> linux:105 (KEY_LEFT) -> atset1:57419 */
"ArrowRight": 0xe04d, /* html:ArrowRight (ArrowRight) -> linux:106 (KEY_RIGHT) -> atset1:57421 */
"ArrowUp": 0xe048, /* html:ArrowUp (ArrowUp) -> linux:103 (KEY_UP) -> atset1:57416 */
"AudioVolumeDown": 0xe02e, /* html:AudioVolumeDown (AudioVolumeDown) -> linux:114 (KEY_VOLUMEDOWN) -> atset1:57390 */
"AudioVolumeMute": 0xe020, /* html:AudioVolumeMute (AudioVolumeMute) -> linux:113 (KEY_MUTE) -> atset1:57376 */
"AudioVolumeUp": 0xe030, /* html:AudioVolumeUp (AudioVolumeUp) -> linux:115 (KEY_VOLUMEUP) -> atset1:57392 */
"Backquote": 0x29, /* html:Backquote (Backquote) -> linux:41 (KEY_GRAVE) -> atset1:41 */
"Backslash": 0x2b, /* html:Backslash (Backslash) -> linux:43 (KEY_BACKSLASH) -> atset1:43 */
"Backspace": 0xe, /* html:Backspace (Backspace) -> linux:14 (KEY_BACKSPACE) -> atset1:14 */
"BracketLeft": 0x1a, /* html:BracketLeft (BracketLeft) -> linux:26 (KEY_LEFTBRACE) -> atset1:26 */
"BracketRight": 0x1b, /* html:BracketRight (BracketRight) -> linux:27 (KEY_RIGHTBRACE) -> atset1:27 */
"BrowserBack": 0xe06a, /* html:BrowserBack (BrowserBack) -> linux:158 (KEY_BACK) -> atset1:57450 */
"BrowserFavorites": 0xe066, /* html:BrowserFavorites (BrowserFavorites) -> linux:156 (KEY_BOOKMARKS) -> atset1:57446 */
"BrowserForward": 0xe069, /* html:BrowserForward (BrowserForward) -> linux:159 (KEY_FORWARD) -> atset1:57449 */
"BrowserHome": 0xe032, /* html:BrowserHome (BrowserHome) -> linux:172 (KEY_HOMEPAGE) -> atset1:57394 */
"BrowserRefresh": 0xe067, /* html:BrowserRefresh (BrowserRefresh) -> linux:173 (KEY_REFRESH) -> atset1:57447 */
"BrowserSearch": 0xe065, /* html:BrowserSearch (BrowserSearch) -> linux:217 (KEY_SEARCH) -> atset1:57445 */
"BrowserStop": 0xe068, /* html:BrowserStop (BrowserStop) -> linux:128 (KEY_STOP) -> atset1:57448 */
"CapsLock": 0x3a, /* html:CapsLock (CapsLock) -> linux:58 (KEY_CAPSLOCK) -> atset1:58 */
"Comma": 0x33, /* html:Comma (Comma) -> linux:51 (KEY_COMMA) -> atset1:51 */
"ContextMenu": 0xe05d, /* html:ContextMenu (ContextMenu) -> linux:127 (KEY_COMPOSE) -> atset1:57437 */
"ControlLeft": 0x1d, /* html:ControlLeft (ControlLeft) -> linux:29 (KEY_LEFTCTRL) -> atset1:29 */
"ControlRight": 0xe01d, /* html:ControlRight (ControlRight) -> linux:97 (KEY_RIGHTCTRL) -> atset1:57373 */
"Convert": 0x79, /* html:Convert (Convert) -> linux:92 (KEY_HENKAN) -> atset1:121 */
"Copy": 0xe078, /* html:Copy (Copy) -> linux:133 (KEY_COPY) -> atset1:57464 */
"Cut": 0xe03c, /* html:Cut (Cut) -> linux:137 (KEY_CUT) -> atset1:57404 */
"Delete": 0xe053, /* html:Delete (Delete) -> linux:111 (KEY_DELETE) -> atset1:57427 */
"Digit0": 0xb, /* html:Digit0 (Digit0) -> linux:11 (KEY_0) -> atset1:11 */
"Digit1": 0x2, /* html:Digit1 (Digit1) -> linux:2 (KEY_1) -> atset1:2 */
"Digit2": 0x3, /* html:Digit2 (Digit2) -> linux:3 (KEY_2) -> atset1:3 */
"Digit3": 0x4, /* html:Digit3 (Digit3) -> linux:4 (KEY_3) -> atset1:4 */
"Digit4": 0x5, /* html:Digit4 (Digit4) -> linux:5 (KEY_4) -> atset1:5 */
"Digit5": 0x6, /* html:Digit5 (Digit5) -> linux:6 (KEY_5) -> atset1:6 */
"Digit6": 0x7, /* html:Digit6 (Digit6) -> linux:7 (KEY_6) -> atset1:7 */
"Digit7": 0x8, /* html:Digit7 (Digit7) -> linux:8 (KEY_7) -> atset1:8 */
"Digit8": 0x9, /* html:Digit8 (Digit8) -> linux:9 (KEY_8) -> atset1:9 */
"Digit9": 0xa, /* html:Digit9 (Digit9) -> linux:10 (KEY_9) -> atset1:10 */
"Eject": 0xe07d, /* html:Eject (Eject) -> linux:162 (KEY_EJECTCLOSECD) -> atset1:57469 */
"End": 0xe04f, /* html:End (End) -> linux:107 (KEY_END) -> atset1:57423 */
"Enter": 0x1c, /* html:Enter (Enter) -> linux:28 (KEY_ENTER) -> atset1:28 */
"Equal": 0xd, /* html:Equal (Equal) -> linux:13 (KEY_EQUAL) -> atset1:13 */
"Escape": 0x1, /* html:Escape (Escape) -> linux:1 (KEY_ESC) -> atset1:1 */
"F1": 0x3b, /* html:F1 (F1) -> linux:59 (KEY_F1) -> atset1:59 */
"F10": 0x44, /* html:F10 (F10) -> linux:68 (KEY_F10) -> atset1:68 */
"F11": 0x57, /* html:F11 (F11) -> linux:87 (KEY_F11) -> atset1:87 */
"F12": 0x58, /* html:F12 (F12) -> linux:88 (KEY_F12) -> atset1:88 */
"F13": 0x5d, /* html:F13 (F13) -> linux:183 (KEY_F13) -> atset1:93 */
"F14": 0x5e, /* html:F14 (F14) -> linux:184 (KEY_F14) -> atset1:94 */
"F15": 0x5f, /* html:F15 (F15) -> linux:185 (KEY_F15) -> atset1:95 */
"F16": 0x55, /* html:F16 (F16) -> linux:186 (KEY_F16) -> atset1:85 */
"F17": 0xe003, /* html:F17 (F17) -> linux:187 (KEY_F17) -> atset1:57347 */
"F18": 0xe077, /* html:F18 (F18) -> linux:188 (KEY_F18) -> atset1:57463 */
"F19": 0xe004, /* html:F19 (F19) -> linux:189 (KEY_F19) -> atset1:57348 */
"F2": 0x3c, /* html:F2 (F2) -> linux:60 (KEY_F2) -> atset1:60 */
"F20": 0x5a, /* html:F20 (F20) -> linux:190 (KEY_F20) -> atset1:90 */
"F21": 0x74, /* html:F21 (F21) -> linux:191 (KEY_F21) -> atset1:116 */
"F22": 0xe079, /* html:F22 (F22) -> linux:192 (KEY_F22) -> atset1:57465 */
"F23": 0x6d, /* html:F23 (F23) -> linux:193 (KEY_F23) -> atset1:109 */
"F24": 0x6f, /* html:F24 (F24) -> linux:194 (KEY_F24) -> atset1:111 */
"F3": 0x3d, /* html:F3 (F3) -> linux:61 (KEY_F3) -> atset1:61 */
"F4": 0x3e, /* html:F4 (F4) -> linux:62 (KEY_F4) -> atset1:62 */
"F5": 0x3f, /* html:F5 (F5) -> linux:63 (KEY_F5) -> atset1:63 */
"F6": 0x40, /* html:F6 (F6) -> linux:64 (KEY_F6) -> atset1:64 */
"F7": 0x41, /* html:F7 (F7) -> linux:65 (KEY_F7) -> atset1:65 */
"F8": 0x42, /* html:F8 (F8) -> linux:66 (KEY_F8) -> atset1:66 */
"F9": 0x43, /* html:F9 (F9) -> linux:67 (KEY_F9) -> atset1:67 */
"Find": 0xe041, /* html:Find (Find) -> linux:136 (KEY_FIND) -> atset1:57409 */
"Help": 0xe075, /* html:Help (Help) -> linux:138 (KEY_HELP) -> atset1:57461 */
"Hiragana": 0x77, /* html:Hiragana (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */
"Home": 0xe047, /* html:Home (Home) -> linux:102 (KEY_HOME) -> atset1:57415 */
"Insert": 0xe052, /* html:Insert (Insert) -> linux:110 (KEY_INSERT) -> atset1:57426 */
"IntlBackslash": 0x56, /* html:IntlBackslash (IntlBackslash) -> linux:86 (KEY_102ND) -> atset1:86 */
"IntlRo": 0x73, /* html:IntlRo (IntlRo) -> linux:89 (KEY_RO) -> atset1:115 */
"IntlYen": 0x7d, /* html:IntlYen (IntlYen) -> linux:124 (KEY_YEN) -> atset1:125 */
"KanaMode": 0x70, /* html:KanaMode (KanaMode) -> linux:93 (KEY_KATAKANAHIRAGANA) -> atset1:112 */
"Katakana": 0x78, /* html:Katakana (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */
"KeyA": 0x1e, /* html:KeyA (KeyA) -> linux:30 (KEY_A) -> atset1:30 */
"KeyB": 0x30, /* html:KeyB (KeyB) -> linux:48 (KEY_B) -> atset1:48 */
"KeyC": 0x2e, /* html:KeyC (KeyC) -> linux:46 (KEY_C) -> atset1:46 */
"KeyD": 0x20, /* html:KeyD (KeyD) -> linux:32 (KEY_D) -> atset1:32 */
"KeyE": 0x12, /* html:KeyE (KeyE) -> linux:18 (KEY_E) -> atset1:18 */
"KeyF": 0x21, /* html:KeyF (KeyF) -> linux:33 (KEY_F) -> atset1:33 */
"KeyG": 0x22, /* html:KeyG (KeyG) -> linux:34 (KEY_G) -> atset1:34 */
"KeyH": 0x23, /* html:KeyH (KeyH) -> linux:35 (KEY_H) -> atset1:35 */
"KeyI": 0x17, /* html:KeyI (KeyI) -> linux:23 (KEY_I) -> atset1:23 */
"KeyJ": 0x24, /* html:KeyJ (KeyJ) -> linux:36 (KEY_J) -> atset1:36 */
"KeyK": 0x25, /* html:KeyK (KeyK) -> linux:37 (KEY_K) -> atset1:37 */
"KeyL": 0x26, /* html:KeyL (KeyL) -> linux:38 (KEY_L) -> atset1:38 */
"KeyM": 0x32, /* html:KeyM (KeyM) -> linux:50 (KEY_M) -> atset1:50 */
"KeyN": 0x31, /* html:KeyN (KeyN) -> linux:49 (KEY_N) -> atset1:49 */
"KeyO": 0x18, /* html:KeyO (KeyO) -> linux:24 (KEY_O) -> atset1:24 */
"KeyP": 0x19, /* html:KeyP (KeyP) -> linux:25 (KEY_P) -> atset1:25 */
"KeyQ": 0x10, /* html:KeyQ (KeyQ) -> linux:16 (KEY_Q) -> atset1:16 */
"KeyR": 0x13, /* html:KeyR (KeyR) -> linux:19 (KEY_R) -> atset1:19 */
"KeyS": 0x1f, /* html:KeyS (KeyS) -> linux:31 (KEY_S) -> atset1:31 */
"KeyT": 0x14, /* html:KeyT (KeyT) -> linux:20 (KEY_T) -> atset1:20 */
"KeyU": 0x16, /* html:KeyU (KeyU) -> linux:22 (KEY_U) -> atset1:22 */
"KeyV": 0x2f, /* html:KeyV (KeyV) -> linux:47 (KEY_V) -> atset1:47 */
"KeyW": 0x11, /* html:KeyW (KeyW) -> linux:17 (KEY_W) -> atset1:17 */
"KeyX": 0x2d, /* html:KeyX (KeyX) -> linux:45 (KEY_X) -> atset1:45 */
"KeyY": 0x15, /* html:KeyY (KeyY) -> linux:21 (KEY_Y) -> atset1:21 */
"KeyZ": 0x2c, /* html:KeyZ (KeyZ) -> linux:44 (KEY_Z) -> atset1:44 */
"Lang1": 0x72, /* html:Lang1 (Lang1) -> linux:122 (KEY_HANGEUL) -> atset1:114 */
"Lang2": 0x71, /* html:Lang2 (Lang2) -> linux:123 (KEY_HANJA) -> atset1:113 */
"Lang3": 0x78, /* html:Lang3 (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */
"Lang4": 0x77, /* html:Lang4 (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */
"Lang5": 0x76, /* html:Lang5 (Lang5) -> linux:85 (KEY_ZENKAKUHANKAKU) -> atset1:118 */
"LaunchApp1": 0xe06b, /* html:LaunchApp1 (LaunchApp1) -> linux:157 (KEY_COMPUTER) -> atset1:57451 */
"LaunchApp2": 0xe021, /* html:LaunchApp2 (LaunchApp2) -> linux:140 (KEY_CALC) -> atset1:57377 */
"LaunchMail": 0xe06c, /* html:LaunchMail (LaunchMail) -> linux:155 (KEY_MAIL) -> atset1:57452 */
"MediaPlayPause": 0xe022, /* html:MediaPlayPause (MediaPlayPause) -> linux:164 (KEY_PLAYPAUSE) -> atset1:57378 */
"MediaSelect": 0xe06d, /* html:MediaSelect (MediaSelect) -> linux:226 (KEY_MEDIA) -> atset1:57453 */
"MediaStop": 0xe024, /* html:MediaStop (MediaStop) -> linux:166 (KEY_STOPCD) -> atset1:57380 */
"MediaTrackNext": 0xe019, /* html:MediaTrackNext (MediaTrackNext) -> linux:163 (KEY_NEXTSONG) -> atset1:57369 */
"MediaTrackPrevious": 0xe010, /* html:MediaTrackPrevious (MediaTrackPrevious) -> linux:165 (KEY_PREVIOUSSONG) -> atset1:57360 */
"MetaLeft": 0xe05b, /* html:MetaLeft (MetaLeft) -> linux:125 (KEY_LEFTMETA) -> atset1:57435 */
"MetaRight": 0xe05c, /* html:MetaRight (MetaRight) -> linux:126 (KEY_RIGHTMETA) -> atset1:57436 */
"Minus": 0xc, /* html:Minus (Minus) -> linux:12 (KEY_MINUS) -> atset1:12 */
"NonConvert": 0x7b, /* html:NonConvert (NonConvert) -> linux:94 (KEY_MUHENKAN) -> atset1:123 */
"NumLock": 0x45, /* html:NumLock (NumLock) -> linux:69 (KEY_NUMLOCK) -> atset1:69 */
"Numpad0": 0x52, /* html:Numpad0 (Numpad0) -> linux:82 (KEY_KP0) -> atset1:82 */
"Numpad1": 0x4f, /* html:Numpad1 (Numpad1) -> linux:79 (KEY_KP1) -> atset1:79 */
"Numpad2": 0x50, /* html:Numpad2 (Numpad2) -> linux:80 (KEY_KP2) -> atset1:80 */
"Numpad3": 0x51, /* html:Numpad3 (Numpad3) -> linux:81 (KEY_KP3) -> atset1:81 */
"Numpad4": 0x4b, /* html:Numpad4 (Numpad4) -> linux:75 (KEY_KP4) -> atset1:75 */
"Numpad5": 0x4c, /* html:Numpad5 (Numpad5) -> linux:76 (KEY_KP5) -> atset1:76 */
"Numpad6": 0x4d, /* html:Numpad6 (Numpad6) -> linux:77 (KEY_KP6) -> atset1:77 */
"Numpad7": 0x47, /* html:Numpad7 (Numpad7) -> linux:71 (KEY_KP7) -> atset1:71 */
"Numpad8": 0x48, /* html:Numpad8 (Numpad8) -> linux:72 (KEY_KP8) -> atset1:72 */
"Numpad9": 0x49, /* html:Numpad9 (Numpad9) -> linux:73 (KEY_KP9) -> atset1:73 */
"NumpadAdd": 0x4e, /* html:NumpadAdd (NumpadAdd) -> linux:78 (KEY_KPPLUS) -> atset1:78 */
"NumpadComma": 0x7e, /* html:NumpadComma (NumpadComma) -> linux:121 (KEY_KPCOMMA) -> atset1:126 */
"NumpadDecimal": 0x53, /* html:NumpadDecimal (NumpadDecimal) -> linux:83 (KEY_KPDOT) -> atset1:83 */
"NumpadDivide": 0xe035, /* html:NumpadDivide (NumpadDivide) -> linux:98 (KEY_KPSLASH) -> atset1:57397 */
"NumpadEnter": 0xe01c, /* html:NumpadEnter (NumpadEnter) -> linux:96 (KEY_KPENTER) -> atset1:57372 */
"NumpadEqual": 0x59, /* html:NumpadEqual (NumpadEqual) -> linux:117 (KEY_KPEQUAL) -> atset1:89 */
"NumpadMultiply": 0x37, /* html:NumpadMultiply (NumpadMultiply) -> linux:55 (KEY_KPASTERISK) -> atset1:55 */
"NumpadParenLeft": 0xe076, /* html:NumpadParenLeft (NumpadParenLeft) -> linux:179 (KEY_KPLEFTPAREN) -> atset1:57462 */
"NumpadParenRight": 0xe07b, /* html:NumpadParenRight (NumpadParenRight) -> linux:180 (KEY_KPRIGHTPAREN) -> atset1:57467 */
"NumpadSubtract": 0x4a, /* html:NumpadSubtract (NumpadSubtract) -> linux:74 (KEY_KPMINUS) -> atset1:74 */
"Open": 0x64, /* html:Open (Open) -> linux:134 (KEY_OPEN) -> atset1:100 */
"PageDown": 0xe051, /* html:PageDown (PageDown) -> linux:109 (KEY_PAGEDOWN) -> atset1:57425 */
"PageUp": 0xe049, /* html:PageUp (PageUp) -> linux:104 (KEY_PAGEUP) -> atset1:57417 */
"Paste": 0x65, /* html:Paste (Paste) -> linux:135 (KEY_PASTE) -> atset1:101 */
"Pause": 0xe046, /* html:Pause (Pause) -> linux:119 (KEY_PAUSE) -> atset1:57414 */
"Period": 0x34, /* html:Period (Period) -> linux:52 (KEY_DOT) -> atset1:52 */
"Power": 0xe05e, /* html:Power (Power) -> linux:116 (KEY_POWER) -> atset1:57438 */
"PrintScreen": 0x54, /* html:PrintScreen (PrintScreen) -> linux:99 (KEY_SYSRQ) -> atset1:84 */
"Props": 0xe006, /* html:Props (Props) -> linux:130 (KEY_PROPS) -> atset1:57350 */
"Quote": 0x28, /* html:Quote (Quote) -> linux:40 (KEY_APOSTROPHE) -> atset1:40 */
"ScrollLock": 0x46, /* html:ScrollLock (ScrollLock) -> linux:70 (KEY_SCROLLLOCK) -> atset1:70 */
"Semicolon": 0x27, /* html:Semicolon (Semicolon) -> linux:39 (KEY_SEMICOLON) -> atset1:39 */
"ShiftLeft": 0x2a, /* html:ShiftLeft (ShiftLeft) -> linux:42 (KEY_LEFTSHIFT) -> atset1:42 */
"ShiftRight": 0x36, /* html:ShiftRight (ShiftRight) -> linux:54 (KEY_RIGHTSHIFT) -> atset1:54 */
"Slash": 0x35, /* html:Slash (Slash) -> linux:53 (KEY_SLASH) -> atset1:53 */
"Sleep": 0xe05f, /* html:Sleep (Sleep) -> linux:142 (KEY_SLEEP) -> atset1:57439 */
"Space": 0x39, /* html:Space (Space) -> linux:57 (KEY_SPACE) -> atset1:57 */
"Suspend": 0xe025, /* html:Suspend (Suspend) -> linux:205 (KEY_SUSPEND) -> atset1:57381 */
"Tab": 0xf, /* html:Tab (Tab) -> linux:15 (KEY_TAB) -> atset1:15 */
"Undo": 0xe007, /* html:Undo (Undo) -> linux:131 (KEY_UNDO) -> atset1:57351 */
"WakeUp": 0xe063, /* html:WakeUp (WakeUp) -> linux:143 (KEY_WAKEUP) -> atset1:57443 */
};

@ -0,0 +1,312 @@
import { encodeUTF8 } from './util/strings.js';
import EventTargetMixin from './util/eventtarget.js';
import legacyCrypto from './crypto/crypto.js';
class RA2Cipher {
constructor() {
this._cipher = null;
this._counter = new Uint8Array(16);
}
async setKey(key) {
this._cipher = await legacyCrypto.importKey(
"raw", key, { name: "AES-EAX" }, false, ["encrypt, decrypt"]);
}
async makeMessage(message) {
const ad = new Uint8Array([(message.length & 0xff00) >>> 8, message.length & 0xff]);
const encrypted = await legacyCrypto.encrypt({
name: "AES-EAX",
iv: this._counter,
additionalData: ad,
}, this._cipher, message);
for (let i = 0; i < 16 && this._counter[i]++ === 255; i++);
const res = new Uint8Array(message.length + 2 + 16);
res.set(ad);
res.set(encrypted, 2);
return res;
}
async receiveMessage(length, encrypted) {
const ad = new Uint8Array([(length & 0xff00) >>> 8, length & 0xff]);
const res = await legacyCrypto.decrypt({
name: "AES-EAX",
iv: this._counter,
additionalData: ad,
}, this._cipher, encrypted);
for (let i = 0; i < 16 && this._counter[i]++ === 255; i++);
return res;
}
}
export default class RSAAESAuthenticationState extends EventTargetMixin {
constructor(sock, getCredentials) {
super();
this._hasStarted = false;
this._checkSock = null;
this._checkCredentials = null;
this._approveServerResolve = null;
this._sockReject = null;
this._credentialsReject = null;
this._approveServerReject = null;
this._sock = sock;
this._getCredentials = getCredentials;
}
_waitSockAsync(len) {
return new Promise((resolve, reject) => {
const hasData = () => !this._sock.rQwait('RA2', len);
if (hasData()) {
resolve();
} else {
this._checkSock = () => {
if (hasData()) {
resolve();
this._checkSock = null;
this._sockReject = null;
}
};
this._sockReject = reject;
}
});
}
_waitApproveKeyAsync() {
return new Promise((resolve, reject) => {
this._approveServerResolve = resolve;
this._approveServerReject = reject;
});
}
_waitCredentialsAsync(subtype) {
const hasCredentials = () => {
if (subtype === 1 && this._getCredentials().username !== undefined &&
this._getCredentials().password !== undefined) {
return true;
} else if (subtype === 2 && this._getCredentials().password !== undefined) {
return true;
}
return false;
};
return new Promise((resolve, reject) => {
if (hasCredentials()) {
resolve();
} else {
this._checkCredentials = () => {
if (hasCredentials()) {
resolve();
this._checkCredentials = null;
this._credentialsReject = null;
}
};
this._credentialsReject = reject;
}
});
}
checkInternalEvents() {
if (this._checkSock !== null) {
this._checkSock();
}
if (this._checkCredentials !== null) {
this._checkCredentials();
}
}
approveServer() {
if (this._approveServerResolve !== null) {
this._approveServerResolve();
this._approveServerResolve = null;
}
}
disconnect() {
if (this._sockReject !== null) {
this._sockReject(new Error("disconnect normally"));
this._sockReject = null;
}
if (this._credentialsReject !== null) {
this._credentialsReject(new Error("disconnect normally"));
this._credentialsReject = null;
}
if (this._approveServerReject !== null) {
this._approveServerReject(new Error("disconnect normally"));
this._approveServerReject = null;
}
}
async negotiateRA2neAuthAsync() {
this._hasStarted = true;
// 1: Receive server public key
await this._waitSockAsync(4);
const serverKeyLengthBuffer = this._sock.rQpeekBytes(4);
const serverKeyLength = this._sock.rQshift32();
if (serverKeyLength < 1024) {
throw new Error("RA2: server public key is too short: " + serverKeyLength);
} else if (serverKeyLength > 8192) {
throw new Error("RA2: server public key is too long: " + serverKeyLength);
}
const serverKeyBytes = Math.ceil(serverKeyLength / 8);
await this._waitSockAsync(serverKeyBytes * 2);
const serverN = this._sock.rQshiftBytes(serverKeyBytes);
const serverE = this._sock.rQshiftBytes(serverKeyBytes);
const serverRSACipher = await legacyCrypto.importKey(
"raw", { n: serverN, e: serverE }, { name: "RSA-PKCS1-v1_5" }, false, ["encrypt"]);
const serverPublickey = new Uint8Array(4 + serverKeyBytes * 2);
serverPublickey.set(serverKeyLengthBuffer);
serverPublickey.set(serverN, 4);
serverPublickey.set(serverE, 4 + serverKeyBytes);
// verify server public key
let approveKey = this._waitApproveKeyAsync();
this.dispatchEvent(new CustomEvent("serververification", {
detail: { type: "RSA", publickey: serverPublickey }
}));
await approveKey;
// 2: Send client public key
const clientKeyLength = 2048;
const clientKeyBytes = Math.ceil(clientKeyLength / 8);
const clientRSACipher = (await legacyCrypto.generateKey({
name: "RSA-PKCS1-v1_5",
modulusLength: clientKeyLength,
publicExponent: new Uint8Array([1, 0, 1]),
}, true, ["encrypt"])).privateKey;
const clientExportedRSAKey = await legacyCrypto.exportKey("raw", clientRSACipher);
const clientN = clientExportedRSAKey.n;
const clientE = clientExportedRSAKey.e;
const clientPublicKey = new Uint8Array(4 + clientKeyBytes * 2);
clientPublicKey[0] = (clientKeyLength & 0xff000000) >>> 24;
clientPublicKey[1] = (clientKeyLength & 0xff0000) >>> 16;
clientPublicKey[2] = (clientKeyLength & 0xff00) >>> 8;
clientPublicKey[3] = clientKeyLength & 0xff;
clientPublicKey.set(clientN, 4);
clientPublicKey.set(clientE, 4 + clientKeyBytes);
this._sock.sQpushBytes(clientPublicKey);
this._sock.flush();
// 3: Send client random
const clientRandom = new Uint8Array(16);
window.crypto.getRandomValues(clientRandom);
const clientEncryptedRandom = await legacyCrypto.encrypt(
{ name: "RSA-PKCS1-v1_5" }, serverRSACipher, clientRandom);
const clientRandomMessage = new Uint8Array(2 + serverKeyBytes);
clientRandomMessage[0] = (serverKeyBytes & 0xff00) >>> 8;
clientRandomMessage[1] = serverKeyBytes & 0xff;
clientRandomMessage.set(clientEncryptedRandom, 2);
this._sock.sQpushBytes(clientRandomMessage);
this._sock.flush();
// 4: Receive server random
await this._waitSockAsync(2);
if (this._sock.rQshift16() !== clientKeyBytes) {
throw new Error("RA2: wrong encrypted message length");
}
const serverEncryptedRandom = this._sock.rQshiftBytes(clientKeyBytes);
const serverRandom = await legacyCrypto.decrypt(
{ name: "RSA-PKCS1-v1_5" }, clientRSACipher, serverEncryptedRandom);
if (serverRandom === null || serverRandom.length !== 16) {
throw new Error("RA2: corrupted server encrypted random");
}
// 5: Compute session keys and set ciphers
let clientSessionKey = new Uint8Array(32);
let serverSessionKey = new Uint8Array(32);
clientSessionKey.set(serverRandom);
clientSessionKey.set(clientRandom, 16);
serverSessionKey.set(clientRandom);
serverSessionKey.set(serverRandom, 16);
clientSessionKey = await window.crypto.subtle.digest("SHA-1", clientSessionKey);
clientSessionKey = new Uint8Array(clientSessionKey).slice(0, 16);
serverSessionKey = await window.crypto.subtle.digest("SHA-1", serverSessionKey);
serverSessionKey = new Uint8Array(serverSessionKey).slice(0, 16);
const clientCipher = new RA2Cipher();
await clientCipher.setKey(clientSessionKey);
const serverCipher = new RA2Cipher();
await serverCipher.setKey(serverSessionKey);
// 6: Compute and exchange hashes
let serverHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2);
let clientHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2);
serverHash.set(serverPublickey);
serverHash.set(clientPublicKey, 4 + serverKeyBytes * 2);
clientHash.set(clientPublicKey);
clientHash.set(serverPublickey, 4 + clientKeyBytes * 2);
serverHash = await window.crypto.subtle.digest("SHA-1", serverHash);
clientHash = await window.crypto.subtle.digest("SHA-1", clientHash);
serverHash = new Uint8Array(serverHash);
clientHash = new Uint8Array(clientHash);
this._sock.sQpushBytes(await clientCipher.makeMessage(clientHash));
this._sock.flush();
await this._waitSockAsync(2 + 20 + 16);
if (this._sock.rQshift16() !== 20) {
throw new Error("RA2: wrong server hash");
}
const serverHashReceived = await serverCipher.receiveMessage(
20, this._sock.rQshiftBytes(20 + 16));
if (serverHashReceived === null) {
throw new Error("RA2: failed to authenticate the message");
}
for (let i = 0; i < 20; i++) {
if (serverHashReceived[i] !== serverHash[i]) {
throw new Error("RA2: wrong server hash");
}
}
// 7: Receive subtype
await this._waitSockAsync(2 + 1 + 16);
if (this._sock.rQshift16() !== 1) {
throw new Error("RA2: wrong subtype");
}
let subtype = (await serverCipher.receiveMessage(
1, this._sock.rQshiftBytes(1 + 16)));
if (subtype === null) {
throw new Error("RA2: failed to authenticate the message");
}
subtype = subtype[0];
let waitCredentials = this._waitCredentialsAsync(subtype);
if (subtype === 1) {
if (this._getCredentials().username === undefined ||
this._getCredentials().password === undefined) {
this.dispatchEvent(new CustomEvent(
"credentialsrequired",
{ detail: { types: ["username", "password"] } }));
}
} else if (subtype === 2) {
if (this._getCredentials().password === undefined) {
this.dispatchEvent(new CustomEvent(
"credentialsrequired",
{ detail: { types: ["password"] } }));
}
} else {
throw new Error("RA2: wrong subtype");
}
await waitCredentials;
let username;
if (subtype === 1) {
username = encodeUTF8(this._getCredentials().username).slice(0, 255);
} else {
username = "";
}
const password = encodeUTF8(this._getCredentials().password).slice(0, 255);
const credentials = new Uint8Array(username.length + password.length + 2);
credentials[0] = username.length;
credentials[username.length + 1] = password.length;
for (let i = 0; i < username.length; i++) {
credentials[i + 1] = username.charCodeAt(i);
}
for (let i = 0; i < password.length; i++) {
credentials[username.length + 2 + i] = password.charCodeAt(i);
}
this._sock.sQpushBytes(await clientCipher.makeMessage(credentials));
this._sock.flush();
}
get hasStarted() {
return this._hasStarted;
}
set hasStarted(s) {
this._hasStarted = s;
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,233 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*
* Browser feature support detection
*/
import * as Log from './logging.js';
import Base64 from '../base64.js';
// Touch detection
export let isTouchDevice = ('ontouchstart' in document.documentElement) ||
// required for Chrome debugger
(document.ontouchstart !== undefined) ||
// required for MS Surface
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0);
window.addEventListener('touchstart', function onFirstTouch() {
isTouchDevice = true;
window.removeEventListener('touchstart', onFirstTouch, false);
}, false);
// The goal is to find a certain physical width, the devicePixelRatio
// brings us a bit closer but is not optimal.
export let dragThreshold = 10 * (window.devicePixelRatio || 1);
let _supportsCursorURIs = false;
try {
const target = document.createElement('canvas');
target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default';
if (target.style.cursor.indexOf("url") === 0) {
Log.Info("Data URI scheme cursor supported");
_supportsCursorURIs = true;
} else {
Log.Warn("Data URI scheme cursor not supported");
}
} catch (exc) {
Log.Error("Data URI scheme cursor test exception: " + exc);
}
export const supportsCursorURIs = _supportsCursorURIs;
let _hasScrollbarGutter = true;
try {
// Create invisible container
const container = document.createElement('div');
container.style.visibility = 'hidden';
container.style.overflow = 'scroll'; // forcing scrollbars
document.body.appendChild(container);
// Create a div and place it in the container
const child = document.createElement('div');
container.appendChild(child);
// Calculate the difference between the container's full width
// and the child's width - the difference is the scrollbars
const scrollbarWidth = (container.offsetWidth - child.offsetWidth);
// Clean up
container.parentNode.removeChild(container);
_hasScrollbarGutter = scrollbarWidth != 0;
} catch (exc) {
Log.Error("Scrollbar test exception: " + exc);
}
export const hasScrollbarGutter = _hasScrollbarGutter;
export let supportsWebCodecsH264Decode = false;
async function _checkWebCodecsH264DecodeSupport() {
if (!('VideoDecoder' in window)) {
return false;
}
// We'll need to make do with some placeholders here
const config = {
codec: 'avc1.42401f',
codedWidth: 1920,
codedHeight: 1080,
optimizeForLatency: true,
};
let support = await VideoDecoder.isConfigSupported(config);
if (!support.supported) {
return false;
}
// Firefox incorrectly reports supports for H.264 under some
// circumstances, so we need to actually test a real frame
// https://bugzilla.mozilla.org/show_bug.cgi?id=1932392
const data = new Uint8Array(Base64.decode(
'AAAAAWdCwBTZnpuAgICgAAADACAAAAZB4oVNAAAAAWjJYyyAAAABBgX//4Hc' +
'Rem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY0IHIzMTA4IDMxZTE5Zjkg' +
'LSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDIz' +
'IC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9u' +
'czogY2FiYWM9MCByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgxOjB4' +
'MTExIG1lPWhleCBzdWJtZT04IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4' +
'ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0yIDh4' +
'OGRjdD0wIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJv' +
'bWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MSBsb29rYWhlYWRfdGhyZWFkcz0x' +
'IHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9' +
'MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVz' +
'PTAgd2VpZ2h0cD0wIGtleWludD1pbmZpbml0ZSBrZXlpbnRfbWluPTI1IHNj' +
'ZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NTAgcmM9' +
'YWJyIG1idHJlZT0xIGJpdHJhdGU9NDAwIHJhdGV0b2w9MS4wIHFjb21wPTAu' +
'NjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFx' +
'PTE6MS4wMACAAAABZYiEBrxmKAAPVccAAS044AA5DRJMnkycJk4TPw=='));
let gotframe = false;
let error = null;
let decoder = new VideoDecoder({
output: (frame) => { gotframe = true; frame.close(); },
error: (e) => { error = e; },
});
let chunk = new EncodedVideoChunk({
timestamp: 0,
type: 'key',
data: data,
});
decoder.configure(config);
decoder.decode(chunk);
try {
await decoder.flush();
} catch (e) {
// Firefox incorrectly throws an exception here
// https://bugzilla.mozilla.org/show_bug.cgi?id=1932566
error = e;
}
// Firefox fails to deliver the error on Windows, so we need to
// check if we got a frame instead
// https://bugzilla.mozilla.org/show_bug.cgi?id=1932579
if (!gotframe) {
return false;
}
if (error !== null) {
return false;
}
return true;
}
supportsWebCodecsH264Decode = await _checkWebCodecsH264DecodeSupport();
/*
* The functions for detection of platforms and browsers below are exported
* but the use of these should be minimized as much as possible.
*
* It's better to use feature detection than platform detection.
*/
/* OS */
export function isMac() {
return !!(/mac/i).exec(navigator.platform);
}
export function isWindows() {
return !!(/win/i).exec(navigator.platform);
}
export function isIOS() {
return (!!(/ipad/i).exec(navigator.platform) ||
!!(/iphone/i).exec(navigator.platform) ||
!!(/ipod/i).exec(navigator.platform));
}
export function isAndroid() {
/* Android sets navigator.platform to Linux :/ */
return !!navigator.userAgent.match('Android ');
}
export function isChromeOS() {
/* ChromeOS sets navigator.platform to Linux :/ */
return !!navigator.userAgent.match(' CrOS ');
}
/* Browser */
export function isSafari() {
return !!navigator.userAgent.match('Safari/...') &&
!navigator.userAgent.match('Chrome/...') &&
!navigator.userAgent.match('Chromium/...') &&
!navigator.userAgent.match('Epiphany/...');
}
export function isFirefox() {
return !!navigator.userAgent.match('Firefox/...') &&
!navigator.userAgent.match('Seamonkey/...');
}
export function isChrome() {
return !!navigator.userAgent.match('Chrome/...') &&
!navigator.userAgent.match('Chromium/...') &&
!navigator.userAgent.match('Edg/...') &&
!navigator.userAgent.match('OPR/...');
}
export function isChromium() {
return !!navigator.userAgent.match('Chromium/...');
}
export function isOpera() {
return !!navigator.userAgent.match('OPR/...');
}
export function isEdge() {
return !!navigator.userAgent.match('Edg/...');
}
/* Engine */
export function isGecko() {
return !!navigator.userAgent.match('Gecko/...');
}
export function isWebKit() {
return !!navigator.userAgent.match('AppleWebKit/...') &&
!navigator.userAgent.match('Chrome/...');
}
export function isBlink() {
return !!navigator.userAgent.match('Chrome/...');
}

@ -0,0 +1,249 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
*/
import { supportsCursorURIs, isTouchDevice } from './browser.js';
const useFallback = !supportsCursorURIs || isTouchDevice;
export default class Cursor {
constructor() {
this._target = null;
this._canvas = document.createElement('canvas');
if (useFallback) {
this._canvas.style.position = 'fixed';
this._canvas.style.zIndex = '65535';
this._canvas.style.pointerEvents = 'none';
// Safari on iOS can select the cursor image
// https://bugs.webkit.org/show_bug.cgi?id=249223
this._canvas.style.userSelect = 'none';
this._canvas.style.WebkitUserSelect = 'none';
// Can't use "display" because of Firefox bug #1445997
this._canvas.style.visibility = 'hidden';
}
this._position = { x: 0, y: 0 };
this._hotSpot = { x: 0, y: 0 };
this._eventHandlers = {
'mouseover': this._handleMouseOver.bind(this),
'mouseleave': this._handleMouseLeave.bind(this),
'mousemove': this._handleMouseMove.bind(this),
'mouseup': this._handleMouseUp.bind(this),
};
}
attach(target) {
if (this._target) {
this.detach();
}
this._target = target;
if (useFallback) {
document.body.appendChild(this._canvas);
const options = { capture: true, passive: true };
this._target.addEventListener('mouseover', this._eventHandlers.mouseover, options);
this._target.addEventListener('mouseleave', this._eventHandlers.mouseleave, options);
this._target.addEventListener('mousemove', this._eventHandlers.mousemove, options);
this._target.addEventListener('mouseup', this._eventHandlers.mouseup, options);
}
this.clear();
}
detach() {
if (!this._target) {
return;
}
if (useFallback) {
const options = { capture: true, passive: true };
this._target.removeEventListener('mouseover', this._eventHandlers.mouseover, options);
this._target.removeEventListener('mouseleave', this._eventHandlers.mouseleave, options);
this._target.removeEventListener('mousemove', this._eventHandlers.mousemove, options);
this._target.removeEventListener('mouseup', this._eventHandlers.mouseup, options);
if (document.contains(this._canvas)) {
document.body.removeChild(this._canvas);
}
}
this._target = null;
}
change(rgba, hotx, hoty, w, h) {
if ((w === 0) || (h === 0)) {
this.clear();
return;
}
this._position.x = this._position.x + this._hotSpot.x - hotx;
this._position.y = this._position.y + this._hotSpot.y - hoty;
this._hotSpot.x = hotx;
this._hotSpot.y = hoty;
let ctx = this._canvas.getContext('2d');
this._canvas.width = w;
this._canvas.height = h;
let img = new ImageData(new Uint8ClampedArray(rgba), w, h);
ctx.clearRect(0, 0, w, h);
ctx.putImageData(img, 0, 0);
if (useFallback) {
this._updatePosition();
} else {
let url = this._canvas.toDataURL();
this._target.style.cursor = 'url(' + url + ')' + hotx + ' ' + hoty + ', default';
}
}
clear() {
this._target.style.cursor = 'none';
this._canvas.width = 0;
this._canvas.height = 0;
this._position.x = this._position.x + this._hotSpot.x;
this._position.y = this._position.y + this._hotSpot.y;
this._hotSpot.x = 0;
this._hotSpot.y = 0;
}
// Mouse events might be emulated, this allows
// moving the cursor in such cases
move(clientX, clientY) {
if (!useFallback) {
return;
}
// clientX/clientY are relative the _visual viewport_,
// but our position is relative the _layout viewport_,
// so try to compensate when we can
if (window.visualViewport) {
this._position.x = clientX + window.visualViewport.offsetLeft;
this._position.y = clientY + window.visualViewport.offsetTop;
} else {
this._position.x = clientX;
this._position.y = clientY;
}
this._updatePosition();
let target = document.elementFromPoint(clientX, clientY);
this._updateVisibility(target);
}
_handleMouseOver(event) {
// This event could be because we're entering the target, or
// moving around amongst its sub elements. Let the move handler
// sort things out.
this._handleMouseMove(event);
}
_handleMouseLeave(event) {
// Check if we should show the cursor on the element we are leaving to
this._updateVisibility(event.relatedTarget);
}
_handleMouseMove(event) {
this._updateVisibility(event.target);
this._position.x = event.clientX - this._hotSpot.x;
this._position.y = event.clientY - this._hotSpot.y;
this._updatePosition();
}
_handleMouseUp(event) {
// We might get this event because of a drag operation that
// moved outside of the target. Check what's under the cursor
// now and adjust visibility based on that.
let target = document.elementFromPoint(event.clientX, event.clientY);
this._updateVisibility(target);
// Captures end with a mouseup but we can't know the event order of
// mouseup vs releaseCapture.
//
// In the cases when releaseCapture comes first, the code above is
// enough.
//
// In the cases when the mouseup comes first, we need wait for the
// browser to flush all events and then check again if the cursor
// should be visible.
if (this._captureIsActive()) {
window.setTimeout(() => {
// We might have detached at this point
if (!this._target) {
return;
}
// Refresh the target from elementFromPoint since queued events
// might have altered the DOM
target = document.elementFromPoint(event.clientX,
event.clientY);
this._updateVisibility(target);
}, 0);
}
}
_showCursor() {
if (this._canvas.style.visibility === 'hidden') {
this._canvas.style.visibility = '';
}
}
_hideCursor() {
if (this._canvas.style.visibility !== 'hidden') {
this._canvas.style.visibility = 'hidden';
}
}
// Should we currently display the cursor?
// (i.e. are we over the target, or a child of the target without a
// different cursor set)
_shouldShowCursor(target) {
if (!target) {
return false;
}
// Easy case
if (target === this._target) {
return true;
}
// Other part of the DOM?
if (!this._target.contains(target)) {
return false;
}
// Has the child its own cursor?
// FIXME: How can we tell that a sub element has an
// explicit "cursor: none;"?
if (window.getComputedStyle(target).cursor !== 'none') {
return false;
}
return true;
}
_updateVisibility(target) {
// When the cursor target has capture we want to show the cursor.
// So, if a capture is active - look at the captured element instead.
if (this._captureIsActive()) {
target = document.captureElement;
}
if (this._shouldShowCursor(target)) {
this._showCursor();
} else {
this._hideCursor();
}
}
_updatePosition() {
this._canvas.style.left = this._position.x + "px";
this._canvas.style.top = this._position.y + "px";
}
_captureIsActive() {
return document.captureElement &&
document.documentElement.contains(document.captureElement);
}
}

@ -0,0 +1,32 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2020 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
/*
* HTML element utility functions
*/
export function clientToElement(x, y, elem) {
const bounds = elem.getBoundingClientRect();
let pos = { x: 0, y: 0 };
// Clip to target bounds
if (x < bounds.left) {
pos.x = 0;
} else if (x >= bounds.right) {
pos.x = bounds.width - 1;
} else {
pos.x = x - bounds.left;
}
if (y < bounds.top) {
pos.y = 0;
} else if (y >= bounds.bottom) {
pos.y = bounds.height - 1;
} else {
pos.y = y - bounds.top;
}
return pos;
}

@ -0,0 +1,138 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2018 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
/*
* Cross-browser event and position routines
*/
export function getPointerEvent(e) {
return e.changedTouches ? e.changedTouches[0] : e.touches ? e.touches[0] : e;
}
export function stopEvent(e) {
e.stopPropagation();
e.preventDefault();
}
// Emulate Element.setCapture() when not supported
let _captureRecursion = false;
let _elementForUnflushedEvents = null;
document.captureElement = null;
function _captureProxy(e) {
// Recursion protection as we'll see our own event
if (_captureRecursion) return;
// Clone the event as we cannot dispatch an already dispatched event
const newEv = new e.constructor(e.type, e);
_captureRecursion = true;
if (document.captureElement) {
document.captureElement.dispatchEvent(newEv);
} else {
_elementForUnflushedEvents.dispatchEvent(newEv);
}
_captureRecursion = false;
// Avoid double events
e.stopPropagation();
// Respect the wishes of the redirected event handlers
if (newEv.defaultPrevented) {
e.preventDefault();
}
// Implicitly release the capture on button release
if (e.type === "mouseup") {
releaseCapture();
}
}
// Follow cursor style of target element
function _capturedElemChanged() {
const proxyElem = document.getElementById("noVNC_mouse_capture_elem");
proxyElem.style.cursor = window.getComputedStyle(document.captureElement).cursor;
}
const _captureObserver = new MutationObserver(_capturedElemChanged);
export function setCapture(target) {
if (target.setCapture) {
target.setCapture();
document.captureElement = target;
} else {
// Release any existing capture in case this method is
// called multiple times without coordination
releaseCapture();
let proxyElem = document.getElementById("noVNC_mouse_capture_elem");
if (proxyElem === null) {
proxyElem = document.createElement("div");
proxyElem.id = "noVNC_mouse_capture_elem";
proxyElem.style.position = "fixed";
proxyElem.style.top = "0px";
proxyElem.style.left = "0px";
proxyElem.style.width = "100%";
proxyElem.style.height = "100%";
proxyElem.style.zIndex = 10000;
proxyElem.style.display = "none";
document.body.appendChild(proxyElem);
// This is to make sure callers don't get confused by having
// our blocking element as the target
proxyElem.addEventListener('contextmenu', _captureProxy);
proxyElem.addEventListener('mousemove', _captureProxy);
proxyElem.addEventListener('mouseup', _captureProxy);
}
document.captureElement = target;
// Track cursor and get initial cursor
_captureObserver.observe(target, {attributes: true});
_capturedElemChanged();
proxyElem.style.display = "";
// We listen to events on window in order to keep tracking if it
// happens to leave the viewport
window.addEventListener('mousemove', _captureProxy);
window.addEventListener('mouseup', _captureProxy);
}
}
export function releaseCapture() {
if (document.releaseCapture) {
document.releaseCapture();
document.captureElement = null;
} else {
if (!document.captureElement) {
return;
}
// There might be events already queued. The event proxy needs
// access to the captured element for these queued events.
// E.g. contextmenu (right-click) in Microsoft Edge
//
// Before removing the capturedElem pointer we save it to a
// temporary variable that the unflushed events can use.
_elementForUnflushedEvents = document.captureElement;
document.captureElement = null;
_captureObserver.disconnect();
const proxyElem = document.getElementById("noVNC_mouse_capture_elem");
proxyElem.style.display = "none";
window.removeEventListener('mousemove', _captureProxy);
window.removeEventListener('mouseup', _captureProxy);
}
}

@ -0,0 +1,35 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
export default class EventTargetMixin {
constructor() {
this._listeners = new Map();
}
addEventListener(type, callback) {
if (!this._listeners.has(type)) {
this._listeners.set(type, new Set());
}
this._listeners.get(type).add(callback);
}
removeEventListener(type, callback) {
if (this._listeners.has(type)) {
this._listeners.get(type).delete(callback);
}
}
dispatchEvent(event) {
if (!this._listeners.has(event.type)) {
return true;
}
this._listeners.get(event.type)
.forEach(callback => callback.call(this, event));
return !event.defaultPrevented;
}
}

@ -0,0 +1,15 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2020 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
export function toUnsigned32bit(toConvert) {
return toConvert >>> 0;
}
export function toSigned32bit(toConvert) {
return toConvert | 0;
}

@ -0,0 +1,56 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
/*
* Logging/debug routines
*/
let _logLevel = 'warn';
let Debug = () => {};
let Info = () => {};
let Warn = () => {};
let Error = () => {};
export function initLogging(level) {
if (typeof level === 'undefined') {
level = _logLevel;
} else {
_logLevel = level;
}
Debug = Info = Warn = Error = () => {};
if (typeof window.console !== "undefined") {
/* eslint-disable no-console, no-fallthrough */
switch (level) {
case 'debug':
Debug = console.debug.bind(window.console);
case 'info':
Info = console.info.bind(window.console);
case 'warn':
Warn = console.warn.bind(window.console);
case 'error':
Error = console.error.bind(window.console);
case 'none':
break;
default:
throw new window.Error("invalid logging type '" + level + "'");
}
/* eslint-enable no-console, no-fallthrough */
}
}
export function getLogging() {
return _logLevel;
}
export { Debug, Info, Warn, Error };
// Initialize logging level
initLogging();

@ -0,0 +1,28 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
// Decode from UTF-8
export function decodeUTF8(utf8string, allowLatin1=false) {
try {
return decodeURIComponent(escape(utf8string));
} catch (e) {
if (e instanceof URIError) {
if (allowLatin1) {
// If we allow Latin1 we can ignore any decoding fails
// and in these cases return the original string
return utf8string;
}
}
throw e;
}
}
// Encode to UTF-8
export function encodeUTF8(DOMString) {
return unescape(encodeURIComponent(DOMString));
}

@ -0,0 +1,369 @@
/*
* Websock: high-performance buffering wrapper
* Copyright (C) 2019 The noVNC authors
* Licensed under MPL 2.0 (see LICENSE.txt)
*
* Websock is similar to the standard WebSocket / RTCDataChannel object
* but with extra buffer handling.
*
* Websock has built-in receive queue buffering; the message event
* does not contain actual data but is simply a notification that
* there is new data available. Several rQ* methods are available to
* read binary data off of the receive queue.
*/
import * as Log from './util/logging.js';
// this has performance issues in some versions Chromium, and
// doesn't gain a tremendous amount of performance increase in Firefox
// at the moment. It may be valuable to turn it on in the future.
const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
// Constants pulled from RTCDataChannelState enum
// https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum
const DataChannel = {
CONNECTING: "connecting",
OPEN: "open",
CLOSING: "closing",
CLOSED: "closed"
};
const ReadyStates = {
CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING],
OPEN: [WebSocket.OPEN, DataChannel.OPEN],
CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING],
CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED],
};
// Properties a raw channel must have, WebSocket and RTCDataChannel are two examples
const rawChannelProps = [
"send",
"close",
"binaryType",
"onerror",
"onmessage",
"onopen",
"protocol",
"readyState",
];
export default class Websock {
constructor() {
this._websocket = null; // WebSocket or RTCDataChannel object
this._rQi = 0; // Receive queue index
this._rQlen = 0; // Next write position in the receive queue
this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
// called in init: this._rQ = new Uint8Array(this._rQbufferSize);
this._rQ = null; // Receive queue
this._sQbufferSize = 1024 * 10; // 10 KiB
// called in init: this._sQ = new Uint8Array(this._sQbufferSize);
this._sQlen = 0;
this._sQ = null; // Send queue
this._eventHandlers = {
message: () => {},
open: () => {},
close: () => {},
error: () => {}
};
}
// Getters and setters
get readyState() {
let subState;
if (this._websocket === null) {
return "unused";
}
subState = this._websocket.readyState;
if (ReadyStates.CONNECTING.includes(subState)) {
return "connecting";
} else if (ReadyStates.OPEN.includes(subState)) {
return "open";
} else if (ReadyStates.CLOSING.includes(subState)) {
return "closing";
} else if (ReadyStates.CLOSED.includes(subState)) {
return "closed";
}
return "unknown";
}
// Receive queue
rQpeek8() {
return this._rQ[this._rQi];
}
rQskipBytes(bytes) {
this._rQi += bytes;
}
rQshift8() {
return this._rQshift(1);
}
rQshift16() {
return this._rQshift(2);
}
rQshift32() {
return this._rQshift(4);
}
// TODO(directxman12): test performance with these vs a DataView
_rQshift(bytes) {
let res = 0;
for (let byte = bytes - 1; byte >= 0; byte--) {
res += this._rQ[this._rQi++] << (byte * 8);
}
return res >>> 0;
}
rQlen() {
return this._rQlen - this._rQi;
}
rQshiftStr(len) {
let str = "";
// Handle large arrays in steps to avoid long strings on the stack
for (let i = 0; i < len; i += 4096) {
let part = this.rQshiftBytes(Math.min(4096, len - i), false);
str += String.fromCharCode.apply(null, part);
}
return str;
}
rQshiftBytes(len, copy=true) {
this._rQi += len;
if (copy) {
return this._rQ.slice(this._rQi - len, this._rQi);
} else {
return this._rQ.subarray(this._rQi - len, this._rQi);
}
}
rQshiftTo(target, len) {
// TODO: make this just use set with views when using a ArrayBuffer to store the rQ
target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
this._rQi += len;
}
rQpeekBytes(len, copy=true) {
if (copy) {
return this._rQ.slice(this._rQi, this._rQi + len);
} else {
return this._rQ.subarray(this._rQi, this._rQi + len);
}
}
// Check to see if we must wait for 'num' bytes (default to FBU.bytes)
// to be available in the receive queue. Return true if we need to
// wait (and possibly print a debug message), otherwise false.
rQwait(msg, num, goback) {
if (this._rQlen - this._rQi < num) {
if (goback) {
if (this._rQi < goback) {
throw new Error("rQwait cannot backup " + goback + " bytes");
}
this._rQi -= goback;
}
return true; // true means need more data
}
return false;
}
// Send queue
sQpush8(num) {
this._sQensureSpace(1);
this._sQ[this._sQlen++] = num;
}
sQpush16(num) {
this._sQensureSpace(2);
this._sQ[this._sQlen++] = (num >> 8) & 0xff;
this._sQ[this._sQlen++] = (num >> 0) & 0xff;
}
sQpush32(num) {
this._sQensureSpace(4);
this._sQ[this._sQlen++] = (num >> 24) & 0xff;
this._sQ[this._sQlen++] = (num >> 16) & 0xff;
this._sQ[this._sQlen++] = (num >> 8) & 0xff;
this._sQ[this._sQlen++] = (num >> 0) & 0xff;
}
sQpushString(str) {
let bytes = str.split('').map(chr => chr.charCodeAt(0));
this.sQpushBytes(new Uint8Array(bytes));
}
sQpushBytes(bytes) {
for (let offset = 0;offset < bytes.length;) {
this._sQensureSpace(1);
let chunkSize = this._sQbufferSize - this._sQlen;
if (chunkSize > bytes.length - offset) {
chunkSize = bytes.length - offset;
}
this._sQ.set(bytes.subarray(offset, offset + chunkSize), this._sQlen);
this._sQlen += chunkSize;
offset += chunkSize;
}
}
flush() {
if (this._sQlen > 0 && this.readyState === 'open') {
this._websocket.send(new Uint8Array(this._sQ.buffer, 0, this._sQlen));
this._sQlen = 0;
}
}
_sQensureSpace(bytes) {
if (this._sQbufferSize - this._sQlen < bytes) {
this.flush();
}
}
// Event handlers
off(evt) {
this._eventHandlers[evt] = () => {};
}
on(evt, handler) {
this._eventHandlers[evt] = handler;
}
_allocateBuffers() {
this._rQ = new Uint8Array(this._rQbufferSize);
this._sQ = new Uint8Array(this._sQbufferSize);
}
init() {
this._allocateBuffers();
this._rQi = 0;
this._websocket = null;
}
open(uri, protocols) {
this.attach(new WebSocket(uri, protocols));
}
attach(rawChannel) {
this.init();
// Must get object and class methods to be compatible with the tests.
const channelProps = [...Object.keys(rawChannel), ...Object.getOwnPropertyNames(Object.getPrototypeOf(rawChannel))];
for (let i = 0; i < rawChannelProps.length; i++) {
const prop = rawChannelProps[i];
if (channelProps.indexOf(prop) < 0) {
throw new Error('Raw channel missing property: ' + prop);
}
}
this._websocket = rawChannel;
this._websocket.binaryType = "arraybuffer";
this._websocket.onmessage = this._recvMessage.bind(this);
this._websocket.onopen = () => {
Log.Debug('>> WebSock.onopen');
if (this._websocket.protocol) {
Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
}
this._eventHandlers.open();
Log.Debug("<< WebSock.onopen");
};
this._websocket.onclose = (e) => {
Log.Debug(">> WebSock.onclose");
this._eventHandlers.close(e);
Log.Debug("<< WebSock.onclose");
};
this._websocket.onerror = (e) => {
Log.Debug(">> WebSock.onerror: " + e);
this._eventHandlers.error(e);
Log.Debug("<< WebSock.onerror: " + e);
};
}
close() {
if (this._websocket) {
if (this.readyState === 'connecting' ||
this.readyState === 'open') {
Log.Info("Closing WebSocket connection");
this._websocket.close();
}
this._websocket.onmessage = () => {};
}
}
// private methods
// We want to move all the unread data to the start of the queue,
// e.g. compacting.
// The function also expands the receive que if needed, and for
// performance reasons we combine these two actions to avoid
// unnecessary copying.
_expandCompactRQ(minFit) {
// if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place
// instead of resizing
const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8;
const resizeNeeded = this._rQbufferSize < requiredBufferSize;
if (resizeNeeded) {
// Make sure we always *at least* double the buffer size, and have at least space for 8x
// the current amount of data
this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize);
}
// we don't want to grow unboundedly
if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
this._rQbufferSize = MAX_RQ_GROW_SIZE;
if (this._rQbufferSize - (this._rQlen - this._rQi) < minFit) {
throw new Error("Receive queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
}
}
if (resizeNeeded) {
const oldRQbuffer = this._rQ.buffer;
this._rQ = new Uint8Array(this._rQbufferSize);
this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi));
} else {
this._rQ.copyWithin(0, this._rQi, this._rQlen);
}
this._rQlen = this._rQlen - this._rQi;
this._rQi = 0;
}
// push arraybuffer values onto the end of the receive que
_recvMessage(e) {
if (this._rQlen == this._rQi) {
// All data has now been processed, this means we
// can reset the receive queue.
this._rQlen = 0;
this._rQi = 0;
}
const u8 = new Uint8Array(e.data);
if (u8.length > this._rQbufferSize - this._rQlen) {
this._expandCompactRQ(u8.length);
}
this._rQ.set(u8, this._rQlen);
this._rQlen += u8.length;
if (this._rQlen - this._rQi > 0) {
this._eventHandlers.message();
} else {
Log.Debug("Ignoring empty message");
}
}
}

@ -0,0 +1,21 @@
(The MIT License)
Copyright (C) 2014-2016 by Vitaly Puzrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -0,0 +1,6 @@
This is an ES6-modules-compatible version of
https://github.com/nodeca/pako, based on pako version 1.0.3.
It's more-or-less a direct translation of the original, with unused parts
removed, and the dynamic support for non-typed arrays removed (since ES6
modules don't work well with dynamic exports).

@ -0,0 +1,45 @@
// reduce buffer size, avoiding mem copy
export function shrinkBuf (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
export function arraySet (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
}
// Join array of chunks to single array.
export function flattenChunks (chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length; i < l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
export var Buf8 = Uint8Array;
export var Buf16 = Uint16Array;
export var Buf32 = Int32Array;

@ -0,0 +1,27 @@
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
export default function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}

@ -0,0 +1,47 @@
export default {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};

@ -0,0 +1,36 @@
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
export default function makeTable() {
var c, table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc ^= -1;
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,35 @@
export default function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}

@ -0,0 +1,324 @@
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
export default function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,322 @@
import * as utils from "../utils/common.js";
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
export default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* process all codes and make table entries */
for (;;) {
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};

@ -0,0 +1,11 @@
export default {
2: 'need dictionary', /* Z_NEED_DICT 2 */
1: 'stream end', /* Z_STREAM_END 1 */
0: '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,24 @@
export default function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,79 @@
"""Database sessions bind to immutable user IDs, not reusable usernames."""
from __future__ import annotations
import json
import time
import pytest
from virsh_panel.auth import DatabaseSessionStore, SessionStore
class _Records:
def __init__(self):
self.values = {}
def get(self, record_type, record_key):
return self.values.get((record_type, record_key))
def set(self, record_type, record_key, value):
self.values[(record_type, record_key)] = value
def delete(self, record_type, record_key):
self.values.pop((record_type, record_key), None)
def test_database_session_round_trips_immutable_user_id():
records = _Records()
sessions = DatabaseSessionStore(records)
created = sessions.issue("operator", user_id=47)
assert created.user_id == 47
key = sessions._key(created.token)
payload = json.loads(records.get("session", key))
assert payload["user_id"] == 47
assert created.token not in records.get("session", key)
restored = DatabaseSessionStore(records).get(created.token)
assert restored == created
@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0])
def test_database_session_issue_refuses_missing_or_invalid_user_id(invalid_id):
sessions = DatabaseSessionStore(_Records())
with pytest.raises(ValueError, match="positive user ID"):
sessions.issue("operator", user_id=invalid_id)
@pytest.mark.parametrize("invalid_id", [None, 0, -1, True, "47", 47.0])
def test_database_session_get_rejects_legacy_or_invalid_id(invalid_id):
records = _Records()
sessions = DatabaseSessionStore(records)
token = "legacy-token"
payload = {
"username": "operator", "csrf_token": "csrf-token",
"expires_at": time.time() + 100,
}
if invalid_id is not None:
payload["user_id"] = invalid_id
records.set("session", sessions._key(token), json.dumps(payload))
assert sessions.get(token) is None
def test_database_session_expired_token_is_removed():
records = _Records()
sessions = DatabaseSessionStore(records)
token = "expired-token"
key = sessions._key(token)
records.set("session", key, json.dumps({
"username": "operator", "user_id": 47,
"csrf_token": "csrf-token", "expires_at": time.time() - 1,
}))
assert sessions.get(token) is None
assert records.get("session", key) is None
def test_injected_memory_sessions_keep_username_only_compatibility():
sessions = SessionStore()
created = sessions.issue("test-admin")
assert created.user_id is None
assert sessions.get(created.token) == created

@ -0,0 +1,230 @@
"""Cloud-init public networking and NoCloud seed behavior."""
from __future__ import annotations
import importlib.util
import json
import uuid
import pytest
from virsh_panel.cloud_init import (
build_seed_iso, generate_root_password, hash_root_password, read_seed_network,
validate_cloud_network,
)
PUBLIC_KEY = (
"ssh-ed25519 "
"AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 "
"panel-test"
)
GUEST_PASSWORD = "A-strong-guest-password-2026"
def _user_data(seed: bytes) -> dict:
"""Read the single-line JSON cloud-config embedded in the generated ISO."""
prefix = b"#cloud-config\n"
start = seed.index(prefix) + len(prefix)
return json.loads(seed[start:seed.index(b"\n", start)])
@pytest.mark.parametrize(
("address", "gateway"),
[
("8.8.8.18/24", "8.8.8.1"),
("8.8.8.18/28", "8.8.8.17"),
("123.123.123.114/24", "123.123.123.113"),
],
)
def test_public_network_accepts_24_and_28(address, gateway):
validated = validate_cloud_network(
address, gateway, ["1.1.1.1", "8.8.8.8"], PUBLIC_KEY,
)
assert validated == {
"public_ip_cidr": address,
"gateway": gateway,
"dns_servers": ["1.1.1.1", "8.8.8.8"],
"guest_ssh_public_key": PUBLIC_KEY,
}
def test_cloud_login_accepts_key_and_root_password_together():
network = ("8.8.8.18/24", "8.8.8.1", ["1.1.1.1"])
password_hash = hash_root_password(GUEST_PASSWORD)
assert password_hash.startswith("$6$")
assert GUEST_PASSWORD not in password_hash
assert hash_root_password(GUEST_PASSWORD) != password_hash
validated = validate_cloud_network(
*network, "", root_password_hash=password_hash,
)
assert validated["root_password_hash"] == password_hash
assert not validated["guest_ssh_public_key"]
together = validate_cloud_network(
*network, PUBLIC_KEY, root_password_hash=password_hash,
)
assert together["guest_ssh_public_key"] == PUBLIC_KEY
assert together["root_password_hash"] == password_hash
with pytest.raises(ValueError):
validate_cloud_network(*network, "", root_password_hash=None)
with pytest.raises(ValueError):
validate_cloud_network(*network, "", root_password_hash=GUEST_PASSWORD)
@pytest.mark.parametrize("invalid", [
"Short1!", "alllowercase12!", "ALLUPPERCASE12!", "NoSymbolPassword12",
"A-lowercase\npassword12", "A-lowercase-password-" + "x" * 110,
])
def test_manual_root_password_requires_length_case_and_symbol(invalid):
with pytest.raises(ValueError, match="初始 root 密码"):
hash_root_password(invalid)
def test_generated_root_password_always_meets_policy():
samples = set()
for _ in range(50):
password = generate_root_password()
samples.add(password)
assert len(password) == 32
assert any(char.isupper() for char in password)
assert any(char.islower() for char in password)
assert any(not char.isalnum() for char in password)
assert len(samples) == 50
assert hash_root_password(password).startswith("$6$")
@pytest.mark.parametrize(
("address", "gateway"),
[
("192.168.1.18/24", "192.168.1.1"),
("10.0.0.18/24", "10.0.0.1"),
("172.16.0.18/24", "172.16.0.1"),
("127.0.0.18/24", "127.0.0.1"),
("169.254.0.18/24", "169.254.0.1"),
("224.0.0.18/24", "224.0.0.1"),
("2001:4860:4860::8888/64", "2001:4860:4860::1"),
("8.8.8.0/24", "8.8.8.1"),
("8.8.8.255/24", "8.8.8.1"),
("8.8.8.18/28", "8.8.8.1"),
("8.8.8.18", "8.8.8.1"),
],
)
def test_public_network_rejects_nonpublic_or_unroutable_pairs(address, gateway):
with pytest.raises(ValueError):
validate_cloud_network(address, gateway, ["1.1.1.1"], PUBLIC_KEY)
@pytest.mark.parametrize(
("dns", "key"),
[
(["not-an-ip"], PUBLIC_KEY),
(["192.168.1.1"], PUBLIC_KEY),
([], PUBLIC_KEY),
(["1.1.1.1"], "not-an-ssh-key"),
(["1.1.1.1"], PUBLIC_KEY + "\nruncmd: [evil]"),
],
)
def test_public_network_rejects_bad_dns_and_ssh_key(dns, key):
with pytest.raises(ValueError):
validate_cloud_network("8.8.8.18/24", "8.8.8.1", dns, key)
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_seed_iso_has_nocloud_files_and_mac_specific_static_network():
vm_uuid = str(uuid.uuid4())
mac = "52:54:00:12:34:56"
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
)
seed = build_seed_iso(vm_uuid, "cloud-vm", mac, validated)
assert isinstance(seed, bytes)
assert seed[32769:32774] == b"CD001" # ISO-9660 primary volume descriptor
assert b"CIDATA" in seed
for marker in (
b"user-data", b"meta-data", b"network-config", b"8.8.8.18/28",
b"8.8.8.17", b"1.1.1.1", mac.encode(), PUBLIC_KEY.encode(),
):
assert marker in seed
assert b'"routes": [{"to": "0.0.0.0/0", "via": "8.8.8.17"}]' in seed
assert b'"to": "default"' not in seed
user_data = _user_data(seed)
assert user_data["disable_root"] is False
assert user_data["ssh_pwauth"] is False
assert user_data["users"][0]["name"] == "root"
assert user_data["users"][0]["ssh_authorized_keys"] == [PUBLIC_KEY]
assert "hashed_passwd" not in user_data["users"][0]
assert "passwd" not in user_data["users"][0]
sshd_dropin = user_data["write_files"][0]
assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf"
assert "PermitRootLogin prohibit-password" in sshd_dropin["content"]
assert "PasswordAuthentication no" in sshd_dropin["content"]
assert b"almalinux" not in seed
assert read_seed_network(seed) == {
"public_ip_cidr": "8.8.8.18/28",
"gateway": "8.8.8.17",
"dns_servers": ["1.1.1.1"],
"mac": mac,
}
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_read_seed_network_rejects_invalid_iso_without_exposing_credentials():
with pytest.raises(ValueError):
read_seed_network(b"not an ISO")
with pytest.raises(ValueError):
read_seed_network(b"x" * (1024 * 1024 + 1))
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_password_seed_sets_root_hash_and_enables_ssh_password_login():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], "",
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "password-vm", "52:54:00:12:34:56", validated,
)
user_data = _user_data(seed)
assert user_data["disable_root"] is False
assert user_data["ssh_pwauth"] is True
assert user_data["users"][0]["name"] == "root"
assert user_data["users"][0]["lock_passwd"] is False
assert user_data["users"][0]["hashed_passwd"] == password_hash
assert "ssh_authorized_keys" not in user_data["users"][0]
sshd_dropin = user_data["write_files"][0]
assert sshd_dropin["path"] == "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf"
assert "PermitRootLogin yes" in sshd_dropin["content"]
assert "PasswordAuthentication yes" in sshd_dropin["content"]
assert GUEST_PASSWORD.encode() not in seed
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_seed_allows_root_password_and_ssh_key_together():
password_hash = hash_root_password(GUEST_PASSWORD)
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
root_password_hash=password_hash,
)
seed = build_seed_iso(
str(uuid.uuid4()), "both-vm", "52:54:00:12:34:56", validated,
)
user_data = _user_data(seed)
root = user_data["users"][0]
assert root["name"] == "root"
assert root["lock_passwd"] is False
assert root["ssh_authorized_keys"] == [PUBLIC_KEY]
assert root["hashed_passwd"] == password_hash
assert user_data["ssh_pwauth"] is True
assert "PermitRootLogin yes" in user_data["write_files"][0]["content"]
assert "PasswordAuthentication yes" in user_data["write_files"][0]["content"]
assert GUEST_PASSWORD.encode() not in seed

@ -0,0 +1,181 @@
"""Official-image import restrictions and private template catalog tests."""
from __future__ import annotations
import hashlib
import io
import stat
import struct
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from virsh_panel.cloud_templates import (
TemplateError,
TemplateStore,
_RejectRedirects,
download_verified_image,
image_version_for,
template_id_for,
template_scope,
template_volume_name,
validate_image_url,
)
OFFICIAL = (
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/"
"AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2"
)
OFFICIAL_9 = (
"https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/"
"AlmaLinux-9-GenericCloud-latest.x86_64.qcow2"
)
def test_official_almalinux_9_and_10_are_distinct_supported_versions():
assert validate_image_url(OFFICIAL_9) == OFFICIAL_9
assert image_version_for(OFFICIAL_9) == "9"
assert image_version_for(OFFICIAL) == "10"
scope = "a" * 64
digest = "b" * 64
assert template_id_for(scope, digest, "9").startswith("alma9-")
assert template_id_for(scope, digest, "10").startswith("alma10-")
assert template_volume_name(template_id_for(scope, digest, "9")).startswith(
"panel-template-alma9-"
)
with pytest.raises(TemplateError):
validate_image_url(OFFICIAL_9.replace("/almalinux/9/", "/almalinux/10/"))
with pytest.raises(TemplateError):
validate_image_url(OFFICIAL_9.replace("AlmaLinux-9-", "AlmaLinux-8-"))
with pytest.raises(TemplateError):
template_id_for(scope, digest, "8")
def qcow2_fixture(virtual_size=2 * 1024**3) -> bytes:
header = bytearray(104)
header[:4] = b"QFI\xfb"
header[4:8] = struct.pack(">I", 3)
header[20:24] = struct.pack(">I", 16)
header[24:32] = struct.pack(">Q", virtual_size)
header[100:104] = struct.pack(">I", 104)
return bytes(header) + b"fake qcow2 content for controlled import test"
@pytest.mark.parametrize(
"url",
[
"http://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://repo.almalinux.org.evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://user:pass@repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/../../etc/passwd",
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2?token=secret",
],
)
def test_import_url_rejects_nonofficial_and_ambiguous_targets(url):
with pytest.raises(TemplateError):
validate_image_url(url)
def test_verified_image_is_private_and_has_expected_virtual_size(tmp_path):
body = qcow2_fixture()
digest = hashlib.sha256(body).hexdigest()
opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body))
with patch("virsh_panel.cloud_templates.urllib.request.build_opener",
return_value=opener):
downloaded, virtual_size = download_verified_image(OFFICIAL, digest, tmp_path)
try:
assert downloaded.read_bytes() == body
assert virtual_size == 2 * 1024**3
assert stat.S_IMODE(downloaded.stat().st_mode) == 0o600
finally:
downloaded.unlink()
def test_failed_hash_never_leaves_unverified_template_file(tmp_path):
body = qcow2_fixture()
opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body))
with patch("virsh_panel.cloud_templates.urllib.request.build_opener",
return_value=opener):
with pytest.raises(TemplateError, match="SHA-256"):
download_verified_image(OFFICIAL, "0" * 64, tmp_path)
assert list(tmp_path.iterdir()) == []
def test_redirect_to_nonofficial_target_is_rejected_before_following():
handler = _RejectRedirects()
with pytest.raises(TemplateError, match="重定向"):
handler.redirect_request(None, None, 302, "Found", {},
"http://127.0.0.1/private")
def test_external_data_file_feature_is_rejected(tmp_path):
body = bytearray(qcow2_fixture())
body[72:80] = struct.pack(">Q", 4)
digest = hashlib.sha256(body).hexdigest()
opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body))
with patch("virsh_panel.cloud_templates.urllib.request.build_opener",
return_value=opener):
with pytest.raises(TemplateError, match="外部依赖"):
download_verified_image(OFFICIAL, digest, tmp_path)
assert list(tmp_path.iterdir()) == []
def test_template_catalog_is_private_and_scoped_to_host_and_disk_pool(tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
store = TemplateStore(data_dir)
profile = {
"host": "hypervisor.example", "port": 2222,
"fingerprint": "SHA256:fixture", "storage_pool": "/home/kvm",
}
scope = template_scope(profile)
other_scope = template_scope({**profile, "storage_pool": "/other/pool"})
record = {
"id": "alma10-example", "name": "AlmaLinux 10", "sha256": "a" * 64,
"volume_name": "alma10-cloud.qcow2", "virtual_size": 2 * 1024**3,
}
assert store.add(scope, record) == record
assert store.list(scope) == [record]
assert store.list(other_scope) == []
assert TemplateStore(data_dir).get(scope, record["id"]) == record
assert stat.S_IMODE(store.file.stat().st_mode) == 0o600
with pytest.raises(TemplateError):
store.get(other_scope, record["id"])
with pytest.raises(TemplateError):
store.add(scope, record)
def test_template_rename_preserves_image_record_and_host_scope(tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
store = TemplateStore(data_dir)
scope = "a" * 64
other_scope = "b" * 64
template_id = template_id_for(scope, "c" * 64, "9")
record = {
"id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux",
"os_version": "9", "sha256": "c" * 64,
"volume_name": template_volume_name(template_id), "virtual_size": 2 * 1024**3,
}
store.add(scope, record)
store.add(scope, {**record, "id": "other", "name": "Another name"})
store.add(other_scope, {**record, "name": "Other host"})
with pytest.raises(TemplateError) as inaccessible:
store.rename(other_scope, "other", "Missing")
assert inaccessible.value.status == 404
with pytest.raises(TemplateError) as duplicate:
store.rename(scope, template_id, "another NAME")
assert duplicate.value.status == 409
for invalid in ("", "x" * 65, "bad\x7fentry"):
with pytest.raises(TemplateError):
store.rename(scope, template_id, invalid)
updated = store.rename(scope, template_id, " 新名称 ")
assert updated == {**record, "name": "新名称"}
assert TemplateStore(data_dir).get(scope, template_id) == updated
assert store.get(other_scope, template_id)["name"] == "Other host"
assert stat.S_IMODE(store.file.stat().st_mode) == 0o600

@ -0,0 +1,31 @@
"""The panel starts without a prefilled host or administrator config file."""
from dataclasses import replace
from pathlib import Path
import pytest
from virsh_panel.config import PROJECT_DIR, Settings
def test_default_data_directory_stays_inside_project(monkeypatch):
monkeypatch.delenv("PANEL_DATA_DIR", raising=False)
assert Settings.from_env().data_dir == PROJECT_DIR / "data"
def test_runtime_settings_require_no_host_or_admin_values(tmp_path):
settings = Settings(data_dir=tmp_path)
settings.validate()
assert settings.secure_cookie is True
assert settings.ssh_binary == "ssh"
@pytest.mark.parametrize("bad_path", [Path("relative/data"), Path("/")])
def test_rejects_unsafe_data_directory(bad_path):
with pytest.raises(ValueError):
replace(Settings(), data_dir=bad_path).validate()
def test_rejects_missing_static_assets(tmp_path):
with pytest.raises(ValueError):
replace(Settings(), static_dir=tmp_path / "missing").validate()

@ -0,0 +1,199 @@
"""Focused tests for the SSH backed browser console stream."""
from __future__ import annotations
import asyncio
import unittest
from unittest.mock import AsyncMock, patch
from virsh_panel.console import ConsoleRelayError, WebSocketDisconnect, relay_console
class FakeStdin:
def __init__(self) -> None:
self.data = bytearray()
self.written = asyncio.Event()
self.closed = False
def write(self, data: bytes) -> None:
self.data.extend(data)
self.written.set()
async def drain(self) -> None:
await asyncio.sleep(0)
def close(self) -> None:
self.closed = True
class FakeProcess:
def __init__(self) -> None:
self.stdin = FakeStdin()
self.stdout = asyncio.StreamReader()
self.returncode: int | None = None
self.exited = asyncio.Event()
self.terminated = False
self.killed = False
async def wait(self) -> int:
await self.exited.wait()
assert self.returncode is not None
return self.returncode
def finish(self, code: int) -> None:
self.returncode = code
self.exited.set()
self.stdout.feed_eof()
def terminate(self) -> None:
self.terminated = True
self.finish(-15)
def kill(self) -> None:
self.killed = True
self.finish(-9)
class FakeWebSocket:
def __init__(self) -> None:
self.incoming: asyncio.Queue[dict[str, object]] = asyncio.Queue()
self.sent: list[bytes] = []
self.sent_event = asyncio.Event()
async def receive(self) -> dict[str, object]:
return await self.incoming.get()
async def send_bytes(self, data: bytes) -> None:
self.sent.append(data)
self.sent_event.set()
class RelayConsoleTests(unittest.IsolatedAsyncioTestCase):
async def test_relay_binary_frames_and_disconnect_cleans_up(self) -> None:
process = FakeProcess()
websocket = FakeWebSocket()
spawn = AsyncMock(return_value=process)
with patch("virsh_panel.console.asyncio.create_subprocess_exec", spawn):
running = asyncio.create_task(
relay_console(
websocket,
port=5901,
ssh_target="operator@hypervisor.example",
known_hosts_file="/home/virsh-panel/data/current/known_hosts",
ssh_config_file="/home/virsh-panel/data/current/config",
)
)
process.stdout.feed_data(b"RFB 003.008\n")
await asyncio.wait_for(websocket.sent_event.wait(), 1)
await websocket.incoming.put(
{"type": "websocket.receive", "bytes": b"client bytes"}
)
await asyncio.wait_for(process.stdin.written.wait(), 1)
await websocket.incoming.put({"type": "websocket.disconnect"})
await asyncio.wait_for(running, 1)
self.assertEqual(websocket.sent, [b"RFB 003.008\n"])
self.assertEqual(bytes(process.stdin.data), b"client bytes")
self.assertTrue(process.stdin.closed)
self.assertTrue(process.terminated)
command = spawn.await_args.args
self.assertEqual(command[0], "ssh")
self.assertEqual(command[1:3], ("-F", "/home/virsh-panel/data/current/config"))
self.assertIn("BatchMode=yes", command)
self.assertIn("StrictHostKeyChecking=yes", command)
self.assertIn("UserKnownHostsFile=/home/virsh-panel/data/current/known_hosts", command)
self.assertEqual(command[-3:], ("-W", "127.0.0.1:5901", "operator@hypervisor.example"))
self.assertEqual(spawn.await_args.kwargs["stderr"], asyncio.subprocess.DEVNULL)
async def test_ssh_failure_is_reported(self) -> None:
process = FakeProcess()
process.finish(255)
websocket = FakeWebSocket()
with patch(
"virsh_panel.console.asyncio.create_subprocess_exec",
AsyncMock(return_value=process),
):
with self.assertRaisesRegex(ConsoleRelayError, "status 255"):
await relay_console(websocket, port=5900, ssh_target="host.example")
self.assertTrue(process.stdin.closed)
self.assertFalse(process.terminated)
async def test_cancellation_terminates_ssh(self) -> None:
process = FakeProcess()
websocket = FakeWebSocket()
spawn = AsyncMock(return_value=process)
with patch("virsh_panel.console.asyncio.create_subprocess_exec", spawn):
running = asyncio.create_task(
relay_console(websocket, port=5900, ssh_target="host.example")
)
for _ in range(10):
if spawn.await_count:
break
await asyncio.sleep(0)
running.cancel()
with self.assertRaises(asyncio.CancelledError):
await running
self.assertTrue(process.stdin.closed)
self.assertTrue(process.terminated)
async def test_rejects_text_frames(self) -> None:
process = FakeProcess()
websocket = FakeWebSocket()
await websocket.incoming.put({"type": "websocket.receive", "text": "hello"})
with patch(
"virsh_panel.console.asyncio.create_subprocess_exec",
AsyncMock(return_value=process),
):
with self.assertRaisesRegex(ConsoleRelayError, "binary"):
await relay_console(websocket, port=5900, ssh_target="host.example")
self.assertTrue(process.terminated)
async def test_send_disconnect_terminates_ssh(self) -> None:
class DisconnectingWebSocket(FakeWebSocket):
async def send_bytes(self, data: bytes) -> None:
raise WebSocketDisconnect(1006)
process = FakeProcess()
process.stdout.feed_data(b"VNC")
with patch(
"virsh_panel.console.asyncio.create_subprocess_exec",
AsyncMock(return_value=process),
):
await relay_console(
DisconnectingWebSocket(), port=5900, ssh_target="host.example"
)
self.assertTrue(process.terminated)
async def test_invalid_endpoint_never_spawns_ssh(self) -> None:
spawn = AsyncMock()
with patch("virsh_panel.console.asyncio.create_subprocess_exec", spawn):
for port, target in (
(0, "host.example"),
(65536, "host.example"),
(True, "host.example"),
(5900, "-oProxyCommand=evil"),
(5900, "host.example ; evil"),
(5900, "ssh://host.example"),
):
with self.subTest(port=port, target=target):
with self.assertRaises(ValueError):
await relay_console(FakeWebSocket(), port=port, ssh_target=target)
with self.assertRaises(ValueError):
await relay_console(
FakeWebSocket(),
port=5900,
ssh_target="host.example",
known_hosts_file="relative/known_hosts",
)
with self.assertRaises(ValueError):
await relay_console(
FakeWebSocket(),
port=5900,
ssh_target="host.example",
ssh_config_file="relative/config",
)
spawn.assert_not_awaited()
if __name__ == "__main__":
unittest.main()

@ -0,0 +1,517 @@
"""Database-backed state behavior without requiring a live MariaDB server."""
from __future__ import annotations
import base64
import json
import os
import stat
import struct
import subprocess
from pathlib import Path
from types import SimpleNamespace
import pytest
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from virsh_panel.auth import hash_password, verify_password
from virsh_panel.cloud_templates import TemplateError
from virsh_panel.database import (
DatabasePanelState,
DatabaseRemoteHostManager,
DatabaseStore,
DatabaseTemplateStore,
)
from virsh_panel.remote_host import HostProfile, RemoteHostError
from virsh_panel.ssh_agent import SSHAgentError
PRIVATE_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nZmFrZQ==\n-----END OPENSSH PRIVATE KEY-----\n"
class MemoryStore:
def __init__(self) -> None:
self.records: dict[tuple[str, str], str] = {}
def get(self, kind: str, key: str) -> str | None:
return self.records.get((kind, key))
def set(self, kind: str, key: str, value: str) -> None:
self.records[(kind, key)] = value
def insert(self, kind: str, key: str, value: str) -> bool:
if (kind, key) in self.records:
return False
self.records[(kind, key)] = value
return True
def delete(self, kind: str, key: str) -> None:
self.records.pop((kind, key), None)
def list(self, kind: str) -> dict[str, str]:
return {key: value for (record_type, key), value in self.records.items()
if record_type == kind}
class MemoryUsers:
def __init__(self, store: MemoryStore) -> None:
self.store = store
def has_users(self) -> bool:
return self.store.get("test_user", "initial") is not None
def create_initial_user(self, username: str, password: str, email=None):
self.store.set("test_user", "initial", json.dumps({
"id": 1, "username": username, "email": email,
"password_hash": hash_password(password), "admin": False,
"approved": True, "email_verified": True, "created_at": 100,
}))
def get_by_username(self, username: str):
record = self.store.get("test_user", "initial")
user = json.loads(record) if record else None
return user if user and user["username"] == username else None
class EncryptedMemoryStore(MemoryStore):
"""Exercise the production record envelope without a MariaDB server."""
def __init__(self) -> None:
super().__init__()
self.records: dict[tuple[str, str], bytes] = {}
self._cipher_store = DatabaseStore.__new__(DatabaseStore)
self._cipher_store._cipher = AESGCM(b"a" * 32)
def get(self, kind: str, key: str) -> str | None:
payload = self.records.get((kind, key))
return (None if payload is None else
self._cipher_store._decrypt(kind, key, payload))
def set(self, kind: str, key: str, value: str) -> None:
self.records[(kind, key)] = self._cipher_store._encrypt(kind, key, value)
def test_database_ciphertext_is_randomized_and_bound_to_record_key():
store = DatabaseStore.__new__(DatabaseStore)
store._cipher = AESGCM(b"a" * 32)
first = store._encrypt("secret", "gitea_token", "private-token")
second = store._encrypt("secret", "gitea_token", "private-token")
assert first != second
assert b"private-token" not in first
assert store._decrypt("secret", "gitea_token", first) == "private-token"
with pytest.raises(Exception, match="密文"):
store._decrypt("secret", "different_name", first)
with pytest.raises(Exception, match="密文"):
store._decrypt("secret", "gitea_token", first[:-1] + b"0")
def test_linux_tmpfs_agent_socket_path_fits_openssh_limit():
# Linux pid_max cannot exceed 4,194,304; the runtime name is deliberately
# short so SSHAgentSession's <100-byte socket guard accepts it.
longest = (
"/dev/shm/v4194304-abcd/generations/gen-" + "f" * 32
+ "/agent-" + "f" * 16 + ".sock"
)
assert len(longest.encode()) < 100
def test_non_linux_rejects_disk_backed_private_key_fallback(tmp_path, monkeypatch):
monkeypatch.setattr("virsh_panel.database.sys", SimpleNamespace(platform="darwin"))
data_dir = tmp_path / "panel"
with pytest.raises(RemoteHostError, match="仅支持 Linux"):
DatabaseRemoteHostManager(MemoryStore(), data_dir)
assert not list(data_dir.rglob("id_private"))
def test_initial_user_hash_is_database_only_and_bootstrap_token_is_consumed(tmp_path: Path):
store = MemoryStore()
data_dir = tmp_path / "panel"
state = DatabasePanelState(data_dir, store, MemoryUsers(store))
token = state.initialize_setup_token()
assert token
state.create_admin(token, "admin", "a-valid-very-long-password")
assert not (data_dir / "state.json").exists()
assert not (data_dir / "setup-token").exists()
assert stat.S_IMODE(data_dir.stat().st_mode) == 0o700
reopened = DatabasePanelState(data_dir, store, MemoryUsers(store))
user = reopened.users.get_by_username("admin")
assert user["admin"] is False and user["approved"] is True
assert user["email"] is None
assert verify_password("a-valid-very-long-password", user["password_hash"])
assert reopened.initialize_setup_token() is None
def test_templates_are_isolated_by_host_scope_and_atomic_insert():
store = MemoryStore()
templates = DatabaseTemplateStore(store)
record = {"id": "alma10-12345678-abcdef0123456789", "name": "AlmaLinux"}
assert templates.add("a" * 64, record) == record
assert templates.list("a" * 64) == [record]
assert templates.list("b" * 64) == []
with pytest.raises(TemplateError) as duplicate:
templates.add("a" * 64, record)
assert duplicate.value.status == 409
def test_database_template_rename_persists_only_name_and_rejects_duplicate():
store = MemoryStore()
templates = DatabaseTemplateStore(store)
scope = "a" * 64
other_scope = "b" * 64
record = {
"id": "alma9-12345678-abcdef0123456789", "name": "AlmaLinux 9",
"os_family": "AlmaLinux", "os_version": "9", "sha256": "f" * 64,
"volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2",
}
templates.add(scope, record)
templates.add(scope, {**record, "id": "second", "name": "Second"})
templates.add(other_scope, {**record, "name": "Other host"})
with pytest.raises(TemplateError) as duplicate_import:
templates.add(scope, {**record, "id": "third", "name": "ALMALINUX 9"})
assert duplicate_import.value.status == 409
with pytest.raises(TemplateError) as wrong_host:
templates.rename(other_scope, "second", "Missing")
assert wrong_host.value.status == 404
with pytest.raises(TemplateError) as duplicate_rename:
templates.rename(scope, record["id"], "second")
assert duplicate_rename.value.status == 409
updated = templates.rename(scope, record["id"], " 自定义名称 ")
assert updated == {**record, "name": "自定义名称"}
assert DatabaseTemplateStore(store).get(scope, record["id"]) == updated
assert templates.get(other_scope, record["id"])["name"] == "Other host"
def _host_key() -> str:
blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + b"a" * 32
return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii")
def _fake_ssh(argv, **_kwargs):
if argv[0] == "ssh-keyscan":
return subprocess.CompletedProcess(argv, 0, "host.example " + _host_key() + "\n", "")
if argv[0] == "ssh-keygen":
return subprocess.CompletedProcess(argv, 0, "ssh-ed25519 fake-public-key\n", "")
if argv[0] == "ssh":
return subprocess.CompletedProcess(argv, 0, "ok", "")
raise AssertionError(argv)
def _encrypted_ssh(argv, **kwargs):
if argv[0] == "ssh-keygen":
return subprocess.CompletedProcess(argv, 255, "", "passphrase required")
return _fake_ssh(argv, **kwargs)
class FakeAgent:
def __init__(self, generation: Path, _key_path: Path, passphrase: str) -> None:
if passphrase != "open-sesame":
raise SSHAgentError("bad passphrase")
self.socket_path = generation / "fake-agent.sock"
self.public_key = _host_key()
self.alive = True
def close(self) -> None:
self.alive = False
def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
data_dir = tmp_path / "panel"
first = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh,
)
scan = first.scan("host.example", 22)
profile = HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], storage_pool="/home/kvm",
iso_pool="/home/iso", default_network="bridge:br0", region="东京",
public_pool_cidr="1.2.3.1/28", public_gateway="1.2.3.1",
public_dns_servers=["1.1.1.1", "8.8.8.8"],
public_reserved_ips=["1.2.3.10"], public_vm_prefix=24,
)
staged = first.stage(profile, scan["fingerprint"])
assert first.test(staged)["libvirt"] == "available"
current = first.commit(staged)
assert current["host"] == "host.example"
assert current["libvirt_uri"].find("runtime-wrappers") >= 0
assert ("host", "current") in store.records
assert not list(data_dir.rglob("id_private"))
assert not list(data_dir.rglob("profile.json"))
first.close()
second = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh,
)
assert second.current()["storage_pool"] == "/home/kvm"
assert second.current()["default_network"] == "bridge:br0"
assert second.current()["region"] == "东京"
assert second.current()["public_pool_cidr"] == "1.2.3.0/28"
assert second.current()["public_vm_prefix"] == 24
assert second.current()["public_gateway"] == "1.2.3.1"
assert second.current()["public_dns_servers"] == ["1.1.1.1", "8.8.8.8"]
assert second.current()["public_reserved_ips"] == ["1.2.3.10"]
assert (second._current_generation() / "id_private").read_text() == PRIVATE_KEY
assert not list(data_dir.rglob("id_private"))
second.close()
assert not list(runtime_parent.rglob("id_private"))
legacy = json.loads(store.records[("host", "current")])
legacy["metadata"].pop("region")
for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", "public_reserved_ips", "public_vm_prefix"):
legacy["metadata"].pop(key)
store.records[("host", "current")] = json.dumps(legacy)
third = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh,
)
assert third.current()["region"] == ""
assert third.current()["public_pool_cidr"] == ""
assert third.current()["public_gateway"] == ""
assert third.current()["public_dns_servers"] == []
assert third.current()["public_vm_prefix"] is None
third.close()
def test_host_commit_does_not_read_database_after_activation(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
manager = DatabaseRemoteHostManager(
store, tmp_path / "panel", runtime_parent=runtime_parent, runner=_fake_ssh,
)
scan = manager.scan("host.example", 22)
staged = manager.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"],
), scan["fingerprint"])
manager.test(staged)
original_get = store.get
reads = 0
def one_read_only(kind: str, key: str) -> str | None:
nonlocal reads
reads += 1
if reads > 1:
raise RuntimeError("database read unavailable after activation")
return original_get(kind, key)
store.get = one_read_only
assert manager.commit(staged)["host"] == "host.example"
assert reads == 1
assert ("host", "current") in store.records
manager.close()
def test_encrypted_host_key_auto_unlocks_after_process_restart(tmp_path: Path):
store = EncryptedMemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
data_dir = tmp_path / "panel"
first = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
scan = first.scan("host.example", 22)
staged = first.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
first.test(staged)
saved = first.commit(staged)
assert saved["key_locked"] is False
assert saved["private_key_passphrase_saved"] is True
ciphertext = store.records[("host", "current")]
assert ciphertext.startswith(b"vp1")
assert b"open-sesame" not in ciphertext
assert b"open-sesame" not in b"".join(
path.read_bytes() for path in data_dir.rglob("*") if path.is_file()
)
first.close()
second = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
assert second.current()["key_locked"] is False
assert second.current()["private_key_passphrase_saved"] is True
second.close()
def test_bad_saved_passphrase_keeps_host_locked_without_blocking_startup(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
data_dir = tmp_path / "panel"
first = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
scan = first.scan("host.example", 22)
staged = first.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
first.test(staged)
first.commit(staged)
first.close()
record = json.loads(store.get("host", "current"))
record["private_key_passphrase"] = "wrong-secret"
store.set("host", "current", json.dumps(record))
attempts = []
def counting_agent(*args):
attempts.append(1)
return FakeAgent(*args)
second = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=counting_agent,
)
assert len(attempts) == 1
assert second.current()["key_locked"] is True
assert second.current()["private_key_passphrase_saved"] is True
assert second.current_for_background()["key_locked"] is True
assert second.current_for_background()["key_locked"] is True
assert len(attempts) == 2
assert second.unlock_current("open-sesame")["key_locked"] is False
second.close()
def test_background_recovers_ssh_agent_after_it_exits(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
manager = DatabaseRemoteHostManager(
store, tmp_path / "panel", runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
scan = manager.scan("host.example", 22)
staged = manager.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
manager.test(staged)
manager.commit(staged)
generation = manager._current_generation()
manager._agents[generation].close()
assert manager.current()["key_locked"] is True
assert manager.current_for_background()["key_locked"] is False
manager.close()
def test_resaving_same_key_can_reuse_saved_passphrase(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
manager = DatabaseRemoteHostManager(
store, tmp_path / "panel", runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
scan = manager.scan("host.example", 22)
initial = manager.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
manager.test(initial)
manager.commit(initial)
for key in ("", PRIVATE_KEY):
staged = manager.stage(HostProfile(
host="host.example", port=22, private_key=key,
host_key=scan["known_hosts_line"], private_key_passphrase="",
), scan["fingerprint"])
manager.test(staged)
assert manager.commit(staged)["private_key_passphrase_saved"] is True
assert json.loads(store.get("host", "current"))["private_key_passphrase"] == "open-sesame"
manager.close()
def test_replacing_key_cannot_inherit_previous_passphrase(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
manager = DatabaseRemoteHostManager(
store, tmp_path / "panel", runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
scan = manager.scan("host.example", 22)
initial = manager.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
manager.test(initial)
manager.commit(initial)
previous = store.get("host", "current")
different_key = PRIVATE_KEY.replace("ZmFrZQ==", "b3RoZXI=")
with pytest.raises(RemoteHostError, match="填写私钥口令"):
manager.stage(HostProfile(
host="host.example", port=22, private_key=different_key,
host_key=scan["known_hosts_line"], private_key_passphrase="",
), scan["fingerprint"])
assert store.get("host", "current") == previous
manager.close()
def test_legacy_saved_host_requiring_password_remains_locked_until_resaved(tmp_path: Path):
store = MemoryStore()
runtime_parent = tmp_path / "simulated-tmpfs"
runtime_parent.mkdir()
data_dir = tmp_path / "panel"
first = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
scan = first.scan("host.example", 22)
initial = first.stage(HostProfile(
host="host.example", port=22, private_key=PRIVATE_KEY,
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
first.test(initial)
first.commit(initial)
record = json.loads(store.get("host", "current"))
record.pop("private_key_passphrase")
store.set("host", "current", json.dumps(record))
first.close()
second = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
assert second.current()["key_locked"] is True
assert second.current()["private_key_passphrase_saved"] is False
assert second.unlock_current("open-sesame")["key_locked"] is False
assert second.current()["private_key_passphrase_saved"] is False
staged = second.stage(HostProfile(
host="host.example", port=22, private_key="",
host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame",
), scan["fingerprint"])
second.test(staged)
assert second.commit(staged)["private_key_passphrase_saved"] is True
second.close()
third = DatabaseRemoteHostManager(
store, data_dir, runtime_parent=runtime_parent,
runner=_encrypted_ssh, agent_factory=FakeAgent,
)
assert third.current()["key_locked"] is False
third.close()
def test_startup_prunes_only_marked_runtime_of_dead_process(tmp_path: Path, monkeypatch):
dead = tmp_path / "v99999999-dead"
live = tmp_path / f"v{os.getpid()}-abcd"
dead.mkdir(mode=0o700)
live.mkdir(mode=0o700)
(dead / ".owner").write_text("99999999:123\n")
(live / ".owner").write_text(f"{os.getpid()}:456\n")
(dead / ".owner").chmod(0o600)
(live / ".owner").chmod(0o600)
monkeypatch.setattr(
DatabaseRemoteHostManager, "_process_start_ticks",
staticmethod(lambda pid: "456" if pid == os.getpid() else None),
)
DatabaseRemoteHostManager._clean_stale_runtime(tmp_path)
assert not dead.exists()
assert live.exists()

@ -0,0 +1,84 @@
"""The only local durable configuration is encrypted database bootstrap data."""
from __future__ import annotations
import json
import stat
import pytest
from virsh_panel.database_bootstrap import (
DatabaseBootstrap, DatabaseSetupError, validate_database_config,
)
CONFIG = {
"host": "db.example.test", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "not-a-public-database-password",
}
def test_bootstrap_requires_token_and_encrypts_connection_settings(tmp_path):
bootstrap = DatabaseBootstrap(tmp_path / "data")
token = bootstrap.ensure_token()
assert bootstrap.ensure_token() == token
calls = []
def connect(config, key):
calls.append((config, key))
return "connected"
with pytest.raises(DatabaseSetupError) as wrong:
bootstrap.configure(CONFIG, "wrong-token", connect)
assert wrong.value.status == 403
assert calls == []
assert bootstrap.configure(CONFIG, token, connect) == "connected"
assert len(calls[0][1]) == 32
assert bootstrap.load_config() == CONFIG
assert CONFIG["password"].encode() not in bootstrap.config_file.read_bytes()
assert CONFIG["username"].encode() not in bootstrap.config_file.read_bytes()
assert stat.S_IMODE(bootstrap.data_dir.stat().st_mode) == 0o700
assert stat.S_IMODE(bootstrap.key_file.stat().st_mode) == 0o600
assert stat.S_IMODE(bootstrap.config_file.stat().st_mode) == 0o600
with pytest.raises(DatabaseSetupError) as repeated:
bootstrap.configure(CONFIG, token, connect)
assert repeated.value.status == 409
def test_bootstrap_does_not_commit_failed_connection(tmp_path):
bootstrap = DatabaseBootstrap(tmp_path / "data")
token = bootstrap.ensure_token()
def fail(_config, _key):
raise ConnectionError("database unavailable")
with pytest.raises(ConnectionError):
bootstrap.configure(CONFIG, token, fail)
assert not bootstrap.configured()
assert bootstrap.ensure_token() == token
def test_bootstrap_rejects_tampering_and_unsafe_files(tmp_path):
bootstrap = DatabaseBootstrap(tmp_path / "data")
token = bootstrap.ensure_token()
bootstrap.configure(CONFIG, token, lambda *_: None)
envelope = json.loads(bootstrap.config_file.read_text())
envelope["ciphertext"] = "AAAA"
bootstrap.config_file.write_text(json.dumps(envelope))
with pytest.raises(ValueError, match="损坏"):
bootstrap.load_config()
bootstrap.config_file.chmod(0o644)
with pytest.raises(ValueError, match="0600"):
bootstrap.load_config()
@pytest.mark.parametrize("bad", [
{**CONFIG, "host": "https://evil.example"},
{**CONFIG, "port": 0},
{**CONFIG, "database": "other;DROP TABLE admin"},
{**CONFIG, "username": "bad\nname"},
{**CONFIG, "password": ""},
])
def test_database_config_validation_rejects_unsafe_values(bad):
with pytest.raises(DatabaseSetupError):
validate_database_config(bad)

@ -0,0 +1,439 @@
"""First-run database and update routes with isolated in-memory dependencies."""
from __future__ import annotations
import json
import stat
import sys
import threading
import types
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from types import SimpleNamespace
from fastapi.testclient import TestClient
# The HTTP boundary is tested with fake VM services; native libvirt is not
# available on ordinary development machines.
try:
import libvirt # noqa: F401
except ModuleNotFoundError:
stub = types.ModuleType("libvirt")
stub.libvirtError = type("libvirtError", (Exception,), {})
sys.modules["libvirt"] = stub
from virsh_panel import app as app_module
from virsh_panel.auth import hash_password
from virsh_panel.config import Settings
from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore
from virsh_panel.users import UserError, normalize_email
class MemoryUsers:
"""Only the SQL user-store boundary is replaced in isolated HTTP tests."""
def __init__(self, store):
self.store = store
def has_users(self):
return any(kind == "test_user" for kind, _key in self.store.records)
def get_by_username(self, username):
raw = self.store.get("test_user", username)
return json.loads(raw) if raw else None
def get_by_email(self, email):
try:
email = normalize_email(email)
except UserError:
return None
for (kind, _key), raw in self.store.records.items():
if kind == "test_user":
account = json.loads(raw)
if account["email"] == email:
return account
return None
def get_by_id(self, user_id):
for (kind, _key), raw in self.store.records.items():
if kind == "test_user":
user = json.loads(raw)
if user["id"] == user_id:
return user
return None
def create_initial_user(self, username, password, email=None):
email = normalize_email(email) if email is not None else None
account = {
"id": 1, "username": username, "email": email,
"password_hash": hash_password(password), "admin": False,
"approved": True, "email_verified": True, "created_at": 100,
}
self.store.set("test_user", username, json.dumps(account))
return account
def promote(self, username):
account = self.get_by_username(username)
account["admin"] = True
self.store.set("test_user", username, json.dumps(account))
def owns_vm(self, host_scope, vm_id, user_id):
return self.store.get("test_vm_owner", f"{host_scope}:{vm_id}") == str(user_id)
def assign_vm(self, host_scope, vm_id, user_id):
self.store.set("test_vm_owner", f"{host_scope}:{vm_id}", str(user_id))
def delete_vm_owner(self, host_scope, vm_id):
self.store.delete("test_vm_owner", f"{host_scope}:{vm_id}")
def list_owned_vm_ids(self, host_scope, user_id):
prefix = f"{host_scope}:"
return {key[len(prefix):] for key, owner in self.store.list("test_vm_owner").items()
if key.startswith(prefix) and owner == str(user_id)}
def list_pending_users(self):
pending = []
for (kind, _key), raw in self.store.records.items():
if kind == "test_user":
account = json.loads(raw)
if not account["approved"]:
pending.append({key: value for key, value in account.items()
if key != "password_hash"})
return pending
def approve_user(self, user_id):
account = self.get_by_id(user_id)
if account is None:
return None
account["approved"] = True
self.store.set("test_user", account["username"], json.dumps(account))
return account
@staticmethod
def generate_code():
return "123456"
def issue_registration_code(self, email, code):
if any(json.loads(raw)["email"] == email for (kind, _key), raw in self.store.records.items()
if kind == "test_user"):
return False
self.store.set("test_code", email, code)
return True
def revoke_registration_code(self, email, code):
if self.store.get("test_code", email) != code:
return False
self.store.delete("test_code", email)
return True
def register_with_code(self, username, email, password, code):
if self.store.get("test_code", email) != code:
raise UserError("验证码无效或已过期")
email = normalize_email(email)
if self.get_by_username(username) is not None or self.get_by_email(email) is not None:
raise UserError("用户名或邮箱已存在", 409)
account = {
"id": 1 + sum(kind == "test_user" for kind, _key in self.store.records),
"username": username, "email": email,
"password_hash": hash_password(password), "admin": False,
"approved": False, "email_verified": True, "created_at": 101,
}
self.store.set("test_user", username, json.dumps(account))
self.store.delete("test_code", email)
return account
class MemoryStore:
def __init__(self) -> None:
self.records = {}
self.users = MemoryUsers(self)
def get(self, kind, key):
return self.records.get((kind, key))
def set(self, kind, key, value):
self.records[(kind, key)] = value
def insert(self, kind, key, value):
if (kind, key) in self.records:
return False
self.set(kind, key, value)
return True
def delete(self, kind, key):
self.records.pop((kind, key), None)
def list(self, kind):
return {key: value for (record_type, key), value in self.records.items()
if record_type == kind}
def get_secret(self, key):
return self.get("secret", key)
def set_secret(self, key, value):
self.set("secret", key, value)
def get_value(self, key):
return self.get("value", key)
def set_value(self, key, value):
self.set("value", key, value)
class FakeManager:
def current(self):
return None
def close(self):
pass
def test_first_run_requires_database_then_admin_and_ignores_old_json(monkeypatch, tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
(data_dir / "state.json").write_text(
'{"version":1,"admin":{"username":"old","password_hash":"old"}}',
encoding="utf-8",
)
store = MemoryStore()
calls = []
def make_components(directory, config, key, _ssh_binary):
calls.append((config, key))
return (DatabasePanelState(directory, store, store.users), FakeManager(),
DatabaseTemplateStore(store), store)
monkeypatch.setattr(app_module, "make_components", make_components)
settings = Settings(data_dir=data_dir,
static_dir=Path(__file__).resolve().parents[1] / "static")
app = app_module.create_app(settings)
token = (data_dir / "setup-token").read_text(encoding="ascii").strip()
config = {
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "test-database-password",
}
with TestClient(app, base_url="https://panel.example.test") as client:
assert client.get("/api/v1/database/status").json() == {
"configured": False, "setup_required": True,
}
assert client.get("/api/v1/setup/status").status_code == 409
assert client.post("/api/v1/database/setup", json={
**config, "setup_token": "invalid",
}).status_code == 403
assert calls == []
response = client.post("/api/v1/database/setup", json={
**config, "setup_token": token,
})
assert response.status_code == 200
assert response.json() == {"configured": True}
assert calls[0][0] == config and len(calls[0][1]) == 32
assert client.get("/api/v1/setup/status").json() == {"setup_required": True}
created = client.post("/api/v1/setup/admin", json={
"token": token, "username": "admin",
"password": "correct-horse-battery-staple",
})
assert created.status_code == 200
assert client.get("/api/v1/setup/status").json() == {"setup_required": False}
session_cookie = client.cookies.get("virsh_panel_session")
assert ("test_user", "admin") in store.records
assert store.users.get_by_username("admin")["admin"] is False
assert store.users.get_by_username("admin")["email"] is None
assert store.users.get_by_email("admin@example.test") is None
assert not (data_dir / "setup-token").exists()
encrypted = (data_dir / "database-config.json").read_bytes()
assert b"test-database-password" not in encrypted
assert stat.S_IMODE((data_dir / "master.key").stat().st_mode) == 0o600
store.set("import_job", "interrupted-job", json.dumps({
"status": "running", "scope": "previous-host",
}))
restarted = app_module.create_app(settings)
assert json.loads(store.get("import_job", "interrupted-job"))["status"] == "failed"
with TestClient(restarted, base_url="https://panel.example.test") as client:
client.cookies.set("virsh_panel_session", session_cookie)
assert client.get("/api/v1/session").json()["authenticated"] is True
def test_update_routes_require_auth_and_never_return_token(monkeypatch, tmp_path):
data_dir = tmp_path / "data"
store = MemoryStore()
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), FakeManager(),
DatabaseTemplateStore(store), store,
))
settings = Settings(data_dir=data_dir,
static_dir=Path(__file__).resolve().parents[1] / "static")
app = app_module.create_app(settings)
token = (data_dir / "setup-token").read_text(encoding="ascii").strip()
class FakeUpdater:
def __init__(self, *_args):
self.token = None
self.job = None
def settings(self):
return {
"repository": "https://g.luoli.live/root/virt.git", "branch": "main",
"token_configured": self.token is not None, "checkout_ready": True,
"current_commit": "a" * 40, "active_job_id": None,
}
def set_token(self, token):
self.token = token
def check(self):
return {
"repository": "https://g.luoli.live/root/virt.git", "branch": "main",
"current_commit": "a" * 40, "remote_commit": "b" * 40,
"status": "update_available",
}
def create_job(self, *, expected_current_commit=None, expected_remote_commit=None):
assert expected_current_commit == "a" * 40
assert expected_remote_commit == "b" * 40
self.job = {"job_id": "test-job-00000001", "status": "queued"}
return self.job
def get_job(self, job_id):
return self.job if self.job and job_id == self.job["job_id"] else None
def fail_job(self, job_id, error):
self.job = {"job_id": job_id, "status": "failed", "error": error}
monkeypatch.setattr(app_module, "Updater", FakeUpdater)
monkeypatch.setattr(app_module.subprocess, "run", lambda *args, **kwargs:
SimpleNamespace(returncode=0, stdout="inactive"))
with TestClient(app, base_url="https://panel.example.test") as client:
assert client.get("/api/v1/update/settings").status_code == 401
client.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "test-database-password",
"setup_token": token,
})
response = client.post("/api/v1/setup/admin", json={
"token": token, "username": "admin",
"password": "correct-horse-battery-staple",
})
assert response.status_code == 200
store.users.promote("admin")
csrf = response.json()["csrf_token"]
assert client.put("/api/v1/update/settings", json={
"access_token": "some-very-private-gitea-token",
}).status_code == 403
saved = client.put("/api/v1/update/settings", json={
"access_token": "some-very-private-gitea-token",
}, headers={"X-CSRF-Token": csrf})
assert saved.status_code == 200
assert saved.json()["configured"] is True
assert "some-very-private-gitea-token" not in saved.text
checked = client.post("/api/v1/update/check", headers={
"X-CSRF-Token": csrf,
})
assert checked.status_code == 200
assert checked.json()["update_available"] is True
queued = client.post("/api/v1/update/apply", json={
"expected_current_commit": "a" * 40,
"expected_remote_commit": "b" * 40,
}, headers={
"X-CSRF-Token": csrf,
})
assert queued.status_code == 202
job_id = queued.json()["job_id"]
assert client.get(f"/api/v1/update/jobs/{job_id}").json()["status"] == "queued"
def test_vm_creation_finishes_before_update_is_queued(monkeypatch, tmp_path):
data_dir = tmp_path / "data"
store = MemoryStore()
vm_started = threading.Event()
release_vm = threading.Event()
update_received = threading.Event()
update_queued = threading.Event()
class ConfiguredManager(FakeManager):
def current(self):
return {"key_locked": False}
class BlockingVMService:
def create_vm(self, spec):
vm_started.set()
assert release_vm.wait(timeout=5), "test did not release VM creation"
return {"uuid": spec["vm_uuid"]}
class FakeUpdater:
def __init__(self, _repo_dir, data_store):
self.store = data_store
self.job = None
def create_job(self, **_kwargs):
self.job = {"job_id": "test-job-00000001", "status": "queued"}
self.store.set_value("update.active_job", self.job["job_id"])
update_queued.set()
return self.job
def get_job(self, job_id):
return self.job if self.job and job_id == self.job["job_id"] else None
def fail_job(self, _job_id, _message):
raise AssertionError("the mocked update service must start")
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), ConfiguredManager(),
DatabaseTemplateStore(store), store,
))
monkeypatch.setattr(app_module, "Updater", FakeUpdater)
monkeypatch.setattr(
app_module.subprocess, "run",
lambda argv, **_kwargs: SimpleNamespace(
returncode=3 if "is-active" in argv else 0,
stdout="inactive" if "is-active" in argv else "",
),
)
settings = Settings(data_dir=data_dir,
static_dir=Path(__file__).resolve().parents[1] / "static")
app = app_module.create_app(settings, service_factory=lambda _profile: BlockingVMService())
@app.middleware("http")
async def observe_update(request, call_next):
if request.url.path == "/api/v1/update/apply":
update_received.set()
return await call_next(request)
token = (data_dir / "setup-token").read_text(encoding="ascii").strip()
with TestClient(app, base_url="https://panel.example.test") as client:
configured = client.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "test-database-password",
"setup_token": token,
})
assert configured.status_code == 200
admin = client.post("/api/v1/setup/admin", json={
"token": token, "username": "admin",
"password": "correct-horse-battery-staple",
})
assert admin.status_code == 200
store.users.promote("admin")
headers = {"X-CSRF-Token": admin.json()["csrf_token"]}
with ThreadPoolExecutor(max_workers=2) as executor:
creating = executor.submit(client.post, "/api/v1/vms", json={
"name": "new-vm", "vcpu": 2, "memory_mib": 2048,
"disk_gib": 20, "network": "default", "iso": "AlmaLinux-10.iso",
}, headers=headers)
assert vm_started.wait(timeout=5)
updating = executor.submit(client.post, "/api/v1/update/apply", json={
"expected_current_commit": "a" * 40,
"expected_remote_commit": "b" * 40,
}, headers=headers)
try:
assert update_received.wait(timeout=5)
assert not update_queued.wait(timeout=0.2)
assert not updating.done()
finally:
release_vm.set()
assert creating.result(timeout=5).status_code == 201
assert updating.result(timeout=5).status_code == 202
assert update_queued.is_set()
blocked = client.post("/api/v1/vms", json={
"name": "another-vm", "vcpu": 2, "memory_mib": 2048,
"disk_gib": 20, "network": "default", "iso": "AlmaLinux-10.iso",
}, headers=headers)
assert blocked.status_code == 409

@ -0,0 +1,413 @@
"""Private engine tests: no PHP cookies, no real DB and no real hypervisor."""
from __future__ import annotations
import base64
import asyncio
import hashlib
import json
import threading
from contextlib import contextmanager
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from test_app import CREATE_BODY, FakeRemoteManager, FakeVMService, HOST_BODY, VM_ID
from virsh_panel.app import create_app
from virsh_panel.config import Settings
from virsh_panel.database import DatabaseTemplateStore
from virsh_panel.engine_context import (EngineComponents, ExternalOwnership, HostStore,
LogStore, MainStore, TRUSTED_ACTOR)
from virsh_panel.engine_security import (EngineAuthError, authenticate, encode_actor,
signed_headers)
from virsh_panel.internal import EngineApplication, HostRegistry
from virsh_panel.metrics import host_scope
SECRET = b"s" * 32
USER = {"user_id": 41, "is_admin": False, "is_super_admin": False,
"can_manage": True, "session_id": "test-session"}
SUPER = {**USER, "user_id": 1, "is_admin": True, "is_super_admin": True}
ADMIN = {**SUPER, "is_super_admin": False}
class MemoryStore:
def __init__(self):
self.records = {}
self.nonces = set()
self.lock = threading.RLock()
def get(self, kind, key):
with self.lock:
return self.records.get((kind, key))
def set(self, kind, key, value):
with self.lock:
self.records[kind, key] = value
def insert(self, kind, key, value):
with self.lock:
if (kind, key) in self.records:
return False
self.records[kind, key] = value
return True
def delete(self, kind, key):
with self.lock:
self.records.pop((kind, key), None)
def list(self, kind):
with self.lock:
return {key: value for (row_kind, key), value in self.records.items() if row_kind == kind}
def consume_nonce(self, nonce, expires_at, now):
with self.lock:
if nonce in self.nonces:
return False
self.nonces.add(nonce)
return True
def query_metric_samples(self, *args, **kwargs):
return [{"timestamp": 123, "cpu_percent": 20.0}]
class Service(FakeVMService):
def __init__(self):
super().__init__()
self.create_failure = False
self.absent = False
self.vm.update(managed=True, os_source="iso")
def create_vm(self, spec):
self.calls.append(("create_vm", spec))
if self.create_failure:
from virsh_panel.libvirt_service import VMError
raise VMError("宿主机失联,回滚状态不明", 502)
self.vm.update(uuid=spec["vm_uuid"], name=spec["name"])
return self.vm.copy()
def provisioning_absent(self, vm_uuid, name):
return self.absent
@pytest.fixture
def boundary(tmp_path):
store = MemoryStore()
logs = MemoryStore()
config = {"service_secret": base64.b64encode(SECRET).decode(), "data_dir": str(tmp_path)}
services = {}
def factory(host_id):
(tmp_path / host_id).mkdir(mode=0o700, exist_ok=True)
scoped = HostStore(store, host_id)
manager = FakeRemoteManager()
manager.profile = {"host_id": host_id, "host": "host.example.test", "port": 22,
"fingerprint": "SHA256:example", "key_locked": False, "storage_pool": "images",
"iso_pool": "iso", "rescue_iso_pool": "rescue", "default_network": "default",
"libvirt_uri": "fake", "ssh_target": "fake", "ssh_config_file": "/fake/config",
"ssh_known_hosts_file": "/fake/known_hosts"}
service = Service()
services[host_id] = service
components = EngineComponents(SimpleNamespace(users=ExternalOwnership(scoped)), manager,
DatabaseTemplateStore(scoped), scoped, logs)
app = create_app(Settings(data_dir=tmp_path / host_id), engine_components=components,
service_factory=lambda profile: service)
return components, app
registry = HostRegistry(config, store, logs, factory=factory)
async def active(*args):
return True
engine = EngineApplication(config, store, logs, registry=registry, introspection=active)
engine._service = lambda profile: services[profile["host_id"]]
with TestClient(engine, base_url="http://127.0.0.1") as client:
yield client, engine, store, logs, services
def call(client, method, path, actor=USER, value=None, raw=None, headers=None):
body = raw if raw is not None else b"" if value is None else json.dumps(value, separators=(",", ":")).encode()
signed = signed_headers(SECRET, method, path, body, actor)
if value is not None:
signed["Content-Type"] = "application/json"
signed.update(headers or {})
return client.request(method, path, content=body, headers=signed)
def test_hmac_binds_actor_payload_target_and_rejects_replay():
store = MemoryStore()
body = b"{}"
target = "/internal/v1/hosts/hk/vms?range=1h"
headers = {key.lower(): value for key, value in signed_headers(SECRET, "POST", target, body, USER,
timestamp=1000, nonce="n" * 24).items()}
assert authenticate(headers, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1000) == USER
with pytest.raises(EngineAuthError):
authenticate(headers, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1000)
changed = {**headers, "x-cloud-actor": encode_actor(SUPER)}
with pytest.raises(EngineAuthError):
authenticate(changed, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1000)
with pytest.raises(EngineAuthError):
authenticate(headers, SECRET, "POST", target + "x", hashlib.sha256(body).hexdigest(), store, now=1000)
with pytest.raises(EngineAuthError):
authenticate(headers, SECRET, "POST", target, hashlib.sha256(b"other").hexdigest(), store, now=1000)
with pytest.raises(EngineAuthError):
authenticate(headers, SECRET, "POST", target, hashlib.sha256(body).hexdigest(), store, now=1061)
def test_private_route_allowlist_and_no_browser_admin_cookie(boundary):
client, *_ = boundary
for path in ("/api/v1/vms", "/internal/v1/hosts/hk/register", "/internal/v1/hosts/hk/setup/admin",
"/internal/v1/hosts/hk/update/apply", "/internal/v1/hosts/hk/smtp/settings"):
assert call(client, "POST", path, SUPER, {}).status_code == 404
assert client.get("/internal/v1/hosts/hk/vms", cookies={"virsh_panel_session": "admin"}).status_code == 401
assert TRUSTED_ACTOR.get() is None
def test_user_admin_super_admin_boundaries_and_cross_user_vm(boundary):
client, engine, *_ = boundary
path = "/internal/v1/hosts/hk"
assert call(client, "GET", path + "/host").status_code == 403
assert call(client, "GET", path + "/host", ADMIN).status_code == 200
assert call(client, "POST", path + "/host/scan", ADMIN, {"host": "x", "port": 22}).status_code == 403
assert call(client, "POST", path + "/host/scan", SUPER, {"host": "x", "port": 22}).status_code == 200
assert call(client, "POST", "/internal/v1/hosts/scan", ADMIN, {"host": "x", "port": 22}).status_code == 403
component = engine.registry.components["hk"]
component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41)
assert call(client, "GET", path + f"/vms/{VM_ID}").status_code == 200
assert call(client, "GET", path + f"/vms/{VM_ID}", {**USER, "user_id": 42}).status_code == 404
assert call(client, "GET", path + "/vms", {**USER, "user_id": 42}).json()["items"] == []
assert call(client, "POST", path + f"/vms/{VM_ID}/actions", {**USER, "can_manage": False},
{"action": "reboot"}).status_code == 403
def test_stable_host_identity_and_namespaces():
store = MemoryStore()
first, second = HostStore(store, "a"), HostStore(store, "b")
first.set("host", "current", "one")
second.set("host", "current", "two")
assert first.get("host", "current") == "one"
assert second.get("host", "current") == "two"
a = {"host_id": "a", "host": "1.2.3.4", "port": 22, "fingerprint": "old"}
assert host_scope(a) == host_scope({**a, "host": "changed", "port": 2222, "fingerprint": "new"})
assert host_scope(a) != host_scope({**a, "host_id": "b"})
assert MainStore.RECORD_TABLE == "engine_records"
assert LogStore.METRIC_TABLE == "engine_vm_metric_samples"
def test_only_paid_operations_can_create_and_retry_never_duplicates(boundary):
client, engine, store, _, services = boundary
path = "/internal/v1/hosts/hk/vms"
assert call(client, "POST", path, USER, CREATE_BODY).status_code == 403
provisioning = {**USER, "can_provision": True, "operation_id": "order-000001"}
created = call(client, "POST", path, provisioning, CREATE_BODY)
assert created.status_code == 201, created.text
vm_id = created.json()["uuid"]
assert created.json()["result"]["uuid"] == vm_id
assert created.json()["status"] == "succeeded"
component = engine.registry.components["hk"]
assert component.state.users.owns_vm(host_scope(component.manager.profile), vm_id, 41)
again = call(client, "POST", path, provisioning, CREATE_BODY)
assert again.status_code == 201 and again.json()["uuid"] == vm_id
assert len([row for row in services["hk"].calls if row[0] == "create_vm"]) == 1
assert call(client, "POST", path, provisioning, {**CREATE_BODY, "vcpu": 4}).status_code == 409
operation = call(client, "GET", "/internal/v1/operations/order-000001").json()
assert operation["status"] == "succeeded" and operation["result"]["uuid"] == vm_id
assert operation["safe_to_refund"] is False
assert call(client, "GET", "/internal/v1/operations/order-000001", {**USER, "user_id": 42}).status_code == 404
def test_uncertain_creation_never_refunds_or_recreates(boundary):
client, engine, store, _, services = boundary
path = "/internal/v1/hosts/hk/vms"
call(client, "GET", path)
services["hk"].create_failure = True
actor = {**USER, "can_provision": True, "operation_id": "order-uncertain"}
failed = call(client, "POST", path, actor, CREATE_BODY)
assert failed.status_code == 502
assert failed.json()["status"] == "uncertain" and not failed.json()["safe_to_refund"]
record = json.loads(store.get("operation", "order-uncertain"))
component = engine.registry.components["hk"]
scope = host_scope(component.manager.profile)
assert component.state.users.owns_vm(scope, record["vm_uuid"], 41)
component.store.set("vm_credential", f"{scope}.{record['vm_uuid']}", "saved-password")
component.store.set("ip_claim", f"{scope}.192.0.2.1", json.dumps({"vm_uuid": record["vm_uuid"]}))
again = call(client, "POST", path, actor, CREATE_BODY)
assert again.status_code == 202 and again.json()["status"] == "uncertain"
assert len([row for row in services["hk"].calls if row[0] == "create_vm"]) == 1
services["hk"].absent = True
operation = call(client, "GET", "/internal/v1/operations/order-uncertain").json()
assert operation["status"] == "failed" and operation["safe_to_refund"] is True
assert not component.state.users.owns_vm(scope, record["vm_uuid"], 41)
assert component.store.get("vm_credential", f"{scope}.{record['vm_uuid']}") is None
assert component.store.list("ip_claim") == {}
@pytest.mark.parametrize("payload", [{"name": "invalid"}, ["not-an-object"],
{**CREATE_BODY, "guest_ssh_key_id": 3}])
def test_rejected_create_has_durable_safe_failure_even_when_response_is_lost(boundary, payload):
client, engine, _, _, services = boundary
path = "/internal/v1/hosts/hk/vms"
actor = {**USER, "can_provision": True, "operation_id": "rejected-create"}
response = call(client, "POST", path, actor, payload)
assert response.status_code == 422
# Simulate a dispatcher losing the POST response and querying after restart.
engine.active_operations.clear()
saved = call(client, "GET", "/internal/v1/operations/rejected-create").json()
assert saved["status"] == "failed" and saved["safe_to_refund"] is True
assert call(client, "POST", path, actor, payload).status_code == 422
assert call(client, "POST", path, actor, CREATE_BODY).status_code == 409
assert not any(row[0] == "create_vm" for row in services["hk"].calls)
def test_admin_created_vm_also_has_external_owner(boundary):
client, engine, *_ = boundary
actor = {**SUPER, "can_provision": True, "operation_id": "order-admin"}
response = call(client, "POST", "/internal/v1/hosts/hk/vms", actor, CREATE_BODY)
assert response.status_code == 201
components = engine.registry.components["hk"]
assert components.state.users.owns_vm(host_scope(components.manager.profile), response.json()["uuid"], 1)
def test_power_action_has_persistent_idempotency(boundary):
client, engine, _, _, services = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
components = engine.registry.components["hk"]
components.state.users.assign_vm(host_scope(components.manager.profile), VM_ID, 41)
path = f"/internal/v1/hosts/hk/vms/{VM_ID}/actions"
assert call(client, "POST", path, USER, {"action": "reboot"}).status_code == 403
actor = {**USER, "operation_id": "reboot-operation"}
assert call(client, "POST", path, actor, {"action": "reboot"}).status_code == 200
assert call(client, "POST", path, actor, {"action": "reboot"}).status_code == 200
assert len([row for row in services["hk"].calls if row[0] == "action"]) == 1
assert call(client, "POST", path, actor, {"action": "poweroff"}).status_code == 409
operation = call(client, "GET", "/internal/v1/operations/reboot-operation").json()
assert operation["status"] == "succeeded" and operation["safe_to_refund"] is False
def test_async_mutation_operation_survives_lost_job_response_and_does_not_retry(boundary):
client, engine, store, *_ = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
components = engine.registry.components["hk"]
job = {"operation_id": "lost-rescue-job", "owner": "php:41", "vm_id": VM_ID,
"status": "running", "phase": "正在救援"}
components.store.set("rescue_job", "job-abc", json.dumps(job))
operation = {"operation_id": "lost-rescue-job", "host_id": "hk", "user_id": 41,
"kind": "mutation", "resource": f"vms/{VM_ID}/rescue", "vm_uuid": VM_ID,
"status": "uncertain", "result": None, "safe_to_refund": False}
store.set("operation", "lost-rescue-job", json.dumps(operation))
recovered = call(client, "GET", "/internal/v1/operations/lost-rescue-job").json()
assert recovered["status"] == "running" and recovered["result"]["vm_id"] == VM_ID
job.update(status="completed", phase="救援系统启动")
components.store.set("rescue_job", "job-abc", json.dumps(job))
completed = call(client, "GET", "/internal/v1/operations/lost-rescue-job").json()
assert completed["status"] == "succeeded"
assert not completed["safe_to_refund"]
def test_interrupted_async_job_stays_uncertain(boundary):
client, engine, store, *_ = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
components = engine.registry.components["hk"]
components.store.set("reinstall_job", "job-abcd", json.dumps({
"operation_id": "interrupted-job", "owner": "php:41", "vm_id": VM_ID,
"status": "failed", "phase": "面板重启,任务已中断"}))
store.set("operation", "interrupted-job", json.dumps({"operation_id": "interrupted-job",
"host_id": "hk", "user_id": 41, "kind": "mutation", "resource": f"vms/{VM_ID}/reinstall",
"vm_uuid": VM_ID, "status": "pending", "result": None, "safe_to_refund": False}))
recovered = call(client, "GET", "/internal/v1/operations/interrupted-job").json()
assert recovered["status"] == "uncertain"
def test_metrics_query_uses_log_store_and_owner_permission(boundary):
client, engine, *_ = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
component = engine.registry.components["hk"]
component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41)
response = call(client, "GET", f"/internal/v1/hosts/hk/vms/{VM_ID}/metrics?range=30d")
assert response.status_code == 200 and response.json()["points"][0]["cpu_percent"] == 20
def test_console_ticket_is_one_use_session_bound_and_no_url_secret(boundary):
client, engine, store, *_ = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
component = engine.registry.components["hk"]
component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41)
issued = call(client, "POST", f"/internal/v1/hosts/hk/vms/{VM_ID}/console-ticket", USER, {})
assert issued.status_code == 200, issued.text
assert issued.json()["websocket_path"] == "/engine-console"
ticket = issued.json()["ticket"]
key = hashlib.sha256(ticket.encode()).hexdigest()
record = json.loads(store.get("console_ticket", key))
assert record["actor"]["user_id"] == 41 and record["actor"]["session_id"] == "test-session"
assert call(client, "POST", f"/internal/v1/hosts/hk/vms/{VM_ID}/console-ticket",
{**USER, "user_id": 42}, {}).status_code == 404
from starlette.websockets import WebSocketDisconnect
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("wss://panel.example.test/engine-console", headers={"Origin": "https://evil.example"},
subprotocols=["cloud-ticket." + ticket]):
pass
assert store.get("console_ticket", key) is not None
def test_console_consumes_ticket_and_closes_after_php_session_revocation(boundary):
client, engine, store, *_ = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
component = engine.registry.components["hk"]
component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41)
checks = 0
async def active(*args):
nonlocal checks
checks += 1
return checks <= 2 # Ticket issuance + handshake; then PHP revokes.
engine.introspection = active
engine.console_check_interval = 0.01
issued = call(client, "POST", f"/internal/v1/hosts/hk/vms/{VM_ID}/console-ticket", USER, {})
ticket = issued.json()["ticket"]
protocol = "cloud-ticket." + ticket
async def relay(socket, **kwargs):
await socket.send_bytes(b"vnc")
await asyncio.Event().wait()
from starlette.websockets import WebSocketDisconnect
with patch("virsh_panel.console.relay_console", relay):
with client.websocket_connect("wss://panel.example.test/engine-console",
headers={"Origin": "https://panel.example.test"}, subprotocols=[protocol]) as socket:
assert socket.accepted_subprotocol == protocol
assert socket.receive_bytes() == b"vnc"
with pytest.raises(WebSocketDisconnect):
socket.receive_bytes()
key = hashlib.sha256(ticket.encode()).hexdigest()
assert store.get("console_ticket", key) is None
assert store.get("ticket_used", key) == "1"
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("wss://panel.example.test/engine-console",
headers={"Origin": "https://panel.example.test"}, subprotocols=[protocol]):
pass
def test_streamed_iso_digest_must_match_before_import_is_queued(boundary):
client, engine, store, _, services = boundary
path = "/internal/v1/hosts/hk/rescue-templates?name=rescue"
signed_body = b"A" * (1024 * 1024)
wrong_body = b"B" * len(signed_body)
signed = signed_headers(SECRET, "POST", path, signed_body, SUPER)
signed["X-Cloud-Content-SHA256"] = hashlib.sha256(signed_body).hexdigest()
signed["Content-Type"] = "application/octet-stream"
response = client.post(path, content=wrong_body, headers=signed)
assert response.status_code == 401, response.text
assert not any(row[0] == "import_rescue_iso" for row in services["hk"].calls)
assert engine.registry.components["hk"].store.list("rescue_import_job") == {}
def test_main_and_log_schema_do_not_create_python_accounts_or_cross_database_tables():
connection = MagicMock()
cursor = connection.cursor.return_value.__enter__.return_value
config = {"host": "db", "port": 3306, "database": "main", "username": "engine", "password": "test",
"ssl_ca": "/private/test/ca.pem"}
with patch("virsh_panel.database.pymysql.connect", return_value=connection):
main = MainStore(config, b"m" * 32)
statements = [call.args[0] for call in cursor.execute.call_args_list]
assert any("engine_records" in statement for statement in statements)
assert not any("CREATE TABLE IF NOT EXISTS users" in statement for statement in statements)
assert not any("vm_metric_samples" in statement for statement in statements)
assert main._config["ssl_verify_identity"] is True
cursor.reset_mock()
LogStore({**config, "database": "logs"}, b"m" * 32)
statements = [call.args[0] for call in cursor.execute.call_args_list]
assert len(statements) == 1 and "engine_vm_metric_samples" in statements[0]

@ -0,0 +1,200 @@
"""Keep VM creation and reinstall in the dashboard, not in modal dialogs."""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
from html.parser import HTMLParser
from pathlib import Path
import pytest
STATIC_DIR = Path(__file__).resolve().parents[1] / "static"
VOID_TAGS = {
"area", "base", "br", "col", "embed", "hr", "img", "input",
"link", "meta", "param", "source", "track", "wbr",
}
@dataclass(frozen=True)
class Element:
tag: str
attrs: dict[str, str | None]
ancestors: tuple[Element, ...]
@property
def element_id(self) -> str | None:
return self.attrs.get("id")
class PageParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.stack: list[Element] = []
self.elements: list[Element] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
element = Element(tag, dict(attrs), tuple(self.stack))
self.elements.append(element)
if tag not in VOID_TAGS:
self.stack.append(element)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.elements.append(Element(tag, dict(attrs), tuple(self.stack)))
def handle_endtag(self, tag: str) -> None:
for index in range(len(self.stack) - 1, -1, -1):
if self.stack[index].tag == tag:
del self.stack[index:]
return
@pytest.fixture(scope="module")
def page() -> tuple[list[Element], dict[str, list[Element]]]:
parser = PageParser()
parser.feed((STATIC_DIR / "index.html").read_text(encoding="utf-8"))
assert not parser.stack, "Unclosed HTML element in the dashboard page"
by_id: dict[str, list[Element]] = defaultdict(list)
for element in parser.elements:
if element.element_id:
by_id[element.element_id].append(element)
return parser.elements, by_id
@pytest.mark.parametrize("prefix", ["create", "reinstall"])
def test_vm_form_is_a_dashboard_page_not_a_modal(page, prefix: str) -> None:
_, by_id = page
forms = by_id[f"{prefix}-form"]
assert len(forms) == 1
form = forms[0]
assert form.tag == "form"
ancestor_ids = {ancestor.element_id for ancestor in form.ancestors}
assert {"dashboard-view", "vm-workspace", f"{prefix}-view"} <= ancestor_ids
for element in (*form.ancestors, form):
assert element.tag != "dialog"
assert element.attrs.get("role") != "dialog"
assert "modal-backdrop" not in (element.attrs.get("class") or "").split()
back_buttons = by_id[f"{prefix}-back"]
assert len(back_buttons) == 1
assert back_buttons[0].tag == "button"
assert f"{prefix}-view" in {
ancestor.element_id for ancestor in back_buttons[0].ancestors
}
def test_old_vm_modal_elements_and_js_references_are_removed(page) -> None:
_, by_id = page
script = (STATIC_DIR / "app.js").read_text(encoding="utf-8")
for element_id in ("create-modal", "reinstall-modal"):
assert element_id not in by_id
assert element_id not in script
def test_every_html_id_is_unique(page) -> None:
_, by_id = page
duplicates = sorted(element_id for element_id, elements in by_id.items() if len(elements) > 1)
assert duplicates == []
def test_rescue_iso_pool_is_a_distinct_host_setting(page) -> None:
_, by_id = page
rescue_pool = by_id["host-rescue-iso-pool"][0]
assert rescue_pool.tag == "input"
assert rescue_pool.attrs["name"] == "rescue_iso_pool"
assert "required" not in rescue_pool.attrs # Existing installations can configure it later.
assert "host-form" in {ancestor.element_id for ancestor in rescue_pool.ancestors}
assert "rescue-templates-workspace" in {
ancestor.element_id for ancestor in by_id["rescue-directory-note"][0].ancestors
}
html = (STATIC_DIR / "index.html").read_text(encoding="utf-8")
assert "面板只注册已存在的目录,不会自动创建" in html
assert "不会出现在创建虚拟机的安装 ISO 列表中" in html
script = (STATIC_DIR / "app.js").read_text(encoding="utf-8")
assert 'byId("host-rescue-iso-pool").value = configured ? (hostConfig.rescue_iso_pool || "") : "";' in script
assert 'rescue_iso_pool: rescueIsoPool' in script
assert 'rescueIsoPool && rescueIsoPool === isoPool' in script
assert '"host-iso-pool", "host-rescue-iso-pool", "host-network"' in script
assert 'text("rescue-directory-note", rescueIsoPool' in script
def test_rescue_pages_are_separate_dashboard_pages(page) -> None:
_, by_id = page
rescue = by_id["rescue-view"][0]
assert {ancestor.element_id for ancestor in rescue.ancestors} >= {
"dashboard-view", "vm-workspace",
}
assert "hidden" in rescue.attrs
form = by_id["rescue-form"][0]
assert "rescue-view" in {ancestor.element_id for ancestor in form.ancestors}
assert "modal-backdrop" not in {
token
for ancestor in (*form.ancestors, form)
for token in (ancestor.attrs.get("class") or "").split()
}
catalog = by_id["rescue-templates-workspace"][0]
assert "dashboard-view" in {ancestor.element_id for ancestor in catalog.ancestors}
assert "hidden" in catalog.attrs
upload = by_id["rescue-template-upload-form"][0]
assert "rescue-templates-workspace" in {
ancestor.element_id for ancestor in upload.ancestors
}
assert by_id["rescue-template-file"][0].attrs["type"] == "file"
def test_rescue_frontend_uses_streaming_upload_and_job_status(page) -> None:
_, by_id = page
assert by_id["rescue-templates-button"][0].tag == "button"
assert by_id["rescue-templates-mobile-button"][0].tag == "button"
script = (STATIC_DIR / "app.js").read_text(encoding="utf-8")
assert '"rescue-templates-button", "rescue-templates-mobile-button"' in script
assert 'rawBody: file, contentType: "application/octet-stream"' in script
assert "file.text()" not in script.split(
'byId("rescue-template-upload-form").addEventListener', 1
)[1].split("async function startRescueVmAction", 1)[0]
assert '"/api/v1/rescue-templates"' in script
assert '/rescue/exit`' in script
assert 'pollRescueImport(jobId' in script
assert 'pollVmRescueJob(jobId' in script
assert 'actionButton("紧急救援"' in script
assert 'const rescueMode = vm.rescue_mode === true;' in script
assert 'const rescueStaged = vm.rescue_staged === true;' in script
assert 'const rescueGuard = rescueMode || rescueStaged;' in script
assert 'typeof job.warning === "string"' in script
html = (STATIC_DIR / "index.html").read_text(encoding="utf-8")
assert "救援系统的登录方式和密码由该 ISO 自身决定" in html
def test_rescue_timeout_advises_manual_power_cycle_only_when_iso_is_staged(page) -> None:
_, by_id = page
assert "rescue-view" in by_id
script = (STATIC_DIR / "app.js").read_text(encoding="utf-8")
html = (STATIC_DIR / "index.html").read_text(encoding="utf-8")
assert "正常关机失败或超时" in html
assert "只有救援页显示“已预挂载”时" in html
assert "点击“强制重启进入救援”" in html
assert "强制断电并冷启动" in html
assert "“强制重置”不保证读取新保存的启动配置" in html
assert "若预挂载未成功,请先核查错误" in html
assert 'shutdownFailed && job.operation === "enter"' in script
assert 'shutdownFailed && job.operation === "exit"' in script
assert 'current?.staged === true && job.operation === "enter"' in script
assert 'state.rescueStaged = result?.staged === true;' in script
assert 'state.rescuePowerState = String(result?.power_state || "unknown");' in script
assert 'job.pending_manual_restart === true' in script
assert "正常关机失败或超时,救援 ISO 已预挂载但尚未进入救援系统" in script
assert '/rescue/force-start`' in script
assert 'ack_data_loss: true' in script
assert 'byId("rescue-force-start").addEventListener' in script
assert by_id["rescue-force-start"][0].attrs["type"] == "button"
assert 'disabled: busy || (rescueMode && !rescueStaged)' in script
assert 'title: rescueStaged ? "从已预挂载的救援 ISO 开机"' in script
assert "“强制重置”不保证读取新启动配置" in script
assert "面板不会自动强制断电" in script
assert 'else if (shuttingDown)' in script
assert '() => openConfirm(vm, "poweroff")' in script
assert "客服" not in html
assert "客服" not in script

File diff suppressed because it is too large Load Diff

@ -0,0 +1,470 @@
"""VM metric math, DB persistence, and the process-local collection lifecycle."""
from __future__ import annotations
import threading
import pytest
from virsh_panel.database import DatabaseStore
from virsh_panel.metrics import (
MAX_QUERY_POINTS, RANGES, MetricSampler, MetricsCollector, RawVMStats,
host_scope, query_interval_seconds,
)
VM_ID = "00000000-0000-4000-8000-000000000001"
HOST = {"host": "hypervisor.example", "port": 2222,
"fingerprint": "SHA256:one", "storage_pool": "/home/kvm"}
def raw(*, generation=12, cpu=1_000_000_000, block_read=100,
block_write=200, network_rx=1000, network_tx=2000,
memory_time=1000, extra=None):
values = {
"cpu.time": cpu,
"balloon.available": 2 * 1024 * 1024,
"balloon.usable": 512 * 1024,
"balloon.last-update": memory_time,
"block.count": 1,
"block.0.name": "vda",
"block.0.rd.bytes": block_read,
"block.0.wr.bytes": block_write,
"net.count": 1,
"net.0.name": "vnet1",
"net.0.rx.bytes": network_rx,
"net.0.tx.bytes": network_tx,
}
values.update(extra or {})
return RawVMStats(VM_ID, generation, 2, values)
def test_host_scope_ignores_pool_but_changes_with_ssh_host_identity():
first = host_scope(HOST)
assert first == host_scope({**HOST, "storage_pool": "/different"})
assert first != host_scope({**HOST, "fingerprint": "SHA256:two"})
assert first != host_scope({**HOST, "port": 22})
def test_interval_caps_all_ranges_at_600_epoch_aligned_buckets():
for seconds in RANGES.values():
interval = query_interval_seconds(seconds)
assert interval % 60 == 0
assert seconds // interval + 2 <= MAX_QUERY_POINTS
def test_initial_sample_and_fresh_guest_memory_then_rates():
sampler = MetricSampler()
scope = host_scope(HOST)
first = sampler.observe(scope, raw(), timestamp=1000, monotonic=10)
assert first["cpu_percent"] is None
assert first["disk_read_bps"] is None
assert first["network_rx_bps"] is None
assert first["memory_used_mib"] == 1536
assert first["memory_total_mib"] == 2048
second = sampler.observe(
scope,
raw(cpu=61_000_000_000, block_read=700, block_write=1400,
network_rx=2200, network_tx=2600, memory_time=1050),
timestamp=1060, monotonic=70,
)
assert second["cpu_percent"] == 50
assert second["disk_read_bps"] == 10
assert second["disk_write_bps"] == 20
assert second["network_rx_bps"] == 20
assert second["network_tx_bps"] == 10
def test_cpu_time_over_vcpu_capacity_is_displayed_as_100_percent():
sampler = MetricSampler()
scope = host_scope(HOST)
sampler.observe(scope, raw(), timestamp=1000, monotonic=10)
# 130 CPU-seconds across two vCPUs in a 60-second interval; libvirt can
# include QEMU auxiliary threads in cpu.time.
point = sampler.observe(scope, raw(cpu=131_000_000_000),
timestamp=1060, monotonic=70)
assert point["cpu_percent"] == 100
def test_memory_missing_or_stale_balloon_stats_never_uses_rss_or_current():
sampler = MetricSampler()
scope = host_scope(HOST)
values = {"balloon.current": 2 * 1024 * 1024, "balloon.rss": 512 * 1024}
for extra in (
{"balloon.last-update": 1},
{"balloon.usable": None},
{"balloon.available": None},
):
point = sampler.observe(scope, raw(extra={**values, **extra}),
timestamp=1000, monotonic=10)
assert point["memory_used_mib"] is None
assert point["memory_total_mib"] is None
def test_counter_reset_reboot_device_change_and_partial_data_are_unknown():
sampler = MetricSampler()
scope = host_scope(HOST)
sampler.observe(scope, raw(), timestamp=1000, monotonic=10)
reset = sampler.observe(scope, raw(cpu=100, block_read=1, network_rx=1),
timestamp=1060, monotonic=70)
assert reset["cpu_percent"] is None
assert reset["disk_read_bps"] is None
assert reset["network_rx_bps"] is None
# Even if a second disk masks the first disk's decreasing counter in the
# aggregate, device change must not produce a transient spike.
changed = sampler.observe(scope, raw(extra={
"block.count": 2, "block.1.name": "vdb",
"block.1.rd.bytes": 10_000, "block.1.wr.bytes": 20_000,
}), timestamp=1120, monotonic=130)
assert changed["disk_read_bps"] is None
assert changed["disk_write_bps"] is None
partial = sampler.observe(scope, raw(extra={
"block.count": 2, "block.1.name": "vdb",
"block.1.rd.bytes": 11_000,
}), timestamp=1180, monotonic=190)
assert partial["disk_write_bps"] is None # second device missing wr.bytes
assert partial["disk_read_bps"] is not None
reboot = sampler.observe(scope, raw(generation=13, cpu=200_000_000_000),
timestamp=1240, monotonic=250)
assert reboot["cpu_percent"] is None
assert reboot["network_tx_bps"] is None
def test_cdrom_without_byte_counters_does_not_hide_disk_rates():
sampler = MetricSampler()
scope = host_scope(HOST)
cdrom = {"block.count": 2, "block.1.name": "sda"}
sampler.observe(scope, raw(extra=cdrom), timestamp=1000, monotonic=10)
second = sampler.observe(
scope, raw(block_read=700, block_write=1400, extra={
**cdrom, "balloon.last-update": 1060,
}), timestamp=1060, monotonic=70,
)
assert second["disk_read_bps"] == 10
assert second["disk_write_bps"] == 20
def test_single_device_counter_rollback_is_not_masked_by_another_device():
sampler = MetricSampler()
scope = host_scope(HOST)
second_disk = {"block.count": 2, "block.1.name": "vdb",
"block.1.rd.bytes": 1_000, "block.1.wr.bytes": 1_000}
sampler.observe(scope, raw(extra=second_disk), timestamp=1000, monotonic=10)
point = sampler.observe(scope, raw(block_read=1, block_write=1, extra={
**second_disk, "block.1.rd.bytes": 10_000,
"block.1.wr.bytes": 10_000,
}), timestamp=1060, monotonic=70)
assert point["disk_read_bps"] is None
assert point["disk_write_bps"] is None
def test_unobserved_long_gap_is_not_averaged_as_current_rate():
sampler = MetricSampler()
scope = host_scope(HOST)
sampler.observe(scope, raw(), timestamp=1000, monotonic=10)
delayed = sampler.observe(scope, raw(cpu=50_000_000_000, block_read=2000),
timestamp=1600, monotonic=610)
assert delayed["cpu_percent"] is None
assert delayed["disk_read_bps"] is None
class FakeCursor:
def __init__(self, rows=(), delete_counts=()):
self.rows = rows
self.commands = []
self.delete_counts = list(delete_counts)
self.rowcount = 0
def __enter__(self):
return self
def __exit__(self, *_args):
return None
def execute(self, sql, args=None):
self.commands.append((sql, args))
self.rowcount = (self.delete_counts.pop(0)
if sql.startswith("DELETE FROM vm_metric_samples")
and self.delete_counts else 0)
def executemany(self, sql, args):
self.commands.append((sql, args))
def fetchall(self):
return self.rows
class FakeConnection:
def __init__(self, rows=(), delete_counts=()):
self.fake_cursor = FakeCursor(rows, delete_counts)
self.commits = 0
self.closed = False
def cursor(self):
return self.fake_cursor
def commit(self):
self.commits += 1
def rollback(self):
raise AssertionError("unexpected rollback")
def close(self):
self.closed = True
def test_metric_and_user_tables_created_with_record_table():
connection = FakeConnection()
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: connection
store._initialize_schema()
assert len(connection.fake_cursor.commands) == 6
assert "vm_metric_samples" in connection.fake_cursor.commands[1][0]
assert "vm_metric_retention" in connection.fake_cursor.commands[1][0]
assert "CREATE TABLE IF NOT EXISTS users" in connection.fake_cursor.commands[2][0]
assert "CREATE TABLE IF NOT EXISTS registration_codes" in connection.fake_cursor.commands[3][0]
assert "CREATE TABLE IF NOT EXISTS vm_ownership" in connection.fake_cursor.commands[4][0]
assert "CREATE TABLE IF NOT EXISTS user_ssh_keys" in connection.fake_cursor.commands[5][0]
assert connection.commits == 1 and connection.closed
def test_metric_store_prunes_physically_and_queries_only_scoped_recent_data():
scope = host_scope(HOST)
connection = FakeConnection([{
"timestamp": 1000,
"cpu_percent": 12.5,
"memory_used_mib": 1024,
"memory_total_mib": 2048,
"disk_read_bps": None,
"disk_write_bps": None,
"network_rx_bps": 256,
"network_tx_bps": 0,
}])
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: connection
point = {"vm_id": VM_ID, "timestamp": 1000, "cpu_percent": 12.5,
"memory_used_mib": 1024, "memory_total_mib": 2048,
"disk_read_bps": None, "disk_write_bps": None,
"network_rx_bps": 256, "network_tx_bps": 0}
store.save_metric_samples(scope, [point])
store.prune_metric_samples(500)
result = store.query_metric_samples(scope, VM_ID, since=500, until=1100,
interval_seconds=60, limit=600)
assert result[0]["cpu_percent"] == 12.5
assert result[0]["disk_read_bps"] is None
insert, delete, query = connection.fake_cursor.commands
assert "INSERT INTO vm_metric_samples" in insert[0]
assert "DELETE FROM vm_metric_samples WHERE sampled_at < %s" in delete[0]
assert delete[1] == (500, 5000)
assert "host_scope=%s AND vm_uuid=%s AND sampled_at >= %s" in query[0]
assert "LIMIT %s" in query[0]
assert query[1] == (scope, VM_ID, 500, 1100, 60, 600)
assert connection.commits == 2 and connection.closed
def test_metric_prune_is_one_index_ordered_batch_per_transaction():
connection = FakeConnection(delete_counts=[5000] * 10)
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: connection
assert store.prune_metric_samples(1234) == 5000
assert len(connection.fake_cursor.commands) == 1
assert connection.commits == 1 and connection.closed
assert all("ORDER BY sampled_at LIMIT %s" in command
and args == (1234, 5000)
for command, args in connection.fake_cursor.commands)
def test_metric_prune_reports_short_final_batch():
connection = FakeConnection(delete_counts=[275])
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: connection
assert store.prune_metric_samples(1234) == 275
assert len(connection.fake_cursor.commands) == 1
assert connection.commits == 1
def test_metric_store_rejects_invalid_host_and_uuid_before_db_query():
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: pytest.fail("invalid scope must not query database")
with pytest.raises(ValueError):
store.query_metric_samples("bad-scope", VM_ID, since=0, until=1,
interval_seconds=60)
with pytest.raises(ValueError):
store.query_metric_samples(host_scope(HOST), "not-uuid", since=0, until=1,
interval_seconds=60)
def test_collector_prunes_when_ssh_locked_and_starts_after_db_configuration():
class Store:
def __init__(self):
self.pruned = []
self.saved = []
self.pruned_event = threading.Event()
self.saved_event = threading.Event()
def prune_metric_samples(self, cutoff):
self.pruned.append(cutoff)
self.pruned_event.set()
return 0
def save_metric_samples(self, scope, points):
self.saved.append((scope, points))
self.saved_event.set()
current = {"store": None, "profile": None}
store = Store()
class Service:
def metric_counters(self):
return [raw()]
collector = MetricsCollector(lambda: current["store"],
lambda: current["profile"],
lambda _profile: Service(), interval_seconds=0.01)
collector.start()
current["profile"] = {**HOST, "key_locked": True}
current["store"] = store
try:
assert store.pruned_event.wait(timeout=2)
assert store.pruned and not store.saved
current["profile"]["key_locked"] = False
assert store.saved_event.wait(timeout=2)
assert store.saved
finally:
collector.close()
def test_background_collector_keeps_sampling_without_an_http_session():
"""The 30-day history must not depend on a logged-in browser polling it."""
saved_twice = threading.Event()
class Store:
def __init__(self):
self.saved = []
def save_metric_samples(self, scope, points):
self.saved.append((scope, points))
if len(self.saved) >= 2:
saved_twice.set()
def prune_metric_samples(self, _cutoff):
return 0
class Service:
calls = 0
def metric_counters(self):
self.calls += 1
return [raw(cpu=self.calls * 1_000_000_000,
block_read=self.calls * 1000,
network_rx=self.calls * 1000)]
store = Store()
service = Service()
profile = {**HOST, "key_locked": False}
collector = MetricsCollector(lambda: store, lambda: profile,
lambda _profile: service,
interval_seconds=0.01)
collector.start()
try:
assert saved_twice.wait(timeout=2)
finally:
collector.close()
assert service.calls >= 2
assert all(scope == host_scope(HOST) for scope, _ in store.saved)
assert all(points[0]["vm_id"] == VM_ID for _, points in store.saved)
def test_metric_cleanup_failure_does_not_discard_current_sample(caplog):
events = []
attempted = threading.Event()
class Store:
def save_metric_samples(self, _scope, points):
events.append(("saved", points))
def prune_metric_samples(self, _cutoff):
events.append(("prune", None))
attempted.set()
raise RuntimeError("secret database details")
class Service:
def metric_counters(self):
return [raw()]
collector = MetricsCollector(lambda: Store(), lambda: HOST,
lambda _profile: Service(), interval_seconds=1)
collector.start()
assert attempted.wait(timeout=2)
collector.close()
assert [event[0] for event in events] == ["saved", "prune"]
assert "RuntimeError" in caplog.text
assert "secret database details" not in caplog.text
def test_backlog_cleanup_continues_in_other_thread_without_stalling_samples():
second_saved = threading.Event()
prune_entered = threading.Event()
release_prune = threading.Event()
backlog_drained = threading.Event()
class Store:
def __init__(self):
self.saved = 0
self.pruned = 0
def save_metric_samples(self, _scope, _points):
self.saved += 1
if self.saved >= 2:
second_saved.set()
def prune_metric_samples(self, _cutoff):
self.pruned += 1
if self.pruned == 1:
prune_entered.set()
assert release_prune.wait(timeout=2)
if self.pruned < 3:
return 5000
backlog_drained.set()
return 0
class Service:
def metric_counters(self):
return [raw()]
store = Store()
collector = MetricsCollector(lambda: store, lambda: HOST,
lambda _profile: Service(), interval_seconds=0.01)
collector.start()
try:
assert prune_entered.wait(timeout=2)
assert second_saved.wait(timeout=2)
release_prune.set()
assert backlog_drained.wait(timeout=2)
assert store.pruned >= 3
finally:
release_prune.set()
collector.close()
def test_collector_thread_starts_before_db_configuration_and_stops():
ready = threading.Event()
current = {"store": None}
class Store:
def prune_metric_samples(self, _cutoff):
ready.set()
return 0
collector = MetricsCollector(lambda: current["store"], lambda: None,
lambda _profile: pytest.fail("no host configured"),
interval_seconds=0.01)
collector.start()
current["store"] = Store()
assert ready.wait(timeout=2)
collector.close()
assert collector._thread is not None and not collector._thread.is_alive()
assert collector._prune_thread is not None and not collector._prune_thread.is_alive()

@ -0,0 +1,111 @@
"""Persistent setup state and one-time token safety checks."""
from __future__ import annotations
import os
import stat
from concurrent.futures import ThreadPoolExecutor
import pytest
from virsh_panel.auth import verify_password
from virsh_panel.panel_state import PanelState, SetupError
def test_token_is_reused_before_setup_and_removed_after_setup(tmp_path):
state = PanelState(tmp_path / "panel-data")
first = state.initialize_setup_token()
assert first and len(first) >= 32
assert state.initialize_setup_token() == first
assert stat.S_IMODE(state.token_file.stat().st_mode) == 0o600
assert stat.S_IMODE(state.data_dir.stat().st_mode) == 0o700
with pytest.raises(SetupError) as invalid:
state.create_admin("invalid", "admin", "correct-horse-battery-staple")
assert invalid.value.status == 403
assert state.setup_required()
assert state.create_admin(first, "admin", "correct-horse-battery-staple") == "admin"
assert not state.token_file.exists()
assert stat.S_IMODE(state.state_file.stat().st_mode) == 0o600
restarted = PanelState(state.data_dir)
username, encoded = restarted.admin()
assert username == "admin"
assert verify_password("correct-horse-battery-staple", encoded)
assert restarted.initialize_setup_token() is None
with pytest.raises(SetupError) as duplicate:
restarted.create_admin(first, "admin", "another-good-password")
assert duplicate.value.status == 409
def test_rejects_public_data_dir_and_setup_token(tmp_path):
data_dir = tmp_path / "public-data"
data_dir.mkdir(mode=0o755)
os.chmod(data_dir, 0o755)
with pytest.raises(ValueError, match="private directory"):
PanelState(data_dir)
state = PanelState(tmp_path / "private-data")
state.initialize_setup_token()
os.chmod(state.token_file, 0o644)
with pytest.raises(ValueError, match="private"):
state.initialize_setup_token()
def test_systemd_style_parent_symlink_is_supported_but_final_symlink_is_not(tmp_path):
private_parent = tmp_path / "private" / "virsh-panel"
private_parent.mkdir(parents=True, mode=0o700)
public_alias = tmp_path / "virsh-panel"
public_alias.symlink_to(private_parent, target_is_directory=True)
state = PanelState(public_alias / "state")
assert state.data_dir == private_parent / "state"
assert state.initialize_setup_token()
final_alias = tmp_path / "state-alias"
final_alias.symlink_to(state.data_dir, target_is_directory=True)
with pytest.raises(ValueError, match="symlink"):
PanelState(final_alias)
def test_concurrent_process_style_initialization_reuses_one_token(tmp_path):
data_dir = tmp_path / "panel-data"
def start_panel(_index):
return PanelState(data_dir).initialize_setup_token()
with ThreadPoolExecutor(max_workers=8) as workers:
tokens = list(workers.map(start_panel, range(16)))
assert len(set(tokens)) == 1
assert stat.S_IMODE((data_dir / ".setup.lock").stat().st_mode) == 0o600
def test_concurrent_admin_creation_has_one_winner(tmp_path):
data_dir = tmp_path / "panel-data"
token = PanelState(data_dir).initialize_setup_token()
def create(index):
try:
return PanelState(data_dir).create_admin(
token, f"admin{index}", "correct-horse-battery-staple"
)
except SetupError as exc:
return exc.status
with ThreadPoolExecutor(max_workers=2) as workers:
results = list(workers.map(create, range(2)))
assert sorted(str(item) for item in results) in (
["409", "admin0"], ["409", "admin1"],
)
assert not (data_dir / "setup-token").exists()
def test_stale_token_after_admin_write_is_not_relogged(tmp_path):
state = PanelState(tmp_path / "panel-data")
token = state.initialize_setup_token()
state.create_admin(token, "admin", "correct-horse-battery-staple")
# Emulate power loss between the atomic admin write and token removal.
state.token_file.write_text(token + "\n", encoding="ascii")
os.chmod(state.token_file, 0o600)
assert PanelState(state.data_dir).initialize_setup_token() is None
assert not state.token_file.exists()

@ -0,0 +1,112 @@
"""Validation of a host's public IPv4 allocation range."""
from __future__ import annotations
import pytest
from virsh_panel.remote_host import RemoteHostError, validate_public_pool
_DEFAULT = object()
def validate(cidr="1.2.3.0/24", gateway="1.2.3.1", dns=_DEFAULT, reserved=_DEFAULT,
vm_prefix=None):
return validate_public_pool(
cidr,
gateway,
["1.1.1.1", "8.8.8.8"] if dns is _DEFAULT else dns,
[] if reserved is _DEFAULT else reserved,
"1.2.3.2",
vm_prefix,
)
def test_unconfigured_public_pool_has_empty_defaults():
assert validate_public_pool("", "", [], [], "host.example") == {
"public_pool_cidr": "",
"public_gateway": "",
"public_dns_servers": [],
"public_reserved_ips": [],
"public_vm_prefix": None,
}
with pytest.raises(RemoteHostError):
validate_public_pool("", "", [], [], "host.example", 24)
def test_public_pool_normalizes_and_deduplicates_addresses():
assert validate(
dns=["1.1.1.1", "1.1.1.1", "8.8.8.8"],
reserved=["1.2.3.10", "1.2.3.10", "1.2.3.20"],
) == {
"public_pool_cidr": "1.2.3.0/24",
"public_gateway": "1.2.3.1",
"public_dns_servers": ["1.1.1.1", "8.8.8.8"],
"public_reserved_ips": ["1.2.3.10", "1.2.3.20"],
"public_vm_prefix": None,
}
@pytest.mark.parametrize("cidr", ["123.123.123.112/28", "123.123.123.113/28"])
def test_provider_28_is_normalized_without_widening_to_24(cidr):
configured = validate(
cidr, "123.123.123.113", ["1.1.1.1"],
["123.123.123.114", "123.123.123.126"],
)
assert configured["public_pool_cidr"] == "123.123.123.112/28"
assert configured["public_gateway"] == "123.123.123.113"
assert configured["public_reserved_ips"] == [
"123.123.123.114", "123.123.123.126",
]
def test_guest_mask_can_be_24_while_allocation_remains_28():
configured = validate("123.123.123.112/28", "123.123.123.113",
["1.1.1.1"], [], vm_prefix=24)
assert configured["public_pool_cidr"] == "123.123.123.112/28"
assert configured["public_vm_prefix"] == 24
@pytest.mark.parametrize("prefix", [23, 29, 31, True, "24"])
def test_guest_mask_rejects_values_outside_pool_bounds(prefix):
with pytest.raises(RemoteHostError):
validate("123.123.123.112/28", "123.123.123.113",
["1.1.1.1"], [], vm_prefix=prefix)
@pytest.mark.parametrize(
("cidr", "gateway", "dns", "reserved"),
[
("1.2.3.0/24", "", ["1.1.1.1"], []),
("", "1.2.3.1", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.1", [], []),
("", "", [], ["1.2.3.10"]),
("1.2.3.1/24", "1.2.3.1", ["1.1.1.1"], []),
("1.2.2.0/23", "1.2.3.1", ["1.1.1.1"], []),
("1.2.3.0/31", "1.2.3.1", ["1.1.1.1"], []),
("123.123.123.112/28", "123.123.123.111", ["1.1.1.1"], []),
("123.123.123.112/28", "123.123.123.127", ["1.1.1.1"], []),
("123.123.123.112/28", "123.123.123.113", ["1.1.1.1"], ["123.123.123.128"]),
("10.0.0.0/24", "10.0.0.1", ["1.1.1.1"], []),
("203.0.113.0/24", "203.0.113.1", ["1.1.1.1"], []),
("2001:db8::/24", "2001:db8::1", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.4.1", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.0", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.255", ["1.1.1.1"], []),
("1.2.3.0/24", "1.2.3.1", ["10.0.0.1"], []),
("1.2.3.0/24", "1.2.3.1",
["1.1.1.1", "8.8.8.8", "9.9.9.9", "208.67.222.222", "208.67.220.220"], []),
("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.4.2"]),
("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.3.0"]),
("1.2.3.0/24", "1.2.3.1", ["1.1.1.1"], ["1.2.3.255"]),
],
)
def test_public_pool_rejects_invalid_configuration(cidr, gateway, dns, reserved):
with pytest.raises(RemoteHostError):
validate(cidr, gateway, dns, reserved)
@pytest.mark.parametrize("value", [None, "1.1.1.1", ["1.1.1.1", None]])
def test_dns_must_be_list_of_ip_strings(value):
with pytest.raises(RemoteHostError):
validate(dns=value)

@ -0,0 +1,982 @@
"""Production database-mode registration and authorization HTTP boundary."""
from __future__ import annotations
import asyncio
import ipaddress
import json
import sys
import time
import types
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
try:
import libvirt # noqa: F401
except ModuleNotFoundError:
stub = types.ModuleType("libvirt")
stub.libvirtError = type("libvirtError", (Exception,), {})
sys.modules["libvirt"] = stub
from tests.test_database_http import MemoryStore # noqa: E402
from virsh_panel import app as app_module # noqa: E402
from virsh_panel.auth import hash_password # noqa: E402
from virsh_panel.config import Settings # noqa: E402
from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402
from virsh_panel.libvirt_service import VMError # noqa: E402
from virsh_panel.metrics import host_scope # noqa: E402
from virsh_panel.cloud_templates import template_scope # noqa: E402
from virsh_panel.ssh_keys import SSHKeyError, _name, _public_key # noqa: E402
ORIGIN = "https://panel.example.test"
PASSWORD = "correct-horse-battery-staple"
CREATE_VM = {
"name": "tenant-vm", "vcpu": 2, "memory_mib": 2048,
"disk_gib": 20, "network": "bridge:br0", "iso": "AlmaLinux-10.iso",
}
GUEST_PUBLIC_KEY = (
"ssh-ed25519 "
"AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 "
"panel-test"
)
CLOUD_VM = {
"source": "cloud", "template_id": "alma10-template",
"name": "tenant-cloud", "vcpu": 2, "memory_mib": 2048,
"disk_gib": 20, "network": "bridge:br0", "public_ip_cidr": "8.8.8.18/24",
"gateway": "8.8.8.1", "dns_servers": ["1.1.1.1"],
}
class _MemorySSHKeys:
"""Mimic the owner-scoped SQL boundary for production-mode HTTP tests."""
def __init__(self):
self.rows = {}
self.next_id = 1
def list_for_user(self, user_id):
return [row.copy() for owner, row in self.rows.values() if owner == user_id]
def create_for_user(self, user_id, name, public_key):
name = _name(name)
public_key, fingerprint = _public_key(public_key)
if any(owner == user_id and row["fingerprint"] == fingerprint
for owner, row in self.rows.values()):
raise SSHKeyError("此 SSH 公钥已添加到当前账户", 409)
key_id = self.next_id
self.next_id += 1
row = {"id": key_id, "name": name, "public_key": public_key,
"fingerprint": fingerprint, "created_at": 100}
self.rows[key_id] = (user_id, row)
return row.copy()
def get_for_user(self, user_id, key_id):
found = self.rows.get(key_id)
return found[1].copy() if found is not None and found[0] == user_id else None
def delete_for_user(self, user_id, key_id):
if self.get_for_user(user_id, key_id) is None:
return False
del self.rows[key_id]
return True
class _Manager:
profile = {
"host": "vmhost.example.test", "port": 22,
"fingerprint": "SHA256:configured-host", "key_locked": False,
"region": "东京", "storage_pool": "/home/kvm", "iso_pool": "/home/iso",
"default_network": "bridge:br0", "ssh_target": "vp-managed",
"ssh_config_file": "/fake/config", "ssh_known_hosts_file": "/fake/known_hosts",
}
def current(self):
return self.profile
def close(self):
pass
class _Service:
def __init__(self):
self.vms = {}
self.console_calls = []
self.cloud_specs = []
self.reinstall_specs = []
def create_vm(self, spec):
vm = {
"uuid": spec["vm_uuid"], "name": spec["name"], "state": "running",
"vcpu": spec["vcpu"], "memory_mib": spec["memory_mib"],
"disks": [], "autostart": True,
}
self.vms[vm["uuid"]] = vm
return vm
def create_cloud_vm(self, spec, volume_name):
self.cloud_specs.append((spec.copy(), volume_name))
vm = self.create_vm(spec)
vm.update({
"managed": True,
"os_source": "cloud_template",
"public_ip_cidr": spec["public_ip_cidr"],
"credential_generation": f"panel-seed-{vm['uuid']}.iso",
})
return vm
def reinstall_cloud_vm(self, vm_id, volume_name, *, os_name=None,
ssh_public_key="", root_password_hash=None,
progress=None):
vm = self.get_vm(vm_id)
self.reinstall_specs.append((vm_id, volume_name, ssh_public_key,
root_password_hash, os_name))
if progress is not None:
progress("completed")
generation = f"panel-seed-reinstall-{vm_id}.iso"
vm["credential_generation"] = generation
return {"vm": vm, "credential_generation": generation}
def resources(self):
return {"networks": ["bridge:br0"], "isos": [], "storage_pool": "/home/kvm"}
def list_vms(self):
return list(self.vms.values())
def get_vm(self, vm_id):
if vm_id not in self.vms:
raise VMError("虚拟机不存在", 404)
return self.vms[vm_id]
def action(self, vm_id, _action):
return self.get_vm(vm_id)
def delete_vm(self, vm_id, _delete_disks):
self.get_vm(vm_id)
del self.vms[vm_id]
return {"uuid": vm_id, "deleted": True, "deleted_disks": []}
def console_port(self, vm_id):
self.console_calls.append(vm_id)
self.get_vm(vm_id)
return 5907
class _NoMetrics:
def __init__(self, *_args, **_kwargs):
pass
def start(self):
pass
def close(self):
pass
def _login(client: TestClient, email: str):
response = client.post("/api/v1/login", json={
"email": email, "password": PASSWORD,
})
assert response.status_code == 200
return {"X-CSRF-Token": response.json()["csrf_token"]}
def _register(client: TestClient, address: str, username: str):
code = client.post("/api/v1/register/code", json={"email": address})
assert code.status_code == 200 and code.json() == {"sent": True}
response = client.post("/api/v1/register", json={
"username": username, "email": address,
"password": PASSWORD, "code": "123456",
})
assert response.status_code == 201
assert response.json() == {"registered": True, "approved": False}
def test_template_rename_is_admin_only_and_ordinary_users_can_list(monkeypatch, tmp_path):
store = MemoryStore()
service = _Service()
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), _Manager(),
DatabaseTemplateStore(store), store,
))
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
scope = template_scope(_Manager.profile)
template_id = "alma9-12345678-abcdef0123456789"
record = {
"id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux",
"os_version": "9", "sha256": "f" * 64,
"volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2",
}
endpoint = f"/api/v1/vm-templates/{template_id}"
with TestClient(app, base_url=ORIGIN) as admin:
assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 401
configured = admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
})
assert configured.status_code == 200
created = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "initial", "password": PASSWORD,
})
assert created.status_code == 200
admin_headers = {"X-CSRF-Token": created.json()["csrf_token"]}
templates = DatabaseTemplateStore(store)
templates.add(scope, record)
templates.add(scope, {**record, "id": "another", "name": "Other template"})
templates.add("b" * 64, {**record, "name": "Different host"})
assert admin.patch(endpoint, json={"name": "Rename"},
headers=admin_headers).status_code == 403
store.users.promote("initial")
store.set("test_user", "tenant", json.dumps({
"id": 2, "username": "tenant", "email": "tenant@example.test",
"password_hash": hash_password(PASSWORD), "admin": False,
"approved": True, "email_verified": True, "created_at": 100,
}))
with TestClient(app, base_url=ORIGIN) as tenant:
tenant_headers = _login(tenant, "tenant@example.test")
listed = tenant.get("/api/v1/vm-templates")
assert listed.status_code == 200
assert [row["id"] for row in listed.json()["templates"]] == [
template_id, "another",
]
assert tenant.patch(endpoint, json={"name": "Hijack"},
headers=tenant_headers).status_code == 403
assert tenant.post("/api/v1/vm-templates/import", json={
"name": "Extra", "url": "https://invalid.example/image.qcow2",
"sha256": "a" * 64,
}, headers=tenant_headers).status_code == 403
assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 403
assert admin.patch(endpoint, json={"name": "Other TEMPLATE"},
headers=admin_headers).status_code == 409
assert admin.patch(endpoint, json={"name": " "},
headers=admin_headers).status_code == 400
missing = admin.patch("/api/v1/vm-templates/missing", json={"name": "Missing"},
headers=admin_headers)
assert missing.status_code == 404
renamed = admin.patch(endpoint, json={"name": " AlmaLinux 9 Gold "},
headers=admin_headers)
assert renamed.status_code == 200
assert renamed.json()["template"] == {**record, "name": "AlmaLinux 9 Gold"}
assert DatabaseTemplateStore(store).get(scope, template_id) == renamed.json()["template"]
assert templates.get("b" * 64, template_id)["name"] == "Different host"
def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_path):
store = MemoryStore()
service = _Service()
sent = []
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), _Manager(),
DatabaseTemplateStore(store), store,
))
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
monkeypatch.setattr(
app_module, "send_verification_code",
lambda config, email, code: sent.append((config.host, email, code)),
)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
with TestClient(app, base_url=ORIGIN) as admin:
configured = admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
})
assert configured.status_code == 200
initial = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "firstuser", "password": PASSWORD,
})
assert initial.status_code == 200
admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
assert admin.get("/api/v1/session").json()["admin"] is False
assert admin.get("/api/v1/smtp/settings").status_code == 403
# The operator promotes the initial account and adds its email in MariaDB.
store.users.promote("firstuser")
assert admin.get("/api/v1/session").json()["admin"] is True
initial_account = store.users.get_by_username("firstuser")
assert initial_account["email"] is None
with TestClient(app, base_url=ORIGIN) as missing_email:
assert missing_email.post("/api/v1/login", json={
"email": "first@example.test", "password": PASSWORD,
}).status_code == 401
store.set("test_user", "firstuser", json.dumps({
**initial_account, "email": "first@example.test",
}))
with TestClient(app, base_url=ORIGIN) as fresh_admin:
assert fresh_admin.post("/api/v1/login", json={
"username": "firstuser", "password": PASSWORD,
}).status_code == 422
assert fresh_admin.post("/api/v1/login", json={
"email": "firstuser", "password": PASSWORD,
}).status_code == 401
assert _login(fresh_admin, "FIRST@EXAMPLE.TEST")
assert fresh_admin.get("/api/v1/session").json()["admin"] is True
smtp = admin.put("/api/v1/smtp/settings", json={
"host": "smtp.example.test", "port": 587, "tls_mode": "starttls",
"from_address": "panel@example.test", "username": "mailer",
"password": "smtp-secret-password",
}, headers=admin_headers)
assert smtp.status_code == 200
assert "smtp-secret-password" not in smtp.text
original_sender = app_module.send_verification_code
def fail_delivery(_config, _email, _code):
raise app_module.SMTPError("模拟 SMTP 发送失败", 502)
monkeypatch.setattr(app_module, "send_verification_code", fail_delivery)
with TestClient(app, base_url=ORIGIN) as visitor:
failed_send = visitor.post("/api/v1/register/code", json={
"email": "delivery-fail@example.test",
})
assert failed_send.status_code == 200
assert failed_send.json() == {"sent": True}
# A failed background delivery must remove the challenge so the
# user is not trapped behind the resend cooldown.
assert store.get("test_code", "delivery-fail@example.test") is None
monkeypatch.setattr(app_module, "send_verification_code", original_sender)
with TestClient(app, base_url=ORIGIN) as visitor:
retried = visitor.post("/api/v1/register/code", json={
"email": "delivery-fail@example.test",
})
assert retried.status_code == failed_send.status_code
assert retried.json() == failed_send.json()
assert store.get("test_code", "delivery-fail@example.test") == "123456"
sent.clear()
with TestClient(app, base_url=ORIGIN) as first:
_register(first, "one@example.test", "tenantone")
assert sent == [("smtp.example.test", "one@example.test", "123456")]
first_headers = _login(first, "ONE@EXAMPLE.TEST")
assert first.get("/api/v1/session").json()["approved"] is False
assert first.post("/api/v1/vms", json=CREATE_VM,
headers=first_headers).status_code == 403
for protected in (
"/api/v1/host", "/api/v1/update/settings",
"/api/v1/smtp/settings", "/api/v1/users/pending",
):
assert first.get(protected).status_code == 403
pending = admin.get("/api/v1/users/pending")
assert pending.status_code == 200
items = pending.json()["items"]
assert len(items) == 1 and items[0]["username"] == "tenantone"
assert "password_hash" not in items[0]
approve = admin.post(f"/api/v1/users/{items[0]['id']}/approve",
headers=admin_headers)
assert approve.status_code == 200
assert first.get("/api/v1/session").json()["approved"] is True
own = first.post("/api/v1/vms", json=CREATE_VM, headers=first_headers)
assert own.status_code == 201
own_id = own.json()["uuid"]
with TestClient(app, base_url=ORIGIN) as second:
_register(second, "two@example.test", "tenanttwo")
second_headers = _login(second, "two@example.test")
second_id = store.users.get_by_username("tenanttwo")["id"]
assert admin.post(f"/api/v1/users/{second_id}/approve",
headers=admin_headers).status_code == 200
other = second.post("/api/v1/vms", json={**CREATE_VM, "name": "other-vm"},
headers=second_headers)
assert other.status_code == 201
other_id = other.json()["uuid"]
assert [vm["uuid"] for vm in first.get("/api/v1/vms").json()["items"]] == [own_id]
assert [vm["uuid"] for vm in second.get("/api/v1/vms").json()["items"]] == [other_id]
assert len(admin.get("/api/v1/vms").json()["items"]) == 2
assert first.get(f"/api/v1/vms/{other_id}").status_code == 404
assert first.post(f"/api/v1/vms/{other_id}/credential",
headers=first_headers).status_code == 404
assert first.get(f"/api/v1/vms/{other_id}/metrics").status_code == 404
assert first.post(f"/api/v1/vms/{other_id}/actions", json={
"action": "reboot",
}, headers=first_headers).status_code == 404
assert first.delete(f"/api/v1/vms/{other_id}",
headers=first_headers).status_code == 404
assert first.get(f"/api/v1/vms/{own_id}").status_code == 200
assert first.get("/api/v1/host").status_code == 403
assert first.put("/api/v1/update/settings", json={
"repository_url": "https://g.luoli.live/root/virt.git", "branch": "main",
"access_token": "forbidden",
}, headers=first_headers).status_code == 403
assert first.put("/api/v1/smtp/settings", json={
"host": "evil.example.test", "port": 587, "tls_mode": "starttls",
"from_address": "evil@example.test",
}, headers=first_headers).status_code == 403
assert first.post(f"/api/v1/users/{second_id}/approve",
headers=first_headers).status_code == 403
cookie = first.cookies.get("virsh_panel_session")
with pytest.raises(WebSocketDisconnect) as denied:
with first.websocket_connect(
f"wss://panel.example.test/api/v1/vms/{other_id}/console",
headers={
"host": "panel.example.test", "origin": ORIGIN,
"cookie": f"virsh_panel_session={cookie}",
},
):
pass
assert denied.value.code == 4404
assert service.console_calls == []
monkeypatch.setattr(app_module, "CONSOLE_ACCESS_CHECK_SECONDS", 0.05)
async def held_console(_websocket, **_kwargs):
# If the watchdog fails to close promptly, the relay
# closes with 1011 after a bounded fallback delay.
await asyncio.sleep(1)
raise app_module.ConsoleRelayError("test relay timeout")
monkeypatch.setattr(app_module, "relay_console", held_console)
own_console = f"wss://panel.example.test/api/v1/vms/{own_id}/console"
own_cookie = first.cookies.get("virsh_panel_session")
with first.websocket_connect(own_console, headers={
"host": "panel.example.test", "origin": ORIGIN,
"cookie": f"virsh_panel_session={own_cookie}",
}) as console:
assert first.post("/api/v1/logout", headers=first_headers).status_code == 200
with pytest.raises(WebSocketDisconnect) as revoked:
console.receive_text()
assert revoked.value.code == 4403
first_headers = _login(first, "one@example.test")
own_cookie = first.cookies.get("virsh_panel_session")
with first.websocket_connect(own_console, headers={
"host": "panel.example.test", "origin": ORIGIN,
"cookie": f"virsh_panel_session={own_cookie}",
}) as console:
store.users.delete_vm_owner(host_scope(_Manager.profile), own_id)
with pytest.raises(WebSocketDisconnect) as ownership_revoked:
console.receive_text()
assert ownership_revoked.value.code == 4403
# A deleted username may later be reused. Its old bearer
# cookie must not acquire the replacement account's role.
old_account = store.users.get_by_username("tenantone")
store.delete("test_user", "tenantone")
replacement = {**old_account, "id": old_account["id"] + 1000,
"admin": True}
store.set("test_user", "tenantone", json.dumps(replacement))
assert first.get("/api/v1/session").json()["authenticated"] is False
assert first.get("/api/v1/smtp/settings").status_code == 401
assert first.post("/api/v1/vms", json=CREATE_VM,
headers=first_headers).status_code == 401
def test_per_user_ssh_key_library_and_cloud_vm_selection(monkeypatch, tmp_path):
store = MemoryStore()
key_store = _MemorySSHKeys()
service = _Service()
def components(directory, *_args):
state = DatabasePanelState(directory, store, store.users)
state.ssh_keys = key_store
return state, _Manager(), DatabaseTemplateStore(store), store
monkeypatch.setattr(app_module, "make_components", components)
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
with TestClient(app, base_url=ORIGIN) as admin:
assert admin.get("/api/v1/ssh-keys").status_code == 401
assert admin.post("/api/v1/ssh-keys", json={
"name": "initial", "public_key": GUEST_PUBLIC_KEY,
}).status_code == 401
assert admin.delete("/api/v1/ssh-keys/1").status_code == 401
assert admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
}).status_code == 200
initial = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "firstuser", "password": PASSWORD,
})
assert initial.status_code == 200
admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
store.users.promote("firstuser")
DatabaseTemplateStore(store).add(template_scope(_Manager.profile), {
"id": "alma10-template", "name": "AlmaLinux 10",
"volume_name": "panel-template-alma10.qcow2",
})
# Even an administrator has a personal key library, not every
# tenant's keys. No private-key content is accepted by the API.
assert admin.get("/api/v1/ssh-keys").json() == {"items": []}
rejected_private = admin.post("/api/v1/ssh-keys", json={
"name": "wrong", "public_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nsecret",
}, headers=admin_headers)
assert rejected_private.status_code in (400, 422)
store.users.issue_registration_code("one@example.test", "123456")
first_account = store.users.register_with_code(
"tenantone", "one@example.test", PASSWORD, "123456",
)
store.users.issue_registration_code("two@example.test", "123456")
second_account = store.users.register_with_code(
"tenanttwo", "two@example.test", PASSWORD, "123456",
)
with TestClient(app, base_url=ORIGIN) as first, \
TestClient(app, base_url=ORIGIN) as second:
first_headers = _login(first, "one@example.test")
second_headers = _login(second, "two@example.test")
assert first.get("/api/v1/session").json()["approved"] is False
assert first.get("/api/v1/ssh-keys").json() == {"items": []}
assert first.post("/api/v1/ssh-keys", json={
"name": "laptop", "public_key": GUEST_PUBLIC_KEY,
}).status_code == 403
imported = first.post("/api/v1/ssh-keys", json={
"name": "laptop", "public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers)
assert imported.status_code == 201
first_key = imported.json()
assert first_key["name"] == "laptop"
assert first_key["public_key"].startswith("ssh-ed25519 ")
assert first_key["fingerprint"].startswith("SHA256:")
assert isinstance(first_key["id"], int)
assert first.post("/api/v1/ssh-keys", json={
"name": "duplicate comment", "public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers).status_code == 409
assert first.get("/api/v1/ssh-keys").json()["items"] == [first_key]
assert second.get("/api/v1/ssh-keys").json() == {"items": []}
assert admin.get("/api/v1/ssh-keys").json() == {"items": []}
assert first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": first_key["id"],
}, headers=first_headers).status_code == 403
# The same public key is allowed in another account, but its
# record has a different ID and remains independently owned.
second_import = second.post("/api/v1/ssh-keys", json={
"name": "other laptop", "public_key": GUEST_PUBLIC_KEY,
}, headers=second_headers)
assert second_import.status_code == 201
second_key = second_import.json()
assert second_key["id"] != first_key["id"]
assert second.get("/api/v1/ssh-keys").json()["items"] == [second_key]
assert second.delete(f"/api/v1/ssh-keys/{first_key['id']}",
headers=second_headers).status_code == 404
assert first.delete("/api/v1/ssh-keys/-1",
headers=first_headers).status_code == 404
assert admin.delete(f"/api/v1/ssh-keys/{first_key['id']}",
headers=admin_headers).status_code == 404
assert first.get("/api/v1/ssh-keys").json()["items"] == [first_key]
assert admin.post(f"/api/v1/users/{first_account['id']}/approve",
headers=admin_headers).status_code == 200
assert admin.post(f"/api/v1/users/{second_account['id']}/approve",
headers=admin_headers).status_code == 200
before = len(service.cloud_specs)
for client, headers, forbidden_id in (
(first, first_headers, second_key["id"]),
(second, second_headers, first_key["id"]),
(admin, admin_headers, first_key["id"]),
):
forbidden = client.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": forbidden_id,
}, headers=headers)
assert forbidden.status_code == 404
missing = first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": 999999,
}, headers=first_headers)
assert missing.status_code == 404
for conflicting in (
{"guest_ssh_key_id": first_key["id"],
"guest_ssh_public_key": GUEST_PUBLIC_KEY},
):
response = first.post("/api/v1/vms", json={
**CLOUD_VM, **conflicting,
}, headers=first_headers)
assert response.status_code == 422
assert len(service.cloud_specs) == before
selected = first.post("/api/v1/vms", json={
**CLOUD_VM, "guest_ssh_key_id": first_key["id"],
"root_password": "A-strong-guest-password-2026",
}, headers=first_headers)
assert selected.status_code == 201
spec, _volume = service.cloud_specs[-1]
assert spec["guest_ssh_public_key"] == first_key["public_key"]
assert "guest_ssh_key_id" not in spec
assert spec["root_password_hash"].startswith("$6$")
assert selected.json()["auth_mode"] == "ssh_key_password"
assert selected.json()["password_available"]
assert first.post(
f"/api/v1/vms/{selected.json()['uuid']}/credential",
headers=first_headers,
).json()["password"] == "A-strong-guest-password-2026"
assert second.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 404
key_with_generated_password = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "saved-key-auto-password",
"public_ip_cidr": "8.8.8.21/24",
"guest_ssh_key_id": first_key["id"],
"root_password": "",
}, headers=first_headers)
assert key_with_generated_password.status_code == 201
key_spec, _key_volume = service.cloud_specs[-1]
assert key_spec["guest_ssh_public_key"] == first_key["public_key"]
assert key_spec["root_password_hash"].startswith("$6$")
assert key_with_generated_password.json()["auth_mode"] == "ssh_key_password"
assert key_with_generated_password.json()["password_available"]
key_credential = first.post(
f"/api/v1/vms/{key_with_generated_password.json()['uuid']}/credential",
headers=first_headers,
).json()
assert key_credential["auth_mode"] == "ssh_key_password"
assert len(key_credential["password"]) >= 24
assert any(c.isupper() for c in key_credential["password"])
assert any(c.islower() for c in key_credential["password"])
assert any(not c.isalnum() and not c.isspace()
for c in key_credential["password"])
from passlib.hash import sha512_crypt
assert sha512_crypt.verify(
key_credential["password"], key_spec["root_password_hash"],
)
assert key_credential["password"] not in key_with_generated_password.text
assert key_credential["password"] not in repr(service.cloud_specs)
assert second.get(
f"/api/v1/vms/{key_with_generated_password.json()['uuid']}"
).status_code == 404
reinstall_url = f"/api/v1/vms/{selected.json()['uuid']}/reinstall"
reinstall_body = {"template_id": "alma10-template",
"confirmation_name": "tenant-cloud"}
for client, headers, key_id in (
(first, first_headers, second_key["id"]),
(admin, admin_headers, first_key["id"]),
):
assert client.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": key_id,
}, headers=headers).status_code == 404
assert second.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": second_key["id"],
}, headers=second_headers).status_code == 404
assert first.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": first_key["id"],
"ssh_public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers).status_code == 422
assert service.reinstall_specs == []
queued = first.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": first_key["id"],
"root_password": "A-strong-guest-password-2026",
}, headers=first_headers)
assert queued.status_code == 202
for _ in range(100):
job = first.get(f"/api/v1/reinstall-jobs/{queued.json()['job_id']}",
headers=first_headers)
assert job.status_code == 200
if job.json()["status"] != "queued" and job.json()["status"] != "running":
break
time.sleep(0.01)
assert job.json()["status"] == "succeeded"
assert service.reinstall_specs[-1][2] == first_key["public_key"]
assert service.reinstall_specs[-1][3].startswith("$6$")
assert "generated_password" not in job.json()
assert first.post(
f"/api/v1/vms/{selected.json()['uuid']}/credential",
headers=first_headers,
).json()["password"] == "A-strong-guest-password-2026"
# Existing create paths continue to accept a one-off pasted key
# or an initial root password without a saved-key ID.
manual = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "manual-key-vm",
"public_ip_cidr": "8.8.8.19/24",
"guest_ssh_public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers)
assert manual.status_code == 201
assert service.cloud_specs[-1][0]["guest_ssh_public_key"] == GUEST_PUBLIC_KEY
manual_claim = f"{host_scope(_Manager.profile)}.8.8.8.19"
assert store.get("ip_claim", manual_claim) is not None
duplicate_manual = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "duplicate-manual-ip",
"public_ip_cidr": "8.8.8.19/24",
"guest_ssh_public_key": GUEST_PUBLIC_KEY,
}, headers=first_headers)
assert duplicate_manual.status_code == 409
assert first.delete(f"/api/v1/vms/{manual.json()['uuid']}",
headers=first_headers).status_code == 200
assert store.get("ip_claim", manual_claim) is None
password = first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "password-vm",
"public_ip_cidr": "8.8.8.20/24",
"root_password": "A-strong-guest-password-2026",
}, headers=first_headers)
assert password.status_code == 201
assert password.json()["auth_mode"] == "password"
assert first.delete(f"/api/v1/ssh-keys/{first_key['id']}").status_code == 403
deleted = first.delete(f"/api/v1/ssh-keys/{first_key['id']}",
headers=first_headers)
assert 200 <= deleted.status_code < 300
assert first.get("/api/v1/ssh-keys").json() == {"items": []}
assert second.get("/api/v1/ssh-keys").json()["items"] == [second_key]
assert first.post("/api/v1/vms", json={
**CLOUD_VM, "name": "deleted-key-vm",
"guest_ssh_key_id": first_key["id"],
}, headers=first_headers).status_code == 404
assert first.post(reinstall_url, json={
**reinstall_body, "ssh_key_id": first_key["id"],
}, headers=first_headers).status_code == 404
assert first.get(f"/api/v1/vms/{selected.json()['uuid']}").status_code == 200
def test_host_public_pool_allocates_globally_and_preserves_tenant_isolation(
monkeypatch, tmp_path,
):
store = MemoryStore()
service = _Service()
manager = _Manager()
manager.profile = {
**_Manager.profile,
"host": "8.8.8.3",
"public_pool_cidr": "8.8.8.0/24",
"public_gateway": "8.8.8.1",
"public_dns_servers": ["1.1.1.1", "8.8.4.4"],
"public_reserved_ips": ["8.8.8.2", "8.8.8.5"],
}
# An existing, panel-visible libvirt guest already occupies one address.
service.vms["00000000-0000-4000-8000-000000000004"] = {
"uuid": "00000000-0000-4000-8000-000000000004",
"name": "existing-vm", "state": "running", "vcpu": 1,
"memory_mib": 1024, "disks": [], "autostart": True,
"public_ip_cidr": "8.8.8.4/24",
}
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), manager,
DatabaseTemplateStore(store), store,
))
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
automatic_body = {
key: value for key, value in CLOUD_VM.items()
if key not in {"public_ip_cidr", "gateway", "dns_servers"}
}
automatic_body["guest_ssh_public_key"] = GUEST_PUBLIC_KEY
network = ipaddress.ip_network(manager.profile["public_pool_cidr"])
excluded = {"8.8.8.0", "8.8.8.1", "8.8.8.2", "8.8.8.3",
"8.8.8.4", "8.8.8.5", "8.8.8.6", "8.8.8.255"}
with TestClient(app, base_url=ORIGIN) as admin:
assert admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
}).status_code == 200
initial = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "operator", "password": PASSWORD,
})
assert initial.status_code == 200
admin_headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
store.users.promote("operator")
DatabaseTemplateStore(store).add(template_scope(manager.profile), {
"id": "alma10-template", "name": "AlmaLinux 10",
"volume_name": "panel-template-alma10.qcow2",
})
# A claim from another panel worker remains occupied even when its VM
# is not yet visible through libvirt's list API.
pool_scope = host_scope(manager.profile)
assert store.insert("ip_claim", f"{pool_scope}.8.8.8.6", json.dumps({
"vm_uuid": "00000000-0000-4000-8000-000000000006",
}))
for username in ("tenantone", "tenanttwo"):
email = f"{username}@example.test"
store.users.issue_registration_code(email, "123456")
account = store.users.register_with_code(username, email, PASSWORD, "123456")
assert admin.post(f"/api/v1/users/{account['id']}/approve",
headers=admin_headers).status_code == 200
with TestClient(app, base_url=ORIGIN) as first, \
TestClient(app, base_url=ORIGIN) as second:
first_headers = _login(first, "tenantone@example.test")
second_headers = _login(second, "tenanttwo@example.test")
resources = first.get("/api/v1/resources")
assert resources.status_code == 200
assert resources.json()["public_pool_enabled"] is True
assert resources.json()["public_pool_cidr"] == "8.8.8.0/24"
assert first.get("/api/v1/host").status_code == 403
# Explicit client-side networking cannot bypass the host pool.
for field, value in (
("public_ip_cidr", "8.8.8.99/24"),
("gateway", "8.8.8.1"),
("dns_servers", ["1.1.1.1"]),
):
rejected = first.post("/api/v1/vms", json={
**automatic_body, field: value,
}, headers=first_headers)
assert rejected.status_code == 422
assert service.cloud_specs == []
first_created = first.post("/api/v1/vms", json=automatic_body,
headers=first_headers)
second_created = second.post("/api/v1/vms", json={
**automatic_body, "name": "tenant-two-cloud",
}, headers=second_headers)
assert first_created.status_code == second_created.status_code == 201
first_ip = service.cloud_specs[0][0]["public_ip_cidr"]
second_ip = service.cloud_specs[1][0]["public_ip_cidr"]
for ip_cidr in (first_ip, second_ip):
interface = ipaddress.ip_interface(ip_cidr)
assert interface.network == network
assert str(interface.ip) not in excluded
assert first_ip != second_ip
for spec, _volume in service.cloud_specs:
assert spec["gateway"] == "8.8.8.1"
assert spec["dns_servers"] == ["1.1.1.1", "8.8.4.4"]
first_id = first_created.json()["uuid"]
second_id = second_created.json()["uuid"]
assert first.get(f"/api/v1/vms/{second_id}").status_code == 404
assert second.get(f"/api/v1/vms/{first_id}").status_code == 404
# Every usable address is occupied in libvirt metadata: no IP may
# be reused even after the allocator has exhausted the /24 pool.
for address in network.hosts():
ip = str(address)
if ip not in excluded and ip not in {first_ip.split("/")[0],
second_ip.split("/")[0]}:
service.vms[f"used-{ip}"] = {"uuid": f"used-{ip}",
"public_ip_cidr": f"{ip}/24"}
exhausted = first.post("/api/v1/vms", json={
**automatic_body, "name": "no-ip-left",
}, headers=first_headers)
assert exhausted.status_code == 409
assert len(service.cloud_specs) == 2
first_claim = f"{pool_scope}.{first_ip.split('/')[0]}"
assert store.get("ip_claim", first_claim) is not None
deleted = first.delete(f"/api/v1/vms/{first_id}", headers=first_headers)
assert deleted.status_code == 200
assert store.get("ip_claim", first_claim) is None
replacement = first.post("/api/v1/vms", json={
**automatic_body, "name": "freed-ip-reused",
}, headers=first_headers)
assert replacement.status_code == 201
assert service.cloud_specs[-1][0]["public_ip_cidr"] == first_ip
# With exactly one free address, a clearly rolled-back libvirt
# failure must release the temporary claim for the next attempt.
del service.vms["used-8.8.8.250"]
free_claim = f"{pool_scope}.8.8.8.250"
original_create = service.create_cloud_vm
def rolled_back(_spec, _volume):
raise VMError("模拟创建失败,回滚已完成", 502)
monkeypatch.setattr(service, "create_cloud_vm", rolled_back)
failed = first.post("/api/v1/vms", json={
**automatic_body, "name": "rolled-back-vm",
}, headers=first_headers)
assert failed.status_code == 502
assert store.get("ip_claim", free_claim) is None
# If libvirt reports incomplete rollback, conservatively retain
# the address claim even though this fake exposes no resulting VM.
def incomplete_rollback(_spec, _volume):
raise VMError("模拟回滚不完整,请人工检查", 502)
monkeypatch.setattr(service, "create_cloud_vm", incomplete_rollback)
uncertain = first.post("/api/v1/vms", json={
**automatic_body, "name": "uncertain-vm",
}, headers=first_headers)
assert uncertain.status_code == 502
assert store.get("ip_claim", free_claim) is not None
monkeypatch.setattr(service, "create_cloud_vm", original_create)
still_exhausted = first.post("/api/v1/vms", json={
**automatic_body, "name": "uncertain-ip-protected",
}, headers=first_headers)
assert still_exhausted.status_code == 409
@pytest.mark.parametrize(("vm_prefix", "first_ip"), [
(None, "123.123.123.114/28"),
(24, "123.123.123.114/24"),
])
def test_provider_28_pool_allocates_only_inside_assigned_block(
monkeypatch, tmp_path, vm_prefix, first_ip,
):
store = MemoryStore()
service = _Service()
manager = _Manager()
manager.profile = {
**_Manager.profile,
"host": "123.123.123.113",
"public_pool_cidr": "123.123.123.112/28",
"public_gateway": "123.123.123.113",
"public_dns_servers": ["1.1.1.1"],
"public_reserved_ips": ["123.123.123.115"],
"public_vm_prefix": vm_prefix,
}
monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
DatabasePanelState(directory, store, store.users), manager,
DatabaseTemplateStore(store), store,
))
monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
settings = Settings(
data_dir=tmp_path / "data",
static_dir=Path(__file__).resolve().parents[1] / "static",
)
app = app_module.create_app(settings, service_factory=lambda _profile: service)
token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
automatic_body = {
key: value for key, value in CLOUD_VM.items()
if key not in {"public_ip_cidr", "gateway", "dns_servers"}
}
automatic_body["guest_ssh_public_key"] = GUEST_PUBLIC_KEY
with TestClient(app, base_url=ORIGIN) as admin:
assert admin.post("/api/v1/database/setup", json={
"host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
"username": "panel", "password": "database-password", "setup_token": token,
}).status_code == 200
initial = admin.post("/api/v1/setup/admin", json={
"token": token, "username": "operator", "password": PASSWORD,
})
assert initial.status_code == 200
headers = {"X-CSRF-Token": initial.json()["csrf_token"]}
store.users.promote("operator")
DatabaseTemplateStore(store).add(template_scope(manager.profile), {
"id": "alma10-template", "name": "AlmaLinux 10",
"volume_name": "panel-template-alma10.qcow2",
})
created = admin.post("/api/v1/vms", json=automatic_body, headers=headers)
assert created.status_code == 201
assert service.cloud_specs[0][0]["public_ip_cidr"] == first_ip
assert service.cloud_specs[0][0]["gateway"] == "123.123.123.113"
# Exhaust the small provider allocation; never spill into the /24.
for address in ipaddress.ip_network("123.123.123.112/28").hosts():
ip = str(address)
if ip not in {"123.123.123.113", "123.123.123.114", "123.123.123.115"}:
service.vms[f"used-{ip}"] = {"uuid": f"used-{ip}",
"public_ip_cidr": f"{ip}/{vm_prefix or 28}"}
exhausted = admin.post("/api/v1/vms", json={
**automatic_body, "name": "no-provider-ip-left",
}, headers=headers)
assert exhausted.status_code == 409
assert len(service.cloud_specs) == 1

@ -0,0 +1,561 @@
"""SSH host configuration is pinned, private, and switched only after test."""
from __future__ import annotations
import base64
import hashlib
import itertools
import json
import shutil
import stat
import struct
import subprocess
from dataclasses import replace
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
import pytest
from virsh_panel.remote_host import (
HostProfile,
RemoteHostError,
RemoteHostManager,
)
from virsh_panel.ssh_agent import SSHAgentError
def host_key(seed: bytes) -> str:
blob = (
struct.pack("!I", len(b"ssh-ed25519"))
+ b"ssh-ed25519"
+ struct.pack("!I", 32)
+ seed * 32
)
return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii")
PRIVATE_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nZmFrZQ==\n-----END OPENSSH PRIVATE KEY-----\n"
class Runner:
def __init__(self) -> None:
self.key = host_key(b"a")
self.ssh_exit = 0
self.encrypted = False
self.public_key_type = "ssh-ed25519"
self.commands: list[list[str]] = []
def __call__(self, argv, **kwargs):
self.commands.append(argv)
assert kwargs["timeout"] <= 22
assert kwargs["capture_output"] is True
assert kwargs["check"] is False
if argv[0] == "ssh-keyscan":
return subprocess.CompletedProcess(argv, 0, f"[host.example]:2222 {self.key}\n", "")
if argv[0] == "ssh-keygen":
if self.encrypted:
return subprocess.CompletedProcess(argv, 255, "", "passphrase required")
return subprocess.CompletedProcess(argv, 0, f"{self.public_key_type} fake-public-key\n", "")
if argv[0] == "ssh":
return subprocess.CompletedProcess(argv, self.ssh_exit, "", "permission denied")
raise AssertionError(argv)
def make_manager(tmp_path: Path, runner: Runner) -> RemoteHostManager:
return RemoteHostManager(
tmp_path / "service-home",
ssh_user_config_path=tmp_path / "service-home" / ".ssh" / "config",
runner=runner,
)
def make_profile(
scanned: dict, *, key: str = PRIVATE_KEY, host: str = "host.example",
passphrase: str = "", storage_pool: str = "images", iso_pool: str = "iso",
rescue_iso_pool: str = "", default_network: str = "default", region: str = "",
) -> HostProfile:
return HostProfile(
host=host,
port=2222,
private_key=key,
host_key=scanned["known_hosts_line"],
private_key_passphrase=passphrase,
storage_pool=storage_pool,
iso_pool=iso_pool,
rescue_iso_pool=rescue_iso_pool,
default_network=default_network,
region=region,
)
def test_region_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned, region="中国香港"), scanned["fingerprint"])
manager.test(staged)
assert manager.commit(staged)["region"] == "中国香港"
profile_path = staged.path / "profile.json"
legacy = json.loads(profile_path.read_text(encoding="utf-8"))
legacy.pop("region")
profile_path.write_text(json.dumps(legacy), encoding="utf-8")
assert manager.current()["region"] == ""
def test_public_pool_survives_host_save_and_legacy_metadata_defaults_empty(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
profile = replace(
make_profile(scanned),
public_pool_cidr="1.2.3.0/24",
public_gateway="1.2.3.1",
public_dns_servers=["1.1.1.1", "8.8.8.8"],
public_reserved_ips=["1.2.3.10", "1.2.3.10"],
)
staged = manager.stage(profile, scanned["fingerprint"])
assert staged.metadata["public_reserved_ips"] == ["1.2.3.10"]
manager.test(staged)
current = manager.commit(staged)
assert current["public_pool_cidr"] == "1.2.3.0/24"
assert current["public_gateway"] == "1.2.3.1"
assert current["public_dns_servers"] == ["1.1.1.1", "8.8.8.8"]
assert current["public_reserved_ips"] == ["1.2.3.10"]
metadata_path = staged.path / "profile.json"
legacy = json.loads(metadata_path.read_text(encoding="utf-8"))
for key in ("public_pool_cidr", "public_gateway", "public_dns_servers", "public_reserved_ips"):
legacy.pop(key)
metadata_path.write_text(json.dumps(legacy), encoding="utf-8")
assert manager.current()["public_pool_cidr"] == ""
assert manager.current()["public_dns_servers"] == []
assert manager.current()["public_reserved_ips"] == []
def test_provider_28_gateway_cidr_is_saved_as_canonical_network(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
profile = replace(
make_profile(scanned),
public_pool_cidr="123.123.123.113/28",
public_gateway="123.123.123.113",
public_dns_servers=["1.1.1.1"],
public_vm_prefix=24,
)
staged = manager.stage(profile, scanned["fingerprint"])
assert staged.metadata["public_pool_cidr"] == "123.123.123.112/28"
assert staged.metadata["public_vm_prefix"] == 24
manager.test(staged)
assert manager.commit(staged)["public_pool_cidr"] == "123.123.123.112/28"
assert manager.current()["public_vm_prefix"] == 24
class FakeAgent:
sequence = itertools.count()
def __init__(self, generation: Path, _key_path: Path, passphrase: str) -> None:
if passphrase != "open-sesame":
raise SSHAgentError("bad passphrase")
self.socket_path = generation / f"agent-{next(self.sequence)}.sock"
self.public_key = host_key(b"b")
self.alive = True
def close(self) -> None:
self.alive = False
def test_scan_returns_fingerprint_without_trusting_key(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
digest = hashlib.sha256(base64.b64decode(runner.key.split()[1])).digest()
assert scanned == {
"host": "host.example",
"port": 2222,
"key_type": "ssh-ed25519",
"fingerprint": "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("="),
"host_key": runner.key,
"known_hosts_line": "vp-managed " + runner.key,
}
assert manager.current() is None
assert not manager.ssh_user_config_path.exists()
assert runner.commands[0] == [
"ssh-keyscan", "-T", "8", "-p", "2222", "-t", "ed25519", "host.example",
]
def test_encrypted_key_is_memory_only_and_requires_unlock_after_restart(tmp_path):
runner = Runner()
runner.encrypted = True
data_dir = tmp_path / "panel-data"
manager = RemoteHostManager(data_dir, runner=runner, agent_factory=FakeAgent)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(
make_profile(scanned, passphrase="open-sesame"), scanned["fingerprint"],
)
config = (staged.path / "config").read_text(encoding="ascii")
assert f'IdentityFile "{staged.path / "identity.pub"}"' in config
assert f'IdentityAgent "{manager._agents[staged.path].socket_path}"' in config
assert all(
b"open-sesame" not in path.read_bytes()
for path in staged.path.iterdir() if path.is_file()
)
manager.test(staged)
manager.commit(staged)
assert manager.current()["private_key_encrypted"] is True
assert manager.current()["key_locked"] is False
manager.close()
assert manager.current()["key_locked"] is True
restarted = RemoteHostManager(data_dir, runner=runner, agent_factory=FakeAgent)
assert restarted.current()["key_locked"] is True
original_config = (staged.path / "config").read_text(encoding="ascii")
with pytest.raises(RemoteHostError, match="口令错误"):
restarted.unlock_current("wrong")
assert restarted.current()["key_locked"] is True
assert (staged.path / "config").read_text(encoding="ascii") == original_config
unlocked = restarted.unlock_current("open-sesame")
assert unlocked["key_locked"] is False
assert str(restarted._agents[staged.path].socket_path) in (
staged.path / "config"
).read_text(encoding="ascii")
restarted.close()
def test_encrypted_key_needs_passphrase_and_rejects_wrong_one(tmp_path):
runner = Runner()
runner.encrypted = True
manager = RemoteHostManager(tmp_path / "panel-data", runner=runner, agent_factory=FakeAgent)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="填写私钥口令"):
manager.stage(make_profile(scanned), scanned["fingerprint"])
with pytest.raises(RemoteHostError, match="口令错误"):
manager.stage(make_profile(scanned, passphrase="wrong"), scanned["fingerprint"])
assert not list((manager.data_dir / "generations").iterdir())
def test_existing_host_directories_are_accepted_as_pool_selectors(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(
make_profile(scanned, storage_pool="/home/kvm", iso_pool="/home/iso"),
scanned["fingerprint"],
)
assert staged.metadata["storage_pool"] == "/home/kvm"
assert staged.metadata["iso_pool"] == "/home/iso"
manager.abort(staged)
def test_rescue_iso_pool_survives_host_save_and_legacy_defaults_unconfigured(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(
make_profile(scanned, iso_pool="/home/iso", rescue_iso_pool="/home/rescue-iso"),
scanned["fingerprint"],
)
assert staged.metadata["rescue_iso_pool"] == "/home/rescue-iso"
manager.test(staged)
assert manager.commit(staged)["rescue_iso_pool"] == "/home/rescue-iso"
profile_path = staged.path / "profile.json"
legacy = json.loads(profile_path.read_text(encoding="utf-8"))
legacy.pop("rescue_iso_pool")
profile_path.write_text(json.dumps(legacy), encoding="utf-8")
assert manager.current()["rescue_iso_pool"] == ""
@pytest.mark.parametrize(
"rescue_selector,iso_selector",
[
("iso", "iso"),
("/home/iso", "/home/iso"),
],
)
def test_rescue_pool_cannot_equal_install_iso_pool(
tmp_path, rescue_selector, iso_selector,
):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="不能与安装 ISO 池相同"):
manager.stage(
make_profile(scanned, iso_pool=iso_selector, rescue_iso_pool=rescue_selector),
scanned["fingerprint"],
)
@pytest.mark.parametrize("selector", ["/", "/home/../iso", "/home//iso", "/home/iso/", None])
def test_rejects_invalid_rescue_pool_selector(tmp_path, selector):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="救援 ISO 池"):
manager.stage(
make_profile(scanned, rescue_iso_pool=selector),
scanned["fingerprint"],
)
def test_explicit_host_bridge_selector_is_accepted(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(
make_profile(scanned, default_network="bridge:br0"), scanned["fingerprint"],
)
assert staged.metadata["default_network"] == "bridge:br0"
manager.abort(staged)
@pytest.mark.parametrize(
"selector", ["bridge:", "bridge:br/0", "bridge:br 0", "bridge:-br0",
"bridge:" + "a" * 16],
)
def test_invalid_host_bridge_selector_is_rejected(tmp_path, selector):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="网桥名称格式无效"):
manager.stage(make_profile(scanned, default_network=selector), scanned["fingerprint"])
def test_unencrypted_ecdsa_private_key_does_not_require_passphrase(tmp_path):
runner = Runner()
runner.public_key_type = "ecdsa-sha2-nistp256"
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned), scanned["fingerprint"])
assert staged.metadata["private_key_encrypted"] is False
assert "IdentityAgent none" in (staged.path / "config").read_text()
manager.abort(staged)
@pytest.mark.parametrize("bad_path", ["/", "/home/../kvm", "/home//kvm", "/home/kvm/"])
def test_rejects_unsafe_pool_paths(tmp_path, bad_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="磁盘池"):
manager.stage(make_profile(scanned, storage_pool=bad_path), scanned["fingerprint"])
def test_stage_test_commit_writes_private_pinned_ssh_config(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
stage = manager.stage(make_profile(scanned), scanned["fingerprint"])
assert stage.tested is False
assert manager.current() is None
for name in ("id_private", "known_hosts", "config", "profile.json"):
path = stage.path / name
assert stat.S_IMODE(path.stat().st_mode) == 0o600
assert stat.S_IMODE(stage.path.stat().st_mode) == 0o700
config = (stage.path / "config").read_text()
assert "Host vp-managed\n" in config
assert "HostName host.example\n" in config
assert "Port 2222\n" in config
assert "User root\n" in config
assert "HostKeyAlias vp-managed\n" in config
assert "StrictHostKeyChecking yes\n" in config
assert "BatchMode yes\n" in config
assert "IdentitiesOnly yes\n" in config
assert "PasswordAuthentication no\n" in config
assert "HostKeyAlgorithms ssh-ed25519\n" in config
assert "ServerAliveInterval 15\n" in config
assert "ServerAliveCountMax 2\n" in config
assert (stage.path / "known_hosts").read_text() == scanned["known_hosts_line"] + "\n"
assert (stage.path / "id_private").read_text() == PRIVATE_KEY
wrapper = stage.path / "ssh-wrapper"
assert stat.S_IMODE(wrapper.stat().st_mode) == 0o700
assert parse_qs(urlsplit(stage.libvirt_uri).query)["command"] == [str(wrapper)]
assert manager.test(stage) == {"ok": True, "ssh": "connected", "libvirt": "available"}
assert runner.commands[-1][0:4] == ["ssh", "-F", stage.ssh_config_file, "-T"]
current = manager.commit(stage)
assert current["host"] == "host.example"
assert current["port"] == 2222
assert current["fingerprint"] == scanned["fingerprint"]
assert current["private_key_configured"] is True
assert current["libvirt_uri"].startswith(
"qemu+ssh://root@vp-managed/system?no_tty=1&command="
)
assert parse_qs(urlsplit(current["libvirt_uri"]).query)["command"] == [str(wrapper)]
assert manager.libvirt_uri == current["libvirt_uri"]
assert current["ssh_target"] == "vp-managed"
assert "private_key" not in current
assert PRIVATE_KEY not in repr(current)
assert manager.ssh_user_config_path.is_symlink()
assert manager.ssh_user_config_path.resolve() == stage.path / "config"
assert stat.S_IMODE(manager.ssh_user_config_path.parent.stat().st_mode) == 0o700
def test_rejects_unconfirmed_or_changed_host_key(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="确认"):
manager.stage(make_profile(scanned), "")
runner.key = host_key(b"b")
with pytest.raises(RemoteHostError) as error:
manager.stage(make_profile(scanned), scanned["fingerprint"])
assert error.value.status == 409
assert manager.current() is None
def test_failed_test_preserves_old_connection_and_key_can_be_reused(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
first_scan = manager.scan("host.example", 2222)
first = manager.stage(make_profile(first_scan), first_scan["fingerprint"])
manager.test(first)
manager.commit(first)
first_config = manager.ssh_user_config_path.resolve()
next_scan = manager.scan("other.example", 2222)
second = manager.stage(
make_profile(next_scan, key="", host="other.example"),
next_scan["fingerprint"],
)
assert (second.path / "id_private").read_text() == PRIVATE_KEY
runner.ssh_exit = 255
with pytest.raises(RemoteHostError) as error:
manager.test(second)
assert error.value.status == 502
with pytest.raises(RemoteHostError, match="测试"):
manager.commit(second)
assert manager.ssh_user_config_path.resolve() == first_config
assert manager.current()["host"] == "host.example"
manager.abort(second)
assert not second.path.exists()
def test_first_connection_needs_key_and_does_not_replace_existing_config(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
with pytest.raises(RemoteHostError, match="首次"):
manager.stage(make_profile(scanned, key=""), scanned["fingerprint"])
manager.ssh_user_config_path.parent.mkdir(mode=0o700, parents=True)
manager.ssh_user_config_path.write_text("Host unrelated\n")
staged = manager.stage(make_profile(scanned), scanned["fingerprint"])
manager.test(staged)
with pytest.raises(RemoteHostError, match="已有其他 SSH 配置"):
manager.commit(staged)
assert manager.ssh_user_config_path.read_text() == "Host unrelated\n"
assert manager.current() is None
@pytest.mark.skipif(shutil.which("ssh") is None, reason="OpenSSH client unavailable")
def test_openssh_reads_staged_nondefault_port_and_root_identity(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned), scanned["fingerprint"])
result = subprocess.run(
["ssh", "-G", "-F", staged.ssh_config_file, "vp-managed"],
check=True,
capture_output=True,
text=True,
timeout=8,
)
options = dict(line.split(" ", 1) for line in result.stdout.splitlines() if " " in line)
assert options["hostname"] == "host.example"
assert options["port"] == "2222"
assert options["user"] == "root"
assert options["hostkeyalias"] == "vp-managed"
assert options["stricthostkeychecking"] == "true"
assert options["identityfile"] == str(staged.path / "id_private")
assert options["userknownhostsfile"] == str(staged.path / "known_hosts")
def test_staged_wrapper_passes_config_to_ssh_without_shell(tmp_path):
runner = Runner()
manager = RemoteHostManager(
tmp_path / "service-home", ssh_binary="/bin/echo", runner=runner
)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned), scanned["fingerprint"])
result = subprocess.run(
[str(staged.path / "ssh-wrapper"), "-T", "root@vp-managed"],
check=True,
capture_output=True,
text=True,
timeout=8,
)
assert result.stdout.strip() == f"-F {staged.ssh_config_file} -T root@vp-managed"
def test_only_retired_generations_are_pruned(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
first = manager.stage(make_profile(scanned), scanned["fingerprint"])
manager.test(first)
manager.commit(first)
second = manager.stage(make_profile(scanned, key=""), scanned["fingerprint"])
# An uncommitted generation must not be deleted by background cleanup.
assert manager.cleanup_inactive(grace_seconds=0) == 0
assert second.path.is_dir()
manager.test(second)
manager.commit(second)
assert manager.cleanup_inactive(grace_seconds=60) == 0
assert first.path.is_dir()
assert manager.cleanup_inactive(grace_seconds=0) == 1
assert not first.path.exists()
assert second.path.is_dir()
assert manager.current()["ssh_config_file"] == second.ssh_config_file
def test_symlinked_parent_keeps_active_generation(tmp_path):
# A lexical/canonical path mismatch must not classify the active
# generation as retired.
actual_parent = tmp_path / "private" / "virsh-panel"
actual_parent.mkdir(parents=True)
public_parent = tmp_path / "public-parent"
public_parent.symlink_to(actual_parent, target_is_directory=True)
runner = Runner()
manager = RemoteHostManager(public_parent / "state", runner=runner)
assert manager.data_dir == actual_parent / "state"
scanned = manager.scan("host.example", 2222)
first = manager.stage(make_profile(scanned), scanned["fingerprint"])
manager.test(first)
manager.commit(first)
assert manager.current()["ssh_config_file"] == first.ssh_config_file
assert manager.cleanup_inactive(grace_seconds=0) == 0
assert first.path.is_dir()
restarted = RemoteHostManager(public_parent / "state", runner=runner)
assert restarted.current()["ssh_config_file"] == first.ssh_config_file
assert restarted.cleanup_inactive(grace_seconds=0) == 0
assert first.path.is_dir()
second = restarted.stage(make_profile(scanned, key=""), scanned["fingerprint"])
restarted.test(second)
restarted.commit(second)
assert restarted.cleanup_inactive(grace_seconds=0) == 1
assert not first.path.exists()
assert second.path.is_dir()
assert restarted.current()["ssh_config_file"] == second.ssh_config_file
def test_rejects_symlink_as_final_data_directory(tmp_path):
actual = tmp_path / "actual"
actual.mkdir()
alias = tmp_path / "alias"
alias.symlink_to(actual, target_is_directory=True)
with pytest.raises(RemoteHostError, match="符号链接"):
RemoteHostManager(alias, runner=Runner())
@pytest.mark.parametrize("host,port", [
("-oProxyCommand=bad", 22),
("host.example\nUser attacker", 22),
("example.com", 0),
("example.com", 65536),
("example.com", True),
])
def test_rejects_host_and_port_injection(tmp_path, host, port):
runner = Runner()
manager = make_manager(tmp_path, runner)
with pytest.raises(RemoteHostError):
manager.scan(host, port)
assert runner.commands == []

@ -0,0 +1,71 @@
"""Rescue ISO catalog and bootable-file boundary tests."""
from __future__ import annotations
import pytest
from virsh_panel.cloud_templates import TemplateError
from virsh_panel.rescue_templates import (
RescueTemplateStore, rescue_scope, rescue_volume_name, verify_bootable_iso,
)
def _profile(rescue_iso_pool="rescue"):
return {
"host": "vmhost.example", "port": 2222, "fingerprint": "SHA256:vmhost",
"iso_pool": "iso", "rescue_iso_pool": rescue_iso_pool,
}
def _iso_bytes(bootable=True):
image = bytearray(1024 * 1024)
for sector, kind in ((16, 1), (17, 0 if bootable else 2), (18, 255)):
offset = sector * 2048
image[offset] = kind
image[offset + 1:offset + 6] = b"CD001"
image[offset + 6] = 1
if bootable:
image[17 * 2048 + 7:17 * 2048 + 30] = b"EL TORITO SPECIFICATION"
image[17 * 2048 + 71:17 * 2048 + 75] = (20).to_bytes(4, "little")
return bytes(image)
def test_rescue_catalog_is_scoped_to_rescue_pool_and_rejects_duplicate_names():
catalog = RescueTemplateStore(None)
first_scope = rescue_scope(_profile())
second_scope = rescue_scope(_profile("other-rescue"))
assert first_scope != second_scope
template_id = "a" * 32
record = {
"id": template_id, "name": "System Rescue",
"volume_name": rescue_volume_name(template_id),
"size_bytes": 1024 * 1024, "sha256": "b" * 64,
}
catalog.add(first_scope, record)
assert catalog.list(second_scope) == []
assert catalog.get(first_scope, template_id)["name"] == "System Rescue"
with pytest.raises(TemplateError):
catalog.add(first_scope, {**record, "id": "c" * 32,
"volume_name": rescue_volume_name("c" * 32)})
catalog.delete(first_scope, template_id)
assert catalog.list(first_scope) == []
def test_rescue_catalog_requires_separate_configured_pool():
with pytest.raises(TemplateError, match="救援 ISO 目录"):
rescue_scope(_profile(""))
assert rescue_scope(_profile()) == rescue_scope({
**_profile(), "iso_pool": "other-install-iso",
})
def test_rescue_iso_must_include_el_torito_boot_record(tmp_path):
path = tmp_path / "rescue.iso"
path.write_bytes(_iso_bytes())
verify_bootable_iso(path)
path.write_bytes(_iso_bytes(bootable=False))
with pytest.raises(TemplateError, match="El Torito"):
verify_bootable_iso(path)
path.write_bytes(b"not an ISO")
with pytest.raises(TemplateError):
verify_bootable_iso(path)

@ -0,0 +1,201 @@
"""SMTP settings safety and registration mail transport tests."""
from __future__ import annotations
import smtplib
import pytest
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from virsh_panel.database import DatabaseStore
from virsh_panel.smtp_service import (
SMTPConfig, SMTPError, SMTPSettingsStore, send_verification_code, validate_email,
)
def _settings(**overrides):
values = {
"host": "smtp.example.com", "port": 587, "tls_mode": "starttls",
"from_address": "no-reply@example.com", "username": "account@example.com",
"password": "app-password-secret",
}
values.update(overrides)
return values
class EncryptedRecords:
def __init__(self):
self.cipher = DatabaseStore.__new__(DatabaseStore)
self.cipher._cipher = AESGCM(b"s" * 32)
self.data = {}
def get(self, kind, key):
encrypted = self.data.get((kind, key))
return None if encrypted is None else self.cipher._decrypt(kind, key, encrypted)
def set(self, kind, key, value):
self.data[(kind, key)] = self.cipher._encrypt(kind, key, value)
def test_smtp_settings_are_encrypted_and_password_never_returns_in_status():
records = EncryptedRecords()
settings = SMTPSettingsStore(records)
assert settings.public_status() == {"configured": False}
config = settings.save(_settings())
assert config.password == "app-password-secret"
ciphertext = records.data[("smtp", "current")]
assert b"app-password-secret" not in ciphertext
assert b"smtp.example.com" not in ciphertext
status = settings.public_status()
assert status == {
"configured": True, "host": "smtp.example.com", "port": 587,
"tls_mode": "starttls", "from_address": "no-reply@example.com",
"username": "account@example.com", "password_configured": True,
}
assert "app-password-secret" not in repr(config)
assert "password" not in status
def test_smtp_update_keeps_existing_password_only_for_same_account():
settings = SMTPSettingsStore(EncryptedRecords())
settings.save(_settings())
assert settings.save(_settings(host="new.example.com", password="")).password == "app-password-secret"
with pytest.raises(SMTPError, match="必须同时填写"):
settings.save(_settings(username="other@example.com", password=""))
assert settings.get().host == "new.example.com"
assert settings.get().username == "account@example.com"
@pytest.mark.parametrize("value", [
_settings(host="smtp.example.com\r\nX-Injected: yes"),
_settings(port=True),
_settings(port=0),
_settings(tls_mode="invalid"),
_settings(tls_mode=[]),
_settings(from_address="Sender <sender@example.com>"),
_settings(username="x", password="", tls_mode="starttls"),
_settings(tls_mode="none"),
])
def test_invalid_smtp_settings_are_rejected(value):
with pytest.raises(SMTPError):
SMTPConfig.from_mapping(value)
@pytest.mark.parametrize("address", [
"user@example.com\r\nBcc: victim@example.com", "Name <user@example.com>",
"user..name@example.com", "user@", "@example.com", " user@example.com",
])
def test_invalid_mailbox_is_rejected(address):
with pytest.raises(SMTPError, match="邮箱地址格式无效"):
validate_email(address)
def test_address_keeps_local_part_and_canonicalizes_domain():
assert validate_email("User+tag@EXAMPLE.COM") == "User+tag@example.com"
class FakeSMTP:
events = []
sent = None
refused = {}
def __init__(self, host, port, **kwargs):
self.events.append(("connect", host, port, kwargs))
def __enter__(self):
return self
def __exit__(self, *_args):
self.events.append("quit")
def ehlo(self):
self.events.append("ehlo")
def starttls(self, **kwargs):
assert "context" in kwargs
self.events.append("starttls")
def login(self, username, password):
self.events.append(("login", username, password))
def send_message(self, message):
self.events.append("send")
self.sent = message
return self.refused
def test_starttls_happens_before_login_and_sends_six_digit_code(monkeypatch):
FakeSMTP.events = []
FakeSMTP.refused = {}
instances = []
def make_client(*args, **kwargs):
client = FakeSMTP(*args, **kwargs)
instances.append(client)
return client
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", make_client)
send_verification_code(SMTPConfig.from_mapping(_settings()), "user@example.com", "012345")
assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 587)
assert FakeSMTP.events[0][3]["timeout"] == 10
assert FakeSMTP.events[1:] == [
"ehlo", "starttls", "ehlo",
("login", "account@example.com", "app-password-secret"), "send", "quit",
]
message = instances[0].sent
assert message["To"] == "user@example.com"
assert message["From"] == "no-reply@example.com"
assert "012345" in message.get_content()
def test_ssl_and_unauthenticated_local_relay(monkeypatch):
FakeSMTP.events = []
FakeSMTP.refused = {}
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP_SSL", FakeSMTP)
send_verification_code(
SMTPConfig.from_mapping(_settings(port=465, tls_mode="ssl")),
"user@example.com", "123456",
)
assert FakeSMTP.events[0][0:3] == ("connect", "smtp.example.com", 465)
assert "context" in FakeSMTP.events[0][3]
assert "starttls" not in FakeSMTP.events
FakeSMTP.events = []
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP)
send_verification_code(
SMTPConfig.from_mapping(_settings(port=25, tls_mode="none", username="", password="")),
"user@example.com", "123456",
)
assert not any(isinstance(event, tuple) and event[0] == "login"
for event in FakeSMTP.events)
def test_smtp_transport_failure_is_redacted(monkeypatch):
class FailingSMTP(FakeSMTP):
def login(self, *_args):
raise smtplib.SMTPAuthenticationError(535, b"secret server reply")
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FailingSMTP)
with pytest.raises(SMTPError) as failure:
send_verification_code(
SMTPConfig.from_mapping(_settings()), "user@example.com", "123456",
)
assert failure.value.status == 502
assert "secret" not in str(failure.value)
assert "app-password" not in str(failure.value)
def test_refused_recipient_and_bad_code_do_not_leak_details(monkeypatch):
FakeSMTP.events = []
FakeSMTP.refused = {"user@example.com": (550, "mailbox secret")}
monkeypatch.setattr("virsh_panel.smtp_service.smtplib.SMTP", FakeSMTP)
config = SMTPConfig.from_mapping(_settings())
with pytest.raises(SMTPError) as failure:
send_verification_code(config, "user@example.com", "123456")
assert failure.value.status == 502
assert "secret" not in str(failure.value)
with pytest.raises(SMTPError, match="验证码格式无效"):
send_verification_code(config, "user@example.com", "00000\n")

@ -0,0 +1,210 @@
"""Exercise passphrase loading without a remote SSH server."""
from __future__ import annotations
import errno
import os
import select
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
import pytest
from virsh_panel.ssh_agent import SSHAgentError, SSHAgentSession
@pytest.fixture
def encrypted_key() -> tuple[Path, Path, str]:
for command in ("ssh-agent", "ssh-add", "ssh-keygen"):
if shutil.which(command) is None:
pytest.skip(f"{command} is unavailable")
temporary_root = "/private/tmp" if Path("/private/tmp").is_dir() else "/tmp"
with tempfile.TemporaryDirectory(prefix="vp-agent-", dir=temporary_root) as directory:
generation = Path(directory) / "generation"
generation.mkdir(mode=0o700)
probe_path = generation / "probe.sock"
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
try:
probe.bind(str(probe_path))
except OSError as exc:
if sys.platform == "darwin" and exc.errno in {errno.EACCES, errno.EPERM}:
pytest.skip("test environment forbids local Unix sockets")
raise
probe_path.unlink()
key_path = generation / "id_private"
passphrase = "integration-test-only-phrase"
subprocess.run(
["ssh-keygen", "-q", "-t", "ed25519", "-N", passphrase, "-f", str(key_path)],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=True,
timeout=10,
)
yield generation, key_path, passphrase
def test_load_encrypted_key_and_close(encrypted_key: tuple[Path, Path, str]) -> None:
generation, key_path, passphrase = encrypted_key
session = SSHAgentSession(generation, key_path, passphrase)
socket_path = session.socket_path
try:
assert socket_path.parent == generation
assert socket_path.is_socket()
assert session.alive
assert session.public_key.startswith("ssh-ed25519 ")
assert not list(generation.glob("askpass-*"))
listed = subprocess.run(
["ssh-add", "-L"],
env={**os.environ, "SSH_AUTH_SOCK": str(socket_path)},
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
check=True,
timeout=5,
)
assert listed.stdout.startswith(session.public_key)
finally:
session.close()
assert not session.alive
assert not socket_path.exists()
def test_wrong_passphrase_cleans_up(encrypted_key: tuple[Path, Path, str]) -> None:
generation, key_path, _passphrase = encrypted_key
with pytest.raises(SSHAgentError, match="无法解锁"):
SSHAgentSession(generation, key_path, "incorrect-test-only-phrase")
assert not list(generation.glob("agent-*.sock"))
assert not list(generation.glob("askpass-*"))
def test_two_sessions_do_not_share_socket(encrypted_key: tuple[Path, Path, str]) -> None:
generation, key_path, passphrase = encrypted_key
first = SSHAgentSession(generation, key_path, passphrase)
second = SSHAgentSession(generation, key_path, passphrase)
try:
assert first.socket_path != second.socket_path
first.close()
assert second.alive
finally:
first.close()
second.close()
@pytest.mark.parametrize("bad", ["x\ny", "x\ry", "x\x00y", "x" * 1024])
def test_rejects_unsafe_passphrase(
encrypted_key: tuple[Path, Path, str], bad: str
) -> None:
generation, key_path, _passphrase = encrypted_key
with pytest.raises(SSHAgentError):
SSHAgentSession(generation, key_path, bad)
assert not list(generation.glob("agent-*.sock"))
def test_passphrase_is_not_in_arguments_or_environment(
encrypted_key: tuple[Path, Path, str], monkeypatch: pytest.MonkeyPatch
) -> None:
generation, key_path, passphrase = encrypted_key
original_run = subprocess.run
observed: list[dict[str, object]] = []
def checking_run(argv: list[str], **kwargs: object) -> subprocess.CompletedProcess[object]:
if Path(argv[0]).name == "ssh-add" and "-q" in argv:
observed.append(kwargs)
assert passphrase not in repr(argv)
assert passphrase not in repr(kwargs.get("env"))
assert kwargs.get("pass_fds")
assert kwargs.get("stdin") == subprocess.DEVNULL
return original_run(argv, **kwargs)
monkeypatch.setattr(subprocess, "run", checking_run)
session = SSHAgentSession(generation, key_path, passphrase)
try:
assert session.alive
assert len(observed) == 1
finally:
session.close()
@pytest.mark.skipif(sys.platform != "linux", reason="Linux parent-death watchdog")
def test_linux_agent_survives_creator_thread_exit(
encrypted_key: tuple[Path, Path, str]
) -> None:
generation, key_path, passphrase = encrypted_key
created: dict[str, object] = {}
def create() -> None:
try:
created["session"] = SSHAgentSession(generation, key_path, passphrase)
except Exception as exc:
created["error"] = exc
thread = threading.Thread(target=create)
thread.start()
thread.join(timeout=20)
assert not thread.is_alive()
error = created.get("error")
if isinstance(error, BaseException):
raise error
session = created["session"]
assert isinstance(session, SSHAgentSession)
try:
# Direct PR_SET_PDEATHSIG on the app-spawned agent would kill it when
# this worker thread exits, even though the panel process is alive.
time.sleep(0.2)
assert session.alive
finally:
session.close()
@pytest.mark.skipif(sys.platform != "linux", reason="Linux parent-death watchdog")
def test_linux_agent_ends_after_panel_sigkill(
encrypted_key: tuple[Path, Path, str]
) -> None:
generation, key_path, passphrase = encrypted_key
child_code = (
"import sys,time\n"
"from pathlib import Path\n"
"from virsh_panel.ssh_agent import SSHAgentSession\n"
"session=SSHAgentSession(Path(sys.argv[1]),Path(sys.argv[2]),"
"sys.stdin.readline().rstrip('\\n'))\n"
"print(session.socket_path, flush=True)\n"
"time.sleep(60)\n"
)
panel = subprocess.Popen(
[sys.executable, "-c", child_code, str(generation), str(key_path)],
cwd=str(Path(__file__).resolve().parents[1]),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
assert panel.stdin is not None
panel.stdin.write(passphrase + "\n")
panel.stdin.close()
assert panel.stdout is not None
readable, _, _ = select.select([panel.stdout], [], [], 15)
assert readable, "panel subprocess did not report its agent socket"
socket_name = panel.stdout.readline().strip()
assert socket_name, "panel subprocess exited before starting its agent"
agent_socket = Path(socket_name)
assert agent_socket.is_socket()
os.kill(panel.pid, signal.SIGKILL)
panel.wait(timeout=5)
deadline = time.monotonic() + 5
while agent_socket.exists() and time.monotonic() < deadline:
time.sleep(0.05)
assert not agent_socket.exists(), "agent socket survived the panel process"
finally:
if panel.poll() is None:
panel.kill()
panel.wait(timeout=5)

@ -0,0 +1,168 @@
"""Owner-isolated MariaDB SSH public key records, using a SQL test adapter."""
from __future__ import annotations
import base64
import hashlib
import sqlite3
import struct
import pytest
from virsh_panel.ssh_keys import DatabaseSSHKeyStore, SSHKeyError
def _valid_key(seed: bytes = b"a", comment: str = "operator@example") -> str:
blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + seed * 32
return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") + " " + comment
class _Cursor:
def __init__(self, connection: sqlite3.Connection) -> None:
self._cursor = connection.cursor()
def __enter__(self):
return self
def __exit__(self, *_exc):
self._cursor.close()
def execute(self, statement, parameters=()):
try:
self._cursor.execute(statement.replace("%s", "?"), parameters)
except sqlite3.IntegrityError as exc:
import pymysql
raise pymysql.err.IntegrityError(1062, str(exc)) from exc
return self
def fetchone(self):
row = self._cursor.fetchone()
return None if row is None else dict(row)
def fetchall(self):
return [dict(row) for row in self._cursor.fetchall()]
@property
def lastrowid(self):
return self._cursor.lastrowid
@property
def rowcount(self):
return self._cursor.rowcount
class _Connection:
def __init__(self) -> None:
self.raw = sqlite3.connect(":memory:")
self.raw.row_factory = sqlite3.Row
self.raw.execute("PRAGMA foreign_keys=ON")
self.raw.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY);
INSERT INTO users (id) VALUES (1), (2);
CREATE TABLE user_ssh_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
public_key TEXT NOT NULL,
fingerprint TEXT NOT NULL,
created_at INTEGER NOT NULL,
UNIQUE (user_id, fingerprint)
);
""")
def cursor(self):
return _Cursor(self.raw)
def commit(self):
self.raw.commit()
def rollback(self):
self.raw.rollback()
def close(self):
# A single in-memory database must outlive individual store calls.
pass
class _Store:
def __init__(self) -> None:
self.connection = _Connection()
def _connect(self):
return self.connection
@pytest.fixture
def key_store():
store = _Store()
yield DatabaseSSHKeyStore(store), store.connection.raw
store.connection.raw.close()
def test_keys_are_strictly_isolated_by_user_on_all_operations(key_store):
repository, database = key_store
first = repository.create_for_user(1, "生产环境", _valid_key(), now=100)
second = repository.create_for_user(2, "另一用户", _valid_key(), now=101)
assert first["id"] != second["id"]
assert first["fingerprint"] == second["fingerprint"]
assert first["public_key"] == _valid_key().rsplit(" ", 1)[0]
blob = base64.b64decode(first["public_key"].split()[1])
assert first["fingerprint"] == (
"SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
)
assert repository.list_for_user(1) == [first]
assert repository.list_for_user(2) == [second]
assert repository.get_for_user(1, second["id"]) is None
assert repository.get_for_user(2, first["id"]) is None
assert repository.delete_for_user(2, first["id"]) is False
assert repository.get_for_user(1, first["id"]) == first
assert repository.delete_for_user(1, first["id"]) is True
assert repository.delete_for_user(1, first["id"]) is False
assert repository.list_for_user(1) == []
assert repository.list_for_user(2) == [second]
database.execute("DELETE FROM users WHERE id=2")
database.commit()
assert database.execute("SELECT COUNT(*) FROM user_ssh_keys").fetchone()[0] == 0
def test_same_wire_key_cannot_be_saved_twice_per_user_even_with_new_comment(key_store):
repository, _database = key_store
repository.create_for_user(1, "第一把", _valid_key(comment="first"))
with pytest.raises(SSHKeyError) as duplicate:
repository.create_for_user(1, "第二把", _valid_key(comment="second"))
assert duplicate.value.status == 409
assert len(repository.list_for_user(1)) == 1
# Unique constraint is owner-scoped, not a global ban on shared keys.
assert repository.create_for_user(2, "允许跨用户重复", _valid_key(comment="second"))["id"] > 0
@pytest.mark.parametrize("invalid_key", [
"-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----",
"ssh-ed25519 not-base64",
"ssh-rsa " + _valid_key().split()[1],
_valid_key() + "\nssh-ed25519 another-key",
"",
])
def test_private_or_invalid_public_keys_are_rejected_without_writes(key_store, invalid_key):
repository, _database = key_store
with pytest.raises(SSHKeyError) as invalid:
repository.create_for_user(1, "键", invalid_key)
assert invalid.value.status == 400
assert repository.list_for_user(1) == []
@pytest.mark.parametrize("invalid_name", ["", " ", " leading", "trailing ", "bad\nname", "x" * 81])
def test_key_name_must_be_safe_and_bounded(key_store, invalid_name):
repository, _database = key_store
with pytest.raises(SSHKeyError):
repository.create_for_user(1, invalid_name, _valid_key())
assert repository.list_for_user(1) == []
def test_list_is_newest_first_and_exposes_no_owner_id(key_store):
repository, _database = key_store
first = repository.create_for_user(1, "first", _valid_key(b"a"), now=100)
second = repository.create_for_user(1, "second", _valid_key(b"b"), now=200)
assert repository.list_for_user(1) == [second, first]
assert "user_id" not in second

@ -0,0 +1,218 @@
"""Guard the administrator-only image catalog and card-based VM image picker."""
from __future__ import annotations
from dataclasses import dataclass
from html.parser import HTMLParser
from pathlib import Path
import re
from xml.etree import ElementTree
import pytest
STATIC = Path(__file__).resolve().parents[1] / "static"
VOID_TAGS = {
"area", "base", "br", "col", "embed", "hr", "img", "input",
"link", "meta", "param", "source", "track", "wbr",
}
@dataclass(frozen=True)
class Element:
tag: str
attrs: dict[str, str | None]
ancestor_ids: tuple[str, ...]
class CatalogPageParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.elements: list[Element] = []
self.stack: list[Element] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
element = Element(
tag,
dict(attrs),
tuple(item.attrs["id"] for item in self.stack if item.attrs.get("id")),
)
self.elements.append(element)
if tag not in VOID_TAGS:
self.stack.append(element)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
if tag not in VOID_TAGS:
self.stack.pop()
def handle_endtag(self, tag: str) -> None:
for index in range(len(self.stack) - 1, -1, -1):
if self.stack[index].tag == tag:
del self.stack[index:]
return
@pytest.fixture(scope="module")
def page() -> tuple[list[Element], dict[str, Element]]:
parser = CatalogPageParser()
parser.feed((STATIC / "index.html").read_text(encoding="utf-8"))
assert not parser.stack, "Unclosed HTML element in the dashboard page"
by_id = {element.attrs["id"]: element for element in parser.elements if element.attrs.get("id")}
assert len(by_id) == sum(bool(element.attrs.get("id")) for element in parser.elements)
return parser.elements, by_id
def test_image_import_is_on_a_dedicated_admin_page(page) -> None:
_, by_id = page
workspace = by_id["template-workspace"]
assert "hidden" in workspace.attrs
assert "dashboard-view" in workspace.ancestor_ids
form = by_id["template-import-form"]
assert form.tag == "form"
assert "template-workspace" in form.ancestor_ids
for element_id in ("template-name", "template-url", "template-sha256", "template-import-button"):
assert "template-import-form" in by_id[element_id].ancestor_ids
assert "create-view" not in by_id[element_id].ancestor_ids
assert "reinstall-view" not in by_id[element_id].ancestor_ids
assert "template-workspace" in by_id["template-admin-list"].ancestor_ids
assert "template-import" not in by_id, "The old inline import details must be removed"
@pytest.mark.parametrize(
("form_id", "field_id", "catalog_id"),
[
("create-form", "vm-template", "vm-template-catalog"),
("reinstall-form", "reinstall-template", "reinstall-template-catalog"),
],
)
def test_vm_image_selection_uses_cards_not_selects(
page, form_id: str, field_id: str, catalog_id: str
) -> None:
elements, by_id = page
field = by_id[field_id]
catalog = by_id[catalog_id]
assert field.tag == "input"
assert field.attrs.get("type") == "hidden"
assert field.attrs.get("name") == "template_id"
assert form_id in field.ancestor_ids
assert catalog.tag == "div"
assert "template-catalog" in (catalog.attrs.get("class") or "").split()
assert form_id in catalog.ancestor_ids
assert not any(
element.tag == "select"
and element.attrs.get("name") == "template_id"
and form_id in element.ancestor_ids
for element in elements
)
def test_catalog_renders_expandable_family_and_version_cards() -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
assert 'makeElement("details", "template-family-card")' in script
assert 'makeElement("button", "template-version-option")' in script
assert 'option.dataset.templateId = id;' in script
assert 'option.setAttribute("aria-pressed"' in script
assert 'input.value = id;' in script
@pytest.mark.parametrize(
("family", "filename"),
[
("AlmaLinux", "almalinux-icon.svg"),
("Debian", "debian-icon.svg"),
("CentOS", "centos-icon.svg"),
("Ubuntu", "ubuntu-icon.svg"),
],
)
def test_system_cards_use_bundled_vector_logos(family: str, filename: str) -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
logo = STATIC / filename
assert logo.is_file()
artwork = logo.read_text(encoding="utf-8")
root = ElementTree.fromstring(artwork)
assert root.tag == "{http://www.w3.org/2000/svg}svg"
assert any(element.tag.endswith("}path") for element in root.iter())
assert f'{family}: "/static/{filename}"' in script
icon_code = script.split("function templateIcon(family, className) {", 1)[1].split(
"function renderTemplateCatalog(inputId) {", 1
)[0]
assert "TEMPLATE_ICON_PATHS[family]" in icon_code
assert 'makeElement("img", "template-system-logo")' in icon_code
assert "logo.src = logoPath;" in icon_code
assert 'icon.append(logo);' in icon_code
assert 'icon.textContent = "A"' not in icon_code
catalog_code = script.split("function renderTemplateCatalog(inputId) {", 1)[1].split(
"function renderTemplateAdminList() {", 1
)[0]
admin_code = script.split("function renderTemplateAdminList() {", 1)[1].split(
"function fillTemplateViews", 1
)[0]
assert 'templateIcon(family, "template-family-icon")' in catalog_code
assert 'templateIcon(family, "template-admin-icon")' in admin_code
def test_system_family_metadata_recognizes_debian_centos_and_ubuntu() -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
names = script.split("const TEMPLATE_FAMILY_NAMES = {", 1)[1].split("};", 1)[0]
for metadata, family in (
("debian", "Debian"),
("centos", "CentOS"),
("centosstream", "CentOS"),
("ubuntu", "Ubuntu"),
):
assert f'{metadata}: "{family}"' in names
system_code = script.split("function templateSystem(item) {", 1)[1].split(
"function templateIcon(family, className) {", 1
)[0]
assert "item?.os_family" in system_code
assert "TEMPLATE_FAMILY_NAMES[familyKey]" in system_code
def test_version_cards_show_only_centered_template_name() -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
catalog_code = script.split("function renderTemplateCatalog(inputId) {", 1)[1].split(
"function renderTemplateAdminList() {", 1
)[0]
option_code = catalog_code.split('const name = String(item.name || id);', 1)[1].split(
'option.addEventListener("click"', 1
)[0]
visible_lines = [
line for line in option_code.splitlines()
if "option.append(" in line or "option.textContent" in line
]
assert len(visible_lines) == 1
assert 'makeElement("strong", "", name)' in visible_lines[0]
assert "versionLabel" not in visible_lines[0]
assert 'makeElement("small"' not in visible_lines[0]
styles = (STATIC / "styles.css").read_text(encoding="utf-8")
version_rules = re.findall(r"\.template-version-option\{([^}]*)\}", styles)
text_align = [
match.group(1)
for rule in version_rules
for match in re.finditer(r"text-align:([^;}]*)", rule)
]
assert text_align[-1] == "center"
def test_admin_only_catalog_navigation_and_rename_control() -> None:
script = (STATIC / "app.js").read_text(encoding="utf-8")
session_code = script.split("function applySession(session) {", 1)[1].split(
"async function continueAfterLogin", 1
)[0]
for element_id in ("template-settings-button", "template-settings-mobile-button"):
assert f'"{element_id}"' in session_code
assert 'byId(id).hidden = !state.admin;' in session_code
rename_code = script.split("function renderTemplateAdminList() {", 1)[1].split(
"function fillTemplateViews", 1
)[0]
assert 'makeElement("form", "template-admin-row")' in rename_code
assert 'name.type = "text";' in rename_code
assert 'method: "PATCH"' in rename_code
assert 'encodeURIComponent(id)' in rename_code

@ -0,0 +1,80 @@
"""The systemd post-stop hook must resolve interrupted update jobs."""
from __future__ import annotations
import unittest
from pathlib import Path
from unittest.mock import patch
from virsh_panel import update_worker
class FakeStore:
def __init__(self, job_id: str | None):
self.job_id = job_id
def get_value(self, name: str) -> str | None:
if name == "update.active_job":
return self.job_id
raise AssertionError(name)
class FakeUpdater:
def __init__(self, job: dict | None):
self.job = job
self.failed: list[tuple[str, str]] = []
def get_job(self, _job_id: str) -> dict | None:
return self.job
def fail_job(self, job_id: str, message: str) -> None:
self.failed.append((job_id, message))
if self.job is not None:
self.job["status"] = "failed"
class FinalizeIncompleteTests(unittest.TestCase):
def test_running_job_is_marked_failed_once(self):
store = FakeStore("job-1234567890123456")
updater = FakeUpdater({"status": "running"})
self.assertTrue(update_worker.finalize_incomplete_job(updater, store))
self.assertEqual(updater.job["status"], "failed")
self.assertEqual(len(updater.failed), 1)
self.assertIn("日志", updater.failed[0][1])
self.assertFalse(update_worker.finalize_incomplete_job(updater, store))
self.assertEqual(len(updater.failed), 1)
def test_queued_job_is_marked_failed(self):
store = FakeStore("job-1234567890123456")
updater = FakeUpdater({"status": "queued"})
self.assertTrue(update_worker.finalize_incomplete_job(updater, store))
self.assertEqual(updater.job["status"], "failed")
def test_terminal_or_missing_job_is_not_modified(self):
for status in ("succeeded", "failed"):
with self.subTest(status=status):
updater = FakeUpdater({"status": status})
self.assertFalse(update_worker.finalize_incomplete_job(
updater, FakeStore("job-1234567890123456")))
self.assertEqual(updater.failed, [])
self.assertFalse(update_worker.finalize_incomplete_job(
FakeUpdater(None), FakeStore("job-1234567890123456")))
self.assertFalse(update_worker.finalize_incomplete_job(
FakeUpdater({"status": "running"}), FakeStore(None)))
def test_cli_finalize_mode_does_not_run_update(self):
store = FakeStore("job-1234567890123456")
updater = FakeUpdater({"status": "running"})
with patch.object(update_worker, "_load_updater", return_value=(updater, store)):
self.assertEqual(update_worker.main(["--finalize-incomplete"]), 0)
self.assertEqual(updater.job["status"], "failed")
def test_private_engine_does_not_enable_legacy_update_service(self):
unit = (Path(__file__).resolve().parents[2] / "deploy" /
"virt-cloud-engine.service").read_text(encoding="utf-8")
self.assertIn("virsh_panel.internal:create_engine", unit)
self.assertNotIn("update_worker", unit)
if __name__ == "__main__":
unittest.main()

@ -0,0 +1,255 @@
"""Offline checks for the private-repository update safety boundary."""
from __future__ import annotations
import subprocess
import tempfile
import unittest
from pathlib import Path
from virsh_panel.updater import REPOSITORY_URL, UpdateError, Updater
class MemoryStore:
def __init__(self):
self.secrets: dict[str, str] = {}
self.values: dict[str, str] = {}
def get_secret(self, name):
return self.secrets.get(name)
def set_secret(self, name, value):
self.secrets[name] = value
def delete_secret(self, name):
self.secrets.pop(name, None)
def get_value(self, name):
return self.values.get(name)
def set_value(self, name, value):
self.values[name] = value
def git(path: Path, *args: str) -> str:
result = subprocess.run(
["git", *args], cwd=path, capture_output=True, text=True, check=True,
)
return result.stdout.strip()
def make_repo(tmp_path: Path) -> Path:
source = tmp_path / "source"
source.mkdir()
git(source, "init", "-b", "main")
git(source, "config", "user.name", "Updater Test")
git(source, "config", "user.email", "updater@example.test")
(source / "README.md").write_text("old\n", encoding="utf-8")
(source / "requirements.txt").write_text("example-package==1.0\n", encoding="utf-8")
git(source, "add", "README.md", "requirements.txt")
git(source, "commit", "-m", "initial")
checkout = tmp_path / "panel"
subprocess.run(
["git", "clone", "--branch", "main", str(source), str(checkout)],
capture_output=True, text=True, check=True,
)
git(checkout, "remote", "set-url", "origin", REPOSITORY_URL)
return checkout
def advance_source(source: Path, *, filename: str = "README.md") -> str:
(source / filename).parent.mkdir(parents=True, exist_ok=True)
(source / filename).write_text("new\n", encoding="utf-8")
git(source, "add", filename)
git(source, "commit", "-m", "next")
return git(source, "rev-parse", "HEAD")
def local_fetch(updater: Updater, source: Path):
def fetch() -> str:
git(updater.repo_dir, "fetch", "--no-tags", str(source), "refs/heads/main")
return git(updater.repo_dir, "rev-parse", "FETCH_HEAD")
updater._fetch_remote = fetch
updater._install_requirements = lambda _target: None
class UpdaterTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="virsh-panel-updater-test-")
self.addCleanup(self.temp.cleanup)
self.tmp_path = Path(self.temp.name)
def test_settings_and_token_never_reveal_secret(self):
checkout = make_repo(self.tmp_path)
store = MemoryStore()
updater = Updater(checkout, store)
updater.set_token("a-test-access-token-123")
settings = updater.settings()
self.assertEqual(settings["repository"], REPOSITORY_URL)
self.assertTrue(settings["token_configured"])
self.assertTrue(settings["checkout_ready"])
self.assertIsNone(settings["active_job_id"])
self.assertIsNone(settings["last_job_id"])
self.assertNotIn("a-test-access-token-123", repr(settings))
with updater._git_auth() as env:
self.assertEqual(env["VIRSH_PANEL_GIT_TOKEN"], "a-test-access-token-123")
self.assertNotIn("a-test-access-token-123", Path(env["GIT_ASKPASS"]).read_text())
updater.clear_token()
self.assertFalse(updater.settings()["token_configured"])
def test_check_is_read_only_and_reports_new_version(self):
checkout = make_repo(self.tmp_path)
updater = Updater(checkout, MemoryStore())
current = git(checkout, "rev-parse", "HEAD")
updater._remote_head = lambda: current
self.assertEqual(updater.check()["status"], "current")
updater._remote_head = lambda: "a" * 40
self.assertEqual(updater.check()["status"], "update_available")
self.assertEqual(git(checkout, "rev-parse", "HEAD"), current)
def test_zip_or_dirty_checkout_is_rejected(self):
plain = self.tmp_path / "plain"
plain.mkdir()
with self.assertRaisesRegex(UpdateError, "Git"):
Updater(plain, MemoryStore()).check()
checkout = make_repo(self.tmp_path)
(checkout / "README.md").write_text("user changes\n", encoding="utf-8")
updater = Updater(checkout, MemoryStore())
with self.assertRaisesRegex(UpdateError, "未提交"):
updater.create_job()
with self.assertRaisesRegex(UpdateError, "未提交"):
updater.apply()
def test_fast_forward_job_is_persisted_and_calls_restart(self):
checkout = make_repo(self.tmp_path)
source = self.tmp_path / "source"
old = git(checkout, "rev-parse", "HEAD")
target = advance_source(source)
store = MemoryStore()
updater = Updater(checkout, store)
updater.set_token("a-test-access-token-123")
local_fetch(updater, source)
queued = updater.create_job()
self.assertEqual(updater.settings()["active_job_id"], queued["job_id"])
restarted = []
result = updater.run_pending_job(restart=lambda: restarted.append(True))
self.assertEqual(result["status"], "succeeded")
self.assertEqual(result["old_commit"], old)
self.assertEqual(result["new_commit"], target)
self.assertTrue(result["rollback_ref"].startswith("refs/virsh-panel/rollback/"))
self.assertEqual(updater.get_job(queued["job_id"]), result)
self.assertEqual(updater.settings()["last_job_id"], queued["job_id"])
self.assertIsNone(updater.settings()["active_job_id"])
self.assertEqual(restarted, [True])
self.assertEqual(git(checkout, "rev-parse", "HEAD"), target)
self.assertEqual(git(checkout, "rev-parse", result["rollback_ref"]), old)
def test_remote_history_rewrite_never_overwrites_local_code(self):
checkout = make_repo(self.tmp_path)
source = self.tmp_path / "source"
target = advance_source(source)
git(checkout, "config", "user.name", "Updater Test")
git(checkout, "config", "user.email", "updater@example.test")
(checkout / "README.md").write_text("local fork\n", encoding="utf-8")
git(checkout, "add", "README.md")
git(checkout, "commit", "-m", "local fork")
local = git(checkout, "rev-parse", "HEAD")
updater = Updater(checkout, MemoryStore())
local_fetch(updater, source)
with self.assertRaisesRegex(UpdateError, "分叉"):
updater.apply()
self.assertEqual(git(checkout, "rev-parse", "HEAD"), local)
self.assertNotEqual(local, target)
def test_failed_dependency_sync_leaves_code_unchanged(self):
checkout = make_repo(self.tmp_path)
source = self.tmp_path / "source"
advance_source(source)
updater = Updater(checkout, MemoryStore())
local_fetch(updater, source)
old = git(checkout, "rev-parse", "HEAD")
def fail_install(_target):
raise UpdateError("依赖失败", 502)
updater._install_requirements = fail_install
with self.assertRaisesRegex(UpdateError, "依赖失败"):
updater.apply()
self.assertEqual(git(checkout, "rev-parse", "HEAD"), old)
def test_git_url_rewrite_is_rejected_before_sending_token(self):
checkout = make_repo(self.tmp_path)
git(checkout, "config", "url.https://evil.example/.insteadOf", "https://g.luoli.live/")
updater = Updater(checkout, MemoryStore())
updater.set_token("a-test-access-token-123")
with self.assertRaisesRegex(UpdateError, "URL 重写"):
updater.check()
def test_new_code_cannot_track_private_data_or_submodules(self):
checkout = make_repo(self.tmp_path)
source = self.tmp_path / "source"
target = advance_source(source, filename="data/master.key")
updater = Updater(checkout, MemoryStore())
local_fetch(updater, source)
old = git(checkout, "rev-parse", "HEAD")
with self.assertRaisesRegex(UpdateError, "数据目录"):
updater.apply()
self.assertEqual(git(checkout, "rev-parse", "HEAD"), old)
self.assertNotEqual(old, target)
def test_failed_restart_is_persisted_without_hiding_applied_commit(self):
checkout = make_repo(self.tmp_path)
source = self.tmp_path / "source"
target = advance_source(source)
updater = Updater(checkout, MemoryStore())
updater.set_token("a-test-access-token-123")
local_fetch(updater, source)
job = updater.create_job()
def fail_restart():
raise UpdateError("重启失败", 500)
with self.assertRaisesRegex(UpdateError, "重启失败"):
updater.run_pending_job(restart=fail_restart)
stored = updater.get_job(job["job_id"])
self.assertEqual(stored["status"], "failed")
self.assertEqual(stored["new_commit"], target)
self.assertTrue(stored["rollback_ref"])
self.assertIn("代码可能已切换", stored["error"])
def test_checked_remote_commit_is_pinned_through_worker_execution(self):
checkout = make_repo(self.tmp_path)
source = self.tmp_path / "source"
old = git(checkout, "rev-parse", "HEAD")
checked = advance_source(source)
store = MemoryStore()
updater = Updater(checkout, store)
updater.set_token("a-test-access-token-123")
updater._remote_head = lambda: checked
local_fetch(updater, source)
queued = updater.create_job(
expected_current_commit=old,
expected_remote_commit=checked,
)
advance_source(source, filename="VERSION")
with self.assertRaisesRegex(UpdateError, "main 分支已变化"):
updater.run_pending_job(restart=lambda: None)
self.assertEqual(git(checkout, "rev-parse", "HEAD"), old)
self.assertEqual(updater.get_job(queued["job_id"])["status"], "failed")
def test_create_job_rejects_changed_remote_since_check(self):
checkout = make_repo(self.tmp_path)
updater = Updater(checkout, MemoryStore())
updater.set_token("a-test-access-token-123")
updater._remote_head = lambda: "b" * 40
with self.assertRaisesRegex(UpdateError, "main 分支已变化"):
updater.create_job(
expected_current_commit=git(checkout, "rev-parse", "HEAD"),
expected_remote_commit="a" * 40,
)
if __name__ == "__main__":
unittest.main()

@ -0,0 +1,253 @@
"""Exercise SQL-backed registration and ownership without a MariaDB daemon."""
from __future__ import annotations
import sqlite3
import uuid
import pytest
from virsh_panel.auth import verify_password
from virsh_panel.users import DatabaseUserStore, UserError, normalize_email
class _Cursor:
def __init__(self, connection: sqlite3.Connection) -> None:
self._cursor = connection.cursor()
def __enter__(self):
return self
def __exit__(self, *_exc):
self._cursor.close()
def execute(self, statement, parameters=()):
sql = statement.replace("%s", "?").replace(" FOR UPDATE", "")
try:
self._cursor.execute(sql, parameters)
except sqlite3.IntegrityError as exc:
import pymysql
raise pymysql.err.IntegrityError(1062, str(exc)) from exc
return self
def fetchone(self):
row = self._cursor.fetchone()
return None if row is None else dict(row)
def fetchall(self):
return [dict(row) for row in self._cursor.fetchall()]
@property
def lastrowid(self):
return self._cursor.lastrowid
@property
def rowcount(self):
return self._cursor.rowcount
class _Connection:
def __init__(self):
self.raw = sqlite3.connect(":memory:")
self.raw.row_factory = sqlite3.Row
self.raw.execute("PRAGMA foreign_keys=ON")
self.raw.executescript("""
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
email TEXT UNIQUE,
password_hash TEXT NOT NULL,
admin INTEGER NOT NULL DEFAULT 0,
approved INTEGER NOT NULL DEFAULT 0,
email_verified INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE registration_codes (
email TEXT PRIMARY KEY,
code_hash TEXT NOT NULL,
sent_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
failed_attempts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE vm_ownership (
host_scope TEXT NOT NULL,
vm_uuid TEXT NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
PRIMARY KEY (host_scope, vm_uuid)
);
""")
def cursor(self):
return _Cursor(self.raw)
def commit(self):
self.raw.commit()
def rollback(self):
self.raw.rollback()
def close(self):
# DatabaseUserStore opens a new wrapper per method. This one fake
# keeps a shared in-memory database alive across the test.
pass
class _Store:
def __init__(self):
self.connection = _Connection()
def _connect(self):
return self.connection
@pytest.fixture
def users():
store = _Store()
yield DatabaseUserStore(store, b"x" * 32), store.connection.raw
store.connection.raw.close()
def test_initial_user_is_not_admin_but_is_approved(users):
repository, _database = users
assert repository.has_users() is False
first = repository.create_initial_user("first", "initial-long-password", now=100)
assert first["admin"] is False
assert first["approved"] is True
assert first["email_verified"] is True
assert first["email"] is None
assert verify_password("initial-long-password", first["password_hash"])
assert repository.has_users() is True
assert repository.get_by_username("first") == first
assert repository.get_by_id(first["id"]) == first
assert repository.get_by_email("first@example.test") is None
assert repository.get_by_email("first") is None
_database.execute("UPDATE users SET email=? WHERE id=?", ("first@example.test", first["id"]))
_database.commit()
assert repository.get_by_email("FIRST@EXAMPLE.TEST")["id"] == first["id"]
with pytest.raises(UserError) as repeated:
repository.create_initial_user("second", "another-long-password", now=101)
assert repeated.value.status == 409
def test_initial_user_rejects_invalid_email_when_provided(users):
repository, _database = users
for email in ("", "not-an-email"):
with pytest.raises(UserError):
repository.create_initial_user("first", "initial-long-password", email)
assert repository.has_users() is False
def test_registration_code_is_keyed_rate_limited_and_one_time(users):
repository, database = users
assert repository.issue_registration_code("User@Example.COM", "123456", now=100)
code_hash = database.execute(
"SELECT code_hash FROM registration_codes WHERE email=?", ("user@example.com",)
).fetchone()[0]
assert len(code_hash) == 64
assert code_hash != "123456"
with pytest.raises(UserError) as cooldown:
repository.issue_registration_code("user@example.com", "654321", now=120)
assert cooldown.value.status == 429
with pytest.raises(UserError):
repository.register_with_code("registered", "user@example.com", "long-user-password", "000000", now=130)
assert database.execute(
"SELECT failed_attempts FROM registration_codes WHERE email=?", ("user@example.com",)
).fetchone()[0] == 1
created = repository.register_with_code(
"registered", "USER@EXAMPLE.COM", "long-user-password", "123456", now=140,
)
assert created["email"] == "user@example.com"
assert created["email_verified"] is True
assert created["admin"] is False
assert created["approved"] is False
assert verify_password("long-user-password", created["password_hash"])
assert repository.issue_registration_code("user@example.com", "222222", now=300) is False
with pytest.raises(UserError):
repository.register_with_code(
"duplicate", "user@example.com", "long-user-password", "123456", now=145,
)
def test_code_expires_and_five_failures_consume_challenge(users):
repository, database = users
repository.issue_registration_code("fail@example.com", "999999", now=100)
for attempt in range(5):
with pytest.raises(UserError):
repository.register_with_code(
"wrong", "fail@example.com", "long-user-password", "000000", now=110 + attempt,
)
assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0
with pytest.raises(UserError):
repository.register_with_code(
"wrong", "fail@example.com", "long-user-password", "999999", now=116,
)
repository.issue_registration_code("expired@example.com", "111111", now=200)
with pytest.raises(UserError):
repository.register_with_code(
"expired", "expired@example.com", "long-user-password", "111111", now=800,
)
assert database.execute(
"SELECT COUNT(*) FROM registration_codes WHERE email='expired@example.com'"
).fetchone()[0] == 0
def test_failed_smtp_delivery_can_revoke_only_matching_code(users):
repository, database = users
repository.issue_registration_code("retry@example.com", "111111", now=100)
assert repository.revoke_registration_code("retry@example.com", "222222") is False
assert repository.revoke_registration_code("retry@example.com", "111111") is True
assert database.execute("SELECT COUNT(*) FROM registration_codes").fetchone()[0] == 0
assert repository.issue_registration_code("retry@example.com", "333333", now=101)
def test_approval_and_manual_admin_flag_are_distinct(users):
repository, database = users
repository.issue_registration_code("awaiting@example.com", "123456", now=100)
account = repository.register_with_code(
"awaiting", "awaiting@example.com", "long-user-password", "123456", now=120,
)
pending = repository.list_pending_users()
assert len(pending) == 1 and pending[0]["username"] == "awaiting"
assert "password_hash" not in pending[0]
approved = repository.approve_user(account["id"])
assert approved["approved"] is True and approved["admin"] is False
assert repository.list_pending_users() == []
database.execute("UPDATE users SET admin=1 WHERE id=?", (account["id"],))
database.commit()
assert repository.get_by_username("awaiting")["admin"] is True
assert repository.approve_user(999999) is None
def test_vm_ownership_is_scoped_to_host_and_user(users):
repository, _database = users
first = repository.create_initial_user("first", "initial-long-password", now=100)
repository.issue_registration_code("other@example.com", "123456", now=101)
other = repository.register_with_code(
"other", "other@example.com", "long-user-password", "123456", now=102,
)
host = "a" * 64
second_host = "b" * 64
vm_id = str(uuid.uuid4())
assert repository.owner_of_vm(host, vm_id) is None
repository.assign_vm(host, vm_id, first["id"], now=103)
repository.assign_vm(host, vm_id, first["id"], now=103)
assert repository.owns_vm(host, vm_id, first["id"]) is True
assert repository.owns_vm(host, vm_id, other["id"]) is False
assert repository.list_owned_vm_ids(host, first["id"]) == {vm_id}
assert repository.list_owned_vm_ids(second_host, first["id"]) == set()
with pytest.raises(UserError) as conflict:
repository.assign_vm(host, vm_id, other["id"], now=104)
assert conflict.value.status == 409
repository.delete_vm_owner(host, vm_id)
assert repository.owner_of_vm(host, vm_id) is None
@pytest.mark.parametrize("address", [
"evil@example.com\r\nBcc: victim@example.com", "not-an-email", "x@localhost",
"a..b@example.com", "x@example..com", "ñ@example.com",
])
def test_email_validation_rejects_unsafe_addresses(address):
with pytest.raises(UserError):
normalize_email(address)

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save