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

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 (118) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +63 -7
  3. package/README.zh.md +62 -6
  4. package/SECURITY.md +18 -4
  5. package/assets/workspace-sessions.js +648 -0
  6. package/assets/workspace.css +160 -0
  7. package/assets/workspace.js +1795 -0
  8. package/config.example.yaml +3 -2
  9. package/dist/codex/CodexEventMapper.js +35 -0
  10. package/dist/codex/CodexEventMapper.js.map +1 -1
  11. package/dist/codex/CodexRuntime.js +50 -4
  12. package/dist/codex/CodexRuntime.js.map +1 -1
  13. package/dist/codex/TraeTaskNotification.js +44 -0
  14. package/dist/codex/TraeTaskNotification.js.map +1 -0
  15. package/dist/config/SettingsStore.js +1 -1
  16. package/dist/config/SettingsStore.js.map +1 -1
  17. package/dist/config/loadConfig.js +3 -2
  18. package/dist/config/loadConfig.js.map +1 -1
  19. package/dist/config/paths.js +3 -0
  20. package/dist/config/paths.js.map +1 -1
  21. package/dist/feishu/CardRenderer.js +56 -12
  22. package/dist/feishu/CardRenderer.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +2 -2
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +103 -16
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/index.js +61 -17
  28. package/dist/index.js.map +1 -1
  29. package/dist/local-files/DiagramPreview.js +1 -1
  30. package/dist/local-files/GitDiffPreview.js +167 -0
  31. package/dist/local-files/GitDiffPreview.js.map +1 -0
  32. package/dist/local-files/LocalFileViewerServer.js +332 -30
  33. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  34. package/dist/local-files/MarkdownFileLinks.js +5 -4
  35. package/dist/local-files/MarkdownFileLinks.js.map +1 -1
  36. package/dist/local-files/TurnPreviewPage.js +138 -58
  37. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  38. package/dist/local-files/WebPageTitle.js +85 -0
  39. package/dist/local-files/WebPageTitle.js.map +1 -0
  40. package/dist/local-files/WorkspaceFiles.js +553 -0
  41. package/dist/local-files/WorkspaceFiles.js.map +1 -0
  42. package/dist/local-files/WorkspaceOrigin.js +38 -0
  43. package/dist/local-files/WorkspaceOrigin.js.map +1 -0
  44. package/dist/local-files/WorkspacePage.js +19 -0
  45. package/dist/local-files/WorkspacePage.js.map +1 -0
  46. package/dist/local-files/WorkspaceSessions.js +689 -0
  47. package/dist/local-files/WorkspaceSessions.js.map +1 -0
  48. package/dist/presentation/TurnStateReducer.js +74 -13
  49. package/dist/presentation/TurnStateReducer.js.map +1 -1
  50. package/dist/presentation/turnActivity.js +41 -0
  51. package/dist/presentation/turnActivity.js.map +1 -0
  52. package/dist/presentation/turnStatus.js +11 -0
  53. package/dist/presentation/turnStatus.js.map +1 -1
  54. package/dist/presentation/visibleTurnActivities.js +4 -2
  55. package/dist/presentation/visibleTurnActivities.js.map +1 -1
  56. package/dist/proxy/ProxySessionController.js +150 -14
  57. package/dist/proxy/ProxySessionController.js.map +1 -1
  58. package/dist/runtime/types.js +1 -1
  59. package/dist/runtime/types.js.map +1 -1
  60. package/dist/state/InboundMessageStore.js +54 -0
  61. package/dist/state/InboundMessageStore.js.map +1 -0
  62. package/dist/state/StateStore.js +71 -1
  63. package/dist/state/StateStore.js.map +1 -1
  64. package/dist/state/TurnPreviewJournal.js +4 -2
  65. package/dist/state/TurnPreviewJournal.js.map +1 -1
  66. package/dist/state/migrations.js +20 -0
  67. package/dist/state/migrations.js.map +1 -1
  68. package/dist/supervision/SafeRestartNotifier.js +1 -0
  69. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  70. package/dist/supervision/SafeRestartScheduler.js +33 -16
  71. package/dist/supervision/SafeRestartScheduler.js.map +1 -1
  72. package/dist/terminal/TerminalLinks.js +32 -0
  73. package/dist/terminal/TerminalLinks.js.map +1 -1
  74. package/dist/terminal/TerminalPage.js +75 -26
  75. package/dist/terminal/TerminalPage.js.map +1 -1
  76. package/dist/terminal/TerminalServer.js +125 -56
  77. package/dist/terminal/TerminalServer.js.map +1 -1
  78. package/docs/technical-reference.md +14 -4
  79. package/docs/technical-reference.zh.md +15 -5
  80. package/npm-shrinkwrap.json +2 -2
  81. package/package.json +1 -1
  82. package/skills/agent-bot/SKILL.md +6 -2
  83. package/src/codex/CodexEventMapper.ts +39 -1
  84. package/src/codex/CodexRuntime.ts +54 -4
  85. package/src/codex/TraeTaskNotification.ts +49 -0
  86. package/src/config/SettingsStore.ts +1 -1
  87. package/src/config/loadConfig.ts +3 -2
  88. package/src/config/paths.ts +4 -0
  89. package/src/feishu/CardRenderer.ts +47 -13
  90. package/src/feishu/FeishuMessageClient.ts +2 -2
  91. package/src/feishu/FeishuTurnPresenter.ts +110 -20
  92. package/src/index.ts +62 -17
  93. package/src/local-files/DiagramPreview.ts +1 -1
  94. package/src/local-files/GitDiffPreview.ts +144 -0
  95. package/src/local-files/LocalFileViewerServer.ts +294 -31
  96. package/src/local-files/MarkdownFileLinks.ts +5 -3
  97. package/src/local-files/TurnPreviewPage.ts +159 -69
  98. package/src/local-files/WebPageTitle.ts +59 -0
  99. package/src/local-files/WorkspaceFiles.ts +468 -0
  100. package/src/local-files/WorkspaceOrigin.ts +31 -0
  101. package/src/local-files/WorkspacePage.ts +21 -0
  102. package/src/local-files/WorkspaceSessions.ts +587 -0
  103. package/src/presentation/TurnStateReducer.ts +76 -14
  104. package/src/presentation/turnActivity.ts +43 -0
  105. package/src/presentation/turnStatus.ts +14 -0
  106. package/src/presentation/turnViewTypes.ts +10 -1
  107. package/src/presentation/visibleTurnActivities.ts +4 -2
  108. package/src/proxy/ProxySessionController.ts +149 -13
  109. package/src/runtime/types.ts +17 -0
  110. package/src/state/InboundMessageStore.ts +72 -0
  111. package/src/state/StateStore.ts +80 -1
  112. package/src/state/TurnPreviewJournal.ts +4 -2
  113. package/src/state/migrations.ts +20 -0
  114. package/src/supervision/SafeRestartNotifier.ts +1 -0
  115. package/src/supervision/SafeRestartScheduler.ts +42 -18
  116. package/src/terminal/TerminalLinks.ts +26 -0
  117. package/src/terminal/TerminalPage.ts +76 -26
  118. package/src/terminal/TerminalServer.ts +119 -48
