@keyou007/agent-bot 0.1.26 → 0.1.27-alpha.0

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +10 -6
  3. package/README.zh.md +10 -6
  4. package/config.example.yaml +3 -2
  5. package/dist/cli/AutostartManager.js +1 -1
  6. package/dist/config/SettingsStore.js +10 -5
  7. package/dist/config/SettingsStore.js.map +1 -1
  8. package/dist/config/loadConfig.js +2 -1
  9. package/dist/config/loadConfig.js.map +1 -1
  10. package/dist/config/schema.js +5 -1
  11. package/dist/config/schema.js.map +1 -1
  12. package/dist/feishu/CardRenderer.js +4 -7
  13. package/dist/feishu/CardRenderer.js.map +1 -1
  14. package/dist/feishu/FeishuConnector.js +1 -1
  15. package/dist/feishu/FeishuConnector.js.map +1 -1
  16. package/dist/feishu/SettingsCard.js +4 -3
  17. package/dist/feishu/SettingsCard.js.map +1 -1
  18. package/dist/index.js +3 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/terminal/TerminalCards.js +1 -1
  21. package/dist/terminal/TerminalPage.js +17 -14
  22. package/dist/terminal/TerminalPage.js.map +1 -1
  23. package/dist/terminal/TerminalServer.js +60 -66
  24. package/dist/terminal/TerminalServer.js.map +1 -1
  25. package/docs/technical-reference.md +13 -14
  26. package/docs/technical-reference.zh.md +13 -14
  27. package/npm-shrinkwrap.json +2 -2
  28. package/package.json +1 -1
  29. package/skills/agent-bot/SKILL.md +5 -3
  30. package/src/cli/AutostartManager.ts +1 -1
  31. package/src/config/SettingsStore.ts +12 -7
  32. package/src/config/loadConfig.ts +2 -1
  33. package/src/config/schema.ts +6 -1
  34. package/src/feishu/CardRenderer.ts +4 -7
  35. package/src/feishu/FeishuConnector.ts +1 -1
  36. package/src/feishu/SettingsCard.ts +3 -2
  37. package/src/index.ts +3 -1
  38. package/src/terminal/TerminalCards.ts +1 -1
  39. package/src/terminal/TerminalPage.ts +17 -14
  40. package/src/terminal/TerminalServer.ts +54 -56
@@ -84,14 +84,15 @@ function renderField(
84
84
  {
85
85
  tag: "input",
86
86
  name: entry.name,
87
- default_value: String(value),
87
+ default_value: entry.kind === "secret" ? "" : String(value),
88
88
  behaviors,
89
89
  input_type: "text",
90
90
  ...(entry.kind === "number"
91
91
  ? { placeholder: plain("0:自动分配并复用") }
92
+ : entry.kind === "secret" ? { placeholder: plain("输入新密码,留空不修改;未设置时为 123456") }
92
93
  : {}),
93
94
  width: "fill",
94
- max_length: entry.kind === "number" ? 5 : 1000,
95
+ max_length: entry.kind === "number" ? 5 : entry.kind === "secret" ? 256 : 1000,
95
96
  },
96
97
  ];
97
98
  }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ import { LocalControlServer } from "./cli/LocalControlServer.js";
8
8
  import { controlEndpoint, type ControlRequest, type ControlResponse } from "./cli/controlProtocol.js";
9
9
  import { readPackageVersion } from "./cli/packageVersion.js";
10
10
  import { loadConfig } from "./config/loadConfig.js";
11
+ import { DEFAULT_TERMINAL_PASSWORD } from "./config/schema.js";
11
12
  import { SettingsStore } from "./config/SettingsStore.js";
12
13
  import { persistFeishuUserOpenIdIfMissing } from "./config/FeishuUserOpenIdStore.js";
