@keyou007/agent-bot 0.1.26 → 0.1.27-alpha.1
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/CHANGELOG.md +17 -0
- package/README.md +18 -8
- package/README.zh.md +17 -7
- package/SECURITY.md +4 -4
- package/config.example.yaml +3 -2
- package/dist/cli/AutostartManager.js +1 -1
- package/dist/config/SettingsStore.js +10 -5
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +2 -1
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/schema.js +5 -1
- package/dist/config/schema.js.map +1 -1
- package/dist/feishu/CardRenderer.js +5 -8
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuConnector.js +1 -1
- package/dist/feishu/FeishuConnector.js.map +1 -1
- package/dist/feishu/SettingsCard.js +4 -3
- package/dist/feishu/SettingsCard.js.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +163 -0
- package/dist/local-files/GitDiffPreview.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +63 -9
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +106 -48
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/terminal/TerminalCards.js +1 -1
- package/dist/terminal/TerminalPage.js +52 -20
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +72 -73
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +23 -14
- package/docs/technical-reference.zh.md +23 -14
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +7 -3
- package/src/cli/AutostartManager.ts +1 -1
- package/src/config/SettingsStore.ts +12 -7
- package/src/config/loadConfig.ts +2 -1
- package/src/config/schema.ts +6 -1
- package/src/feishu/CardRenderer.ts +5 -8
- package/src/feishu/FeishuConnector.ts +1 -1
- package/src/feishu/SettingsCard.ts +3 -2
- package/src/index.ts +3 -1
- package/src/local-files/GitDiffPreview.ts +141 -0
- package/src/local-files/LocalFileViewerServer.ts +54 -9
- package/src/local-files/TurnPreviewPage.ts +124 -60
- package/src/terminal/TerminalCards.ts +1 -1
- package/src/terminal/TerminalPage.ts +53 -20
- package/src/terminal/TerminalServer.ts +69 -62
|
@@ -1,16 +1,21 @@
|
|
|
1
|
-
|
|
1
|
+
import { DEFAULT_TERMINAL_PASSWORD } from "../config/schema.js";
|
|
2
|
+
|
|
3
|
+
export function terminalPage(base: string, recovery = false, autoResume = false, defaultPassword = false): string {
|
|
4
|
+
defaultPassword = defaultPassword && !autoResume;
|
|
2
5
|
base = base.replaceAll("&", "&").replaceAll(String.fromCharCode(34), """).replaceAll("<", "<").replaceAll(">", ">");
|
|
3
6
|
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4
7
|
<title>AgentBot Terminal</title><link rel="stylesheet" href="${base}/assets/xterm.css"><link rel="stylesheet" href="${base}/assets/terminal.css">
|
|
5
8
|
<script defer src="${base}/assets/xterm.js"></script><script defer src="${base}/assets/fit.js"></script><script defer src="${base}/assets/terminal.js"></script></head>
|
|
6
|
-
<body data-base="${base}" data-recovery="${recovery}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect"
|
|
7
|
-
<section id="welcome"><h1
|
|
8
|
-
|
|
9
|
+
<body data-base="${base}" data-recovery="${recovery}" data-resume="${autoResume}" data-default-password="${defaultPassword}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" title="前台连接不因空闲关闭;后台空闲或网页断开 30 分钟后关闭。重连重新计时,可从原会话的终端管理卡打开或关闭终端。" disabled>关闭终端</button></header>
|
|
10
|
+
<section id="welcome"><h1>连接终端</h1><p>此终端拥有 AgentBot 所在电脑的系统用户权限。</p><label for="password">终端密码</label><div class="password-row"><input id="password" type="password" autocomplete="current-password" maxlength="256" value="${defaultPassword ? DEFAULT_TERMINAL_PASSWORD : ""}" aria-describedby="password-hint" autofocus><button id="welcome-connect" type="button">连接</button></div><p id="password-hint">可在飞书 /setting → 高级 → 终端密码中修改默认密码。</p></section><div id="terminal"></div>
|
|
11
|
+
</body></html>`;
|
|
9
12
|
}
|
|
10
13
|
|
|
11
14
|
export const TERMINAL_CSS = `
|
|
12
15
|
#welcome-connect{padding:10px 20px;font:inherit}
|
|
13
|
-
|
|
16
|
+
#welcome{width:100%}.password-row{display:flex;gap:12px;margin-top:8px;max-width:440px}#password{min-width:0;flex:1;background:#191f2b;border:1px solid #415775;border-radius:6px;padding:10px 12px;color:inherit;font:inherit}#password:focus{outline:2px solid #84c1ff;outline-offset:2px}
|
|
17
|
+
:root{color-scheme:dark;font:14px system-ui,sans-serif;background:#10141b;color:#dbe4f1}*{box-sizing:border-box}body{margin:0;height:100dvh;display:flex;flex-direction:column}header{display:flex;gap:12px;align-items:center;padding:12px 18px;background:#191f2b;border-bottom:1px solid #303a4d;flex-wrap:wrap}header strong{font-size:17px}header strong span{font-weight:400;color:#9aacc7}#status{flex:1;color:#adbfdb;font-size:13px}button{background:#25334a;border:1px solid #415775;border-radius:7px;padding:8px 12px;color:#e5efff;cursor:pointer}button:hover{background:#304661}button:disabled{opacity:.45;cursor:default}#close{border-color:#86505a}#welcome{margin:40px auto;max-width:780px;padding:0 24px;line-height:1.8}h1{font-size:25px}#terminal{flex:1;min-height:0;padding:12px 14px;display:none}.xterm{height:100%}body.connected #welcome{display:none}body.connected #terminal{display:block}
|
|
18
|
+
@media(max-width:650px){header{padding:4px 6px;gap:6px;flex-shrink:0}header strong{display:none}#status{flex:0 0 100%;min-width:0;font-size:12px;line-height:1.4;overflow-wrap:anywhere}#status:has(.terminal-directory){flex:1}.terminal-directory{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}header button{flex-shrink:0;min-height:44px;padding:6px 8px;font-size:12px}#terminal{padding:6px}}
|
|
14
19
|
`;
|
|
15
20
|
|
|
16
21
|
export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
@@ -18,12 +23,17 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
18
23
|
const status = document.getElementById('status');
|
|
19
24
|
const connect = document.getElementById('connect');
|
|
20
25
|
const welcomeConnect = document.getElementById('welcome-connect');
|
|
26
|
+
const password = document.getElementById('password');
|
|
21
27
|
const close = document.getElementById('close');
|
|
22
28
|
const interrupt = document.getElementById('interrupt');
|
|
23
29
|
const storageKey = 'agentbot-terminal:' + location.pathname;
|
|
24
30
|
const recovery = document.body.dataset.recovery === 'true';
|
|
31
|
+
const autoResume = recovery && document.body.dataset.resume === 'true';
|
|
32
|
+
const defaultPassword = document.body.dataset.defaultPassword === 'true';
|
|
33
|
+
const initialPassword = password.value;
|
|
34
|
+
if (autoResume) document.getElementById('welcome').hidden = true;
|
|
25
35
|
if (recovery) document.querySelector('#welcome h1').textContent = '恢复已有终端';
|
|
26
|
-
let session, ws, term, observer, retryTimer, socketTimer, checking, visibilityTimer;
|
|
36
|
+
let session, ws, term, observer, retryTimer, socketTimer, checking, visibilityTimer, countdownTimer;
|
|
27
37
|
let socketReady = false;
|
|
28
38
|
let epoch = 0, failures = 0, stopped = false, pageHidden = false, offline = false, busy = false;
|
|
29
39
|
try { session = JSON.parse(sessionStorage.getItem(storageKey) || 'null'); } catch {}
|
|
@@ -48,21 +58,36 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
48
58
|
}
|
|
49
59
|
function buttons(retry = false) {
|
|
50
60
|
for (const button of [connect, welcomeConnect]) {
|
|
51
|
-
button.textContent = session ? '重新连接' : recovery ? '
|
|
61
|
+
button.textContent = session ? '重新连接' : recovery ? '恢复连接' : '连接';
|
|
52
62
|
button.disabled = busy || (!!session && !retry);
|
|
53
63
|
}
|
|
54
64
|
close.disabled = busy || !session;
|
|
65
|
+
password.disabled = busy;
|
|
55
66
|
}
|
|
56
67
|
function invalidate() {
|
|
68
|
+
cancelDefaultConnect();
|
|
57
69
|
epoch++; clearTimeout(retryTimer); clearTimeout(socketTimer);
|
|
58
70
|
clearTimeout(visibilityTimer); socketReady = false;
|
|
59
71
|
checking?.abort(); checking = undefined;
|
|
60
72
|
const old = ws; ws = undefined; old?.close(); interrupt.disabled = true;
|
|
61
73
|
if (term) term.options.disableStdin = true;
|
|
62
74
|
}
|
|
75
|
+
function cancelDefaultConnect() {
|
|
76
|
+
if (countdownTimer === undefined) return;
|
|
77
|
+
clearTimeout(countdownTimer); countdownTimer = undefined;
|
|
78
|
+
status.textContent = '已取消自动连接';
|
|
79
|
+
}
|
|
80
|
+
function countdown(seconds = 5) {
|
|
81
|
+
if (!awake() || busy || session || password.value !== initialPassword) { cancelDefaultConnect(); return; }
|
|
82
|
+
status.textContent = '使用默认密码,' + seconds + ' 秒后自动连接';
|
|
83
|
+
countdownTimer = setTimeout(() => {
|
|
84
|
+
if (!awake() || password.value !== initialPassword) { cancelDefaultConnect(); return; }
|
|
85
|
+
if (seconds === 1) connect.click(); else countdown(seconds - 1);
|
|
86
|
+
}, 1000);
|
|
87
|
+
}
|
|
63
88
|
function forget() {
|
|
64
89
|
session = undefined; sessionStorage.removeItem(storageKey);
|
|
65
|
-
|
|
90
|
+
buttons(true);
|
|
66
91
|
}
|
|
67
92
|
function end(text) { stopped = true; invalidate(); forget(); status.textContent = text; }
|
|
68
93
|
function fail(text) { stopped = true; invalidate(); status.textContent = text; buttons(true); }
|
|
@@ -130,7 +155,10 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
130
155
|
const restored = () => {
|
|
131
156
|
if (!active()) return;
|
|
132
157
|
terminal.options.disableStdin = false; terminal.focus();
|
|
133
|
-
status.textContent = '已连接 · '
|
|
158
|
+
status.textContent = '已连接 · ';
|
|
159
|
+
const directory = document.createElement('span');
|
|
160
|
+
directory.className = 'terminal-directory'; directory.textContent = result.cwd; directory.title = result.cwd;
|
|
161
|
+
status.append(directory); interrupt.disabled = false; buttons();
|
|
134
162
|
};
|
|
135
163
|
// xterm parses asynchronously. Keep replay silent until its write callback,
|
|
136
164
|
// before subsequently queued live output is parsed. Startup output is live.
|
|
@@ -158,7 +186,6 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
158
186
|
const result = await post('status', current, controller);
|
|
159
187
|
if (generation !== epoch || current !== session || stopped || !awake()) return;
|
|
160
188
|
if (result.state === 'approved' || result.state === 'running') openSocket();
|
|
161
|
-
else if (result.state === 'pending') { failures = 0; status.textContent = '等待原会话中的所有者授权'; buttons(); schedule(1500); }
|
|
162
189
|
else end(result.message || '授权已失效,请重新请求连接');
|
|
163
190
|
} catch (error) {
|
|
164
191
|
if (generation !== epoch || current !== session || stopped || !awake()) return;
|
|
@@ -171,22 +198,26 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
171
198
|
if (busy) return;
|
|
172
199
|
stopped = false; failures = 0; invalidate();
|
|
173
200
|
if (session) { status.textContent = '正在恢复已有终端授权…'; buttons(); check(); return; }
|
|
174
|
-
|
|
201
|
+
document.body.classList.remove('connected');
|
|
202
|
+
if (!autoResume && !password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
|
|
203
|
+
busy = true; buttons(); status.textContent = autoResume ? '正在恢复原终端…' : '正在验证密码…';
|
|
175
204
|
try {
|
|
176
|
-
document.body.classList.remove('connected');
|
|
177
205
|
if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器不支持安全随机数,请使用新版浏览器。');
|
|
178
206
|
const browserKey = Array.from(crypto.getRandomValues(new Uint8Array(32)), (n) => n.toString(16).padStart(2,'0')).join('');
|
|
179
|
-
const result = await post('request', {launch:location.pathname,browserKey});
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
status.textContent =
|
|
183
|
-
} catch (error) { status.textContent = '
|
|
207
|
+
const result = await post('request', {launch:location.pathname,browserKey,password:autoResume ? undefined : password.value});
|
|
208
|
+
password.value = '';
|
|
209
|
+
session = {requestId:result.requestId,browserKey}; sessionStorage.setItem(storageKey,JSON.stringify(session));
|
|
210
|
+
status.textContent = autoResume ? '正在恢复原终端…' : '密码已验证,正在连接终端…';
|
|
211
|
+
} catch (error) { status.textContent = '连接失败:' + message(error); password.focus(); }
|
|
184
212
|
finally { busy = false; buttons(!session); }
|
|
185
213
|
check();
|
|
186
214
|
};
|
|
215
|
+
password.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); welcomeConnect.click(); } });
|
|
216
|
+
password.addEventListener('input', cancelDefaultConnect);
|
|
217
|
+
password.addEventListener('change', cancelDefaultConnect);
|
|
187
218
|
interrupt.onclick = () => { if (ws?.readyState === WebSocket.OPEN && !interrupt.disabled) ws.send(JSON.stringify({type:'input',data:String.fromCharCode(3)})); };
|
|
188
219
|
close.onclick = async () => {
|
|
189
|
-
if (busy || !session || !confirm('关闭该终端和 Shell
|
|
220
|
+
if (busy || !session || !confirm('关闭该终端和 Shell?\n' + close.title + '\n已脱离终端的后台进程可能继续运行。')) return;
|
|
190
221
|
busy = true; stopped = true; invalidate(); buttons();
|
|
191
222
|
try { await post('close',session); end('终端已关闭'); }
|
|
192
223
|
catch (error) {
|
|
@@ -208,6 +239,8 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
208
239
|
window.addEventListener('offline', () => { offline = true; suspend(); });
|
|
209
240
|
window.addEventListener('online', () => { offline = false; resume(); });
|
|
210
241
|
window.addEventListener('focus', resume);
|
|
211
|
-
|
|
212
|
-
|
|
242
|
+
buttons();
|
|
243
|
+
if (!session && autoResume) connect.click();
|
|
244
|
+
else if (!session && defaultPassword) countdown();
|
|
245
|
+
else check();
|
|
213
246
|
})();`;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash, randomBytes,
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
4
4
|
import type { Duplex } from "node:stream";
|
|
@@ -8,6 +8,7 @@ import path from "node:path";
|
|
|
8
8
|
import type { Logger } from "pino";
|
|
9
9
|
import { WebSocket, WebSocketServer } from "ws";
|
|
10
10
|
import { z } from "zod";
|
|
11
|
+
import { DEFAULT_TERMINAL_PASSWORD } from "../config/schema.js";
|
|
11
12
|
import type { CardAction } from "../feishu/types.js";
|
|
12
13
|
import { spawnTerminal, type TerminalProcess, type TerminalSpawner } from "./TerminalProcess.js";
|
|
13
14
|
import { terminalPage, TERMINAL_CSS, TERMINAL_SCRIPT } from "./TerminalPage.js";
|
|
@@ -17,7 +18,7 @@ import type { TerminalCommandState } from "./TerminalCommandTracker.js";
|
|
|
17
18
|
const require = createRequire(import.meta.url);
|
|
18
19
|
const AUTH_TTL = 5 * 60_000;
|
|
19
20
|
const IDLE_TTL = 30 * 60_000;
|
|
20
|
-
const DISCONNECT_TTL =
|
|
21
|
+
const DISCONNECT_TTL = 30 * 60_000;
|
|
21
22
|
const FOREGROUND_TTL = 90_000;
|
|
22
23
|
const MAX_TTL = 8 * 60 * 60_000;
|
|
23
24
|
const KEY = z.string().regex(/^[a-f0-9]{64}$/u);
|
|
@@ -30,11 +31,11 @@ const frame = z.discriminatedUnion("type", [
|
|
|
30
31
|
]);
|
|
31
32
|
|
|
32
33
|
export interface TerminalAuthorization {
|
|
33
|
-
requestId: string; approvalToken: string;
|
|
34
|
+
requestId: string; approvalToken: string; cwd: string; expiresAt: number;
|
|
34
35
|
}
|
|
35
36
|
export interface TerminalCardView extends TerminalAuthorization {
|
|
36
37
|
contextKey: string; commandCardMessageId: string; shellStarted: boolean;
|
|
37
|
-
terminalId: string; reopenToken: string; reopenUrl: string; recovery: boolean; state: "
|
|
38
|
+
terminalId: string; reopenToken: string; reopenUrl: string; recovery: boolean; state: "approved" | "running" | "closed";
|
|
38
39
|
connected: boolean; message?: string;
|
|
39
40
|
}
|
|
40
41
|
export interface ActiveTerminal {
|
|
@@ -45,6 +46,7 @@ export interface ActiveTerminal {
|
|
|
45
46
|
export interface TerminalServerOptions {
|
|
46
47
|
stateDirectory: string;
|
|
47
48
|
ownerId(): string | undefined;
|
|
49
|
+
password?(): string;
|
|
48
50
|
canStart?(): boolean;
|
|
49
51
|
readJob(jobId: string): Promise<{ cwd: string; contextKey: string; cardMessageId?: string }>;
|
|
50
52
|
requestApproval(authorization: TerminalCardView): Promise<string | undefined>;
|
|
@@ -56,9 +58,9 @@ export interface TerminalServerOptions {
|
|
|
56
58
|
interface TerminalSession extends TerminalAuthorization {
|
|
57
59
|
reopenToken: string;
|
|
58
60
|
contextKey: string; commandCardMessageId: string;
|
|
59
|
-
ownerId: string; keyHash: Buffer; createdAt: number; lastActivity: number;
|
|
61
|
+
ownerId: string; keyHash: Buffer; passwordHash: Buffer; createdAt: number; lastActivity: number;
|
|
60
62
|
activeAccessId: string;
|
|
61
|
-
state: "
|
|
63
|
+
state: "approved" | "running" | "closed";
|
|
62
64
|
message?: string; cardId?: string; pty?: TerminalProcess; socket?: WebSocket;
|
|
63
65
|
starting?: Promise<void>; output: string;
|
|
64
66
|
attached?: boolean;
|
|
@@ -69,7 +71,7 @@ interface TerminalSession extends TerminalAuthorization {
|
|
|
69
71
|
}
|
|
70
72
|
interface TerminalRecovery extends TerminalAuthorization {
|
|
71
73
|
targetId: string; ownerId: string; keyHash: Buffer; cardId?: string;
|
|
72
|
-
state: "
|
|
74
|
+
state: "approved" | "closed"; message?: string;
|
|
73
75
|
}
|
|
74
76
|
|
|
75
77
|
export class TerminalServer {
|
|
@@ -79,6 +81,7 @@ export class TerminalServer {
|
|
|
79
81
|
private readonly recoveries = new Map<string, TerminalRecovery>();
|
|
80
82
|
private cardUpdates = Promise.resolve();
|
|
81
83
|
private readonly requests: number[] = [];
|
|
84
|
+
private readonly passwordFailures: Array<{ address: string; at: number }> = [];
|
|
82
85
|
private timer?: NodeJS.Timeout;
|
|
83
86
|
private links?: TerminalLinks;
|
|
84
87
|
private base?: URL;
|
|
@@ -189,32 +192,7 @@ export class TerminalServer {
|
|
|
189
192
|
this.publishCards(session); await this.cardUpdates;
|
|
190
193
|
return recovery?.state === "closed" && session.state !== "closed" ? "恢复连接请求已取消,原终端不受影响。" : "终端已关闭。";
|
|
191
194
|
}
|
|
192
|
-
|
|
193
|
-
if (action.value.decision === "allow") {
|
|
194
|
-
if (recovery) {
|
|
195
|
-
if (!this.canReopen(session)) throw new Error("原终端已结束,不能恢复。");
|
|
196
|
-
if (session.state === "approved") {
|
|
197
|
-
this.assertCanStart();
|
|
198
|
-
session.expiresAt = this.now() + AUTH_TTL;
|
|
199
|
-
}
|
|
200
|
-
for (const other of this.recoveries.values()) {
|
|
201
|
-
if (other.targetId === session.requestId && other !== recovery && other.state !== "closed") this.closeRecovery(other, "已由另一网页恢复连接");
|
|
202
|
-
}
|
|
203
|
-
recovery.state = "approved"; session.activeAccessId = recovery.requestId;
|
|
204
|
-
session.socket?.close(1000, "Reconnected from another page"); session.socket = undefined;
|
|
205
|
-
this.markDisconnected(session);
|
|
206
|
-
} else session.state = "approved";
|
|
207
|
-
this.publishCards(session); await this.cardUpdates;
|
|
208
|
-
this.options.logger.info({ requestId: session.requestId }, "Terminal authorized by owner.");
|
|
209
|
-
return session.state === "approved"
|
|
210
|
-
? "已授权,请返回网页连接;若原网页已关闭,点击本卡片的“打开终端”。"
|
|
211
|
-
: "已授权,请返回网页;也可点击本卡片的“重新打开终端”或“关闭终端”。";
|
|
212
|
-
}
|
|
213
|
-
if (action.value.decision !== "deny") throw new Error("无效的终端授权操作。");
|
|
214
|
-
if (recovery) this.closeRecovery(recovery, "恢复连接已拒绝,原终端不受影响");
|
|
215
|
-
else this.disposeSession(session, "终端授权已拒绝");
|
|
216
|
-
this.publishCards(session); await this.cardUpdates;
|
|
217
|
-
return "已拒绝终端连接。";
|
|
195
|
+
throw new Error("请在网页中输入终端密码连接;此卡片仅用于管理终端。");
|
|
218
196
|
}
|
|
219
197
|
|
|
220
198
|
async close(): Promise<void> {
|
|
@@ -243,7 +221,7 @@ export class TerminalServer {
|
|
|
243
221
|
const expire = () => {
|
|
244
222
|
if (session.state !== "running" || session.socket || session.disconnectedAt === undefined) return;
|
|
245
223
|
const remaining = DISCONNECT_TTL - (this.now() - session.disconnectedAt);
|
|
246
|
-
if (remaining <= 0) this.disposeSession(session, "网页已断开
|
|
224
|
+
if (remaining <= 0) this.disposeSession(session, "网页已断开 30 分钟,Shell 已自动关闭");
|
|
247
225
|
else { session.disconnectTimer = setTimeout(expire, remaining); session.disconnectTimer.unref(); }
|
|
248
226
|
};
|
|
249
227
|
session.disconnectTimer = setTimeout(expire, DISCONNECT_TTL); session.disconnectTimer.unref();
|
|
@@ -264,8 +242,8 @@ export class TerminalServer {
|
|
|
264
242
|
}
|
|
265
243
|
private cardView(session: TerminalSession, recovery?: TerminalRecovery): TerminalCardView {
|
|
266
244
|
const auth = recovery ?? session;
|
|
267
|
-
const state = recovery
|
|
268
|
-
return { requestId: auth.requestId, approvalToken: auth.approvalToken,
|
|
245
|
+
const state = recovery?.state === "closed" ? "closed" : session.state;
|
|
246
|
+
return { requestId: auth.requestId, approvalToken: auth.approvalToken, cwd: session.cwd,
|
|
269
247
|
contextKey: session.contextKey, commandCardMessageId: session.commandCardMessageId, shellStarted: Boolean(session.pty),
|
|
270
248
|
expiresAt: auth.expiresAt, terminalId: session.requestId, reopenToken: session.reopenToken, reopenUrl: this.reopenUrl(session), recovery: Boolean(recovery), state,
|
|
271
249
|
connected: session.socket?.readyState === WebSocket.OPEN, message: recovery?.message ?? session.message };
|
|
@@ -303,7 +281,7 @@ export class TerminalServer {
|
|
|
303
281
|
}
|
|
304
282
|
private authenticated(value: unknown): TerminalSession {
|
|
305
283
|
const { authorization, session } = this.access(value);
|
|
306
|
-
if (authorization.state === "
|
|
284
|
+
if (authorization.state === "closed" || session.activeAccessId !== authorization.requestId) {
|
|
307
285
|
throw new Error("终端尚未授权、已结束或已由其他网页恢复。");
|
|
308
286
|
}
|
|
309
287
|
return session;
|
|
@@ -325,7 +303,12 @@ export class TerminalServer {
|
|
|
325
303
|
body = fs.readFileSync(path.join(path.dirname(require.resolve("@xterm/xterm")), "../css/xterm.css"), "utf8"); type = "text/css";
|
|
326
304
|
} else {
|
|
327
305
|
const resumeId = this.resumeId(url.pathname);
|
|
328
|
-
if (this.launchJob(url.pathname) || resumeId) {
|
|
306
|
+
if (this.launchJob(url.pathname) || resumeId) {
|
|
307
|
+
const session = resumeId ? this.sessions.get(resumeId) : undefined;
|
|
308
|
+
body = terminalPage(this.basePath, Boolean(resumeId), session?.state === "running" && Boolean(session.pty),
|
|
309
|
+
(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD) === DEFAULT_TERMINAL_PASSWORD);
|
|
310
|
+
type = "text/html; charset=utf-8";
|
|
311
|
+
}
|
|
329
312
|
}
|
|
330
313
|
this.headers(res); res.statusCode = body === undefined ? 404 : 200; res.setHeader("Content-Type", type);
|
|
331
314
|
res.end(req.method === "HEAD" ? undefined : body ?? "Not found."); return;
|
|
@@ -335,51 +318,78 @@ export class TerminalServer {
|
|
|
335
318
|
}
|
|
336
319
|
const data = await readJson(req);
|
|
337
320
|
if (route === "/api/request") {
|
|
338
|
-
const
|
|
321
|
+
const result = z.object({ launch: z.string().max(300), browserKey: KEY, password: z.string().max(256).optional() }).safeParse(data);
|
|
322
|
+
if (!result.success) { this.json(res, 400, { error: "终端连接参数无效。" }); return; }
|
|
323
|
+
const parsed = result.data;
|
|
324
|
+
const now = this.now();
|
|
339
325
|
const resumeId = this.resumeId(parsed.launch);
|
|
340
326
|
const jobId = this.launchJob(parsed.launch);
|
|
341
327
|
const ownerId = this.options.ownerId();
|
|
342
|
-
if ((!jobId && !resumeId) || !ownerId) throw new Error("终端链接无效,或尚未配置飞书所有者。");
|
|
343
328
|
const existing = resumeId ? this.sessions.get(resumeId) : undefined;
|
|
344
329
|
if (resumeId && (!existing || !this.canReopen(existing) || existing.ownerId !== ownerId)) {
|
|
345
330
|
throw new Error("原终端尚未授权、已结束或服务已重启;请从原命令卡片创建新终端。");
|
|
346
331
|
}
|
|
332
|
+
// A live Shell's recovery link grants reattachment, never a new Shell.
|
|
333
|
+
const resumeRunning = existing?.state === "running" && Boolean(existing.pty) && existing.ownerId === ownerId;
|
|
334
|
+
const passwordHash = hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD);
|
|
335
|
+
if (!resumeRunning) {
|
|
336
|
+
const address = req.socket.remoteAddress ?? "unknown";
|
|
337
|
+
while (this.passwordFailures[0] && this.passwordFailures[0].at <= now - 60_000) this.passwordFailures.shift();
|
|
338
|
+
if (this.passwordFailures.length >= 50 || this.passwordFailures.filter((failure) => failure.address === address).length >= 5) {
|
|
339
|
+
this.json(res, 429, { error: "密码尝试过于频繁,请一分钟后重试。" }); return;
|
|
340
|
+
}
|
|
341
|
+
if (parsed.password === undefined || !timingSafeEqual(hash(parsed.password), passwordHash)) {
|
|
342
|
+
this.passwordFailures.push({ address, at: now });
|
|
343
|
+
this.json(res, 401, { error: "终端密码错误,请重新输入。" }); return;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if ((!jobId && !resumeId) || !ownerId) throw new Error("终端链接无效,或尚未配置飞书所有者。");
|
|
347
347
|
if (!existing || existing.state === "approved") this.assertCanStart();
|
|
348
|
-
const now = this.now();
|
|
349
348
|
while (this.requests[0] !== undefined && this.requests[0] < now - 3600_000) this.requests.shift();
|
|
350
|
-
if (this.requests.length >= 20 || (this.requests.length > 0 && now - this.requests.at(-1)! < 10_000)
|
|
351
|
-
|| (existing
|
|
352
|
-
: [...this.sessions.values()].filter((s) => s.state !== "closed").length >= 3)) {
|
|
349
|
+
if (this.requests.length >= 20 || (!resumeRunning && this.requests.length > 0 && now - this.requests.at(-1)! < 10_000)
|
|
350
|
+
|| (!existing && [...this.sessions.values()].filter((s) => s.state !== "closed").length >= 3)) {
|
|
353
351
|
this.json(res, 429, { error: "终端请求过于频繁或已达 3 个会话上限,请稍后重试。" }); return;
|
|
354
352
|
}
|
|
355
353
|
this.requests.push(now);
|
|
356
354
|
if (existing) {
|
|
357
355
|
const recovery: TerminalRecovery = { requestId: randomBytes(16).toString("hex"), targetId: existing.requestId, ownerId,
|
|
358
|
-
keyHash: hash(parsed.browserKey), approvalToken: randomBytes(32).toString("hex"),
|
|
359
|
-
cwd: existing.cwd, expiresAt: now + AUTH_TTL, state: "
|
|
356
|
+
keyHash: hash(parsed.browserKey), approvalToken: randomBytes(32).toString("hex"),
|
|
357
|
+
cwd: existing.cwd, expiresAt: now + AUTH_TTL, state: "approved" };
|
|
360
358
|
this.recoveries.set(recovery.requestId, recovery);
|
|
361
359
|
try {
|
|
362
360
|
recovery.cardId = await this.options.requestApproval(this.cardView(existing, recovery));
|
|
363
|
-
if (!recovery.cardId) throw new Error("
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
361
|
+
if (!recovery.cardId) throw new Error("无法发送终端管理卡片。");
|
|
362
|
+
if (!this.canReopen(existing) || existing.ownerId !== this.options.ownerId()
|
|
363
|
+
|| !timingSafeEqual(passwordHash, hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD))) {
|
|
364
|
+
throw new Error("终端已结束或连接设置已变化,请重新连接。");
|
|
365
|
+
}
|
|
366
|
+
if (existing.state === "approved") { this.assertCanStart(); existing.expiresAt = this.now() + AUTH_TTL; }
|
|
367
|
+
} catch (error) { this.closeRecovery(recovery, "恢复连接未完成,原终端不受影响"); this.publishCards(existing); throw error; }
|
|
368
|
+
for (const other of this.recoveries.values()) {
|
|
369
|
+
if (other !== recovery && other.targetId === existing.requestId && other.state !== "closed") this.closeRecovery(other, "已由另一网页恢复连接");
|
|
370
|
+
}
|
|
371
|
+
existing.activeAccessId = recovery.requestId;
|
|
372
|
+
existing.socket?.close(1000, "Reconnected from another page"); existing.socket = undefined;
|
|
373
|
+
this.markDisconnected(existing);
|
|
374
|
+
this.publishCards(existing);
|
|
375
|
+
this.json(res, 200, { requestId: recovery.requestId }); return;
|
|
367
376
|
}
|
|
368
377
|
const job = await this.options.readJob(jobId!);
|
|
369
378
|
this.assertCanStart();
|
|
370
379
|
if (!job.cardMessageId || !job.contextKey?.trim()) throw new Error("命令卡片或原始会话信息尚未就绪。");
|
|
371
380
|
const requestId = randomBytes(16).toString("hex");
|
|
372
381
|
const session: TerminalSession = { requestId, reopenToken: this.links!.createRecovery(), activeAccessId: requestId, ownerId, cwd: job.cwd, keyHash: hash(parsed.browserKey),
|
|
382
|
+
passwordHash,
|
|
373
383
|
contextKey: job.contextKey, commandCardMessageId: job.cardMessageId,
|
|
374
|
-
approvalToken: randomBytes(32).toString("hex"),
|
|
375
|
-
createdAt: now, lastActivity: now, expiresAt: now + AUTH_TTL, state: "
|
|
384
|
+
approvalToken: randomBytes(32).toString("hex"),
|
|
385
|
+
createdAt: now, lastActivity: now, expiresAt: now + AUTH_TTL, state: "approved", output: "" };
|
|
376
386
|
this.sessions.set(requestId, session);
|
|
377
387
|
try {
|
|
378
388
|
session.cardId = await this.options.requestApproval(this.cardView(session));
|
|
379
|
-
if (!session.cardId) throw new Error("
|
|
380
|
-
|
|
381
|
-
} catch (error) { this.disposeSession(session, "
|
|
382
|
-
this.json(res, 200, { requestId
|
|
389
|
+
if (!session.cardId) throw new Error("无法发送终端管理卡片。");
|
|
390
|
+
this.publishCards(session);
|
|
391
|
+
} catch (error) { this.disposeSession(session, "终端管理卡发送失败"); throw error; }
|
|
392
|
+
this.json(res, 200, { requestId }); return;
|
|
383
393
|
}
|
|
384
394
|
if (route !== "/api/status" && route !== "/api/close") { this.json(res, 404, { error: "Not found." }); return; }
|
|
385
395
|
const { authorization, session } = this.access(data);
|
|
@@ -490,19 +500,16 @@ export class TerminalServer {
|
|
|
490
500
|
const now = this.now();
|
|
491
501
|
for (const recovery of this.recoveries.values()) {
|
|
492
502
|
const target = this.sessions.get(recovery.targetId);
|
|
493
|
-
if (recovery.state === "pending" && now >= recovery.expiresAt) {
|
|
494
|
-
this.closeRecovery(recovery, "恢复授权已过期,原终端不受影响");
|
|
495
|
-
if (target) this.publishCards(target);
|
|
496
|
-
}
|
|
497
503
|
if (!target || (recovery.state === "closed" && now >= recovery.expiresAt + AUTH_TTL)) this.recoveries.delete(recovery.requestId);
|
|
498
504
|
}
|
|
499
505
|
for (const s of this.sessions.values()) {
|
|
500
|
-
if (s.ownerId !== this.options.ownerId() ||
|
|
506
|
+
if (s.ownerId !== this.options.ownerId() || !timingSafeEqual(s.passwordHash, hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD))
|
|
507
|
+
|| now - s.createdAt >= MAX_TTL
|
|
501
508
|
|| (s.state !== "running" && s.state !== "closed" && now >= s.expiresAt)) {
|
|
502
509
|
this.disposeSession(s, "终端已超时或授权已失效,请重新连接");
|
|
503
510
|
}
|
|
504
511
|
if (s.state === "running" && s.disconnectedAt !== undefined && now - s.disconnectedAt >= DISCONNECT_TTL) {
|
|
505
|
-
this.disposeSession(s, "网页已断开
|
|
512
|
+
this.disposeSession(s, "网页已断开 30 分钟,Shell 已自动关闭");
|
|
506
513
|
}
|
|
507
514
|
if (s.state === "running" && now - Math.max(s.lastActivity, s.foregroundUntil ?? 0) >= IDLE_TTL) {
|
|
508
515
|
this.disposeSession(s, "连续 30 分钟无输入或输出,Shell 已自动关闭");
|