agent-loft 0.2.42 → 0.2.44

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.
@@ -0,0 +1,342 @@
1
+ // agent 回复里提到的文件:路径变成能点的链接,点开在弹层里预览(图片 / PDF / 音视频 / 文本代码),其它的下载。
2
+ // 能不能看由服务端判断(只认回复里写过的路径、挡掉密钥之类的敏感文件,见 core/reply-files.ts)。
3
+ import hljs from "/vendor/hljs.js";
4
+ import { h, icon, starsLoader, toast } from "../lib/dom.js";
5
+ import { api } from "../lib/api.js";
6
+ import { renderMarkdown } from "../lib/markdown.js";
7
+ import { S } from "../state.js";
8
+
9
+ const fileUrl = (key, p, extra = "") =>
10
+ `/api/conversations/${encodeURIComponent(key)}/file?path=${encodeURIComponent(p)}${extra}`;
11
+ /** 网页(含 Codex visualize 画的图表)套好外壳、放进沙箱显示的地址 */
12
+ const htmlUrl = (key, p) => `/api/conversations/${encodeURIComponent(key)}/html?path=${encodeURIComponent(p)}`;
13
+
14
+ // ---------- 认路径 ----------
15
+
16
+ /** 末尾的行号:a.ts:12、a.ts:12:5、a.ts:12-20、a.ts#L12、a.ts#L12-L20 */
17
+ const LINE_SUFFIX = /(?::\d+(?:[:-]\d+)?|#L\d+(?:-L?\d+)?)$/;
18
+
19
+ /** 不带目录的文件名只认这些常见的文档 / 媒体后缀(a.js、Vue.js 这种多半是在说技术名词,不认) */
20
+ const BARE_EXT = /\.(md|markdown|txt|pdf|png|jpe?g|gif|webp|svg|csv|tsv|xlsx?|docx?|pptx?|html?|zip|tgz|gz|mp4|mov|webm|mp3|m4a|wav|log)$/i;
21
+
22
+ /** 路径里不该有的字符(通配符、模板、管道…) */
23
+ const NOT_PATH = /[\s*?{}$<>|"'`]/;
24
+
25
+ function stripLine(p) {
26
+ return p.replace(LINE_SUFFIX, "");
27
+ }
28
+
29
+ /** 行内代码里的字:像不像一个文件路径。像就返回去掉行号后的路径 */
30
+ function codePath(text) {
31
+ const t = stripLine(text.trim());
32
+ if (!t || t.length > 400 || NOT_PATH.test(t) || /^[a-z][\w+.-]*:\/\/(?!\/)/i.test(t)) return null;
33
+ if (/^(?:file:\/\/)?(?:~|\.{1,2})?\//.test(t)) {
34
+ if (t.startsWith("//")) return null;
35
+ // 至少两级(/a/b),或者带后缀(/a.md):单独一个 / 、/tmp 这种多半是在说目录
36
+ const segs = t.replace(/^(?:file:\/\/)?(?:~|\.{1,2})?\//, "").split("/").filter(Boolean);
37
+ return segs.length >= 2 || /\.[A-Za-z]\w{0,9}$/.test(t) ? t : null;
38
+ }
39
+ // 相对路径:a/b.ts 这种带目录、带后缀的
40
+ if (/^[\p{L}\p{N}_.@+-]+(?:\/[\p{L}\p{N}_.@+-]+)+$/u.test(t) && /\.[A-Za-z]\w{0,9}$/.test(t)) return t;
41
+ if (/^[\p{L}\p{N}_.@+-]+$/u.test(t) && BARE_EXT.test(t)) return t;
42
+ return null;
43
+ }
44
+
45
+ /** 链接地址是不是本机文件(没有协议的、file://、绝对路径)。是就返回路径 */
46
+ function hrefPath(raw) {
47
+ if (!raw || raw.startsWith("#") || raw.startsWith("//")) return null;
48
+ if (/^[a-z][\w+.-]*:/i.test(raw) && !raw.startsWith("file://")) return null;
49
+ let p = raw;
50
+ // marked 会把地址里的中文、空格编码掉;服务端拿回复原文对,要还原成原样
51
+ try {
52
+ p = decodeURI(raw);
53
+ } catch {
54
+ // 编码坏了就按原样
55
+ }
56
+ return stripLine(p) || null;
57
+ }
58
+
59
+ /** 正文里的绝对路径(要带后缀,免得把「/ 斜杠」之类的当成路径) */
60
+ const TEXT_PATH = /(?<![\p{L}\p{N}_./~:-])(?:file:\/\/)?~?\/(?!\/)[^\s<>"'`()()[\]{},。;:!?、“”‘’「」|*]+\.[A-Za-z0-9]{1,10}(?::\d+(?::\d+)?)?(?![\p{L}\p{N}_/-])/gu;
61
+
62
+ function fileLink(key, p, ...children) {
63
+ return h(
64
+ "a",
65
+ {
66
+ class: "file-link",
67
+ href: fileUrl(key, p),
68
+ target: "_blank",
69
+ rel: "noopener",
70
+ title: `${p}\n点击预览`,
71
+ onclick: (e) => {
72
+ // 新标签页打开(Ctrl / ⌘ / 中键)照浏览器的来
73
+ if (e.ctrlKey || e.metaKey || e.shiftKey || e.button !== 0) return;
74
+ e.preventDefault();
75
+ openReplyFile(key, p);
76
+ },
77
+ },
78
+ ...children,
79
+ );
80
+ }
81
+
82
+ /** patchMarkdown 的 enhance:把一块回复里的文件路径(链接、行内代码、正文里的绝对路径、图片)变成能点开的 */
83
+ export function linkReplyFiles(box) {
84
+ const key = S.current;
85
+ if (!key) return;
86
+ embedVisualizations(box, key);
87
+ for (const a of box.querySelectorAll("a[href]")) {
88
+ const p = hrefPath(a.getAttribute("href"));
89
+ if (!p) continue;
90
+ a.replaceWith(fileLink(key, p, ...a.childNodes));
91
+ }
92
+ for (const code of box.querySelectorAll("code")) {
93
+ if (code.closest("pre, a")) continue;
94
+ const p = codePath(code.textContent);
95
+ if (p) code.replaceWith(fileLink(key, p, code.cloneNode(true)));
96
+ }
97
+ for (const img of box.querySelectorAll("img[src]")) {
98
+ const p = hrefPath(img.getAttribute("src"));
99
+ if (!p) continue;
100
+ const alt = img.getAttribute("alt") || p.split("/").pop();
101
+ const pic = h("img", { src: fileUrl(key, p), alt, loading: "lazy" });
102
+ const link = fileLink(key, p, pic);
103
+ link.classList.add("file-img");
104
+ // 打不开(文件没了、不能看):退回成一个文字链接,点了会说明原因
105
+ pic.onerror = () => link.replaceChildren(alt);
106
+ img.replaceWith(link);
107
+ }
108
+ linkTextPaths(box, key);
109
+ }
110
+
111
+ function linkTextPaths(box, key) {
112
+ const walker = document.createTreeWalker(box, NodeFilter.SHOW_TEXT, {
113
+ acceptNode: (n) => (n.parentElement?.closest("pre, code, a") ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT),
114
+ });
115
+ const nodes = [];
116
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) if (n.nodeValue.includes("/")) nodes.push(n);
117
+ for (const node of nodes) {
118
+ const text = node.nodeValue;
119
+ const parts = [];
120
+ let last = 0;
121
+ for (const m of text.matchAll(TEXT_PATH)) {
122
+ parts.push(text.slice(last, m.index), fileLink(key, stripLine(m[0]), m[0]));
123
+ last = m.index + m[0].length;
124
+ }
125
+ if (last === 0) continue;
126
+ parts.push(text.slice(last));
127
+ node.replaceWith(...parts.filter((x) => x !== ""));
128
+ }
129
+ }
130
+
131
+ // ---------- Codex visualize 画的图表 ----------
132
+ //
133
+ // Codex 自带的 visualize 插件把图表写成 HTML 片段,回复里单独一行 visualize{"path":"…"} 标出放在哪
134
+ // (官方客户端照这个把图表嵌进对话)。这里一样嵌进来:服务端套好插件的外壳,放进沙箱 iframe
135
+
136
+ const VIZ_LINE = /^\s*(?:::)?visualize\s*(\{.*\})\s*$/s;
137
+
138
+ function vizSpec(text) {
139
+ const m = VIZ_LINE.exec(text);
140
+ if (!m) return null;
141
+ try {
142
+ const spec = JSON.parse(m[1]);
143
+ return typeof spec?.path === "string" && spec.path ? spec : null;
144
+ } catch {
145
+ // 还在输出、JSON 还没写完:先当普通文字
146
+ return null;
147
+ }
148
+ }
149
+
150
+ function embedVisualizations(box, key) {
151
+ for (const p of box.querySelectorAll("p")) {
152
+ if (!p.textContent.includes("visualize")) continue;
153
+ const whole = vizSpec(p.textContent);
154
+ if (whole) {
155
+ p.replaceWith(vizFrame(key, whole));
156
+ continue;
157
+ }
158
+ // 和别的文字挤在同一段里(中间只隔了一个换行)
159
+ for (const n of [...p.childNodes]) {
160
+ const spec = n.nodeType === Node.TEXT_NODE ? vizSpec(n.nodeValue) : null;
161
+ if (!spec) continue;
162
+ if (n.previousSibling?.nodeName === "BR") n.previousSibling.remove();
163
+ if (n.nextSibling?.nodeName === "BR") n.nextSibling.remove();
164
+ n.replaceWith(vizFrame(key, spec));
165
+ }
166
+ }
167
+ }
168
+
169
+ function vizFrame(key, spec) {
170
+ const page = htmlUrl(key, spec.path);
171
+ const name = spec.title || spec.path.split("/").pop();
172
+ const box = h("div", { class: `viz${spec.mode === "wide" ? " wide" : ""}` }, h("div", { class: "viz-loading" }, starsLoader()));
173
+ // 先问一下能不能看:不能的话 iframe 里只会是一页报错
174
+ void api(`${fileUrl(key, spec.path)}&stat=1`).then(
175
+ () => {
176
+ const frame = h("iframe", { class: "viz-frame", src: page, sandbox: "allow-scripts", referrerpolicy: "no-referrer", loading: "lazy", title: name });
177
+ box.replaceChildren(
178
+ frame,
179
+ h(
180
+ "div",
181
+ { class: "viz-actions" },
182
+ h("button", { class: "viz-btn", onclick: () => openReplyFile(key, spec.path) }, "放大"),
183
+ h("a", { class: "viz-btn", href: page, target: "_blank", rel: "noopener" }, "新标签页打开"),
184
+ ),
185
+ );
186
+ },
187
+ (err) => box.replaceChildren(h("div", { class: "viz-error" }, `图表显示不了:${err.message}`, h("div", { class: "viz-path" }, spec.path))),
188
+ );
189
+ return box;
190
+ }
191
+
192
+ // 沙箱里的页面报自己的高度(core/visualize.ts 加的脚本),iframe 跟着变高
193
+ addEventListener("message", (e) => {
194
+ if (e.data?.type !== "aloft-html-size" || !Number.isFinite(e.data.height)) return;
195
+ for (const frame of document.querySelectorAll("iframe.viz-frame")) {
196
+ if (frame.contentWindow !== e.source) continue;
197
+ // 有的页面按视口高度排版,iframe 一变高它也跟着变高:设个上限,别无限长下去
198
+ const height = Math.min(Math.max(Math.ceil(e.data.height), 60), 1600);
199
+ if (Math.abs(frame.offsetHeight - height) > 2) frame.style.height = `${height}px`;
200
+ }
201
+ });
202
+
203
+ // ---------- 预览 ----------
204
+
205
+ const IMAGE = /\.(png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
206
+ const VIDEO = /\.(mp4|m4v|webm|mov)$/i;
207
+ const AUDIO = /\.(mp3|m4a|aac|wav|ogg|oga|opus|flac)$/i;
208
+ const MARKDOWN = /\.(md|markdown)$/i;
209
+ const HTML = /\.html?$/i;
210
+ /** 网页超过这么大就不显示了(和服务端 core/visualize.ts 的 HTML_MAX 一致) */
211
+ const HTML_MAX = 2 * 1024 * 1024;
212
+ /** 明摆着不是文本的:不去读内容,直接给下载 */
213
+ const BINARY = /\.(zip|gz|tgz|bz2|xz|7z|rar|tar|docx?|xlsx?|pptx?|key|numbers|pages|exe|dmg|iso|bin|so|dylib|o|class|jar|wasm|sqlite|db|woff2?|ttf|otf|psd|ai|sketch)$/i;
214
+ /** 文本最多读这么多来预览 */
215
+ const TEXT_MAX = 1024 * 1024;
216
+
217
+ function fmtSize(n) {
218
+ if (!Number.isFinite(n)) return "";
219
+ if (n < 1024) return `${n} B`;
220
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
221
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
222
+ }
223
+
224
+ /** 文件预览弹层:先拿名字和大小,再按类型画内容。点外面、按 Esc 关闭 */
225
+ export async function openReplyFile(key, p) {
226
+ const url = fileUrl(key, p);
227
+ const body = h("div", { class: "fv-body" }, h("div", { class: "fv-loading" }, starsLoader("lg")));
228
+ const title = h("div", { class: "fv-title" }, h("div", { class: "fv-name" }, p.split("/").pop() || p), h("div", { class: "fv-sub" }, p));
229
+ const actions = h("div", { class: "fv-actions" });
230
+ const close = () => {
231
+ overlay.remove();
232
+ document.removeEventListener("keydown", onKey, true);
233
+ };
234
+ const onKey = (e) => {
235
+ if (e.key !== "Escape") return;
236
+ e.preventDefault();
237
+ close();
238
+ };
239
+ const overlay = h(
240
+ "div",
241
+ { class: "file-viewer", onclick: (e) => e.target === overlay && close() },
242
+ h(
243
+ "div",
244
+ { class: "fv-panel" },
245
+ h("div", { class: "fv-head" }, title, actions, h("button", { class: "icon-btn", title: "关闭", onclick: close }, icon("x"))),
246
+ body,
247
+ ),
248
+ );
249
+ document.body.append(overlay);
250
+ document.addEventListener("keydown", onKey, true);
251
+
252
+ let info;
253
+ try {
254
+ info = await api(`${url}&stat=1`);
255
+ } catch (err) {
256
+ close();
257
+ toast(err.message);
258
+ return;
259
+ }
260
+ if (!overlay.isConnected) return;
261
+ title.lastChild.textContent = [info.path, fmtSize(info.size)].filter(Boolean).join(" · ");
262
+ title.firstChild.textContent = info.name;
263
+ const download = h("a", { class: "btn", href: `${url}&download=1`, download: info.name }, "下载");
264
+ const newTab = h("a", { class: "btn ghost", href: url, target: "_blank", rel: "noopener" }, "新标签页打开");
265
+ const name = info.name;
266
+ const media = IMAGE.test(name) || VIDEO.test(name) || AUDIO.test(name) || /\.pdf$/i.test(name);
267
+ actions.replaceChildren(...(media ? [newTab, download] : [download]));
268
+
269
+ if (IMAGE.test(name)) {
270
+ const img = h("img", { class: "fv-img", src: url, alt: name });
271
+ img.onerror = () => body.replaceChildren(notPreviewable("图片打不开", download));
272
+ return body.replaceChildren(img);
273
+ }
274
+ if (/\.pdf$/i.test(name)) return body.replaceChildren(h("iframe", { class: "fv-frame", src: url, title: name }));
275
+ if (VIDEO.test(name)) return body.replaceChildren(h("video", { class: "fv-media", src: url, controls: true, playsinline: true, preload: "metadata" }));
276
+ if (AUDIO.test(name)) return body.replaceChildren(h("audio", { class: "fv-audio", src: url, controls: true, preload: "metadata" }));
277
+ if (BINARY.test(name)) return body.replaceChildren(notPreviewable("这种文件不能在网页里预览", download));
278
+ if (info.size === 0) return body.replaceChildren(notPreviewable("空文件", null));
279
+
280
+ const showText = async () => {
281
+ const view = await textView(url, info, download);
282
+ if (overlay.isConnected) body.replaceChildren(...view);
283
+ };
284
+ // 网页:放进沙箱里显示出来,也能切到源码
285
+ if (HTML.test(name) && info.size <= HTML_MAX) {
286
+ const page = htmlUrl(key, p);
287
+ const frame = h("iframe", { class: "fv-frame fv-html", src: page, sandbox: "allow-scripts", referrerpolicy: "no-referrer", title: name });
288
+ const toggle = h(
289
+ "button",
290
+ {
291
+ class: "btn ghost",
292
+ onclick: () => {
293
+ const toSource = toggle.textContent === "源码";
294
+ toggle.textContent = toSource ? "预览" : "源码";
295
+ if (toSource) void showText();
296
+ else body.replaceChildren(frame);
297
+ },
298
+ },
299
+ "源码",
300
+ );
301
+ actions.replaceChildren(toggle, h("a", { class: "btn ghost", href: page, target: "_blank", rel: "noopener" }, "新标签页打开"), download);
302
+ return body.replaceChildren(frame);
303
+ }
304
+ await showText();
305
+ }
306
+
307
+ /** 当文本显示:太大只读开头,有 NUL 字节的是二进制。返回要放进 body 的节点 */
308
+ async function textView(url, info, download) {
309
+ let buf;
310
+ try {
311
+ const res = await fetch(url, { credentials: "same-origin", headers: info.size > TEXT_MAX ? { Range: `bytes=0-${TEXT_MAX - 1}` } : {} });
312
+ if (!res.ok) throw new Error(`读取失败(${res.status})`);
313
+ buf = new Uint8Array(await res.arrayBuffer());
314
+ } catch (err) {
315
+ return [notPreviewable(err.message, download)];
316
+ }
317
+ if (buf.subarray(0, 8192).includes(0)) return [notPreviewable("这个文件不是文本,不能在网页里预览", download)];
318
+ const text = new TextDecoder("utf-8").decode(buf);
319
+ const cut = info.size > buf.length ? h("div", { class: "fv-cut" }, `文件有 ${fmtSize(info.size)},这里只显示前 ${fmtSize(buf.length)},完整内容请下载`) : null;
320
+ const view = MARKDOWN.test(info.name) ? h("div", { class: "fv-doc" }, renderMarkdown(text)) : codeView(text, info.name);
321
+ return cut ? [cut, view] : [view];
322
+ }
323
+
324
+ function codeView(text, name) {
325
+ const code = h("code", {});
326
+ const ext = (/\.([\w+-]+)$/.exec(name)?.[1] ?? "").toLowerCase();
327
+ const lang = hljs.getLanguage(ext) ? ext : null;
328
+ // 高亮很慢:太大的就原样显示
329
+ if (lang && text.length < 300_000) {
330
+ try {
331
+ code.innerHTML = hljs.highlight(text, { language: lang, ignoreIllegals: true }).value;
332
+ code.classList.add("hljs");
333
+ } catch {
334
+ code.textContent = text;
335
+ }
336
+ } else code.textContent = text;
337
+ return h("pre", { class: "fv-code" }, code);
338
+ }
339
+
340
+ function notPreviewable(message, download) {
341
+ return h("div", { class: "fv-empty" }, h("div", {}, message), download ? download.cloneNode(true) : null);
342
+ }
@@ -11,6 +11,7 @@ import { renderChips, setBusy } from "./composer.js";
11
11
  import { renderScheduled } from "./schedule.js";
12
12
  import { changeCwd, doAction, forkConversation } from "./conv-actions.js";
13
13
  import { scheduleNav } from "./msg-nav.js";
14
+ import { linkReplyFiles } from "./file-preview.js";
14
15
 
15
16
  // ---------- 打开会话 ----------
16
17
 
@@ -520,13 +521,13 @@ function patchAi(item) {
520
521
  v.bodyKey = bodyKey;
521
522
  v.body = silent
522
523
  ? body
523
- ? h("details", { class: "silent-run" }, h("summary", {}, "🔕 定时任务:这次无需提醒"), renderMarkdown(body))
524
+ ? h("details", { class: "silent-run" }, h("summary", {}, "🔕 定时任务:这次无需提醒"), renderMarkdown(body, { enhance: linkReplyFiles }))
524
525
  : h("div", { class: "silent-run" }, "🔕 定时任务:这次无需提醒")
525
526
  : body
526
527
  ? h("div", { class: "md" })
527
528
  : null;
528
529
  }
529
- if (bodyKey === "md") patchMarkdown(v.body, body, { live: working });
530
+ if (bodyKey === "md") patchMarkdown(v.body, body, { live: working, enhance: linkReplyFiles });
530
531
 
531
532
  // 还在回复:末尾挂上星星动画和实时用时;什么都还没出来时旁边带一句「思考中…」
532
533
  if (working) {
@@ -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
- }