@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.3
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 +28 -0
- package/README.md +55 -5
- package/README.zh.md +55 -5
- package/SECURITY.md +14 -0
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +54 -10
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +11 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +359 -37
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +32 -10
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +44 -24
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +103 -39
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +1 -1
- package/docs/technical-reference.zh.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +3 -1
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +45 -11
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +10 -7
- package/src/local-files/LocalFileViewerServer.ts +330 -37
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +35 -9
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +44 -24
- package/src/terminal/TerminalServer.ts +98 -36
|
@@ -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";
|
|
@@ -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
|
-
|
|
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
|
}
|
|
@@ -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
|
|
265
|
-
|
|
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
|
|
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
|
-
|
|
292
|
-
|
|
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,17 +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
|
-
|
|
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) {
|
|
307
352
|
const session = resumeId ? this.sessions.get(resumeId) : undefined;
|
|
308
353
|
body = terminalPage(this.basePath, Boolean(resumeId), session?.state === "running" && Boolean(session.pty),
|
|
309
|
-
(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD) === DEFAULT_TERMINAL_PASSWORD);
|
|
354
|
+
(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD) === DEFAULT_TERMINAL_PASSWORD, Boolean(workspace));
|
|
310
355
|
type = "text/html; charset=utf-8";
|
|
311
356
|
}
|
|
312
357
|
}
|
|
313
|
-
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);
|
|
314
359
|
res.end(req.method === "HEAD" ? undefined : body ?? "Not found."); return;
|
|
315
360
|
}
|
|
316
|
-
if (req.method !== "POST" ||
|
|
361
|
+
if (req.method !== "POST" || req.headers.origin !== origin || req.headers["content-type"] !== "application/json") {
|
|
317
362
|
this.json(res, 403, { error: "Origin or request method rejected." }); return;
|
|
318
363
|
}
|
|
319
364
|
const data = await readJson(req);
|
|
@@ -324,7 +369,10 @@ export class TerminalServer {
|
|
|
324
369
|
const now = this.now();
|
|
325
370
|
const resumeId = this.resumeId(parsed.launch);
|
|
326
371
|
const jobId = this.launchJob(parsed.launch);
|
|
372
|
+
const workspace = this.launchWorkspace(parsed.launch);
|
|
373
|
+
const workspaceAccess = workspace ? this.workspaceAccess(req, origin) : undefined;
|
|
327
374
|
const ownerId = this.options.ownerId();
|
|
375
|
+
if (workspace && workspaceAccess?.owner !== workspace.ownerId) throw new WorkspaceError("请先登录工作台,再打开终端。", 401);
|
|
328
376
|
const existing = resumeId ? this.sessions.get(resumeId) : undefined;
|
|
329
377
|
if (resumeId && (!existing || !this.canReopen(existing) || existing.ownerId !== ownerId)) {
|
|
330
378
|
throw new Error("原终端尚未授权、已结束或服务已重启;请从原命令卡片创建新终端。");
|
|
@@ -332,7 +380,7 @@ export class TerminalServer {
|
|
|
332
380
|
// A live Shell's recovery link grants reattachment, never a new Shell.
|
|
333
381
|
const resumeRunning = existing?.state === "running" && Boolean(existing.pty) && existing.ownerId === ownerId;
|
|
334
382
|
const passwordHash = hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD);
|
|
335
|
-
if (!resumeRunning) {
|
|
383
|
+
if (!workspace && !resumeRunning) {
|
|
336
384
|
const address = req.socket.remoteAddress ?? "unknown";
|
|
337
385
|
while (this.passwordFailures[0] && this.passwordFailures[0].at <= now - 60_000) this.passwordFailures.shift();
|
|
338
386
|
if (this.passwordFailures.length >= 50 || this.passwordFailures.filter((failure) => failure.address === address).length >= 5) {
|
|
@@ -343,7 +391,8 @@ export class TerminalServer {
|
|
|
343
391
|
this.json(res, 401, { error: "终端密码错误,请重新输入。" }); return;
|
|
344
392
|
}
|
|
345
393
|
}
|
|
346
|
-
if ((!jobId && !resumeId) || !ownerId) throw new Error("终端链接无效,或尚未配置飞书所有者。");
|
|
394
|
+
if ((!jobId && !resumeId && !workspace) || !ownerId) throw new Error("终端链接无效,或尚未配置飞书所有者。");
|
|
395
|
+
if (workspace) this.validateWorkspaceDirectory(workspace.cwd);
|
|
347
396
|
if (!existing || existing.state === "approved") this.assertCanStart();
|
|
348
397
|
while (this.requests[0] !== undefined && this.requests[0] < now - 3600_000) this.requests.shift();
|
|
349
398
|
if (this.requests.length >= 20 || (!resumeRunning && this.requests.length > 0 && now - this.requests.at(-1)! < 10_000)
|
|
@@ -374,25 +423,30 @@ export class TerminalServer {
|
|
|
374
423
|
this.publishCards(existing);
|
|
375
424
|
this.json(res, 200, { requestId: recovery.requestId }); return;
|
|
376
425
|
}
|
|
377
|
-
const job = await this.options.readJob(jobId!);
|
|
426
|
+
const job = workspace ? { cwd: workspace.cwd, contextKey: "open_id:" + ownerId, cardMessageId: "" } : await this.options.readJob(jobId!);
|
|
378
427
|
this.assertCanStart();
|
|
379
|
-
if (!job.cardMessageId || !job.contextKey?.trim()) throw new Error("命令卡片或原始会话信息尚未就绪。");
|
|
428
|
+
if ((!workspace && !job.cardMessageId) || !job.contextKey?.trim()) throw new Error("命令卡片或原始会话信息尚未就绪。");
|
|
380
429
|
const requestId = randomBytes(16).toString("hex");
|
|
381
|
-
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),
|
|
382
431
|
passwordHash,
|
|
383
|
-
contextKey: job.contextKey, commandCardMessageId: job.cardMessageId,
|
|
432
|
+
contextKey: job.contextKey, commandCardMessageId: job.cardMessageId ?? "",
|
|
384
433
|
approvalToken: randomBytes(32).toString("hex"),
|
|
385
434
|
createdAt: now, lastActivity: now, expiresAt: now + AUTH_TTL, state: "approved", output: "" };
|
|
386
435
|
this.sessions.set(requestId, session);
|
|
387
|
-
|
|
388
|
-
session.
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
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
|
+
}
|
|
392
446
|
this.json(res, 200, { requestId }); return;
|
|
393
447
|
}
|
|
394
448
|
if (route !== "/api/status" && route !== "/api/close") { this.json(res, 404, { error: "Not found." }); return; }
|
|
395
|
-
const { authorization, session } = this.access(data);
|
|
449
|
+
const { authorization, session } = this.access(data, req, origin);
|
|
396
450
|
if ("targetId" in authorization && authorization.state !== "approved") {
|
|
397
451
|
if (route === "/api/close") { this.closeRecovery(authorization, "恢复连接请求已取消"); this.publishCards(session); }
|
|
398
452
|
this.json(res, 200, { state: authorization.state, message: authorization.message }); return;
|
|
@@ -405,7 +459,7 @@ export class TerminalServer {
|
|
|
405
459
|
this.json(res, 200, { state: session.state, message: session.message });
|
|
406
460
|
}
|
|
407
461
|
|
|
408
|
-
private connect(ws: WebSocket): void {
|
|
462
|
+
private connect(ws: WebSocket, request: IncomingMessage, origin: string): void {
|
|
409
463
|
let session: TerminalSession | undefined; let authenticating = false; let accessId: string | undefined;
|
|
410
464
|
const timeout = setTimeout(() => {
|
|
411
465
|
this.options.logger.warn({ stage: "auth_timeout" }, "Terminal WebSocket authentication timed out.");
|
|
@@ -428,7 +482,7 @@ export class TerminalServer {
|
|
|
428
482
|
if (!session) {
|
|
429
483
|
stage = "auth";
|
|
430
484
|
if (authenticating || value.type !== "auth") throw new Error("Authentication required.");
|
|
431
|
-
authenticating = true; const target = this.authenticated(value);
|
|
485
|
+
authenticating = true; const target = this.authenticated(value, request, origin);
|
|
432
486
|
if (target.state !== "approved" && target.state !== "running") throw new Error("终端尚未授权或已结束。");
|
|
433
487
|
requestId = target.requestId;
|
|
434
488
|
clearTimeout(timeout);
|
|
@@ -437,6 +491,7 @@ export class TerminalServer {
|
|
|
437
491
|
await this.ensureProcess(target);
|
|
438
492
|
if (ws.readyState !== WebSocket.OPEN) return;
|
|
439
493
|
if (target.activeAccessId !== value.requestId) throw new Error("终端已由其他网页恢复。");
|
|
494
|
+
if (target.workspace && this.workspaceAccess(request, origin)?.signal !== target.workspace.signal) this.disposeSession(target, "工作台会话已失效,终端已关闭。");
|
|
440
495
|
if (target.state !== "running") throw new Error(target.message ?? "终端已结束。");
|
|
441
496
|
target.socket?.close(1000, "Reconnected from another page");
|
|
442
497
|
session = target; session.socket = ws; accessId = value.requestId; clearTimeout(timeout);
|
|
@@ -449,6 +504,7 @@ export class TerminalServer {
|
|
|
449
504
|
this.publishCards(session);
|
|
450
505
|
return;
|
|
451
506
|
}
|
|
507
|
+
if (session.workspace && this.workspaceAccess(request, origin)?.signal !== session.workspace.signal) this.disposeSession(session, "工作台会话已失效,终端已关闭。");
|
|
452
508
|
if (session.state !== "running" || session.socket !== ws || session.activeAccessId !== accessId) throw new Error("Terminal is closed.");
|
|
453
509
|
if (value.type === "input") { session.lastActivity = this.now(); session.pty?.write(value.data); }
|
|
454
510
|
else if (value.type === "resize") session.pty?.resize(value.cols, value.rows);
|
|
@@ -470,12 +526,14 @@ export class TerminalServer {
|
|
|
470
526
|
if (session.pty) return;
|
|
471
527
|
if (session.starting) return session.starting;
|
|
472
528
|
this.assertCanStart();
|
|
529
|
+
if (session.workspace) this.validateWorkspaceDirectory(session.cwd);
|
|
473
530
|
const starting = (async () => {
|
|
474
531
|
const pty = await (this.options.spawn ?? spawnTerminal)(session.cwd, 100, 30);
|
|
475
532
|
session.pty = pty;
|
|
476
533
|
pty.onExit(({ exitCode }) => { session.pty = undefined; this.disposeSession(session, `Shell 已退出(${exitCode})`); });
|
|
477
534
|
if (this.closed || this.options.canStart?.() === false || session.state === "closed"
|
|
478
|
-
|| 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)) {
|
|
479
537
|
this.disposeSession(session, "服务正在重启或授权已失效", true); pty.kill(); return;
|
|
480
538
|
}
|
|
481
539
|
session.state = "running"; session.lastActivity = this.now();
|
|
@@ -504,7 +562,7 @@ export class TerminalServer {
|
|
|
504
562
|
}
|
|
505
563
|
for (const s of this.sessions.values()) {
|
|
506
564
|
if (s.ownerId !== this.options.ownerId() || !timingSafeEqual(s.passwordHash, hash(this.options.password?.() ?? DEFAULT_TERMINAL_PASSWORD))
|
|
507
|
-
|| now - s.createdAt >= MAX_TTL
|
|
565
|
+
|| now - s.createdAt >= MAX_TTL || s.workspace?.signal.aborted || now >= (s.workspace?.expires ?? Infinity)
|
|
508
566
|
|| (s.state !== "running" && s.state !== "closed" && now >= s.expiresAt)) {
|
|
509
567
|
this.disposeSession(s, "终端已超时或授权已失效,请重新连接");
|
|
510
568
|
}
|
|
@@ -520,9 +578,13 @@ export class TerminalServer {
|
|
|
520
578
|
private disposeSession(s: TerminalSession, message: string, waitForExit = false): void {
|
|
521
579
|
if (s.state === "closed") return;
|
|
522
580
|
this.clearDisconnectTimer(s);
|
|
581
|
+
if (s.onWorkspaceRevoked) s.workspace?.signal.removeEventListener("abort", s.onWorkspaceRevoked);
|
|
523
582
|
s.state = "closed"; s.message = message; s.lastActivity = this.now();
|
|
524
583
|
const pty = s.pty; if (!waitForExit) s.pty = undefined;
|
|
525
|
-
if (s.socket) {
|
|
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
|
+
}
|
|
526
588
|
try { if (!waitForExit) pty?.kill(); } catch (error) { this.options.logger.warn({ error, requestId: s.requestId }, "Failed to close terminal process."); }
|
|
527
589
|
s.output = "";
|
|
528
590
|
for (const recovery of this.recoveries.values()) {
|
|
@@ -535,11 +597,11 @@ export class TerminalServer {
|
|
|
535
597
|
if (ws.bufferedAmount > 1024 * 1024) { ws.close(1013, "Slow consumer"); return; }
|
|
536
598
|
ws.send(JSON.stringify(value));
|
|
537
599
|
}
|
|
538
|
-
private headers(res: ServerResponse): void {
|
|
600
|
+
private headers(res: ServerResponse, origin = this.base?.origin): void {
|
|
539
601
|
res.setHeader("Cache-Control", "no-store"); res.setHeader("Referrer-Policy", "no-referrer");
|
|
540
|
-
res.setHeader("X-Content-Type-Options", "nosniff"); res.setHeader("X-Frame-Options", "
|
|
541
|
-
const socketOrigin =
|
|
542
|
-
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 '
|
|
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'`);
|
|
543
605
|
}
|
|
544
606
|
private json(res: ServerResponse, status: number, value: unknown): void {
|
|
545
607
|
this.headers(res); res.statusCode = status; res.setHeader("Content-Type", "application/json; charset=utf-8"); res.end(JSON.stringify(value));
|