13
14
  import {
@@ -244,6 +245,7 @@ if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
244
245
  const server = new TerminalServer({
245
246
  stateDirectory: path.join(path.dirname(config.storage.sqlitePath), "terminal"),
246
247
  ownerId: () => config.feishu.userOpenId,
248
+ password: () => config.terminal?.password ?? DEFAULT_TERMINAL_PASSWORD,
247
249
  canStart: () => !shuttingDown && !restartRequested && !safeRestart.scheduled && !safeRestart.restarting,
248
250
  readJob: (jobId) => shellCommandJobs.readJob(jobId),
249
251
  requestApproval: (authorization) => sendTerminalAuthorization(feishuOutbound, authorization),
@@ -253,7 +255,7 @@ if (feishuOutbound && localFileViewer && config.terminal?.enabled !== false) {
253
255
  try {
254
256
  const publicBaseUrl = await server.start(localFileViewer);
255
257
  terminalServer = server;
256
- logger.info({ publicBaseUrl }, "Interactive terminal service started (owner authorization required).");
258
+ logger.info({ publicBaseUrl }, "Interactive terminal service started (password authentication required).");
257
259
  } catch (error) {
258
260
  await server.close();
259
261
  logger.warn({ error }, "Terminal service unavailable; command cards remain usable.");
@@ -10,7 +10,7 @@ export async function sendTerminalAuthorization(
10
10
  const card = new CardRenderer().renderTerminalAuthorization(view);
11
11
  if (isThreadContextKey(view.contextKey)) {
12
12
  if (!outbound.replyInteractiveCard || !view.commandCardMessageId) {
13
- throw new Error("无法向原话题发送终端授权卡,请重新打开命令卡片。");
13
+ throw new Error("无法向原话题发送终端管理卡,请重新打开命令卡片。");
14
14
  }
15
15
  return outbound.replyInteractiveCard(view.contextKey, { messageId: view.commandCardMessageId, replyInThread: true }, card);
16
16
  }
@@ -3,14 +3,15 @@ export function terminalPage(base: string, recovery = false): string {
3
3
  return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>AgentBot Terminal</title><link rel="stylesheet" href="${base}/assets/xterm.css"><link rel="stylesheet" href="${base}/assets/terminal.css">
5
5
  <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">请求连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" disabled>关闭终端</button></header>
7
- <section id="welcome"><h1>在浏览器中使用本机终端</h1><p>命令在 AgentBot 所在电脑上执行,拥有其系统用户权限。不会自动执行或接管原卡片中的命令。</p><p>点击请求连接,然后返回命令所在的飞书会话或话题,由 AgentBot 所有者核对验证码并授权。不要批准非本人发起的请求。</p><button id="welcome-connect" type="button">请求连接</button><p id="code"></p></section><div id="terminal"></div>
6
+ <body data-base="${base}" data-recovery="${recovery}"><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" disabled>关闭终端</button></header>
7
+ <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" autofocus><button id="welcome-connect" type="button">连接</button></div></section><div id="terminal"></div>
8
8
  <footer id="details">前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 3 分钟后自动关闭 Shell · 成功重连取消断开计时并重置空闲计时 · 可从原会话的终端管理卡打开或关闭终端</footer></body></html>`;
9
9
  }
10
10
 
11
11
  export const TERMINAL_CSS = `
12
12
  #welcome-connect{padding:10px 20px;font:inherit}
13
- :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}#code{font-size:24px;letter-spacing:3px;color:#84c1ff}#terminal{flex:1;min-height:0;padding:12px 14px;display:none}.xterm{height:100%}footer{font-size:12px;color:#8f9eb7;padding:9px 18px;border-top:1px solid #293142}body.connected #welcome{display:none}body.connected #terminal{display:block}@media(max-width:650px){header{padding:10px;gap:8px}#status{min-width:100%}footer{padding:7px 10px}#terminal{padding:6px}}
13
+ #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}
14
+ :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%}footer{font-size:12px;color:#8f9eb7;padding:9px 18px;border-top:1px solid #293142}body.connected #welcome{display:none}body.connected #terminal{display:block}@media(max-width:650px){header{padding:10px;gap:8px}#status{min-width:100%}footer{padding:7px 10px}#terminal{padding:6px}}
14
15
  `;
15
16
 
16
17
  export const TERMINAL_SCRIPT = String.raw`(() => {
@@ -18,6 +19,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
18
19
  const status = document.getElementById('status');
19
20
  const connect = document.getElementById('connect');
20
21
  const welcomeConnect = document.getElementById('welcome-connect');
22
+ const password = document.getElementById('password');
21
23
  const close = document.getElementById('close');
22
24
  const interrupt = document.getElementById('interrupt');
23
25
  const storageKey = 'agentbot-terminal:' + location.pathname;
@@ -48,10 +50,11 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
48
50
  }
49
51
  function buttons(retry = false) {
50
52
  for (const button of [connect, welcomeConnect]) {
51
- button.textContent = session ? '重新连接' : recovery ? '请求恢复连接' : '请求连接';
53
+ button.textContent = session ? '重新连接' : recovery ? '恢复连接' : '连接';
52
54
  button.disabled = busy || (!!session && !retry);
53
55
  }
54
56
  close.disabled = busy || !session;
57
+ password.disabled = busy;
55
58
  }
56
59
  function invalidate() {
57
60
  epoch++; clearTimeout(retryTimer); clearTimeout(socketTimer);
@@ -62,7 +65,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
62
65
  }
63
66
  function forget() {
64
67
  session = undefined; sessionStorage.removeItem(storageKey);
65
- document.getElementById('code').textContent = ''; buttons(true);
68
+ buttons(true);
66
69
  }
67
70
  function end(text) { stopped = true; invalidate(); forget(); status.textContent = text; }
68
71
  function fail(text) { stopped = true; invalidate(); status.textContent = text; buttons(true); }
@@ -158,7 +161,6 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
158
161
  const result = await post('status', current, controller);
159
162
  if (generation !== epoch || current !== session || stopped || !awake()) return;
160
163
  if (result.state === 'approved' || result.state === 'running') openSocket();
161
- else if (result.state === 'pending') { failures = 0; status.textContent = '等待原会话中的所有者授权'; buttons(); schedule(1500); }
162
164
  else end(result.message || '授权已失效,请重新请求连接');
163
165
  } catch (error) {
164
166
  if (generation !== epoch || current !== session || stopped || !awake()) return;
@@ -171,19 +173,21 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
171
173
  if (busy) return;
172
174
  stopped = false; failures = 0; invalidate();
173
175
  if (session) { status.textContent = '正在恢复已有终端授权…'; buttons(); check(); return; }
174
- busy = true; buttons(); status.textContent = '正在请求飞书授权…';
176
+ document.body.classList.remove('connected');
177
+ if (!password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
178
+ busy = true; buttons(); status.textContent = '正在验证密码…';
175
179
  try {
176
- document.body.classList.remove('connected');
177
180
  if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器不支持安全随机数,请使用新版浏览器。');
178
181
  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
- session = {requestId:result.requestId,browserKey,code:result.code}; sessionStorage.setItem(storageKey,JSON.stringify(session));
181
- document.getElementById('code').textContent = '验证码:' + result.code;
182
- status.textContent = awake() ? '等待原会话中的所有者授权' : '返回网页后将自动查询授权状态';
183
- } catch (error) { status.textContent = '请求授权失败:' + message(error); }
182
+ const result = await post('request', {launch:location.pathname,browserKey,password:password.value});
183
+ password.value = '';
184
+ session = {requestId:result.requestId,browserKey}; sessionStorage.setItem(storageKey,JSON.stringify(session));
185
+ status.textContent = '密码已验证,正在连接终端…';
186
+ } catch (error) { status.textContent = '连接失败:' + message(error); password.focus(); }
184
187
  finally { busy = false; buttons(!session); }
185
188
  check();
186
189
  };
190
+ password.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); welcomeConnect.click(); } });
187
191
  interrupt.onclick = () => { if (ws?.readyState === WebSocket.OPEN && !interrupt.disabled) ws.send(JSON.stringify({type:'input',data:String.fromCharCode(3)})); };
188
192
  close.onclick = async () => {
189
193
  if (busy || !session || !confirm('关闭该终端和 Shell?已脱离终端的后台进程可能继续运行。')) return;
@@ -208,6 +212,5 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
208
212
  window.addEventListener('offline', () => { offline = true; suspend(); });
209
213
  window.addEventListener('online', () => { offline = false; resume(); });
210
214
  window.addEventListener('focus', resume);
211
- if (session?.code) document.getElementById('code').textContent = '验证码:' + session.code;
212
215
  buttons(); check();
213
216
  })();`;
@@ -1,4 +1,4 @@
1
- import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
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";
@@ -30,11 +31,11 @@ const frame = z.discriminatedUnion("type", [
30
31
  ]);
31
32
 
32
33
  export interface TerminalAuthorization {
33
- requestId: string; approvalToken: string; code: string; cwd: string; expiresAt: number;
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: "pending" | "approved" | "running" | "closed";
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: "pending" | "approved" | "running" | "closed";
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: "pending" | "approved" | "closed"; message?: string;
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
- if (authorization.state !== "pending") throw new Error("该终端授权已处理或过期,请查看原会话中的终端管理卡。");
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> {
@@ -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 && recovery.state !== "approved" ? recovery.state : session.state;
268
- return { requestId: auth.requestId, approvalToken: auth.approvalToken, code: auth.code, cwd: session.cwd,
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 === "pending" || authorization.state === "closed" || session.activeAccessId !== authorization.requestId) {
284
+ if (authorization.state === "closed" || session.activeAccessId !== authorization.requestId) {
307
285
  throw new Error("终端尚未授权、已结束或已由其他网页恢复。");
308
286
  }
309
287
  return session;
@@ -335,7 +313,20 @@ export class TerminalServer {
335
313
  }
336
314
  const data = await readJson(req);
337
315
  if (route === "/api/request") {
338
- const parsed = z.object({ launch: z.string().max(300), browserKey: KEY }).parse(data);
316
+ const result = z.object({ launch: z.string().max(300), browserKey: KEY, password: z.string().max(256).optional() }).safeParse(data);
317
+ if (!result.success) { this.json(res, 400, { error: "终端连接参数无效。" }); return; }
318
+ const parsed = result.data;
319
+ const now = this.now();
320
+ const address = req.socket.remoteAddress ?? "unknown";
321
+ while (this.passwordFailures[0] && this.passwordFailures[0].at <= now - 60_000) this.passwordFailures.shift();
322
+ if (this.passwordFailures.length >= 50 || this.passwordFailures.filter((failure) => failure.address === address).length >= 5) {
323
+ this.json(res, 429, { error: "密码尝试过于频繁,请一分钟后重试。" }); return;
324
+ }
325
+ const passwordHash = hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD);
326
+ if (parsed.password === undefined || !timingSafeEqual(hash(parsed.password), passwordHash)) {
327
+ this.passwordFailures.push({ address, at: now });
328
+ this.json(res, 401, { error: "终端密码错误,请重新输入。" }); return;
329
+ }
339
330
  const resumeId = this.resumeId(parsed.launch);
340
331
  const jobId = this.launchJob(parsed.launch);
341
332
  const ownerId = this.options.ownerId();
@@ -345,41 +336,51 @@ export class TerminalServer {
345
336
  throw new Error("原终端尚未授权、已结束或服务已重启;请从原命令卡片创建新终端。");
346
337
  }
347
338
  if (!existing || existing.state === "approved") this.assertCanStart();
348
- const now = this.now();
349
339
  while (this.requests[0] !== undefined && this.requests[0] < now - 3600_000) this.requests.shift();
350
340
  if (this.requests.length >= 20 || (this.requests.length > 0 && now - this.requests.at(-1)! < 10_000)
351
- || (existing ? [...this.recoveries.values()].filter((r) => r.state === "pending").length >= 3
352
- : [...this.sessions.values()].filter((s) => s.state !== "closed").length >= 3)) {
341
+ || (!existing && [...this.sessions.values()].filter((s) => s.state !== "closed").length >= 3)) {
353
342
  this.json(res, 429, { error: "终端请求过于频繁或已达 3 个会话上限,请稍后重试。" }); return;
354
343
  }
355
344
  this.requests.push(now);
356
345
  if (existing) {
357
346
  const recovery: TerminalRecovery = { requestId: randomBytes(16).toString("hex"), targetId: existing.requestId, ownerId,
358
- keyHash: hash(parsed.browserKey), approvalToken: randomBytes(32).toString("hex"), code: String(randomInt(100000, 1000000)),
359
- cwd: existing.cwd, expiresAt: now + AUTH_TTL, state: "pending" };
347
+ keyHash: hash(parsed.browserKey), approvalToken: randomBytes(32).toString("hex"),
348
+ cwd: existing.cwd, expiresAt: now + AUTH_TTL, state: "approved" };
360
349
  this.recoveries.set(recovery.requestId, recovery);
361
350
  try {
362
351
  recovery.cardId = await this.options.requestApproval(this.cardView(existing, recovery));
363
- if (!recovery.cardId) throw new Error("无法发送飞书授权卡片。");
364
- } catch (error) { this.closeRecovery(recovery, "恢复授权通知失败"); throw error; }
365
- if (existing.state !== "running" || recovery.state !== "pending") this.publishCards(existing);
366
- this.json(res, 200, { requestId: recovery.requestId, code: recovery.code }); return;
352
+ if (!recovery.cardId) throw new Error("无法发送终端管理卡片。");
353
+ if (!this.canReopen(existing) || existing.ownerId !== this.options.ownerId()
354
+ || !timingSafeEqual(passwordHash, hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD))) {
355
+ throw new Error("终端已结束或连接设置已变化,请重新连接。");
356
+ }
357
+ if (existing.state === "approved") { this.assertCanStart(); existing.expiresAt = this.now() + AUTH_TTL; }
358
+ } catch (error) { this.closeRecovery(recovery, "恢复连接未完成,原终端不受影响"); this.publishCards(existing); throw error; }
359
+ for (const other of this.recoveries.values()) {
360
+ if (other !== recovery && other.targetId === existing.requestId && other.state !== "closed") this.closeRecovery(other, "已由另一网页恢复连接");
361
+ }
362
+ existing.activeAccessId = recovery.requestId;
363
+ existing.socket?.close(1000, "Reconnected from another page"); existing.socket = undefined;
364
+ this.markDisconnected(existing);
365
+ this.publishCards(existing);
366
+ this.json(res, 200, { requestId: recovery.requestId }); return;
367
367
  }
368
368
  const job = await this.options.readJob(jobId!);
369
369
  this.assertCanStart();
370
370
  if (!job.cardMessageId || !job.contextKey?.trim()) throw new Error("命令卡片或原始会话信息尚未就绪。");
371
371
  const requestId = randomBytes(16).toString("hex");
372
372
  const session: TerminalSession = { requestId, reopenToken: this.links!.createRecovery(), activeAccessId: requestId, ownerId, cwd: job.cwd, keyHash: hash(parsed.browserKey),
373
+ passwordHash,
373
374
  contextKey: job.contextKey, commandCardMessageId: job.cardMessageId,
374
- approvalToken: randomBytes(32).toString("hex"), code: String(randomInt(100000, 1000000)),
375
- createdAt: now, lastActivity: now, expiresAt: now + AUTH_TTL, state: "pending", output: "" };
375
+ approvalToken: randomBytes(32).toString("hex"),
376
+ createdAt: now, lastActivity: now, expiresAt: now + AUTH_TTL, state: "approved", output: "" };
376
377
  this.sessions.set(requestId, session);
377
378
  try {
378
379
  session.cardId = await this.options.requestApproval(this.cardView(session));
379
- if (!session.cardId) throw new Error("无法发送飞书授权卡片。");
380
- if (session.state !== "pending") this.publishCards(session);
381
- } catch (error) { this.disposeSession(session, "授权通知失败"); throw error; }
382
- this.json(res, 200, { requestId, code: session.code }); return;
380
+ if (!session.cardId) throw new Error("无法发送终端管理卡片。");
381
+ this.publishCards(session);
382
+ } catch (error) { this.disposeSession(session, "终端管理卡发送失败"); throw error; }
383
+ this.json(res, 200, { requestId }); return;
383
384
  }
384
385
  if (route !== "/api/status" && route !== "/api/close") { this.json(res, 404, { error: "Not found." }); return; }
385
386
  const { authorization, session } = this.access(data);
@@ -490,14 +491,11 @@ export class TerminalServer {
490
491
  const now = this.now();
491
492
  for (const recovery of this.recoveries.values()) {
492
493
  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
494
  if (!target || (recovery.state === "closed" && now >= recovery.expiresAt + AUTH_TTL)) this.recoveries.delete(recovery.requestId);
498
495
  }
499
496
  for (const s of this.sessions.values()) {
500
- if (s.ownerId !== this.options.ownerId() || now - s.createdAt >= MAX_TTL
497
+ if (s.ownerId !== this.options.ownerId() || !timingSafeEqual(s.passwordHash, hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD))
498
+ || now - s.createdAt >= MAX_TTL
501
499
  || (s.state !== "running" && s.state !== "closed" && now >= s.expiresAt)) {
502
500
  this.disposeSession(s, "终端已超时或授权已失效,请重新连接");
503
501
  }