@@ -3,6 +3,8 @@ import fs from "node:fs";
3
3
  import type { IncomingMessage, ServerResponse } from "node:http";
4
4
  import type { Duplex } from "node:stream";
5
5
  import type { LocalFileViewerServer } from "../local-files/LocalFileViewerServer.js";
6
+ import { directWorkspaceOrigin } from "../local-files/WorkspaceOrigin.js";
7
+ import { resolveWorkspacePath, WorkspaceError } from "../local-files/WorkspaceFiles.js";
6
8
  import { createRequire } from "node:module";
7
9
  import path from "node:path";
8
10
  import type { Logger } from "pino";
@@ -18,7 +20,7 @@ import type { TerminalCommandState } from "./TerminalCommandTracker.js";
18
20
  const require = createRequire(import.meta.url);
19
21
  const AUTH_TTL = 5 * 60_000;
20
22
  const IDLE_TTL = 30 * 60_000;
21
- const DISCONNECT_TTL = 3 * 60_000;
23
+ const DISCONNECT_TTL = 30 * 60_000;
22
24
  const FOREGROUND_TTL = 90_000;
23
25
  const MAX_TTL = 8 * 60 * 60_000;
24
26
  const KEY = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -43,8 +45,14 @@ export interface ActiveTerminal {
43
45
  state: "starting" | "running" | "closing"; connected: boolean;
44
46
  active: boolean; foreground: boolean; command: TerminalCommandState;
45
47
  }
