agent-loft 0.2.42 → 0.2.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/package.json +2 -1
- package/src/channels/web/desktop.ts +68 -5
- package/src/channels/web/server.ts +1 -1
- package/src/core/desktop.ts +1 -1
- package/src/core/vnc-auth.ts +193 -0
- package/src/core/vnc-transcode.ts +765 -0
- package/web/lib/dom.js +1 -0
- package/web/views/desktop.js +32 -1
- package/src/core/vnc-ard.ts +0 -133
package/README.md
CHANGED
|
@@ -66,7 +66,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
66
66
|
- **定时任务**:像 ChatGPT 的 Tasks,侧栏「最近」上面的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选聊天 / 工作模式和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
|
|
67
67
|
- **技能(skills)**:设置 → 技能。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。每人管自己的,不做分享和技能广场(以前从别人那装过的照常能用,可以卸载)。**使用**:工作模式下 agent 遇到对得上的事自己用;在输入框或定时任务的「要做的事」里打 `@` 选技能,点名这次用哪个(聊天模式下会把技能内容直接附上);飞书里发 `/skills` 看能 @ 哪些。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
|
|
68
68
|
- **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
|
|
69
|
-
- 桌面:走 VNC 协议,网页里用 noVNC
|
|
69
|
+
- 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,工具栏上选画质:流畅 / 标准(默认)/ 高清由服务端把画面缩小到长边 1280 / 1920 / 2560、只把变了的地方压成 JPEG 发过来(macOS 屏幕共享只给无损的 ZRLE,5K 屏一整屏 30MB,原样转发隔着公网几秒一帧),原画是原样转发、只适合局域网;可以缩放到窗口或按原始大小看、全屏(手机上也能,iPhone 上是铺满页面)、「只看不控制」、发送 Ctrl+Alt+Del 之类的组合键。手机上有两种手势(右上角切换,「?」看说明):**触控板模式**(默认)屏幕上有个指针,单指滑动移动、轻点单击、双指轻点右键、长按后拖动是按住左键拖、双指滑动滚动;**触摸模式**点哪就点哪。两种模式都能双指捏合在本地放大画面(放大后小按钮也点得准,右下角「还原」),画面下面一排 Esc / Tab / Ctrl / Alt / Win / 方向键,Ctrl、Alt、Win 点一下会粘住,带给下一个按键或点击;键盘按钮弹出软键盘打字,中文输入法也能用。Linux 上 agent-loft 在有人连时用 x11vnc 共享当前的桌面(Xorg 会话;只听 127.0.0.1、随机端口、每次随机密码,需要 `sudo apt install x11vnc`),没人连着 30 分钟后停掉;macOS 上在 设置 → 远程控制 里改用「已有的 VNC 服务」,接系统自带的屏幕共享:填 VNC 密码,或者屏幕共享没开 VNC 密码时填 Mac 的用户名和登录密码(苹果认证,由服务端登录)。
|
|
70
70
|
- 终端:新终端开在当前对话的工作目录里,可以开多个标签;`Ctrl+Shift+C` / `Ctrl+Shift+V` 复制粘贴。`` Ctrl+` `` 在对话下面拉出终端面板(高度可拖动),面板和远程控制里的是同一批终端。关掉页面、手机切到后台、断线都不结束 shell,重新打开时接着用、补上错过的输出,别的设备上也能接上;没有页面连着超过 30 分钟(设置里可改)才结束,点标签上的 × 立即结束。依赖可选的原生模块 `node-pty`:Linux 上安装时要现场编译(需要 `make`、`g++`、`python3`),没装好时终端用不了,其他功能照常。手机上单指上下滑翻看历史(在 less、vim 里是翻页),长按选中文字、接着拖动扩大选区,再点「复制」;终端下面多一排 Esc / Tab / Ctrl / Alt / 方向键 / Home / End / PgUp / PgDn / 粘贴。iOS 上软键盘弹出来时这排键会垫到键盘上面。
|
|
71
71
|
- 管理员能用;成员要管理员在 设置 → 用户 里单独「开通远程控制」。终端、桌面在 设置 → 远程控制 里各有总开关。
|
|
72
72
|
- **飞书账号绑定**:设置 → 账号 → 飞书账号 →「生成绑定码」,再在飞书私聊机器人发 `/bind 绑定码`(10 分钟内有效,群里发不算)。绑定后这个私聊就是你的个人会话:用你的记忆,`/sessions` 只列你的会话,`/web` 只能接上你自己的 Web 会话,管理员在 Web 上也看不到它。必须本人在两边各操作一次,管理员不能替人绑定(只能解除),否则就能借飞书读到别人的记忆。
|
|
@@ -183,6 +183,8 @@ src/
|
|
|
183
183
|
skills-bridge.ts 技能工具在主进程这头:建 / 改技能(弹授权卡)、skill_request 代发带密钥的请求
|
|
184
184
|
terminals.ts 网页终端:用 node-pty 起 shell、留最近的输出给重连补发、没人连着到点结束、权限收回时结束
|
|
185
185
|
desktop.ts 远程桌面:找这台机器的 X 桌面、按需起 x11vnc(或用已有的 VNC 服务)、没人连着到点停掉
|
|
186
|
+
vnc-auth.ts 由服务端登录 VNC(苹果认证、VNC 密码、不用认证),对页面装成不用认证的
|
|
187
|
+
vnc-transcode.ts 远程桌面转码:服务端当 VNC 客户端收全分辨率画面,缩小、只把变了的格子压成 JPEG 按 Tight 发给页面
|
|
186
188
|
pairing.ts uploads.ts commands.ts …
|
|
187
189
|
mcp/
|
|
188
190
|
memory-server.ts 记忆工具(remember / forget / search_past_chats)的 stdio MCP 服务,两个 agent 共用
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-loft",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.43",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
|
|
6
6
|
"keywords": [
|
|
@@ -53,6 +53,7 @@
|
|
|
53
53
|
"dompurify": "^3.2.0",
|
|
54
54
|
"marked": "^16.0.0",
|
|
55
55
|
"qrcode": "^1.5.4",
|
|
56
|
+
"sharp": "^0.35.5",
|
|
56
57
|
"tsx": "^4.20.6",
|
|
57
58
|
"ws": "^8.18.0"
|
|
58
59
|
},
|
|
@@ -5,10 +5,11 @@ import net from "node:net";
|
|
|
5
5
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
6
6
|
import type { Duplex } from "node:stream";
|
|
7
7
|
import type { WebSocket, WebSocketServer } from "ws";
|
|
8
|
-
import { canUseDesktop, desktopAvailability, desktopTarget, desktopViewer } from "../../core/desktop.js";
|
|
8
|
+
import { canUseDesktop, desktopAvailability, desktopTarget, desktopViewer, type DesktopTarget } from "../../core/desktop.js";
|
|
9
9
|
import { canUseRemote, isAdmin, type User } from "../../core/users.js";
|
|
10
10
|
import { config } from "../../core/config.js";
|
|
11
|
-
import {
|
|
11
|
+
import { ByteReader, serveNoAuth, vncLogin } from "../../core/vnc-auth.js";
|
|
12
|
+
import { isDesktopQuality, loadSharp, transcode, type DesktopQuality } from "../../core/vnc-transcode.js";
|
|
12
13
|
import { sessionUser } from "./auth.js";
|
|
13
14
|
import { HttpError, sendJson } from "./http.js";
|
|
14
15
|
import { terminalStatus } from "./terminal.js";
|
|
@@ -97,8 +98,11 @@ function reject(socket: Duplex, status: string): void {
|
|
|
97
98
|
socket.destroy();
|
|
98
99
|
}
|
|
99
100
|
|
|
100
|
-
/**
|
|
101
|
-
|
|
101
|
+
/**
|
|
102
|
+
* /ws/desktop 的握手:user 已经由调用方核对过登录和 Origin。
|
|
103
|
+
* ?q= 是画质:smooth / standard / high 由服务端缩小、压成 JPEG 再发(vnc-transcode.ts);original 或不带是原样转发
|
|
104
|
+
*/
|
|
105
|
+
export function upgradeDesktop(wss: WebSocketServer, req: IncomingMessage, socket: Duplex, head: Buffer, user: User, token: string, url: URL): void {
|
|
102
106
|
if (!canUseDesktop(user)) return reject(socket, "403 Forbidden");
|
|
103
107
|
if (clients.size >= MAX_CLIENTS) return reject(socket, "429 Too Many Requests");
|
|
104
108
|
// 下面要等 x11vnc 起来(最多 10 秒):这期间浏览器断开的话,socket 上没人接 error 会把进程带崩
|
|
@@ -114,7 +118,9 @@ export function upgradeDesktop(wss: WebSocketServer, req: IncomingMessage, socke
|
|
|
114
118
|
tcp.once("connect", () => {
|
|
115
119
|
if (socket.destroyed) return void tcp.destroy();
|
|
116
120
|
socket.off("error", onError);
|
|
121
|
+
const q = url.searchParams.get("q");
|
|
117
122
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
123
|
+
if (isDesktopQuality(q)) return void transcodeSession(ws, tcp, token, target, q);
|
|
118
124
|
if (!target.username) return bridge(ws, tcp, token);
|
|
119
125
|
void loginThenBridge(ws, tcp, token, target.username, target.password);
|
|
120
126
|
});
|
|
@@ -148,7 +154,7 @@ async function loginThenBridge(ws: WebSocket, tcp: net.Socket, token: string, us
|
|
|
148
154
|
fromPage.fail(err);
|
|
149
155
|
}, LOGIN_TIMEOUT);
|
|
150
156
|
try {
|
|
151
|
-
const login =
|
|
157
|
+
const login = vncLogin(fromVnc, (b) => tcp.write(b), { username, password });
|
|
152
158
|
await serveNoAuth(fromPage, (b) => ws.readyState === ws.OPEN && ws.send(b, { binary: true }), login);
|
|
153
159
|
} catch (err) {
|
|
154
160
|
console.error("[桌面] 苹果认证失败:", err instanceof Error ? err.message : err);
|
|
@@ -165,6 +171,63 @@ async function loginThenBridge(ws: WebSocket, tcp: net.Socket, token: string, us
|
|
|
165
171
|
bridge(ws, tcp, token, fromVnc.rest(), fromPage.rest());
|
|
166
172
|
}
|
|
167
173
|
|
|
174
|
+
function isLoopback(host: string): boolean {
|
|
175
|
+
const h = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
176
|
+
return h === "localhost" || h === "::1" || /^127\./.test(h);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 转码:服务端连 VNC、缩小画面压成 JPEG 发给页面 */
|
|
180
|
+
async function transcodeSession(ws: WebSocket, tcp: net.Socket, token: string, target: DesktopTarget, quality: DesktopQuality): Promise<void> {
|
|
181
|
+
// 握手前那个「回 502」的已经用不上了(socket 交给 WebSocket 了)
|
|
182
|
+
tcp.removeAllListeners("error");
|
|
183
|
+
tcp.on("error", () => tcp.destroy());
|
|
184
|
+
// 压 JPEG 的 sharp 在这台机器上装不上:退回原样转发(原画),别让页面一直重连
|
|
185
|
+
try {
|
|
186
|
+
await loadSharp();
|
|
187
|
+
} catch (err) {
|
|
188
|
+
console.error("[桌面] 加载 sharp 失败,画质设置不起作用,按原画转发:", err instanceof Error ? err.message : err);
|
|
189
|
+
if (!target.username) return bridge(ws, tcp, token);
|
|
190
|
+
return loginThenBridge(ws, tcp, token, target.username, target.password);
|
|
191
|
+
}
|
|
192
|
+
tcp.removeAllListeners("error");
|
|
193
|
+
tcp.setNoDelay(true);
|
|
194
|
+
const client: DesktopClient = { ws, tcp, token, alive: true };
|
|
195
|
+
clients.add(client);
|
|
196
|
+
desktopViewer(1);
|
|
197
|
+
const fromVnc = new ByteReader();
|
|
198
|
+
const fromPage = new ByteReader();
|
|
199
|
+
tcp.on("data", (d: Buffer) => fromVnc.push(d));
|
|
200
|
+
tcp.on("close", () => fromVnc.fail(new Error("VNC 服务断开了连接")));
|
|
201
|
+
tcp.on("error", () => fromVnc.fail(new Error("VNC 服务断开了连接")));
|
|
202
|
+
ws.on("message", (d: Buffer) => fromPage.push(d));
|
|
203
|
+
ws.on("close", () => fromPage.fail(new Error("页面断开了")));
|
|
204
|
+
ws.on("error", () => fromPage.fail(new Error("页面断开了")));
|
|
205
|
+
ws.on("pong", () => (client.alive = true));
|
|
206
|
+
const timer = setTimeout(() => {
|
|
207
|
+
const err = new Error("VNC 服务没有回应");
|
|
208
|
+
fromVnc.fail(err);
|
|
209
|
+
fromPage.fail(err);
|
|
210
|
+
}, LOGIN_TIMEOUT);
|
|
211
|
+
try {
|
|
212
|
+
await transcode({
|
|
213
|
+
vnc: { reader: fromVnc, write: (b) => void (tcp.destroyed || tcp.write(b)) },
|
|
214
|
+
page: { reader: fromPage, write: (b) => void (ws.readyState === ws.OPEN && ws.send(b, { binary: true })), backlog: () => ws.bufferedAmount },
|
|
215
|
+
creds: { username: target.username, password: target.password },
|
|
216
|
+
quality,
|
|
217
|
+
local: isLoopback(target.host),
|
|
218
|
+
onReady: () => clearTimeout(timer),
|
|
219
|
+
});
|
|
220
|
+
} catch (err) {
|
|
221
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
222
|
+
if (!/页面断开了/.test(msg)) console.error("[桌面] 转码会话结束:", msg);
|
|
223
|
+
// 认证失败的原因已经告诉页面了:等它收到再关
|
|
224
|
+
if (ws.readyState === ws.OPEN) setTimeout(() => ws.close(4000, "桌面连接已断开"), 200);
|
|
225
|
+
} finally {
|
|
226
|
+
clearTimeout(timer);
|
|
227
|
+
drop(client);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
168
231
|
/** pending:握手时多读进来、还没转发的字节 */
|
|
169
232
|
function bridge(ws: WebSocket, tcp: net.Socket, token: string, pendingVnc?: Buffer, pendingPage?: Buffer): void {
|
|
170
233
|
const client: DesktopClient = { ws, tcp, token, alive: true };
|
|
@@ -489,7 +489,7 @@ export async function startWeb(): Promise<void> {
|
|
|
489
489
|
}
|
|
490
490
|
const token = cookies(req)[COOKIE] ?? "";
|
|
491
491
|
if (url.pathname === "/ws/term") return upgradeTerminal(wss!, req, socket, head, user, token, url);
|
|
492
|
-
if (url.pathname === "/ws/desktop") return upgradeDesktop(wss!, req, socket, head, user, token);
|
|
492
|
+
if (url.pathname === "/ws/desktop") return upgradeDesktop(wss!, req, socket, head, user, token, url);
|
|
493
493
|
wss!.handleUpgrade(req, socket, head, (ws) => {
|
|
494
494
|
const client: Client = { ws, subs: new Set(), alive: true, token, user, visible: false, viewing: null, seen: Date.now() };
|
|
495
495
|
clients.add(client);
|
package/src/core/desktop.ts
CHANGED
|
@@ -214,7 +214,7 @@ async function startX11vnc(display: string): Promise<Vnc> {
|
|
|
214
214
|
return v;
|
|
215
215
|
}
|
|
216
216
|
|
|
217
|
-
/** username:有就是苹果认证,由服务端登录(见 vnc-
|
|
217
|
+
/** username:有就是苹果认证,由服务端登录(见 vnc-auth.ts),页面不用密码 */
|
|
218
218
|
export type DesktopTarget = { host: string; port: number; password: string; username?: string };
|
|
219
219
|
|
|
220
220
|
/** 要连桌面了:拿到 VNC 服务的地址和密码,必要时先把 x11vnc 起来 */
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// 由服务端登录 VNC 服务,再对页面(noVNC)装成一个不用认证的 VNC 服务。两种情况用得上:
|
|
2
|
+
// - macOS 屏幕共享的苹果认证(Apple Remote Desktop,RFB 安全类型 30):用 Mac 的用户名和登录密码登录。
|
|
3
|
+
// 屏幕共享没开「VNC 显示程序可以使用密码控制屏幕」时只给苹果自己的几种认证,普通 VNC 密码那种没有。
|
|
4
|
+
// 登录密码不用发到浏览器;noVNC 自己做这种认证要用 crypto.subtle,用 http://IP 访问时没有。
|
|
5
|
+
// - 转码(vnc-transcode.ts):服务端自己当 VNC 客户端,普通 VNC 密码、不用认证的也都由这里登录。
|
|
6
|
+
//
|
|
7
|
+
// 苹果认证:服务端给 DH 的生成元、素数和它的公钥;双方算出共享密钥,MD5 一下当 AES-128 的钥匙,
|
|
8
|
+
// 把「用户名 \0 … | 密码 \0 …」各 64 字节(空的地方填随机数)用 AES-ECB 加密,连同自己的公钥发回去。
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { pathToFileURL } from "node:url";
|
|
13
|
+
|
|
14
|
+
/** 按需读字节:数据一段段进来(TCP 的 data、WebSocket 的 message),要多少等多少 */
|
|
15
|
+
export class ByteReader {
|
|
16
|
+
/** 收到还没读的:一段段排着,读的时候才拼(一帧几十 MB 时每来一段就整个拼一遍会慢得要命) */
|
|
17
|
+
private chunks: Buffer[] = [];
|
|
18
|
+
/** 第一段里已经读掉的字节数 */
|
|
19
|
+
private offset = 0;
|
|
20
|
+
private length = 0;
|
|
21
|
+
private waiting: { n: number; resolve: (b: Buffer) => void; reject: (e: Error) => void } | null = null;
|
|
22
|
+
private error: Error | null = null;
|
|
23
|
+
|
|
24
|
+
push(chunk: Buffer): void {
|
|
25
|
+
if (!chunk.length) return;
|
|
26
|
+
this.chunks.push(chunk);
|
|
27
|
+
this.length += chunk.length;
|
|
28
|
+
this.flush();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 那头断了:在等的和以后要读的都报这个错 */
|
|
32
|
+
fail(err: Error): void {
|
|
33
|
+
this.error ??= err;
|
|
34
|
+
const w = this.waiting;
|
|
35
|
+
this.waiting = null;
|
|
36
|
+
w?.reject(this.error);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
read(n: number): Promise<Buffer> {
|
|
40
|
+
if (this.waiting) return Promise.reject(new Error("上一次读还没完"));
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
this.waiting = { n, resolve, reject };
|
|
43
|
+
this.flush();
|
|
44
|
+
if (this.waiting && this.error) this.fail(this.error);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 握手完了:多读进来的那点交给后面原样转发 */
|
|
49
|
+
rest(): Buffer {
|
|
50
|
+
return this.take(this.length);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private take(n: number): Buffer {
|
|
54
|
+
const out = Buffer.allocUnsafe(n);
|
|
55
|
+
let filled = 0;
|
|
56
|
+
while (filled < n) {
|
|
57
|
+
const c = this.chunks[0]!;
|
|
58
|
+
const k = Math.min(n - filled, c.length - this.offset);
|
|
59
|
+
c.copy(out, filled, this.offset, this.offset + k);
|
|
60
|
+
filled += k;
|
|
61
|
+
this.offset += k;
|
|
62
|
+
if (this.offset === c.length) {
|
|
63
|
+
this.chunks.shift();
|
|
64
|
+
this.offset = 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
this.length -= n;
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private flush(): void {
|
|
72
|
+
const w = this.waiting;
|
|
73
|
+
if (!w || this.length < w.n) return;
|
|
74
|
+
this.waiting = null;
|
|
75
|
+
w.resolve(this.take(w.n));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 认证没过(用户名密码不对、服务不支持):message 原样给页面看 */
|
|
80
|
+
export class VncAuthError extends Error {}
|
|
81
|
+
|
|
82
|
+
const TYPE_NONE = 1;
|
|
83
|
+
const TYPE_VNC = 2;
|
|
84
|
+
const TYPE_ARD = 30;
|
|
85
|
+
|
|
86
|
+
/** 左边补 0 到 len 字节(DH 的数可能比素数短) */
|
|
87
|
+
function pad(b: Buffer, len: number): Buffer {
|
|
88
|
+
return b.length >= len ? b.subarray(b.length - len) : Buffer.concat([Buffer.alloc(len - b.length), b]);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 按苹果认证算出要发回去的:加密后的 128 字节凭据 + 自己的公钥 */
|
|
92
|
+
export function ardResponse(generator: Buffer, prime: Buffer, serverKey: Buffer, username: string, password: string): Buffer {
|
|
93
|
+
const dh = crypto.createDiffieHellman(prime, generator);
|
|
94
|
+
const publicKey = pad(dh.generateKeys(), prime.length);
|
|
95
|
+
const shared = pad(dh.computeSecret(serverKey), prime.length);
|
|
96
|
+
const creds = crypto.randomBytes(128);
|
|
97
|
+
// 各最多 63 字节,后面跟一个 \0(和 noVNC、苹果自己的客户端一样)
|
|
98
|
+
const user = Buffer.from(username, "utf8").subarray(0, 63);
|
|
99
|
+
const pass = Buffer.from(password, "utf8").subarray(0, 63);
|
|
100
|
+
user.copy(creds, 0);
|
|
101
|
+
creds[user.length] = 0;
|
|
102
|
+
pass.copy(creds, 64);
|
|
103
|
+
creds[64 + pass.length] = 0;
|
|
104
|
+
const cipher = crypto.createCipheriv("aes-128-ecb", crypto.createHash("md5").update(shared).digest(), null);
|
|
105
|
+
cipher.setAutoPadding(false);
|
|
106
|
+
return Buffer.concat([cipher.update(creds), cipher.final(), publicKey]);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 普通 VNC 密码认证:用密码(最多 8 位)当 DES 钥匙加密服务端给的 16 字节。Node 的 OpenSSL 3 默认没有 DES,借 noVNC 的 */
|
|
110
|
+
async function vncAuthResponse(password: string, challenge: Buffer): Promise<Buffer> {
|
|
111
|
+
const require = createRequire(import.meta.url);
|
|
112
|
+
const file = path.join(path.dirname(require.resolve("@novnc/novnc")), "crypto", "des.js");
|
|
113
|
+
const { DESECBCipher } = (await import(pathToFileURL(file).href)) as {
|
|
114
|
+
DESECBCipher: { importKey(key: number[]): { encrypt(alg: unknown, data: Uint8Array): Uint8Array } };
|
|
115
|
+
};
|
|
116
|
+
// 和 noVNC 的 RFB.genDES 一样:密码按字符码当钥匙
|
|
117
|
+
const key = password.split("").map((c) => c.charCodeAt(0) & 0xff);
|
|
118
|
+
return Buffer.from(DESECBCipher.importKey(key).encrypt(null, new Uint8Array(challenge)));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type VncCreds = { username?: string; password: string };
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 作为客户端和 VNC 服务走完版本协商和认证,停在 ClientInit 之前。
|
|
125
|
+
* 填了用户名就用苹果认证;否则有 VNC 密码认证就用它,再不然不用认证的。
|
|
126
|
+
* 失败抛 VncAuthError(认证的问题)或普通 Error(连接断了)
|
|
127
|
+
*/
|
|
128
|
+
export async function vncLogin(r: ByteReader, write: (b: Buffer) => void, creds: VncCreds): Promise<void> {
|
|
129
|
+
const version = (await r.read(12)).toString("latin1");
|
|
130
|
+
const m = /^RFB (\d{3})\.(\d{3})\n$/.exec(version);
|
|
131
|
+
if (!m) throw new VncAuthError("对方不是 VNC 服务");
|
|
132
|
+
// 3.3 的服务端不给安全类型列表,现在基本没有了
|
|
133
|
+
if (Number(m[1]) < 3 || (Number(m[1]) === 3 && Number(m[2]) < 7)) throw new VncAuthError(`VNC 服务的协议太老(${version.trim()})`);
|
|
134
|
+
// 苹果的是 003.889,按 3.8 谈就行
|
|
135
|
+
write(Buffer.from("RFB 003.008\n", "latin1"));
|
|
136
|
+
const count = (await r.read(1))[0]!;
|
|
137
|
+
if (count === 0) {
|
|
138
|
+
const len = (await r.read(4)).readUInt32BE(0);
|
|
139
|
+
throw new VncAuthError(`VNC 服务拒绝连接:${(await r.read(len)).toString("utf8")}`);
|
|
140
|
+
}
|
|
141
|
+
const types = [...(await r.read(count))];
|
|
142
|
+
if (creds.username) {
|
|
143
|
+
if (!types.includes(TYPE_ARD)) throw new VncAuthError("这个 VNC 服务不支持用 Mac 用户名登录:把设置里的用户名留空,只填 VNC 密码");
|
|
144
|
+
write(Buffer.from([TYPE_ARD]));
|
|
145
|
+
const head = await r.read(4);
|
|
146
|
+
const generator = head.subarray(0, 2);
|
|
147
|
+
const keyLength = head.readUInt16BE(2);
|
|
148
|
+
const prime = await r.read(keyLength);
|
|
149
|
+
const serverKey = await r.read(keyLength);
|
|
150
|
+
write(ardResponse(generator, prime, serverKey, creds.username, creds.password));
|
|
151
|
+
if ((await r.read(4)).readUInt32BE(0) !== 0) throw new VncAuthError("Mac 的用户名或密码不对");
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (types.includes(TYPE_VNC)) {
|
|
155
|
+
write(Buffer.from([TYPE_VNC]));
|
|
156
|
+
const challenge = await r.read(16);
|
|
157
|
+
write(await vncAuthResponse(creds.password, challenge));
|
|
158
|
+
if ((await r.read(4)).readUInt32BE(0) !== 0) throw new VncAuthError("VNC 密码不对");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (types.includes(TYPE_NONE)) {
|
|
162
|
+
write(Buffer.from([TYPE_NONE]));
|
|
163
|
+
if ((await r.read(4)).readUInt32BE(0) !== 0) throw new VncAuthError("VNC 服务拒绝连接");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (types.includes(TYPE_ARD)) {
|
|
167
|
+
throw new VncAuthError("这个 VNC 服务要用户名登录(macOS 屏幕共享没开 VNC 密码):在 设置 → 远程控制 里填上 Mac 的用户名和登录密码");
|
|
168
|
+
}
|
|
169
|
+
throw new VncAuthError(`VNC 服务要的认证方式都不支持(${types.join("、")})`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 对页面那头装成不用认证的 VNC 服务(3.8,只给安全类型 None)。
|
|
174
|
+
* login 是和真正的 VNC 服务认证的过程:它失败时把原因当作认证失败告诉页面
|
|
175
|
+
*/
|
|
176
|
+
export async function serveNoAuth(r: ByteReader, write: (b: Buffer) => void, login: Promise<void>): Promise<void> {
|
|
177
|
+
// 页面那头还没谈完 login 就失败了:先接住,下面 await 时再处理(不然算没人接的 rejection,进程会退出)
|
|
178
|
+
login.catch(() => {});
|
|
179
|
+
write(Buffer.from("RFB 003.008\n", "latin1"));
|
|
180
|
+
await r.read(12);
|
|
181
|
+
write(Buffer.from([1, 1]));
|
|
182
|
+
await r.read(1);
|
|
183
|
+
try {
|
|
184
|
+
await login;
|
|
185
|
+
} catch (err) {
|
|
186
|
+
const reason = Buffer.from(err instanceof VncAuthError ? err.message : `连不上 VNC 服务:${err instanceof Error ? err.message : err}`, "utf8");
|
|
187
|
+
const len = Buffer.alloc(4);
|
|
188
|
+
len.writeUInt32BE(reason.length);
|
|
189
|
+
write(Buffer.concat([Buffer.from([0, 0, 0, 1]), len, reason]));
|
|
190
|
+
throw err;
|
|
191
|
+
}
|
|
192
|
+
write(Buffer.from([0, 0, 0, 0]));
|
|
193
|
+
}
|
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
// 远程桌面转码:服务端自己当 VNC 客户端连上桌面,把画面缩小、压成 JPEG 再给页面(noVNC)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要:macOS 屏幕共享只给 ZRLE(无损)和原始像素,不给 JPEG;5K 屏一整屏 ZRLE 有十几 MB,
|
|
4
|
+
// 隔着公网又卡又费流量,noVNC 的「画质」参数对它也不起作用。这里的做法:
|
|
5
|
+
// - 和 VNC 服务之间收全分辨率的画面,存成内存里的一份「原画」。VNC 服务在本机时要原始像素(本机不怕大,
|
|
6
|
+
// macOS 出原始像素比出 ZRLE 快几倍:5K 屏约 1 秒一帧,ZRLE 要 4 秒);在别的机器上时要 ZRLE;
|
|
7
|
+
// - macOS 每次都把整屏发过来(哪怕只变了一点):和原画逐格比,真变了的格子才更新原画、
|
|
8
|
+
// 按面积平均缩到「输出画面」上,并记下输出画面上哪些格子脏了;
|
|
9
|
+
// - 页面要画面(FramebufferUpdateRequest)时,把脏的格子拼成几个矩形,用 sharp 压成 JPEG,按 Tight 编码发过去;
|
|
10
|
+
// - 页面发来的鼠标坐标按比例放大回原画的坐标,键盘、剪贴板原样转发。
|
|
11
|
+
// 对页面来说就是一个分辨率小一些、只用 Tight JPEG 的 VNC 服务(认证由 vnc-auth.ts 在服务端做完)。
|
|
12
|
+
//
|
|
13
|
+
// 流量控制:页面画完一帧才会要下一帧,WebSocket 积压多了也先不发;和 VNC 服务之间每帧最少隔 FRAME_MS。
|
|
14
|
+
import zlib from "node:zlib";
|
|
15
|
+
import { ByteReader, serveNoAuth, vncLogin, type VncCreds } from "./vnc-auth.js";
|
|
16
|
+
|
|
17
|
+
/** 画质档位:长边缩到多少像素、JPEG 质量 */
|
|
18
|
+
export const DESKTOP_QUALITIES = {
|
|
19
|
+
smooth: { edge: 1280, jpeg: 50 },
|
|
20
|
+
standard: { edge: 1920, jpeg: 70 },
|
|
21
|
+
high: { edge: 2560, jpeg: 82 },
|
|
22
|
+
} as const;
|
|
23
|
+
export type DesktopQuality = keyof typeof DESKTOP_QUALITIES;
|
|
24
|
+
|
|
25
|
+
export function isDesktopQuality(q: unknown): q is DesktopQuality {
|
|
26
|
+
return typeof q === "string" && Object.hasOwn(DESKTOP_QUALITIES, q);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const ENC_RAW = 0;
|
|
30
|
+
const ENC_COPYRECT = 1;
|
|
31
|
+
const ENC_TIGHT = 7;
|
|
32
|
+
const ENC_ZRLE = 16;
|
|
33
|
+
const ENC_DESKTOP_SIZE = -223;
|
|
34
|
+
const ENC_CURSOR = -239;
|
|
35
|
+
|
|
36
|
+
/** 脏格子的边长(输出画面上的像素) */
|
|
37
|
+
const TILE = 64;
|
|
38
|
+
/** 拼出来的矩形最高这么多格:一个 JPEG 别太大(Tight 的长度字段最多 4MB) */
|
|
39
|
+
const MAX_RECT_TILES = 8;
|
|
40
|
+
/** 和 VNC 服务之间每帧最少隔多久(毫秒):解码、缩放都在主线程上,别占满 CPU */
|
|
41
|
+
const FRAME_MS = 40;
|
|
42
|
+
/** 页面收得慢:WebSocket 里积压到这么多就先不发 */
|
|
43
|
+
const HIGH_WATER = 2 * 1024 * 1024;
|
|
44
|
+
|
|
45
|
+
type Rect = { x: number; y: number; w: number; h: number };
|
|
46
|
+
|
|
47
|
+
/** 原画和缩小后的输出画面(都是每像素 4 字节 R G B X),外加输出画面上的脏格子 */
|
|
48
|
+
export class Frame {
|
|
49
|
+
srcW = 0;
|
|
50
|
+
srcH = 0;
|
|
51
|
+
outW = 0;
|
|
52
|
+
outH = 0;
|
|
53
|
+
src = Buffer.alloc(0);
|
|
54
|
+
out = new Uint8Array(0);
|
|
55
|
+
/** 每个输出像素对应原画的哪一段:[x0[i], x1[i]) */
|
|
56
|
+
private x0 = new Int32Array(0);
|
|
57
|
+
private x1 = new Int32Array(0);
|
|
58
|
+
private y0 = new Int32Array(0);
|
|
59
|
+
private y1 = new Int32Array(0);
|
|
60
|
+
private tilesX = 0;
|
|
61
|
+
private tilesY = 0;
|
|
62
|
+
private dirty = new Uint8Array(0);
|
|
63
|
+
private dirtyCount = 0;
|
|
64
|
+
|
|
65
|
+
constructor(
|
|
66
|
+
srcW: number,
|
|
67
|
+
srcH: number,
|
|
68
|
+
private readonly edge: number,
|
|
69
|
+
) {
|
|
70
|
+
this.resize(srcW, srcH);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
resize(srcW: number, srcH: number): void {
|
|
74
|
+
const k = Math.min(1, this.edge / Math.max(srcW, srcH, 1));
|
|
75
|
+
this.srcW = srcW;
|
|
76
|
+
this.srcH = srcH;
|
|
77
|
+
this.outW = Math.max(1, Math.round(srcW * k));
|
|
78
|
+
this.outH = Math.max(1, Math.round(srcH * k));
|
|
79
|
+
this.src = Buffer.alloc(srcW * srcH * 4);
|
|
80
|
+
// 不用缩:输出画面就是原画
|
|
81
|
+
this.out = this.scaled ? new Uint8Array(this.outW * this.outH * 4) : this.src;
|
|
82
|
+
const ranges = (outN: number, srcN: number) => {
|
|
83
|
+
const lo = new Int32Array(outN);
|
|
84
|
+
const hi = new Int32Array(outN);
|
|
85
|
+
for (let i = 0; i < outN; i++) {
|
|
86
|
+
lo[i] = Math.floor((i * srcN) / outN);
|
|
87
|
+
hi[i] = Math.max(lo[i]! + 1, Math.min(srcN, Math.floor(((i + 1) * srcN) / outN)));
|
|
88
|
+
}
|
|
89
|
+
return [lo, hi] as const;
|
|
90
|
+
};
|
|
91
|
+
[this.x0, this.x1] = ranges(this.outW, srcW);
|
|
92
|
+
[this.y0, this.y1] = ranges(this.outH, srcH);
|
|
93
|
+
this.tilesX = Math.ceil(this.outW / TILE);
|
|
94
|
+
this.tilesY = Math.ceil(this.outH / TILE);
|
|
95
|
+
this.dirty = new Uint8Array(this.tilesX * this.tilesY);
|
|
96
|
+
this.dirtyCount = 0;
|
|
97
|
+
this.markOut(0, 0, this.outW, this.outH);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
get scaled(): boolean {
|
|
101
|
+
return this.outW !== this.srcW || this.outH !== this.srcH;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
get hasDirty(): boolean {
|
|
105
|
+
return this.dirtyCount > 0;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 原画上比较变化用的格子边长:对应输出画面上一个脏格子 */
|
|
109
|
+
private get cell(): number {
|
|
110
|
+
return Math.max(TILE, Math.ceil((TILE * this.srcW) / this.outW));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* VNC 服务发来原画上 (x, y, w, h) 这块的新像素(紧凑的 R G B X):逐格和原画比,变了的才写进去、记脏。
|
|
115
|
+
* 返回变了的格子数
|
|
116
|
+
*/
|
|
117
|
+
update(x: number, y: number, w: number, h: number, data: Buffer): number {
|
|
118
|
+
const cell = this.cell;
|
|
119
|
+
const stride = this.srcW * 4;
|
|
120
|
+
let changed = 0;
|
|
121
|
+
for (let cy = y; cy < y + h; cy += cell) {
|
|
122
|
+
const ch = Math.min(cell, y + h - cy);
|
|
123
|
+
for (let cx = x; cx < x + w; cx += cell) {
|
|
124
|
+
const cw = Math.min(cell, x + w - cx);
|
|
125
|
+
const bytes = cw * 4;
|
|
126
|
+
let differs = false;
|
|
127
|
+
for (let row = 0; row < ch && !differs; row++) {
|
|
128
|
+
const from = ((cy - y + row) * w + (cx - x)) * 4;
|
|
129
|
+
const to = (cy + row) * stride + cx * 4;
|
|
130
|
+
differs = data.compare(this.src, to, to + bytes, from, from + bytes) !== 0;
|
|
131
|
+
}
|
|
132
|
+
if (!differs) continue;
|
|
133
|
+
for (let row = 0; row < ch; row++) {
|
|
134
|
+
const from = ((cy - y + row) * w + (cx - x)) * 4;
|
|
135
|
+
data.copy(this.src, (cy + row) * stride + cx * 4, from, from + bytes);
|
|
136
|
+
}
|
|
137
|
+
this.damage(cx, cy, cw, ch);
|
|
138
|
+
changed++;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return changed;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 原画上这块变了:缩到输出画面上,记脏 */
|
|
145
|
+
damage(x: number, y: number, w: number, h: number): void {
|
|
146
|
+
if (w <= 0 || h <= 0) return;
|
|
147
|
+
const ox0 = Math.max(0, Math.floor((x * this.outW) / this.srcW));
|
|
148
|
+
const oy0 = Math.max(0, Math.floor((y * this.outH) / this.srcH));
|
|
149
|
+
const ox1 = Math.min(this.outW, Math.ceil(((x + w) * this.outW) / this.srcW));
|
|
150
|
+
const oy1 = Math.min(this.outH, Math.ceil(((y + h) * this.outH) / this.srcH));
|
|
151
|
+
if (this.scaled) this.downscale(ox0, oy0, ox1, oy1);
|
|
152
|
+
this.markOut(ox0, oy0, ox1 - ox0, oy1 - oy0);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 输出画面上这块要重发(页面要整屏时) */
|
|
156
|
+
markOut(x: number, y: number, w: number, h: number): void {
|
|
157
|
+
const tx1 = Math.min(this.tilesX, Math.ceil((x + w) / TILE));
|
|
158
|
+
const ty1 = Math.min(this.tilesY, Math.ceil((y + h) / TILE));
|
|
159
|
+
for (let ty = Math.max(0, Math.floor(y / TILE)); ty < ty1; ty++) {
|
|
160
|
+
for (let tx = Math.max(0, Math.floor(x / TILE)); tx < tx1; tx++) {
|
|
161
|
+
const i = ty * this.tilesX + tx;
|
|
162
|
+
if (!this.dirty[i]) {
|
|
163
|
+
this.dirty[i] = 1;
|
|
164
|
+
this.dirtyCount++;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 按面积平均:每个输出像素取它盖住的那几个原画像素的平均 */
|
|
171
|
+
private downscale(ox0: number, oy0: number, ox1: number, oy1: number): void {
|
|
172
|
+
const { src, out, srcW, outW, x0, x1, y0, y1 } = this;
|
|
173
|
+
for (let oy = oy0; oy < oy1; oy++) {
|
|
174
|
+
const sy0 = y0[oy]!;
|
|
175
|
+
const sy1 = y1[oy]!;
|
|
176
|
+
let o = (oy * outW + ox0) * 4;
|
|
177
|
+
for (let ox = ox0; ox < ox1; ox++, o += 4) {
|
|
178
|
+
const sx0 = x0[ox]!;
|
|
179
|
+
const sx1 = x1[ox]!;
|
|
180
|
+
let r = 0;
|
|
181
|
+
let g = 0;
|
|
182
|
+
let b = 0;
|
|
183
|
+
for (let sy = sy0; sy < sy1; sy++) {
|
|
184
|
+
let i = (sy * srcW + sx0) * 4;
|
|
185
|
+
for (let sx = sx0; sx < sx1; sx++, i += 4) {
|
|
186
|
+
r += src[i]!;
|
|
187
|
+
g += src[i + 1]!;
|
|
188
|
+
b += src[i + 2]!;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const n = (sx1 - sx0) * (sy1 - sy0);
|
|
192
|
+
out[o] = (r / n + 0.5) | 0;
|
|
193
|
+
out[o + 1] = (g / n + 0.5) | 0;
|
|
194
|
+
out[o + 2] = (b / n + 0.5) | 0;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 把脏格子拼成矩形(横着连成一段,上下段一样宽的再并起来),清掉脏标记 */
|
|
200
|
+
takeDirty(): Rect[] {
|
|
201
|
+
if (!this.dirtyCount) return [];
|
|
202
|
+
const done: Rect[] = [];
|
|
203
|
+
/** 上一行的段:key 是 "起始格,结束格",还能往下接 */
|
|
204
|
+
let open = new Map<string, { tx0: number; tx1: number; ty0: number; ty1: number }>();
|
|
205
|
+
const close = (s: { tx0: number; tx1: number; ty0: number; ty1: number }) => {
|
|
206
|
+
const x = s.tx0 * TILE;
|
|
207
|
+
const y = s.ty0 * TILE;
|
|
208
|
+
done.push({ x, y, w: Math.min(this.outW, s.tx1 * TILE) - x, h: Math.min(this.outH, s.ty1 * TILE) - y });
|
|
209
|
+
};
|
|
210
|
+
for (let ty = 0; ty < this.tilesY; ty++) {
|
|
211
|
+
const next = new Map<string, { tx0: number; tx1: number; ty0: number; ty1: number }>();
|
|
212
|
+
for (let tx = 0; tx < this.tilesX; ) {
|
|
213
|
+
if (!this.dirty[ty * this.tilesX + tx]) {
|
|
214
|
+
tx++;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const tx0 = tx;
|
|
218
|
+
while (tx < this.tilesX && this.dirty[ty * this.tilesX + tx]) tx++;
|
|
219
|
+
const key = `${tx0},${tx}`;
|
|
220
|
+
const prev = open.get(key);
|
|
221
|
+
if (prev && prev.ty1 - prev.ty0 < MAX_RECT_TILES) {
|
|
222
|
+
prev.ty1 = ty + 1;
|
|
223
|
+
open.delete(key);
|
|
224
|
+
next.set(key, prev);
|
|
225
|
+
} else next.set(key, { tx0, tx1: tx, ty0: ty, ty1: ty + 1 });
|
|
226
|
+
}
|
|
227
|
+
for (const s of open.values()) close(s);
|
|
228
|
+
open = next;
|
|
229
|
+
}
|
|
230
|
+
for (const s of open.values()) close(s);
|
|
231
|
+
this.dirty.fill(0);
|
|
232
|
+
this.dirtyCount = 0;
|
|
233
|
+
return done;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 输出画面上一块,拷成紧凑的 RGBX(给 sharp) */
|
|
237
|
+
region(r: Rect): Buffer {
|
|
238
|
+
const buf = Buffer.allocUnsafe(r.w * r.h * 4);
|
|
239
|
+
for (let row = 0; row < r.h; row++) {
|
|
240
|
+
const start = ((r.y + row) * this.outW + r.x) * 4;
|
|
241
|
+
buf.set(this.out.subarray(start, start + r.w * 4), row * r.w * 4);
|
|
242
|
+
}
|
|
243
|
+
return buf;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** 输出画面的坐标 → 原画的坐标(鼠标) */
|
|
247
|
+
toSrc(x: number, y: number): [number, number] {
|
|
248
|
+
const sx = Math.floor(((x + 0.5) * this.srcW) / this.outW);
|
|
249
|
+
const sy = Math.floor(((y + 0.5) * this.srcH) / this.outH);
|
|
250
|
+
return [Math.min(this.srcW - 1, Math.max(0, sx)), Math.min(this.srcH - 1, Math.max(0, sy))];
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ---------- ZRLE ----------
|
|
255
|
+
|
|
256
|
+
/** ZRLE 整条连接共用一个 zlib 流,每个矩形的数据都以 sync flush 结尾 */
|
|
257
|
+
class Inflater {
|
|
258
|
+
private z = zlib.createInflate();
|
|
259
|
+
private chunks: Buffer[] = [];
|
|
260
|
+
private error: Error | null = null;
|
|
261
|
+
|
|
262
|
+
constructor() {
|
|
263
|
+
this.z.on("data", (d: Buffer) => this.chunks.push(d));
|
|
264
|
+
this.z.on("error", (e) => (this.error = e));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
inflate(data: Buffer): Promise<Buffer> {
|
|
268
|
+
return new Promise((resolve, reject) => {
|
|
269
|
+
this.z.write(data);
|
|
270
|
+
this.z.flush(zlib.constants.Z_SYNC_FLUSH, () => {
|
|
271
|
+
if (this.error) return reject(this.error);
|
|
272
|
+
let c: Buffer | null;
|
|
273
|
+
while ((c = this.z.read() as Buffer | null) !== null) this.chunks.push(c);
|
|
274
|
+
const out = Buffer.concat(this.chunks);
|
|
275
|
+
this.chunks = [];
|
|
276
|
+
resolve(out);
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
close(): void {
|
|
282
|
+
this.z.destroy();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** 解一个 w×h 的 ZRLE 矩形到 fb(紧凑的 R G B X)。像素格式是我们定的 32 位,CPIXEL 是前 3 个字节 */
|
|
287
|
+
export function decodeZrle(d: Buffer, fb: Uint8Array, w: number, h: number): void {
|
|
288
|
+
const W = w;
|
|
289
|
+
const x = 0;
|
|
290
|
+
const y = 0;
|
|
291
|
+
let p = 0;
|
|
292
|
+
const palette = new Uint8Array(128 * 3);
|
|
293
|
+
const runLength = () => {
|
|
294
|
+
let n = 1;
|
|
295
|
+
let b: number;
|
|
296
|
+
do {
|
|
297
|
+
b = d[p++]!;
|
|
298
|
+
n += b;
|
|
299
|
+
} while (b === 255);
|
|
300
|
+
return n;
|
|
301
|
+
};
|
|
302
|
+
for (let ty = y; ty < y + h; ty += 64) {
|
|
303
|
+
const th = Math.min(64, y + h - ty);
|
|
304
|
+
for (let tx = x; tx < x + w; tx += 64) {
|
|
305
|
+
const tw = Math.min(64, x + w - tx);
|
|
306
|
+
const sub = d[p++]!;
|
|
307
|
+
if (sub === 0) {
|
|
308
|
+
for (let j = 0; j < th; j++) {
|
|
309
|
+
let i = ((ty + j) * W + tx) * 4;
|
|
310
|
+
for (let k = 0; k < tw; k++, i += 4, p += 3) {
|
|
311
|
+
fb[i] = d[p]!;
|
|
312
|
+
fb[i + 1] = d[p + 1]!;
|
|
313
|
+
fb[i + 2] = d[p + 2]!;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
} else if (sub === 1) {
|
|
317
|
+
const r = d[p]!;
|
|
318
|
+
const g = d[p + 1]!;
|
|
319
|
+
const b = d[p + 2]!;
|
|
320
|
+
p += 3;
|
|
321
|
+
for (let j = 0; j < th; j++) {
|
|
322
|
+
let i = ((ty + j) * W + tx) * 4;
|
|
323
|
+
for (let k = 0; k < tw; k++, i += 4) {
|
|
324
|
+
fb[i] = r;
|
|
325
|
+
fb[i + 1] = g;
|
|
326
|
+
fb[i + 2] = b;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
} else if (sub <= 16) {
|
|
330
|
+
// 调色板 + 每像素 1 / 2 / 4 位的索引,每行补齐到整字节,高位在前
|
|
331
|
+
for (let c = 0; c < sub * 3; c++) palette[c] = d[p++]!;
|
|
332
|
+
const bits = sub === 2 ? 1 : sub <= 4 ? 2 : 4;
|
|
333
|
+
const mask = (1 << bits) - 1;
|
|
334
|
+
for (let j = 0; j < th; j++) {
|
|
335
|
+
let i = ((ty + j) * W + tx) * 4;
|
|
336
|
+
let byte = 0;
|
|
337
|
+
let left = 0;
|
|
338
|
+
for (let k = 0; k < tw; k++, i += 4) {
|
|
339
|
+
if (left === 0) {
|
|
340
|
+
byte = d[p++]!;
|
|
341
|
+
left = 8;
|
|
342
|
+
}
|
|
343
|
+
left -= bits;
|
|
344
|
+
const c = ((byte >> left) & mask) * 3;
|
|
345
|
+
fb[i] = palette[c]!;
|
|
346
|
+
fb[i + 1] = palette[c + 1]!;
|
|
347
|
+
fb[i + 2] = palette[c + 2]!;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
} else if (sub === 128 || sub >= 130) {
|
|
351
|
+
// 游程:128 是颜色 + 长度;130 以上是调色板索引(高位为 1 时后面跟长度)
|
|
352
|
+
const paletted = sub >= 130;
|
|
353
|
+
if (paletted) for (let c = 0; c < (sub - 128) * 3; c++) palette[c] = d[p++]!;
|
|
354
|
+
const total = tw * th;
|
|
355
|
+
let n = 0;
|
|
356
|
+
while (n < total) {
|
|
357
|
+
let r: number;
|
|
358
|
+
let g: number;
|
|
359
|
+
let b: number;
|
|
360
|
+
let run = 1;
|
|
361
|
+
if (paletted) {
|
|
362
|
+
const v = d[p++]!;
|
|
363
|
+
const c = (v & 127) * 3;
|
|
364
|
+
r = palette[c]!;
|
|
365
|
+
g = palette[c + 1]!;
|
|
366
|
+
b = palette[c + 2]!;
|
|
367
|
+
if (v & 128) run = runLength();
|
|
368
|
+
} else {
|
|
369
|
+
r = d[p]!;
|
|
370
|
+
g = d[p + 1]!;
|
|
371
|
+
b = d[p + 2]!;
|
|
372
|
+
p += 3;
|
|
373
|
+
run = runLength();
|
|
374
|
+
}
|
|
375
|
+
const end = Math.min(total, n + run);
|
|
376
|
+
for (; n < end; n++) {
|
|
377
|
+
const i = ((ty + ((n / tw) | 0)) * W + tx + (n % tw)) * 4;
|
|
378
|
+
fb[i] = r;
|
|
379
|
+
fb[i + 1] = g;
|
|
380
|
+
fb[i + 2] = b;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
} else throw new Error(`ZRLE 里有不认识的子编码 ${sub}`);
|
|
384
|
+
if (p > d.length) throw new Error("ZRLE 数据不完整");
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ---------- 会话 ----------
|
|
390
|
+
|
|
391
|
+
export type Endpoint = { reader: ByteReader; write: (b: Buffer) => void };
|
|
392
|
+
export type TranscodeOptions = {
|
|
393
|
+
vnc: Endpoint;
|
|
394
|
+
/** backlog:已经交给页面、还没发出去的字节数(WebSocket 的 bufferedAmount) */
|
|
395
|
+
page: Endpoint & { backlog: () => number };
|
|
396
|
+
creds: VncCreds;
|
|
397
|
+
quality: DesktopQuality;
|
|
398
|
+
/** VNC 服务在本机:要原始像素(见文件开头) */
|
|
399
|
+
local: boolean;
|
|
400
|
+
/** 两头都握手完了(之后就是正常收发画面) */
|
|
401
|
+
onReady?: () => void;
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
/** 「流畅」档和本机的 VNC 服务之间用 16 位色(RGB565):少一半数据,macOS 出图快三成;缩小、压 JPEG 后看不出来 */
|
|
405
|
+
function pixelFormat16(): Buffer {
|
|
406
|
+
const b = Buffer.alloc(16);
|
|
407
|
+
b[0] = 16;
|
|
408
|
+
b[1] = 16;
|
|
409
|
+
b[3] = 1;
|
|
410
|
+
b.writeUInt16BE(31, 4);
|
|
411
|
+
b.writeUInt16BE(63, 6);
|
|
412
|
+
b.writeUInt16BE(31, 8);
|
|
413
|
+
b[10] = 11;
|
|
414
|
+
b[11] = 5;
|
|
415
|
+
b[12] = 0;
|
|
416
|
+
return b;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** RGB565(小端)→ R G B X */
|
|
420
|
+
function expand565(src: Buffer, out: Buffer, n: number): void {
|
|
421
|
+
for (let i = 0, o = 0; i < n; i++, o += 4) {
|
|
422
|
+
const v = src[i * 2]! | (src[i * 2 + 1]! << 8);
|
|
423
|
+
const r = v >> 11;
|
|
424
|
+
const g = (v >> 5) & 63;
|
|
425
|
+
const b = v & 31;
|
|
426
|
+
out[o] = (r << 3) | (r >> 2);
|
|
427
|
+
out[o + 1] = (g << 2) | (g >> 4);
|
|
428
|
+
out[o + 2] = (b << 3) | (b >> 2);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 我们和页面都用的像素格式:32 位、24 位色深、小端、真彩色,R G B 依次在低到高的字节 */
|
|
433
|
+
function pixelFormat(): Buffer {
|
|
434
|
+
const b = Buffer.alloc(16);
|
|
435
|
+
b[0] = 32;
|
|
436
|
+
b[1] = 24;
|
|
437
|
+
b[2] = 0;
|
|
438
|
+
b[3] = 1;
|
|
439
|
+
b.writeUInt16BE(255, 4);
|
|
440
|
+
b.writeUInt16BE(255, 6);
|
|
441
|
+
b.writeUInt16BE(255, 8);
|
|
442
|
+
b[10] = 0;
|
|
443
|
+
b[11] = 8;
|
|
444
|
+
b[12] = 16;
|
|
445
|
+
return b;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function rectHeader(x: number, y: number, w: number, h: number, enc: number): Buffer {
|
|
449
|
+
const b = Buffer.alloc(12);
|
|
450
|
+
b.writeUInt16BE(x, 0);
|
|
451
|
+
b.writeUInt16BE(y, 2);
|
|
452
|
+
b.writeUInt16BE(w, 4);
|
|
453
|
+
b.writeUInt16BE(h, 6);
|
|
454
|
+
b.writeInt32BE(enc, 8);
|
|
455
|
+
return b;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Tight 的长度:每字节 7 位,高位为 1 表示后面还有,最多 3 字节 */
|
|
459
|
+
function compactLength(n: number): Buffer {
|
|
460
|
+
if (n < 0x80) return Buffer.from([n]);
|
|
461
|
+
if (n < 0x4000) return Buffer.from([(n & 0x7f) | 0x80, n >> 7]);
|
|
462
|
+
return Buffer.from([(n & 0x7f) | 0x80, ((n >> 7) & 0x7f) | 0x80, n >> 14]);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
type Cursor = { hotX: number; hotY: number; w: number; h: number; pixels: Buffer; mask: Buffer };
|
|
466
|
+
|
|
467
|
+
/** 光标跟着画面一起缩(最小缩到 16 像素),最近邻 */
|
|
468
|
+
function scaleCursor(c: Cursor, k: number): Cursor {
|
|
469
|
+
const s = Math.min(1, Math.max(k, 16 / Math.max(c.w, c.h, 1)));
|
|
470
|
+
if (s >= 1) return c;
|
|
471
|
+
const w = Math.max(1, Math.round(c.w * s));
|
|
472
|
+
const h = Math.max(1, Math.round(c.h * s));
|
|
473
|
+
const srcStride = Math.ceil(c.w / 8);
|
|
474
|
+
const stride = Math.ceil(w / 8);
|
|
475
|
+
const pixels = Buffer.alloc(w * h * 4);
|
|
476
|
+
const mask = Buffer.alloc(stride * h);
|
|
477
|
+
for (let y = 0; y < h; y++) {
|
|
478
|
+
const sy = Math.min(c.h - 1, Math.floor(y / s));
|
|
479
|
+
for (let x = 0; x < w; x++) {
|
|
480
|
+
const sx = Math.min(c.w - 1, Math.floor(x / s));
|
|
481
|
+
c.pixels.copy(pixels, (y * w + x) * 4, (sy * c.w + sx) * 4, (sy * c.w + sx) * 4 + 4);
|
|
482
|
+
if (c.mask[sy * srcStride + (sx >> 3)]! & (0x80 >> (sx & 7))) mask[y * stride + (x >> 3)]! |= 0x80 >> (x & 7);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return { hotX: Math.min(w - 1, Math.round(c.hotX * s)), hotY: Math.min(h - 1, Math.round(c.hotY * s)), w, h, pixels, mask };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
type Sharp = (typeof import("sharp"))["default"];
|
|
489
|
+
let sharpLoad: Promise<Sharp> | null = null;
|
|
490
|
+
/** sharp 是原生模块:用到时才加载,装不上时只影响转码(调用方退回原样转发) */
|
|
491
|
+
export function loadSharp(): Promise<Sharp> {
|
|
492
|
+
sharpLoad ??= import("sharp").then((m) => m.default);
|
|
493
|
+
sharpLoad.catch(() => (sharpLoad = null));
|
|
494
|
+
return sharpLoad;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* 跑一个转码会话,直到哪一头断开。认证失败时已经按 VNC 的认证失败告诉页面了,再抛出来。
|
|
499
|
+
*/
|
|
500
|
+
export async function transcode(opts: TranscodeOptions): Promise<void> {
|
|
501
|
+
const { vnc, page, creds } = opts;
|
|
502
|
+
const preset = DESKTOP_QUALITIES[opts.quality];
|
|
503
|
+
const sharp = await loadSharp();
|
|
504
|
+
|
|
505
|
+
// 先和 VNC 服务登录、拿到画面大小;同时对页面走完不用认证的握手
|
|
506
|
+
const login = (async () => {
|
|
507
|
+
await vncLogin(vnc.reader, vnc.write, creds);
|
|
508
|
+
// ClientInit:共享(别把别人踢下线)
|
|
509
|
+
vnc.write(Buffer.from([1]));
|
|
510
|
+
const init = await vnc.reader.read(24);
|
|
511
|
+
const name = await vnc.reader.read(init.readUInt32BE(20));
|
|
512
|
+
return { w: init.readUInt16BE(0), h: init.readUInt16BE(2), name };
|
|
513
|
+
})();
|
|
514
|
+
login.catch(() => {});
|
|
515
|
+
await serveNoAuth(
|
|
516
|
+
page.reader,
|
|
517
|
+
page.write,
|
|
518
|
+
login.then(() => {}),
|
|
519
|
+
);
|
|
520
|
+
const server = await login;
|
|
521
|
+
const frame = new Frame(server.w, server.h, preset.edge);
|
|
522
|
+
|
|
523
|
+
// 我们这头要的格式和编码
|
|
524
|
+
const bpp = opts.local && opts.quality === "smooth" ? 2 : 4;
|
|
525
|
+
vnc.write(Buffer.concat([Buffer.from([0, 0, 0, 0]), bpp === 2 ? pixelFormat16() : pixelFormat()]));
|
|
526
|
+
// 光标形状按我们的像素格式发:16 位时不要(noVNC 会画一个小圆点)
|
|
527
|
+
const encs = [
|
|
528
|
+
...(opts.local ? [ENC_RAW, ENC_COPYRECT] : [ENC_ZRLE, ENC_COPYRECT, ENC_RAW]),
|
|
529
|
+
ENC_DESKTOP_SIZE,
|
|
530
|
+
...(bpp === 4 ? [ENC_CURSOR] : []),
|
|
531
|
+
];
|
|
532
|
+
const se = Buffer.alloc(4 + encs.length * 4);
|
|
533
|
+
se[0] = 2;
|
|
534
|
+
se.writeUInt16BE(encs.length, 2);
|
|
535
|
+
encs.forEach((e, i) => se.writeInt32BE(e, 4 + i * 4));
|
|
536
|
+
vnc.write(se);
|
|
537
|
+
|
|
538
|
+
// 页面的 ClientInit,回 ServerInit(缩小后的大小)
|
|
539
|
+
await page.reader.read(1);
|
|
540
|
+
const nameLen = Buffer.alloc(4);
|
|
541
|
+
nameLen.writeUInt32BE(server.name.length);
|
|
542
|
+
page.write(Buffer.concat([Buffer.from([frame.outW >> 8, frame.outW & 255, frame.outH >> 8, frame.outH & 255]), pixelFormat(), nameLen, server.name]));
|
|
543
|
+
opts.onReady?.();
|
|
544
|
+
|
|
545
|
+
// ---------- 状态 ----------
|
|
546
|
+
let closed = false;
|
|
547
|
+
/** 页面支持什么 */
|
|
548
|
+
const pageEnc = { tight: false, cursor: false, desktopSize: false };
|
|
549
|
+
/** 页面的像素格式和我们的一样(光标像素要按它的格式发) */
|
|
550
|
+
let pageFormatOk = true;
|
|
551
|
+
/** 页面在等下一帧 */
|
|
552
|
+
let wanted = false;
|
|
553
|
+
let sending = false;
|
|
554
|
+
let sizeChanged = false;
|
|
555
|
+
let cursor: Cursor | null = null;
|
|
556
|
+
let cursorChanged = false;
|
|
557
|
+
/** VNC 服务的第一帧到了:之前原画还是全黑,别发 */
|
|
558
|
+
let gotFirst = false;
|
|
559
|
+
|
|
560
|
+
const pump = (): void => {
|
|
561
|
+
if (closed || !wanted || sending) return;
|
|
562
|
+
if (!pageEnc.tight || !gotFirst) return;
|
|
563
|
+
if (page.backlog() > HIGH_WATER) {
|
|
564
|
+
setTimeout(pump, 30);
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
const sendCursor = cursorChanged && cursor && pageEnc.cursor && pageFormatOk;
|
|
568
|
+
if (!frame.hasDirty && !sizeChanged && !sendCursor) return;
|
|
569
|
+
wanted = false;
|
|
570
|
+
sending = true;
|
|
571
|
+
const parts: Buffer[] = [];
|
|
572
|
+
let count = 0;
|
|
573
|
+
if (sizeChanged && pageEnc.desktopSize) {
|
|
574
|
+
parts.push(rectHeader(0, 0, frame.outW, frame.outH, ENC_DESKTOP_SIZE));
|
|
575
|
+
count++;
|
|
576
|
+
}
|
|
577
|
+
sizeChanged = false;
|
|
578
|
+
if (sendCursor) {
|
|
579
|
+
const c = scaleCursor(cursor!, frame.outW / frame.srcW);
|
|
580
|
+
parts.push(rectHeader(c.hotX, c.hotY, c.w, c.h, ENC_CURSOR), c.pixels, c.mask);
|
|
581
|
+
count++;
|
|
582
|
+
}
|
|
583
|
+
cursorChanged = false;
|
|
584
|
+
// 先同步把要发的像素拷出来,压 JPEG 时画面再变也不影响这一帧
|
|
585
|
+
const rects = frame.takeDirty().map((r) => ({ r, raw: frame.region(r) }));
|
|
586
|
+
void Promise.all(
|
|
587
|
+
rects.map(({ r, raw }) =>
|
|
588
|
+
sharp(raw, { raw: { width: r.w, height: r.h, channels: 4 } })
|
|
589
|
+
.removeAlpha()
|
|
590
|
+
.jpeg({ quality: preset.jpeg })
|
|
591
|
+
.toBuffer(),
|
|
592
|
+
),
|
|
593
|
+
).then(
|
|
594
|
+
(jpegs) => {
|
|
595
|
+
sending = false;
|
|
596
|
+
if (closed) return;
|
|
597
|
+
rects.forEach(({ r }, i) => {
|
|
598
|
+
parts.push(rectHeader(r.x, r.y, r.w, r.h, ENC_TIGHT), Buffer.from([0x90]), compactLength(jpegs[i]!.length), jpegs[i]!);
|
|
599
|
+
});
|
|
600
|
+
count += rects.length;
|
|
601
|
+
const head = Buffer.alloc(4);
|
|
602
|
+
head.writeUInt16BE(count, 2);
|
|
603
|
+
page.write(Buffer.concat([head, ...parts]));
|
|
604
|
+
// 发的这会儿里页面又要了(不太会)、画面又变了:接着发
|
|
605
|
+
pump();
|
|
606
|
+
},
|
|
607
|
+
(err) => {
|
|
608
|
+
sending = false;
|
|
609
|
+
fail(err);
|
|
610
|
+
},
|
|
611
|
+
);
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
let lastRequest = 0;
|
|
615
|
+
const requestVnc = (incremental: boolean): void => {
|
|
616
|
+
if (closed) return;
|
|
617
|
+
lastRequest = Date.now();
|
|
618
|
+
const b = Buffer.alloc(10);
|
|
619
|
+
b[0] = 3;
|
|
620
|
+
b[1] = incremental ? 1 : 0;
|
|
621
|
+
b.writeUInt16BE(frame.srcW, 6);
|
|
622
|
+
b.writeUInt16BE(frame.srcH, 8);
|
|
623
|
+
vnc.write(b);
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
let failure: ((err: unknown) => void) | null = null;
|
|
627
|
+
const fail = (err: unknown): void => failure?.(err);
|
|
628
|
+
const done = new Promise<void>((_resolve, reject) => {
|
|
629
|
+
failure = (err) => {
|
|
630
|
+
if (closed) return;
|
|
631
|
+
closed = true;
|
|
632
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
633
|
+
};
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
// ---------- VNC 服务 → 我们 ----------
|
|
637
|
+
/** 解码用的暂存:一帧整屏几十 MB,别每次都新分配 */
|
|
638
|
+
let scratch = Buffer.alloc(0);
|
|
639
|
+
const scratchOf = (n: number) => {
|
|
640
|
+
if (scratch.length < n) scratch = Buffer.allocUnsafe(n);
|
|
641
|
+
return scratch.subarray(0, n);
|
|
642
|
+
};
|
|
643
|
+
const fromVnc = async () => {
|
|
644
|
+
const inflater = new Inflater();
|
|
645
|
+
try {
|
|
646
|
+
requestVnc(false);
|
|
647
|
+
for (;;) {
|
|
648
|
+
const type = (await vnc.reader.read(1))[0];
|
|
649
|
+
if (type === 0) {
|
|
650
|
+
const n = (await vnc.reader.read(3)).readUInt16BE(1);
|
|
651
|
+
for (let i = 0; i < n; i++) {
|
|
652
|
+
const hd = await vnc.reader.read(12);
|
|
653
|
+
const x = hd.readUInt16BE(0);
|
|
654
|
+
const y = hd.readUInt16BE(2);
|
|
655
|
+
const w = hd.readUInt16BE(4);
|
|
656
|
+
const h = hd.readUInt16BE(6);
|
|
657
|
+
const enc = hd.readInt32BE(8);
|
|
658
|
+
if (enc === ENC_DESKTOP_SIZE) {
|
|
659
|
+
frame.resize(w, h);
|
|
660
|
+
sizeChanged = true;
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
if (enc === ENC_CURSOR) {
|
|
664
|
+
const pixels = await vnc.reader.read(w * h * 4);
|
|
665
|
+
const mask = await vnc.reader.read(Math.ceil(w / 8) * h);
|
|
666
|
+
cursor = { hotX: x, hotY: y, w, h, pixels, mask };
|
|
667
|
+
cursorChanged = true;
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
if (x + w > frame.srcW || y + h > frame.srcH) throw new Error("VNC 服务发来的矩形超出了画面");
|
|
671
|
+
if (enc === ENC_ZRLE) {
|
|
672
|
+
const len = (await vnc.reader.read(4)).readUInt32BE(0);
|
|
673
|
+
const px = scratchOf(w * h * 4);
|
|
674
|
+
decodeZrle(await inflater.inflate(await vnc.reader.read(len)), px, w, h);
|
|
675
|
+
frame.update(x, y, w, h, px);
|
|
676
|
+
} else if (enc === ENC_RAW) {
|
|
677
|
+
const data = await vnc.reader.read(w * h * bpp);
|
|
678
|
+
if (bpp === 2) {
|
|
679
|
+
const px = scratchOf(w * h * 4);
|
|
680
|
+
expand565(data, px, w * h);
|
|
681
|
+
frame.update(x, y, w, h, px);
|
|
682
|
+
} else frame.update(x, y, w, h, data);
|
|
683
|
+
} else if (enc === ENC_COPYRECT) {
|
|
684
|
+
const s = await vnc.reader.read(4);
|
|
685
|
+
const sx = s.readUInt16BE(0);
|
|
686
|
+
const sy = s.readUInt16BE(2);
|
|
687
|
+
const stride = frame.srcW * 4;
|
|
688
|
+
// 往下挪时从下往上拷,免得覆盖还没拷的
|
|
689
|
+
const rows = [...Array(h).keys()];
|
|
690
|
+
if (y > sy) rows.reverse();
|
|
691
|
+
for (const row of rows) {
|
|
692
|
+
const from = (sy + row) * stride + sx * 4;
|
|
693
|
+
frame.src.copyWithin((y + row) * stride + x * 4, from, from + w * 4);
|
|
694
|
+
}
|
|
695
|
+
frame.damage(x, y, w, h);
|
|
696
|
+
} else throw new Error(`VNC 服务用了不认识的编码 ${enc}`);
|
|
697
|
+
}
|
|
698
|
+
gotFirst = true;
|
|
699
|
+
pump();
|
|
700
|
+
// 下一帧:本机的 VNC 服务会等到画面有变化才回
|
|
701
|
+
setTimeout(() => requestVnc(true), Math.max(0, FRAME_MS - (Date.now() - lastRequest)));
|
|
702
|
+
} else if (type === 1) {
|
|
703
|
+
const n = (await vnc.reader.read(5)).readUInt16BE(3);
|
|
704
|
+
await vnc.reader.read(n * 6);
|
|
705
|
+
} else if (type === 2) {
|
|
706
|
+
page.write(Buffer.from([2]));
|
|
707
|
+
} else if (type === 3) {
|
|
708
|
+
const head = await vnc.reader.read(7);
|
|
709
|
+
const text = await vnc.reader.read(head.readUInt32BE(3));
|
|
710
|
+
page.write(Buffer.concat([Buffer.from([3]), head, text]));
|
|
711
|
+
} else throw new Error(`VNC 服务发来了不认识的消息 ${type}`);
|
|
712
|
+
}
|
|
713
|
+
} finally {
|
|
714
|
+
inflater.close();
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
// ---------- 页面 → 我们 ----------
|
|
719
|
+
const fromPage = async () => {
|
|
720
|
+
for (;;) {
|
|
721
|
+
const type = (await page.reader.read(1))[0];
|
|
722
|
+
if (type === 0) {
|
|
723
|
+
const pf = (await page.reader.read(19)).subarray(3);
|
|
724
|
+
pageFormatOk = pf[0] === 32 && pf[2] === 0 && pf[3] === 1 && pf[10] === 0 && pf[11] === 8 && pf[12] === 16;
|
|
725
|
+
} else if (type === 2) {
|
|
726
|
+
const n = (await page.reader.read(3)).readUInt16BE(1);
|
|
727
|
+
const list = await page.reader.read(n * 4);
|
|
728
|
+
const set = new Set(Array.from({ length: n }, (_, i) => list.readInt32BE(i * 4)));
|
|
729
|
+
pageEnc.tight = set.has(ENC_TIGHT);
|
|
730
|
+
pageEnc.cursor = set.has(ENC_CURSOR);
|
|
731
|
+
pageEnc.desktopSize = set.has(ENC_DESKTOP_SIZE);
|
|
732
|
+
if (!pageEnc.tight) throw new Error("页面不支持 Tight 编码");
|
|
733
|
+
cursorChanged = !!cursor;
|
|
734
|
+
} else if (type === 3) {
|
|
735
|
+
const req = await page.reader.read(9);
|
|
736
|
+
if (!req[0]) frame.markOut(req.readUInt16BE(1), req.readUInt16BE(3), req.readUInt16BE(5), req.readUInt16BE(7));
|
|
737
|
+
wanted = true;
|
|
738
|
+
pump();
|
|
739
|
+
} else if (type === 4) {
|
|
740
|
+
vnc.write(Buffer.concat([Buffer.from([4]), await page.reader.read(7)]));
|
|
741
|
+
} else if (type === 5) {
|
|
742
|
+
const ev = await page.reader.read(5);
|
|
743
|
+
const [sx, sy] = frame.toSrc(ev.readUInt16BE(1), ev.readUInt16BE(3));
|
|
744
|
+
const out = Buffer.alloc(6);
|
|
745
|
+
out[0] = 5;
|
|
746
|
+
out[1] = ev[0]!;
|
|
747
|
+
out.writeUInt16BE(sx, 2);
|
|
748
|
+
out.writeUInt16BE(sy, 4);
|
|
749
|
+
vnc.write(out);
|
|
750
|
+
} else if (type === 6) {
|
|
751
|
+
const head = await page.reader.read(7);
|
|
752
|
+
const text = await page.reader.read(head.readUInt32BE(3));
|
|
753
|
+
vnc.write(Buffer.concat([Buffer.from([6]), head, text]));
|
|
754
|
+
} else throw new Error(`页面发来了不认识的消息 ${type}`);
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
|
|
758
|
+
fromVnc().catch(fail);
|
|
759
|
+
fromPage().catch(fail);
|
|
760
|
+
try {
|
|
761
|
+
await done;
|
|
762
|
+
} finally {
|
|
763
|
+
closed = true;
|
|
764
|
+
}
|
|
765
|
+
}
|
package/web/lib/dom.js
CHANGED
|
@@ -59,6 +59,7 @@ export const ICON = {
|
|
|
59
59
|
pointer: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3l14 7-6 2-2 6Z"/></svg>',
|
|
60
60
|
hand: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11V5a1.5 1.5 0 0 1 3 0v5"/><path d="M12 10V4a1.5 1.5 0 0 1 3 0v6"/><path d="M15 10V6a1.5 1.5 0 0 1 3 0v8a7 7 0 0 1-7 7h-.5a6 6 0 0 1-4.6-2.2L3.4 15a1.6 1.6 0 0 1 2.4-2.1L9 15.5V11"/></svg>',
|
|
61
61
|
help: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 9.2a2.6 2.6 0 0 1 5 .9c0 1.7-2.5 2.3-2.5 3.9M12 17h.01"/></svg>',
|
|
62
|
+
gauge: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/></svg>',
|
|
62
63
|
maximize: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>',
|
|
63
64
|
restore: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"/></svg>',
|
|
64
65
|
laptop: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="5" width="16" height="11" rx="1.5"/><path d="M2 19h20"/></svg>',
|
package/web/views/desktop.js
CHANGED
|
@@ -12,9 +12,20 @@ import { createTouch } from "./desktop-touch.js";
|
|
|
12
12
|
// 进来时不自动连,点了「连接」才连(Linux 上会起 x11vnc)。
|
|
13
13
|
// 离开远程控制页时连接不断,画面在后台照常更新;断线了自己重连,点了「断开」才不连。
|
|
14
14
|
// 手机上:触摸事件由 desktop-touch.js 接管(触控板 / 触摸两种模式、双指本地放大),下面多一排按键。
|
|
15
|
+
// 画质:除了「原画」,服务端都会把画面缩小、压成 JPEG 再发过来(vnc-transcode.ts),换画质要重连。
|
|
16
|
+
|
|
17
|
+
/** 画质档位:和服务端 DESKTOP_QUALITIES 对应,original 是原样转发 */
|
|
18
|
+
const QUALITIES = [
|
|
19
|
+
["smooth", "流畅", "长边 1280,最省流量"],
|
|
20
|
+
["standard", "标准", "长边 1920"],
|
|
21
|
+
["high", "高清", "长边 2560"],
|
|
22
|
+
["original", "原画", "不缩放、无损,很费流量,只适合局域网"],
|
|
23
|
+
];
|
|
24
|
+
const savedQuality = localStorage.getItem("aim.deskQuality");
|
|
15
25
|
|
|
16
26
|
const D = {
|
|
17
27
|
rfb: null,
|
|
28
|
+
quality: QUALITIES.some(([id]) => id === savedQuality) ? savedQuality : "standard",
|
|
18
29
|
/** idle / connecting / connected / error */
|
|
19
30
|
state: "idle",
|
|
20
31
|
message: "",
|
|
@@ -100,7 +111,7 @@ async function connect() {
|
|
|
100
111
|
// 等密码的这会儿里点了断开,或者又发起了一次连接(切回前台、点了重连):这次作罢
|
|
101
112
|
if (!D.want || D.rfb) return;
|
|
102
113
|
const proto = location.protocol === "https:" ? "wss" : "ws";
|
|
103
|
-
const rfb = new RFB(D.screen, `${proto}://${location.host}/ws/desktop`, { credentials: { password }, shared: true, wsProtocols: [] });
|
|
114
|
+
const rfb = new RFB(D.screen, `${proto}://${location.host}/ws/desktop?q=${D.quality}`, { credentials: { password }, shared: true, wsProtocols: [] });
|
|
104
115
|
D.rfb = rfb;
|
|
105
116
|
rfb.scaleViewport = D.fit;
|
|
106
117
|
// 不裁剪:原始大小时 noVNC 的画面容器自己出滚动条
|
|
@@ -293,6 +304,7 @@ function renderTools() {
|
|
|
293
304
|
tool("剪贴板", "clipboard", openClipboard, { disabled: !on }),
|
|
294
305
|
tool("发送按键", "command", (e) => openKeysMenu(e.currentTarget), { disabled: !on || D.viewOnly }),
|
|
295
306
|
tool(D.viewOnly ? "只看(点一下恢复控制)" : "只看不控制", "eye", toggleViewOnly, { on: D.viewOnly }),
|
|
307
|
+
tool(`画质:${QUALITIES.find(([id]) => id === D.quality)[1]}`, "gauge", (e) => openQualityMenu(e.currentTarget)),
|
|
296
308
|
// 手机上靠双指放大,不切原始大小
|
|
297
309
|
isTouch ? null : tool(D.fit ? "原始大小" : "缩放到窗口", D.fit ? "maximize" : "restore", toggleFit),
|
|
298
310
|
tool("全屏", "expand", () => setFull(true)),
|
|
@@ -348,6 +360,25 @@ function toggleViewOnly() {
|
|
|
348
360
|
renderTools();
|
|
349
361
|
}
|
|
350
362
|
|
|
363
|
+
/** 选画质:存下来,连着的话马上按新画质重连 */
|
|
364
|
+
function openQualityMenu(anchor) {
|
|
365
|
+
const r = anchor.getBoundingClientRect();
|
|
366
|
+
showMenu(
|
|
367
|
+
{ x: r.right - 240, y: r.bottom + 4 },
|
|
368
|
+
QUALITIES.map(([id, name, hint]) => ({
|
|
369
|
+
label: `${id === D.quality ? "✓ " : " "}${name} · ${hint}`,
|
|
370
|
+
onclick: () => {
|
|
371
|
+
if (id === D.quality) return;
|
|
372
|
+
D.quality = id;
|
|
373
|
+
localStorage.setItem("aim.deskQuality", id);
|
|
374
|
+
renderTools();
|
|
375
|
+
toast(`画质:${name}`);
|
|
376
|
+
if (D.want) reconnect();
|
|
377
|
+
},
|
|
378
|
+
})),
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
|
|
351
382
|
function toggleFit() {
|
|
352
383
|
D.fit = !D.fit;
|
|
353
384
|
localStorage.setItem("aim.deskFit", D.fit ? "1" : "0");
|
package/src/core/vnc-ard.ts
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
// macOS 屏幕共享的苹果认证(Apple Remote Desktop,RFB 安全类型 30):用 Mac 的用户名和登录密码登录。
|
|
2
|
-
// 屏幕共享没开「VNC 显示程序可以使用密码控制屏幕」时,它只给苹果自己的几种认证,普通 VNC 密码那种没有。
|
|
3
|
-
//
|
|
4
|
-
// 认证在服务端做完,再对页面(noVNC)装成一个不用认证的 VNC 服务:
|
|
5
|
-
// - 登录密码不用发到浏览器;
|
|
6
|
-
// - noVNC 自己做这种认证要用 crypto.subtle,只有 https / localhost 下才有,用 http://IP 访问时用不了。
|
|
7
|
-
//
|
|
8
|
-
// 协议:服务端给 DH 的生成元、素数和它的公钥;双方算出共享密钥,MD5 一下当 AES-128 的钥匙,
|
|
9
|
-
// 把「用户名 \0 … | 密码 \0 …」各 64 字节(空的地方填随机数)用 AES-ECB 加密,连同自己的公钥发回去。
|
|
10
|
-
import crypto from "node:crypto";
|
|
11
|
-
|
|
12
|
-
/** 按需读字节:数据一段段进来(TCP 的 data、WebSocket 的 message),要多少等多少 */
|
|
13
|
-
export class ByteReader {
|
|
14
|
-
private buf = Buffer.alloc(0);
|
|
15
|
-
private waiting: { n: number; resolve: (b: Buffer) => void; reject: (e: Error) => void } | null = null;
|
|
16
|
-
private error: Error | null = null;
|
|
17
|
-
|
|
18
|
-
push(chunk: Buffer): void {
|
|
19
|
-
this.buf = Buffer.concat([this.buf, chunk]);
|
|
20
|
-
this.flush();
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** 那头断了:在等的和以后要读的都报这个错 */
|
|
24
|
-
fail(err: Error): void {
|
|
25
|
-
this.error ??= err;
|
|
26
|
-
const w = this.waiting;
|
|
27
|
-
this.waiting = null;
|
|
28
|
-
w?.reject(this.error);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
read(n: number): Promise<Buffer> {
|
|
32
|
-
if (this.waiting) return Promise.reject(new Error("上一次读还没完"));
|
|
33
|
-
return new Promise((resolve, reject) => {
|
|
34
|
-
this.waiting = { n, resolve, reject };
|
|
35
|
-
this.flush();
|
|
36
|
-
if (this.waiting && this.error) this.fail(this.error);
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** 握手完了:多读进来的那点交给后面原样转发 */
|
|
41
|
-
rest(): Buffer {
|
|
42
|
-
const b = this.buf;
|
|
43
|
-
this.buf = Buffer.alloc(0);
|
|
44
|
-
return b;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
private flush(): void {
|
|
48
|
-
const w = this.waiting;
|
|
49
|
-
if (!w || this.buf.length < w.n) return;
|
|
50
|
-
this.waiting = null;
|
|
51
|
-
const out = this.buf.subarray(0, w.n);
|
|
52
|
-
this.buf = this.buf.subarray(w.n);
|
|
53
|
-
w.resolve(Buffer.from(out));
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** 认证没过(用户名密码不对、服务不支持):message 原样给页面看 */
|
|
58
|
-
export class VncAuthError extends Error {}
|
|
59
|
-
|
|
60
|
-
const TYPE_ARD = 30;
|
|
61
|
-
|
|
62
|
-
/** 左边补 0 到 len 字节(DH 的数可能比素数短) */
|
|
63
|
-
function pad(b: Buffer, len: number): Buffer {
|
|
64
|
-
return b.length >= len ? b.subarray(b.length - len) : Buffer.concat([Buffer.alloc(len - b.length), b]);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** 按苹果认证算出要发回去的:加密后的 128 字节凭据 + 自己的公钥 */
|
|
68
|
-
export function ardResponse(generator: Buffer, prime: Buffer, serverKey: Buffer, username: string, password: string): Buffer {
|
|
69
|
-
const dh = crypto.createDiffieHellman(prime, generator);
|
|
70
|
-
const publicKey = pad(dh.generateKeys(), prime.length);
|
|
71
|
-
const shared = pad(dh.computeSecret(serverKey), prime.length);
|
|
72
|
-
const creds = crypto.randomBytes(128);
|
|
73
|
-
// 各最多 63 字节,后面跟一个 \0(和 noVNC、苹果自己的客户端一样)
|
|
74
|
-
const user = Buffer.from(username, "utf8").subarray(0, 63);
|
|
75
|
-
const pass = Buffer.from(password, "utf8").subarray(0, 63);
|
|
76
|
-
user.copy(creds, 0);
|
|
77
|
-
creds[user.length] = 0;
|
|
78
|
-
pass.copy(creds, 64);
|
|
79
|
-
creds[64 + pass.length] = 0;
|
|
80
|
-
const cipher = crypto.createCipheriv("aes-128-ecb", crypto.createHash("md5").update(shared).digest(), null);
|
|
81
|
-
cipher.setAutoPadding(false);
|
|
82
|
-
return Buffer.concat([cipher.update(creds), cipher.final(), publicKey]);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* 作为客户端和 VNC 服务走完版本协商和苹果认证,停在 ClientInit 之前(后面原样转发就行)。
|
|
87
|
-
* 失败抛 VncAuthError(认证的问题)或普通 Error(连接断了)
|
|
88
|
-
*/
|
|
89
|
-
export async function ardLogin(r: ByteReader, write: (b: Buffer) => void, username: string, password: string): Promise<void> {
|
|
90
|
-
const version = (await r.read(12)).toString("latin1");
|
|
91
|
-
if (!/^RFB \d{3}\.\d{3}\n$/.test(version)) throw new VncAuthError("对方不是 VNC 服务");
|
|
92
|
-
// 苹果的是 003.889,按 3.8 谈就行
|
|
93
|
-
write(Buffer.from("RFB 003.008\n", "latin1"));
|
|
94
|
-
const count = (await r.read(1))[0]!;
|
|
95
|
-
if (count === 0) {
|
|
96
|
-
const len = (await r.read(4)).readUInt32BE(0);
|
|
97
|
-
throw new VncAuthError(`VNC 服务拒绝连接:${(await r.read(len)).toString("utf8")}`);
|
|
98
|
-
}
|
|
99
|
-
const types = [...(await r.read(count))];
|
|
100
|
-
if (!types.includes(TYPE_ARD)) throw new VncAuthError("这个 VNC 服务不支持用 Mac 用户名登录:把设置里的用户名留空,只填 VNC 密码");
|
|
101
|
-
write(Buffer.from([TYPE_ARD]));
|
|
102
|
-
const head = await r.read(4);
|
|
103
|
-
const generator = head.subarray(0, 2);
|
|
104
|
-
const keyLength = head.readUInt16BE(2);
|
|
105
|
-
const prime = await r.read(keyLength);
|
|
106
|
-
const serverKey = await r.read(keyLength);
|
|
107
|
-
write(ardResponse(generator, prime, serverKey, username, password));
|
|
108
|
-
const status = (await r.read(4)).readUInt32BE(0);
|
|
109
|
-
if (status !== 0) throw new VncAuthError("Mac 的用户名或密码不对");
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* 对页面那头装成不用认证的 VNC 服务(3.8,只给安全类型 None)。
|
|
114
|
-
* login 是和真正的 VNC 服务认证的过程:它失败时把原因当作认证失败告诉页面
|
|
115
|
-
*/
|
|
116
|
-
export async function serveNoAuth(r: ByteReader, write: (b: Buffer) => void, login: Promise<void>): Promise<void> {
|
|
117
|
-
// 页面那头还没谈完 login 就失败了:先接住,下面 await 时再处理(不然算没人接的 rejection,进程会退出)
|
|
118
|
-
login.catch(() => {});
|
|
119
|
-
write(Buffer.from("RFB 003.008\n", "latin1"));
|
|
120
|
-
await r.read(12);
|
|
121
|
-
write(Buffer.from([1, 1]));
|
|
122
|
-
await r.read(1);
|
|
123
|
-
try {
|
|
124
|
-
await login;
|
|
125
|
-
} catch (err) {
|
|
126
|
-
const reason = Buffer.from(err instanceof VncAuthError ? err.message : `连不上 VNC 服务:${err instanceof Error ? err.message : err}`, "utf8");
|
|
127
|
-
const len = Buffer.alloc(4);
|
|
128
|
-
len.writeUInt32BE(reason.length);
|
|
129
|
-
write(Buffer.concat([Buffer.from([0, 0, 0, 1]), len, reason]));
|
|
130
|
-
throw err;
|
|
131
|
-
}
|
|
132
|
-
write(Buffer.from([0, 0, 0, 0]));
|
|
133
|
-
}
|