48
+ export interface TerminalWorkspaceAccess {
49
+ readonly owner: string;
50
+ readonly expires: number;
51
+ readonly signal: AbortSignal;
52
+ }
46
53
  export interface TerminalServerOptions {
47
54
  stateDirectory: string;
55
+ workspaceAccess?(request: IncomingMessage, origin: string): TerminalWorkspaceAccess | undefined;
48
56
  ownerId(): string | undefined;
49
57
  password?(): string;
50
58
  canStart?(): boolean;
@@ -56,6 +64,8 @@ export interface TerminalServerOptions {
56
64
  now?: () => number;
57
65
  }
58
66
  interface TerminalSession extends TerminalAuthorization {
67
+ workspace?: TerminalWorkspaceAccess;
68
+ onWorkspaceRevoked?: () => void;
59
69
  reopenToken: string;
60
70
  contextKey: string; commandCardMessageId: string;
61
71
  ownerId: string; keyHash: Buffer; passwordHash: Buffer; createdAt: number; lastActivity: number;
@@ -105,7 +115,7 @@ export class TerminalServer {
105
115
  void this.handleRequest(req, res).catch((error: unknown) => {
106
116
  this.options.logger.warn({ error: error instanceof Error ? error.message : String(error) }, "Terminal HTTP request failed.");
107
117
  if (res.headersSent) res.destroy();
108
- else this.json(res, 400, { error: error instanceof Error ? error.message : "Terminal request failed." });
118
+ else this.json(res, error instanceof WorkspaceError ? error.status : 400, { error: error instanceof Error ? error.message : "Terminal request failed." });
109
119
  });
110
120
  },
111
121
  handleUpgrade: (req, socket, head) => this.handleUpgrade(req, socket, head),
@@ -118,7 +128,8 @@ export class TerminalServer {
118
128
  }
119
129
 
120
130
  private handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {
121
- if (this.closed || !this.validOrigin(req) || req.url !== `${this.basePath}/socket` || this.sockets.clients.size >= 20) {
131
+ const origin = this.requestOrigin(req);
132
+ if (this.closed || !origin || req.headers.origin !== origin || req.url !== `${this.basePath}/socket` || this.sockets.clients.size >= 20) {
122
133
  if (this.now() - this.lastUpgradeWarning >= 10_000) {
123
134
  this.lastUpgradeWarning = this.now();
124
135
  this.options.logger.warn({ stage: "upgrade", hostMatches: req.headers.host === this.base?.host,
@@ -126,7 +137,7 @@ export class TerminalServer {
126
137
  }
127
138
  socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); return;
128
139
  }
129
- this.sockets.handleUpgrade(req, socket, head, (ws) => this.connect(ws));
140
+ this.sockets.handleUpgrade(req, socket, head, (ws) => this.connect(ws, req, origin));
130
141
  }
131
142
 
132
143
  createUrl(jobId: string): string | undefined {
@@ -138,6 +149,21 @@ export class TerminalServer {
138
149
  }
139
150
  }
140
151
 
152
+ createWorkspaceUrl(cwd: string, instance: string, request: IncomingMessage): string {
153
+ if (this.closed || !this.base || !this.links) throw new WorkspaceError("网页终端服务未启用。", 503);
154
+ const origin = this.requestOrigin(request);
155
+ if (!origin) throw new WorkspaceError("终端请求来源不受信任。", 403);
156
+ const access = this.workspaceAccess(request, origin);
157
+ if (!access) throw new WorkspaceError("请先登录工作台,再打开终端。", 401);
158
+ this.validateWorkspaceDirectory(cwd);
159
+ return origin + this.basePath + "/" + this.links.createWorkspace(cwd, access.owner, instance);
160
+ }
161
+
162
+ private validateWorkspaceDirectory(cwd: string): void {
163
+ resolveWorkspacePath(cwd);
164
+ if (!fs.statSync(cwd).isDirectory()) throw new Error("终端项目目录不存在。");
165
+ }
166
+
141
167
  get activeCount(): number {
142
168
  return [...this.sessions.values()].filter((s) => s.pty || s.starting).length;
143
169
  }
@@ -221,7 +247,7 @@ export class TerminalServer {
221
247
  const expire = () => {
222
248
  if (session.state !== "running" || session.socket || session.disconnectedAt === undefined) return;
223
249
  const remaining = DISCONNECT_TTL - (this.now() - session.disconnectedAt);
224
- if (remaining <= 0) this.disposeSession(session, "网页已断开 3 分钟,Shell 已自动关闭");
250
+ if (remaining <= 0) this.disposeSession(session, "网页已断开 30 分钟,Shell 已自动关闭");
225
251
  else { session.disconnectTimer = setTimeout(expire, remaining); session.disconnectTimer.unref(); }
226
252
  };
227
253
  session.disconnectTimer = setTimeout(expire, DISCONNECT_TTL); session.disconnectTimer.unref();
@@ -238,7 +264,7 @@ export class TerminalServer {
238
264
  private resumeId(launch: string): string | undefined {
239
265
  if (!launch.startsWith(`${this.basePath}/`)) return undefined;
240
266
  const token = /^[/]([A-Za-z0-9_-]{8})$/u.exec(launch.slice(this.basePath.length));
241
- return token ? [...this.sessions.values()].find((session) => session.reopenToken === token[1])?.requestId : undefined;
267
+ return token ? [...this.sessions.values()].find((session) => !session.workspace && session.reopenToken === token[1])?.requestId : undefined;
242
268
  }
243
269
  private cardView(session: TerminalSession, recovery?: TerminalRecovery): TerminalCardView {
244
270
  const auth = recovery ?? session;
@@ -261,15 +287,26 @@ export class TerminalServer {
261
287
  private closeRecovery(recovery: TerminalRecovery, message: string): void {
262
288
  recovery.state = "closed"; recovery.message = message;
263
289
  }
264
- private validOrigin(req: IncomingMessage): boolean {
265
- return Boolean(this.base && req.headers.host === this.base.host && req.headers.origin === this.base.origin);
290
+ private requestOrigin(req: IncomingMessage): string | undefined {
291
+ if (!this.base) return;
292
+ return req.headers.host === this.base.host ? this.base.origin : directWorkspaceOrigin(req);
293
+ }
294
+ private workspaceAccess(req: IncomingMessage, origin: string): TerminalWorkspaceAccess | undefined {
295
+ const access = this.options.workspaceAccess?.(req, origin);
296
+ if (!access || access.signal.aborted || access.expires <= this.now() || access.owner !== this.options.ownerId()) return;
297
+ return access;
266
298
  }
267
299
  private launchJob(launch: string): string | undefined {
268
300
  if (!launch.startsWith(`${this.basePath}/`)) return undefined;
269
301
  const token = /^[/]([A-Za-z0-9_-]{8})$/u.exec(launch.slice(this.basePath.length));
270
302
  return token ? this.links?.resolve(token[1]!) : undefined;
271
303
  }
272
- private access(value: unknown): { authorization: TerminalSession | TerminalRecovery; session: TerminalSession } {
304
+ private launchWorkspace(launch: string) {
305
+ if (!launch.startsWith(this.basePath + "/")) return undefined;
306
+ const token = /^[/]([A-Za-z0-9_-]{8})$/u.exec(launch.slice(this.basePath.length));
307
+ return token ? this.links?.resolveWorkspace(token[1]!) : undefined;
308
+ }
309
+ private access(value: unknown, request: IncomingMessage, origin: string): { authorization: TerminalSession | TerminalRecovery; session: TerminalSession } {
273
310
  const parsed = credentials.parse(value);
274
311
  this.sweep();
275
312
  const recovery = this.recoveries.get(parsed.requestId);
@@ -277,10 +314,13 @@ export class TerminalServer {
277
314
  const session = this.sessions.get(recovery?.targetId ?? parsed.requestId);
278
315
  if (!authorization || !session || !timingSafeEqual(authorization.keyHash, hash(parsed.browserKey))
279
316
  || (!recovery && session.activeAccessId !== parsed.requestId)) throw new Error("终端凭证无效或已由其他网页恢复,请从原会话的终端管理卡重新打开。");
317
+ if (session.workspace && this.workspaceAccess(request, origin)?.signal !== session.workspace.signal) {
318
+ throw new WorkspaceError("工作台会话已失效,请重新登录工作台。", 401);
319
+ }
280
320
  return { authorization, session };
281
321
  }
282
- private authenticated(value: unknown): TerminalSession {
283
- const { authorization, session } = this.access(value);
322
+ private authenticated(value: unknown, request: IncomingMessage, origin: string): TerminalSession {
323
+ const { authorization, session } = this.access(value, request, origin);
284
324
  if (authorization.state === "closed" || session.activeAccessId !== authorization.requestId) {
285
325
  throw new Error("终端尚未授权、已结束或已由其他网页恢复。");
286
326
  }
@@ -288,8 +328,9 @@ export class TerminalServer {
288
328
  }
289
329
 
290
330
  private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
291
- if (!this.base || req.headers.host !== this.base.host) { this.json(res, 403, { error: "Invalid Host." }); return; }
292
- const url = new URL(req.url ?? "/", this.base);
331
+ const origin = this.requestOrigin(req);
332
+ if (!origin) { this.json(res, 403, { error: "Invalid Host." }); return; }
333
+ const url = new URL(req.url ?? "/", origin);
293
334
  if (url.search || !url.pathname.startsWith(`${this.basePath}/`)) { this.json(res, 404, { error: "Not found." }); return; }
294
335
  const route = url.pathname.slice(this.basePath.length);
295
336
  this.sweep();
@@ -303,12 +344,21 @@ export class TerminalServer {
303
344
  body = fs.readFileSync(path.join(path.dirname(require.resolve("@xterm/xterm")), "../css/xterm.css"), "utf8"); type = "text/css";
304
345
  } else {
305
346
  const resumeId = this.resumeId(url.pathname);
306
- if (this.launchJob(url.pathname) || resumeId) { body = terminalPage(this.basePath, Boolean(resumeId)); type = "text/html; charset=utf-8"; }
347
+ const workspace = this.launchWorkspace(url.pathname);
348
+ if (workspace && this.workspaceAccess(req, origin)?.owner !== workspace.ownerId) {
349
+ this.json(res, 401, { error: "请先登录工作台,再打开终端。" }); return;
350
+ }
351
+ if (this.launchJob(url.pathname) || resumeId || workspace) {
352
+ const session = resumeId ? this.sessions.get(resumeId) : undefined;
353
+ body = terminalPage(this.basePath, Boolean(resumeId), session?.state === "running" && Boolean(session.pty),
354
+ (this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD) === DEFAULT_TERMINAL_PASSWORD, Boolean(workspace));
355
+ type = "text/html; charset=utf-8";
356
+ }
307
357
  }
308
- this.headers(res); res.statusCode = body === undefined ? 404 : 200; res.setHeader("Content-Type", type);
358
+ this.headers(res, origin); res.statusCode = body === undefined ? 404 : 200; res.setHeader("Content-Type", type);
309
359
  res.end(req.method === "HEAD" ? undefined : body ?? "Not found."); return;
310
360
  }
311
- if (req.method !== "POST" || !this.validOrigin(req) || req.headers["content-type"] !== "application/json") {
361
+ if (req.method !== "POST" || req.headers.origin !== origin || req.headers["content-type"] !== "application/json") {
312
362
  this.json(res, 403, { error: "Origin or request method rejected." }); return;
313
363
  }
314
364
  const data = await readJson(req);
@@ -317,27 +367,35 @@ export class TerminalServer {
317
367
  if (!result.success) { this.json(res, 400, { error: "终端连接参数无效。" }); return; }
318
368
  const parsed = result.data;
319
369
  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
- }
330
370
  const resumeId = this.resumeId(parsed.launch);
331
371
  const jobId = this.launchJob(parsed.launch);
372
+ const workspace = this.launchWorkspace(parsed.launch);
373
+ const workspaceAccess = workspace ? this.workspaceAccess(req, origin) : undefined;
332
374
  const ownerId = this.options.ownerId();
333
- if ((!jobId && !resumeId) || !ownerId) throw new Error("终端链接无效,或尚未配置飞书所有者。");
375
+ if (workspace && workspaceAccess?.owner !== workspace.ownerId) throw new WorkspaceError("请先登录工作台,再打开终端。", 401);
334
376
  const existing = resumeId ? this.sessions.get(resumeId) : undefined;
335
377
  if (resumeId && (!existing || !this.canReopen(existing) || existing.ownerId !== ownerId)) {
336
378
  throw new Error("原终端尚未授权、已结束或服务已重启;请从原命令卡片创建新终端。");
337
379
  }
380
+ // A live Shell's recovery link grants reattachment, never a new Shell.
381
+ const resumeRunning = existing?.state === "running" && Boolean(existing.pty) && existing.ownerId === ownerId;
382
+ const passwordHash = hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD);
383
+ if (!workspace && !resumeRunning) {
384
+ const address = req.socket.remoteAddress ?? "unknown";
385
+ while (this.passwordFailures[0] && this.passwordFailures[0].at <= now - 60_000) this.passwordFailures.shift();
386
+ if (this.passwordFailures.length >= 50 || this.passwordFailures.filter((failure) => failure.address === address).length >= 5) {
387
+ this.json(res, 429, { error: "密码尝试过于频繁,请一分钟后重试。" }); return;
388
+ }
389
+ if (parsed.password === undefined || !timingSafeEqual(hash(parsed.password), passwordHash)) {
390
+ this.passwordFailures.push({ address, at: now });
391
+ this.json(res, 401, { error: "终端密码错误,请重新输入。" }); return;
392
+ }
393
+ }
394
+ if ((!jobId && !resumeId && !workspace) || !ownerId) throw new Error("终端链接无效,或尚未配置飞书所有者。");
395
+ if (workspace) this.validateWorkspaceDirectory(workspace.cwd);
338
396
  if (!existing || existing.state === "approved") this.assertCanStart();
339
397
  while (this.requests[0] !== undefined && this.requests[0] < now - 3600_000) this.requests.shift();
340
- if (this.requests.length >= 20 || (this.requests.length > 0 && now - this.requests.at(-1)! < 10_000)
398
+ if (this.requests.length >= 20 || (!resumeRunning && this.requests.length > 0 && now - this.requests.at(-1)! < 10_000)
341
399
  || (!existing && [...this.sessions.values()].filter((s) => s.state !== "closed").length >= 3)) {
342
400
  this.json(res, 429, { error: "终端请求过于频繁或已达 3 个会话上限,请稍后重试。" }); return;
343
401
  }
@@ -365,25 +423,30 @@ export class TerminalServer {
365
423
  this.publishCards(existing);
366
424
  this.json(res, 200, { requestId: recovery.requestId }); return;
367
425
  }
368
- const job = await this.options.readJob(jobId!);
426
+ const job = workspace ? { cwd: workspace.cwd, contextKey: "open_id:" + ownerId, cardMessageId: "" } : await this.options.readJob(jobId!);
369
427
  this.assertCanStart();
370
- if (!job.cardMessageId || !job.contextKey?.trim()) throw new Error("命令卡片或原始会话信息尚未就绪。");
428
+ if ((!workspace && !job.cardMessageId) || !job.contextKey?.trim()) throw new Error("命令卡片或原始会话信息尚未就绪。");
371
429
  const requestId = randomBytes(16).toString("hex");
372
- const session: TerminalSession = { requestId, reopenToken: this.links!.createRecovery(), activeAccessId: requestId, ownerId, cwd: job.cwd, keyHash: hash(parsed.browserKey),
430
+ const session: TerminalSession = { requestId, reopenToken: workspace?.token ?? this.links!.createRecovery(), activeAccessId: requestId, ownerId, cwd: job.cwd, workspace: workspaceAccess, keyHash: hash(parsed.browserKey),
373
431
  passwordHash,
374
- contextKey: job.contextKey, commandCardMessageId: job.cardMessageId,
432
+ contextKey: job.contextKey, commandCardMessageId: job.cardMessageId ?? "",
375
433
  approvalToken: randomBytes(32).toString("hex"),
376
434
  createdAt: now, lastActivity: now, expiresAt: now + AUTH_TTL, state: "approved", output: "" };
377
435
  this.sessions.set(requestId, session);
378
- try {
379
- session.cardId = await this.options.requestApproval(this.cardView(session));
380
- if (!session.cardId) throw new Error("无法发送终端管理卡片。");
381
- this.publishCards(session);
382
- } catch (error) { this.disposeSession(session, "终端管理卡发送失败"); throw error; }
436
+ if (workspaceAccess) {
437
+ session.onWorkspaceRevoked = () => this.disposeSession(session, "工作台会话已失效,终端已关闭。");
438
+ workspaceAccess.signal.addEventListener("abort", session.onWorkspaceRevoked, { once: true });
439
+ } else {
440
+ try {
441
+ session.cardId = await this.options.requestApproval(this.cardView(session));
442
+ if (!session.cardId) throw new Error("无法发送终端管理卡片。");
443
+ this.publishCards(session);
444
+ } catch (error) { this.disposeSession(session, "终端管理卡发送失败"); throw error; }
445
+ }
383
446
  this.json(res, 200, { requestId }); return;
384
447
  }
385
448
  if (route !== "/api/status" && route !== "/api/close") { this.json(res, 404, { error: "Not found." }); return; }
386
- const { authorization, session } = this.access(data);
449
+ const { authorization, session } = this.access(data, req, origin);
387
450
  if ("targetId" in authorization && authorization.state !== "approved") {
388
451
  if (route === "/api/close") { this.closeRecovery(authorization, "恢复连接请求已取消"); this.publishCards(session); }
389
452
  this.json(res, 200, { state: authorization.state, message: authorization.message }); return;
@@ -396,7 +459,7 @@ export class TerminalServer {
396
459
  this.json(res, 200, { state: session.state, message: session.message });
397
460
  }
398
461
 
399
- private connect(ws: WebSocket): void {
462
+ private connect(ws: WebSocket, request: IncomingMessage, origin: string): void {
400
463
  let session: TerminalSession | undefined; let authenticating = false; let accessId: string | undefined;
401
464
  const timeout = setTimeout(() => {
402
465
  this.options.logger.warn({ stage: "auth_timeout" }, "Terminal WebSocket authentication timed out.");
@@ -419,7 +482,7 @@ export class TerminalServer {
419
482
  if (!session) {
420
483
  stage = "auth";
421
484
  if (authenticating || value.type !== "auth") throw new Error("Authentication required.");
422
- authenticating = true; const target = this.authenticated(value);
485
+ authenticating = true; const target = this.authenticated(value, request, origin);
423
486
  if (target.state !== "approved" && target.state !== "running") throw new Error("终端尚未授权或已结束。");
424
487
  requestId = target.requestId;
425
488
  clearTimeout(timeout);
@@ -428,6 +491,7 @@ export class TerminalServer {
428
491
  await this.ensureProcess(target);
429
492
  if (ws.readyState !== WebSocket.OPEN) return;
430
493
  if (target.activeAccessId !== value.requestId) throw new Error("终端已由其他网页恢复。");
494
+ if (target.workspace && this.workspaceAccess(request, origin)?.signal !== target.workspace.signal) this.disposeSession(target, "工作台会话已失效,终端已关闭。");
431
495
  if (target.state !== "running") throw new Error(target.message ?? "终端已结束。");
432
496
  target.socket?.close(1000, "Reconnected from another page");
433
497
  session = target; session.socket = ws; accessId = value.requestId; clearTimeout(timeout);
@@ -440,6 +504,7 @@ export class TerminalServer {
440
504
  this.publishCards(session);
441
505
  return;
442
506
  }
507
+ if (session.workspace && this.workspaceAccess(request, origin)?.signal !== session.workspace.signal) this.disposeSession(session, "工作台会话已失效,终端已关闭。");
443
508
  if (session.state !== "running" || session.socket !== ws || session.activeAccessId !== accessId) throw new Error("Terminal is closed.");
444
509
  if (value.type === "input") { session.lastActivity = this.now(); session.pty?.write(value.data); }
445
510
  else if (value.type === "resize") session.pty?.resize(value.cols, value.rows);
@@ -461,12 +526,14 @@ export class TerminalServer {
461
526
  if (session.pty) return;
462
527
  if (session.starting) return session.starting;
463
528
  this.assertCanStart();
529
+ if (session.workspace) this.validateWorkspaceDirectory(session.cwd);
464
530
  const starting = (async () => {
465
531
  const pty = await (this.options.spawn ?? spawnTerminal)(session.cwd, 100, 30);
466
532
  session.pty = pty;
467
533
  pty.onExit(({ exitCode }) => { session.pty = undefined; this.disposeSession(session, `Shell 已退出(${exitCode})`); });
468
534
  if (this.closed || this.options.canStart?.() === false || session.state === "closed"
469
- || session.ownerId !== this.options.ownerId() || this.now() >= session.expiresAt) {
535
+ || session.ownerId !== this.options.ownerId() || this.now() >= session.expiresAt
536
+ || session.workspace?.signal.aborted || this.now() >= (session.workspace?.expires ?? Infinity)) {
470
537
  this.disposeSession(session, "服务正在重启或授权已失效", true); pty.kill(); return;
471
538
  }
472
539
  session.state = "running"; session.lastActivity = this.now();
@@ -495,12 +562,12 @@ export class TerminalServer {
495
562
  }
496
563
  for (const s of this.sessions.values()) {
497
564
  if (s.ownerId !== this.options.ownerId() || !timingSafeEqual(s.passwordHash, hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD))
498
- || now - s.createdAt >= MAX_TTL
565
+ || now - s.createdAt >= MAX_TTL || s.workspace?.signal.aborted || now >= (s.workspace?.expires ?? Infinity)
499
566
  || (s.state !== "running" && s.state !== "closed" && now >= s.expiresAt)) {
500
567
  this.disposeSession(s, "终端已超时或授权已失效,请重新连接");
501
568
  }
502
569
  if (s.state === "running" && s.disconnectedAt !== undefined && now - s.disconnectedAt >= DISCONNECT_TTL) {
503
- this.disposeSession(s, "网页已断开 3 分钟,Shell 已自动关闭");
570
+ this.disposeSession(s, "网页已断开 30 分钟,Shell 已自动关闭");
504
571
  }
505
572
  if (s.state === "running" && now - Math.max(s.lastActivity, s.foregroundUntil ?? 0) >= IDLE_TTL) {
506
573
  this.disposeSession(s, "连续 30 分钟无输入或输出,Shell 已自动关闭");
@@ -511,9 +578,13 @@ export class TerminalServer {
511
578
  private disposeSession(s: TerminalSession, message: string, waitForExit = false): void {
512
579
  if (s.state === "closed") return;
513
580
  this.clearDisconnectTimer(s);
581
+ if (s.onWorkspaceRevoked) s.workspace?.signal.removeEventListener("abort", s.onWorkspaceRevoked);
514
582
  s.state = "closed"; s.message = message; s.lastActivity = this.now();
515
583
  const pty = s.pty; if (!waitForExit) s.pty = undefined;
516
- if (s.socket) { this.send(s.socket, { type: "exit", message }); s.socket.close(); s.socket = undefined; }
584
+ if (s.socket) {
585
+ this.send(s.socket, { type: "exit", message, clear: s.workspace?.signal.aborted || undefined });
586
+ s.socket.close(); s.socket = undefined;
587
+ }
517
588
  try { if (!waitForExit) pty?.kill(); } catch (error) { this.options.logger.warn({ error, requestId: s.requestId }, "Failed to close terminal process."); }
518
589
  s.output = "";
519
590
  for (const recovery of this.recoveries.values()) {
@@ -526,11 +597,11 @@ export class TerminalServer {
526
597
  if (ws.bufferedAmount > 1024 * 1024) { ws.close(1013, "Slow consumer"); return; }
527
598
  ws.send(JSON.stringify(value));
528
599
  }
529
- private headers(res: ServerResponse): void {
600
+ private headers(res: ServerResponse, origin = this.base?.origin): void {
530
601
  res.setHeader("Cache-Control", "no-store"); res.setHeader("Referrer-Policy", "no-referrer");
531
- res.setHeader("X-Content-Type-Options", "nosniff"); res.setHeader("X-Frame-Options", "DENY");
532
- const socketOrigin = this.base?.origin.replace(/^http/u, "ws") ?? "";
533
- res.setHeader("Content-Security-Policy", `default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ${socketOrigin}; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'`);
602
+ res.setHeader("X-Content-Type-Options", "nosniff"); res.setHeader("X-Frame-Options", "SAMEORIGIN");
603
+ const socketOrigin = origin?.replace(/^http/u, "ws") ?? "";
604
+ res.setHeader("Content-Security-Policy", `default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ${socketOrigin}; font-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'`);
534
605
  }
535
606
  private json(res: ServerResponse, status: number, value: unknown): void {
536
607
  this.headers(res); res.statusCode = status; res.setHeader("Content-Type", "application/json; charset=utf-8"); res.end(JSON.stringify(value));