-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathserver.js
More file actions
1636 lines (1507 loc) · 62.6 KB
/
Copy pathserver.js
File metadata and controls
1636 lines (1507 loc) · 62.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// server.js — Nexus WebSocket tmux 桥接服务
import express from 'express';
import { WebSocketServer } from 'ws';
import * as pty from 'node-pty';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import { createServer } from 'node:http';
import { exec, spawn, execSync, execFileSync } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join, normalize, isAbsolute, basename } from 'path';
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, unlinkSync, statSync, rmdirSync, renameSync, cpSync, rmSync } from 'fs';
import { readdir, stat as statAsync } from 'fs/promises';
import https from 'node:https';
import multer from 'multer';
// 加载 .env 文件(如果存在)
try {
const envPath = join(dirname(fileURLToPath(import.meta.url)), '.env');
const lines = readFileSync(envPath, 'utf8').split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const idx = trimmed.indexOf('=');
if (idx === -1) continue;
const key = trimmed.slice(0, idx).trim();
const val = trimmed.slice(idx + 1).trim();
if (key && !(key in process.env)) process.env[key] = val;
}
} catch { /* .env 不存在时忽略 */ }
const __dirname = dirname(fileURLToPath(import.meta.url));
// 持久化数据目录(通过 Docker volume 挂载,重建容器不丢失)
const DATA_DIR = join(__dirname, 'data');
const TOOLBAR_CONFIG_FILE = join(DATA_DIR, 'toolbar-config.json');
const CONFIGS_DIR = join(DATA_DIR, 'configs');
if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
if (!existsSync(CONFIGS_DIR)) mkdirSync(CONFIGS_DIR, { recursive: true });
// 自动确保 anthropic.json 存在(无需用户手动创建)
// 优先级:已有文件不覆盖;API_KEY 从环境变量 ANTHROPIC_API_KEY 检测
{
const anthropicProfile = join(CONFIGS_DIR, 'anthropic.json');
if (!existsSync(anthropicProfile)) {
// 检测本地 CC 是否已 login(~/.claude.json 有 oauthAccount)
let isLoggedIn = false;
try {
const claudeJson = JSON.parse(readFileSync(join(process.env.HOME || '~', '.claude.json'), 'utf8'));
isLoggedIn = !!(claudeJson.oauthAccount?.accountUuid);
} catch { /* 未登录或文件不存在 */ }
const apiKey = process.env.ANTHROPIC_API_KEY || '';
if (isLoggedIn || apiKey) {
writeFileSync(anthropicProfile, JSON.stringify({
label: 'Anthropic Claude',
BASE_URL: '',
AUTH_TOKEN: '',
API_KEY: apiKey,
DEFAULT_MODEL: 'claude-sonnet-4-6',
THINK_MODEL: 'claude-opus-4-6',
LONG_CONTEXT_MODEL: 'claude-opus-4-6',
DEFAULT_HAIKU_MODEL: 'claude-haiku-4-5-20251001',
API_TIMEOUT_MS: '3000000',
}, null, 2), 'utf8');
console.log(`[Nexus] Auto-created anthropic profile (${isLoggedIn ? 'oauth login' : 'API key from env'})`);
}
}
}
const app = express();
app.use(express.json());
const {
JWT_SECRET,
ACC_PASSWORD_HASH,
TMUX_SESSION = '~',
WORKSPACE_ROOT = '/workspace',
PORT = '3000',
CLAUDE_PROXY = '',
GITHUB_REPO = 'librae8226/nexus4cc',
} = process.env;
if (!JWT_SECRET || !ACC_PASSWORD_HASH) {
console.error('ERROR: JWT_SECRET and ACC_PASSWORD_HASH must be set in environment');
process.exit(1);
}
function commandExists(cmd) {
try {
execSync(`command -v ${cmd} >/dev/null 2>&1`);
return true;
} catch {
return false;
}
}
const INTERACTIVE_SHELL = commandExists('zsh') ? 'zsh' : 'bash';
const INTERACTIVE_SHELL_CMD = `exec ${INTERACTIVE_SHELL} -i`;
function buildInteractiveShellCmd(prefix = '') {
return `${prefix}${INTERACTIVE_SHELL_CMD}`;
}
// 静态文件:frontend/dist 和 public
app.use(express.static(join(__dirname, 'public')));
app.use(express.static(join(__dirname, 'frontend', 'dist')));
// Auth middleware
function authMiddleware(req, res, next) {
const auth = req.headers.authorization || '';
const token = auth.startsWith('Bearer ') ? auth.slice(7) : null;
if (!token) return res.status(401).json({ error: 'unauthorized' });
try {
jwt.verify(token, JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'unauthorized' });
}
}
// POST /api/auth/login
app.post('/api/auth/login', async (req, res) => {
const { password } = req.body || {};
if (!password) return res.status(400).json({ error: 'password required' });
try {
const ok = await bcrypt.compare(password, ACC_PASSWORD_HASH);
if (!ok) return res.status(401).json({ error: 'unauthorized' });
const token = jwt.sign({}, JWT_SECRET, { expiresIn: '30d' });
res.json({ token });
} catch (err) {
res.status(500).json({ error: 'internal error' });
}
});
// POST /api/windows — F-19: 项目-窗口两级结构
// body: { rel_path?, shell_type?, profile? }
// - 提供 rel_path: 设置 NEXUS_CWD 并在此目录创建窗口(新项目)
// - 不提供 rel_path: 读取 NEXUS_CWD 并在此目录创建窗口(新窗口)
app.post('/api/windows', authMiddleware, (req, res) => {
const { rel_path, shell_type = 'claude', profile } = req.body || {};
const tmuxSession = req.query.session || TMUX_SESSION;
let cwd;
if (rel_path) {
// 新项目:设置 NEXUS_CWD
cwd = rel_path.startsWith('/') ? rel_path : `${WORKSPACE_ROOT}/${rel_path}`;
try {
execSync(`tmux set-environment -t ${tmuxSession} NEXUS_CWD "${cwd}"`);
} catch (err) {
return res.status(500).json({ error: 'failed to set NEXUS_CWD: ' + err.message });
}
} else {
// 新窗口:读取 NEXUS_CWD
try {
const envOutput = execSync(`tmux show-environment -t ${tmuxSession} NEXUS_CWD 2>/dev/null`).toString().trim();
const match = envOutput.match(/^NEXUS_CWD=(.+)$/);
cwd = match ? match[1] : WORKSPACE_ROOT;
} catch {
cwd = WORKSPACE_ROOT;
}
}
// 窗口名称基于目录
const name = cwd.replace(/^\/+|\/+$/g, '').replace(/\//g, '-') || 'window';
// 构建 shell 命令
const proxyVars = {
...(process.env.HTTP_PROXY ? { HTTP_PROXY: process.env.HTTP_PROXY } : {}),
...(process.env.HTTPS_PROXY ? { HTTPS_PROXY: process.env.HTTPS_PROXY } : {}),
...(process.env.ALL_PROXY ? { ALL_PROXY: process.env.ALL_PROXY } : {}),
...(process.env.http_proxy ? { http_proxy: process.env.http_proxy } : {}),
...(process.env.https_proxy ? { https_proxy: process.env.https_proxy } : {}),
...(CLAUDE_PROXY ? { ALL_PROXY: CLAUDE_PROXY, HTTPS_PROXY: CLAUDE_PROXY, HTTP_PROXY: CLAUDE_PROXY, NEXUS_PROXY: CLAUDE_PROXY } : {}),
};
const proxyExports = Object.entries(proxyVars).map(([k, v]) => `export ${k}='${v}'`).join('; ');
const proxyPrefix = proxyExports ? `${proxyExports}; ` : '';
let shellCmd;
if (shell_type === 'bash') {
shellCmd = buildInteractiveShellCmd(proxyPrefix);
} else {
if (profile) {
const runScript = join(__dirname, 'nexus-run-claude.sh');
shellCmd = `${proxyPrefix}bash "${runScript}" ${profile} ${cwd}`;
} else {
shellCmd = `${proxyPrefix}$HOME/.local/bin/claude --dangerously-skip-permissions; ${INTERACTIVE_SHELL_CMD}`;
}
}
// 确保 tmux session 存在
try {
execSync(`tmux has-session -t ${tmuxSession} 2>/dev/null || tmux new-session -d -s ${tmuxSession} -n shell "${INTERACTIVE_SHELL}"`);
} catch {}
// 将代理变量设置到 tmux session 环境
for (const [key, value] of Object.entries(proxyVars)) {
try {
execSync(`tmux set-environment -t ${tmuxSession} ${key} "${value}" 2>/dev/null`);
} catch {}
}
const cmd = `tmux new-window -t ${tmuxSession} -c "${cwd}" -n "${name}" "${shellCmd}"`;
exec(cmd, (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ name, cwd, shell_type, profile: profile || null, session: tmuxSession });
});
});
// POST /api/sessions — 在 tmux 中创建新 window
// body: { rel_path, shell_type?, profile?, session? }
// shell_type: 'claude' | 'bash' (default: 'claude')
// 当 shell_type='claude' 时,profile 可选,使用 nexus-run-claude.sh 启动
// 当 shell_type='bash' 时,启动本地 shell(优先 zsh,不存在时回退 bash)
app.post('/api/sessions', authMiddleware, (req, res) => {
const { rel_path, shell_type = 'claude', profile, session } = req.body || {};
const tmuxSession = session || TMUX_SESSION;
if (!rel_path) return res.status(400).json({ error: 'rel_path required' });
const cwd = rel_path.startsWith('/') ? rel_path : `${WORKSPACE_ROOT}/${rel_path}`;
const name = cwd.replace(/^\/+|\/+$/g, '').replace(/\//g, '-') || 'session';
// 收集代理变量(宿主机环境 + CLAUDE_PROXY 覆盖)
const proxyVars = {
...(process.env.HTTP_PROXY ? { HTTP_PROXY: process.env.HTTP_PROXY } : {}),
...(process.env.HTTPS_PROXY ? { HTTPS_PROXY: process.env.HTTPS_PROXY } : {}),
...(process.env.ALL_PROXY ? { ALL_PROXY: process.env.ALL_PROXY } : {}),
...(process.env.http_proxy ? { http_proxy: process.env.http_proxy } : {}),
...(process.env.https_proxy ? { https_proxy: process.env.https_proxy } : {}),
...(CLAUDE_PROXY ? { ALL_PROXY: CLAUDE_PROXY, HTTPS_PROXY: CLAUDE_PROXY, HTTP_PROXY: CLAUDE_PROXY, NEXUS_PROXY: CLAUDE_PROXY } : {}),
};
const proxyExports = Object.entries(proxyVars).map(([k, v]) => `export ${k}='${v}'`).join('; ');
const proxyPrefix = proxyExports ? `${proxyExports}; ` : '';
let shellCmd;
if (shell_type === 'bash') {
shellCmd = buildInteractiveShellCmd(proxyPrefix);
} else {
if (profile) {
const runScript = join(__dirname, 'nexus-run-claude.sh');
shellCmd = `${proxyPrefix}bash "${runScript}" ${profile} ${cwd}`;
} else {
shellCmd = `${proxyPrefix}$HOME/.local/bin/claude --dangerously-skip-permissions; ${INTERACTIVE_SHELL_CMD}`;
}
}
// 确保 tmux session 存在
try {
execSync(`tmux has-session -t ${tmuxSession} 2>/dev/null || tmux new-session -d -s ${tmuxSession} -n shell "${INTERACTIVE_SHELL}"`);
} catch {}
// 将代理变量设置到 tmux session 环境,新窗口才能继承
for (const [key, value] of Object.entries(proxyVars)) {
try {
execSync(`tmux set-environment -t ${tmuxSession} ${key} "${value}" 2>/dev/null`);
} catch {}
}
const cmd = `tmux new-window -t ${tmuxSession} -c "${cwd}" -n "${name}" "${shellCmd}"`;
exec(cmd, (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ name, cwd, shell_type, profile: profile || null, session: tmuxSession });
});
});
// GET /api/configs — 列出所有 claude 配置 profile
app.get('/api/configs', authMiddleware, (req, res) => {
try {
const files = readdirSync(CONFIGS_DIR, { withFileTypes: true })
.filter(f => f.isFile() && f.name.endsWith('.json'))
.map(f => ({
name: f.name,
mtime: statSync(join(CONFIGS_DIR, f.name)).mtimeMs,
}))
.sort((a, b) => b.mtime - a.mtime)
.map(f => f.name);
const configs = files.map(f => {
const id = f.replace('.json', '');
try {
const data = JSON.parse(readFileSync(join(CONFIGS_DIR, f), 'utf8'));
return { id, label: data.label || id, ...data };
} catch {
return { id, label: id };
}
});
res.json(configs);
} catch {
res.json([]);
}
});
// POST /api/configs/:id — 创建或更新配置 profile
app.post('/api/configs/:id', authMiddleware, (req, res) => {
const id = req.params.id.replace(/[^a-z0-9_-]/gi, '-').toLowerCase();
if (!id) return res.status(400).json({ error: 'invalid id' });
try {
writeFileSync(join(CONFIGS_DIR, `${id}.json`), JSON.stringify(req.body, null, 2), 'utf8');
res.json({ ok: true, id });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// DELETE /api/configs/:id — 删除配置 profile
app.delete('/api/configs/:id', authMiddleware, (req, res) => {
const file = join(CONFIGS_DIR, `${req.params.id}.json`);
try {
if (existsSync(file)) unlinkSync(file);
res.json({ ok: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/toolbar-config — 读取工具栏配置
app.get('/api/toolbar-config', authMiddleware, (req, res) => {
try {
if (!existsSync(TOOLBAR_CONFIG_FILE)) return res.json(null);
const data = readFileSync(TOOLBAR_CONFIG_FILE, 'utf8');
res.json(JSON.parse(data));
} catch {
res.json(null);
}
});
// POST /api/toolbar-config — 保存工具栏配置
app.post('/api/toolbar-config', authMiddleware, (req, res) => {
try {
writeFileSync(TOOLBAR_CONFIG_FILE, JSON.stringify(req.body), 'utf8');
res.json({ ok: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /api/version — 当前版本号及工作区状态
app.get('/api/version', authMiddleware, (req, res) => {
try {
const current = execSync('git describe --tags --abbrev=0', { cwd: __dirname }).toString().trim();
const dirty = execSync('git status --porcelain', { cwd: __dirname }).toString().trim();
res.json({ current, clean: dirty === '' });
} catch {
res.json({ current: 'unknown', clean: true });
}
});
// GET /api/version/latest — 代理 GitHub Tags API 获取最新版本(兼容只有 tag 没有 Release 的 repo)
app.get('/api/version/latest', authMiddleware, (req, res) => {
const options = {
hostname: 'api.github.com',
path: `/repos/${GITHUB_REPO}/tags`,
headers: { 'User-Agent': 'nexus-update-check' },
};
https.get(options, (ghRes) => {
let data = '';
ghRes.on('data', chunk => { data += chunk; });
ghRes.on('end', () => {
try {
const json = JSON.parse(data);
if (!Array.isArray(json) || json.length === 0) return res.status(502).json({ error: 'no tags found' });
const latest = json[0].name;
res.json({ latest, url: `https://github.com/${GITHUB_REPO}/releases/tag/${latest}` });
} catch {
res.status(502).json({ error: 'invalid response from GitHub' });
}
});
}).on('error', () => {
res.status(502).json({ error: 'cannot reach GitHub' });
});
});
app.get('/api/browse', authMiddleware, (req, res) => {
try {
let p = req.query.path || WORKSPACE_ROOT
if (p === '~') p = WORKSPACE_ROOT
if (!isAbsolute(p)) p = join(WORKSPACE_ROOT, p)
p = normalize(p)
const entries = readdirSync(p, { withFileTypes: true })
const dirs = entries
.filter(e => e.isDirectory() && !e.name.startsWith('.'))
.map(e => ({ name: e.name, path: join(p, e.name) }))
.sort((a, b) => a.name.localeCompare(b.name))
const parent = dirname(p) !== p ? dirname(p) : null
res.json({ path: p, parent, dirs })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// GET /api/workspace/files — 浏览文件系统(支持文件和目录,任意路径)
app.get('/api/workspace/files', authMiddleware, async (req, res) => {
try {
let p = req.query.path || WORKSPACE_ROOT
if (p === '~') p = WORKSPACE_ROOT
if (!isAbsolute(p)) p = join(WORKSPACE_ROOT, p)
p = normalize(p)
const showHidden = req.query.showHidden === '1' || req.query.showHidden === 'true'
const dirents = await readdir(p, { withFileTypes: true })
const visible = showHidden ? dirents : dirents.filter(e => !e.name.startsWith('.'))
const entries = await Promise.all(visible.map(async e => {
const fullPath = join(p, e.name)
const st = await statAsync(fullPath)
return {
name: e.name,
type: e.isDirectory() ? 'dir' : 'file',
size: e.isFile() ? st.size : undefined,
mtime: st.mtimeMs,
}
}))
res.json({ path: p, entries })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// 静态文件服务:工作目录文件直接访问(/workspace/相对路径)
// 支持 header 或 query string 传递 token(浏览器直接打开时用 query string)
// 支持通过 ?path=/absolute/path 访问任意路径(仍然限制在 workspaceRoot 内)
app.use('/workspace', (req, res, next) => {
// 尝试从 query string 获取 token
const token = req.query.token
if (token) {
try {
jwt.verify(token, JWT_SECRET)
return next()
} catch {
return res.status(401).send('unauthorized')
}
}
// 否则使用 header auth
return authMiddleware(req, res, next)
}, (req, res) => {
try {
let fullPath
// 如果提供了 path 参数,使用它(绝对路径)
if (req.query.path) {
fullPath = normalize(decodeURIComponent(req.query.path))
} else {
// 否则使用相对路径(基于 WORKSPACE_ROOT)
let relPath = decodeURIComponent(req.path)
relPath = normalize(relPath).replace(/^(\.\.(\/|\|$))+/, '')
fullPath = join(WORKSPACE_ROOT, relPath)
}
// 安全检查:防止路径遍历攻击(规范化后检查是否包含 ..)
if (fullPath.includes('..')) {
return res.status(403).send('access denied: invalid path')
}
if (!existsSync(fullPath) || !statSync(fullPath).isFile()) {
return res.status(404).send('not found')
}
if (req.query.dl === '1') {
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(basename(fullPath))}`)
}
res.sendFile(fullPath)
} catch (err) {
res.status(500).send(err.message)
}
})
// POST /api/workspace/mkdir — 创建文件夹
app.post('/api/workspace/mkdir', authMiddleware, (req, res) => {
try {
let { path: targetPath, name } = req.body
if (!name) return res.status(400).json({ error: 'name required' })
if (!isAbsolute(targetPath)) targetPath = join(WORKSPACE_ROOT, targetPath)
targetPath = normalize(targetPath)
const dirPath = join(targetPath, name)
if (dirPath.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (existsSync(dirPath)) {
return res.status(409).json({ error: 'already exists' })
}
mkdirSync(dirPath, { recursive: true })
res.json({ ok: true, path: dirPath })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// POST /api/workspace/files — 创建新文件
app.post('/api/workspace/files', authMiddleware, (req, res) => {
try {
let { path: targetPath, name, content = '' } = req.body
if (!name) return res.status(400).json({ error: 'name required' })
if (!isAbsolute(targetPath)) targetPath = join(WORKSPACE_ROOT, targetPath)
targetPath = normalize(targetPath)
const filePath = join(targetPath, name)
if (filePath.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (existsSync(filePath)) {
return res.status(409).json({ error: 'already exists' })
}
writeFileSync(filePath, content, 'utf8')
res.json({ ok: true, path: filePath })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// ---- Text file detection utilities ----
// Known binary (non-text) extensions — fast pre-filter to avoid reading large binaries
const BINARY_EXTENSIONS = new Set([
// Images
'png', 'jpg', 'jpeg', 'gif', 'bmp', 'ico', 'webp', 'tiff', 'tif', 'heic', 'heif', 'avif',
// Video / Audio
'mp4', 'webm', 'mkv', 'avi', 'mov', 'wmv', 'flv', 'm4v', 'mpg', 'mpeg',
'mp3', 'wav', 'ogg', 'flac', 'aac', 'wma', 'm4a', 'opus',
// Archives
'zip', 'tar', 'gz', 'bz2', 'xz', '7z', 'rar', 'zst', 'lz4',
// Binaries / executables
'exe', 'dll', 'so', 'dylib', 'o', 'a', 'wasm', 'bin', 'dat',
// Documents (binary formats)
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', 'epub',
// Fonts
'ttf', 'otf', 'woff', 'woff2', 'eot',
// Other binary
'class', 'jar', 'war', 'pyc', 'pyo', 'elc', 'zwc',
'db', 'sqlite', 'sqlite3',
'psd', 'ai', 'sketch',
'iso', 'dmg', 'vhd', 'qcow2',
'pdb', 'obj', 'lib',
'dex', 'apk', 'ipa',
])
function isKnownBinaryExt(filePath) {
const name = basename(filePath).toLowerCase()
const dotIdx = name.lastIndexOf('.')
if (dotIdx <= 0) return false
const ext = name.slice(dotIdx + 1)
return BINARY_EXTENSIONS.has(ext)
}
function isBinaryContent(buffer) {
// Check first 8192 bytes for null bytes — reliable binary indicator
const maxCheck = Math.min(buffer.length, 8192)
for (let i = 0; i < maxCheck; i++) {
if (buffer[i] === 0) return true
}
return false
}
const MAX_EDITOR_FILE_SIZE = 5 * 1024 * 1024 // 5MB hard limit for text editor
// GET /api/workspace/file — 读取文件内容(自动检测二进制,仅文本文件可读)
app.get('/api/workspace/file', authMiddleware, (req, res) => {
try {
let p = req.query.path || ''
if (!isAbsolute(p)) p = join(WORKSPACE_ROOT, p)
p = normalize(p)
if (p.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (!existsSync(p) || !statSync(p).isFile()) {
return res.status(404).json({ error: 'not found' })
}
// Fast pre-filter: known binary extension → reject immediately
if (isKnownBinaryExt(p)) {
return res.status(415).json({ error: 'binary file, cannot open in editor' })
}
// Reject files that are too large for the editor
const st = statSync(p)
if (st.size > MAX_EDITOR_FILE_SIZE) {
return res.status(413).json({ error: 'file too large for editor', size: st.size, max: MAX_EDITOR_FILE_SIZE })
}
// Read as buffer first to detect binary content via null bytes
const buf = readFileSync(p)
if (isBinaryContent(buf)) {
return res.status(415).json({ error: 'binary file detected' })
}
const content = buf.toString('utf8')
res.json({ path: p, content })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// PUT /api/workspace/file — 保存文件内容(自动检测二进制,仅文本文件可写)
app.put('/api/workspace/file', authMiddleware, (req, res) => {
try {
let { path: filePath, content = '' } = req.body
if (!filePath) return res.status(400).json({ error: 'path required' })
if (!isAbsolute(filePath)) filePath = join(WORKSPACE_ROOT, filePath)
filePath = normalize(filePath)
if (filePath.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
// Fast pre-filter: known binary extension → reject
if (isKnownBinaryExt(filePath)) {
return res.status(415).json({ error: 'binary file, cannot save via editor' })
}
writeFileSync(filePath, content, 'utf8')
res.json({ ok: true, path: filePath })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// DELETE /api/workspace/entry — 删除文件或目录
app.delete('/api/workspace/entry', authMiddleware, (req, res) => {
try {
let p = req.body?.path || req.query?.path || ''
if (!p) return res.status(400).json({ error: 'path required' })
if (!isAbsolute(p)) p = join(WORKSPACE_ROOT, p)
p = normalize(p)
if (p.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (!existsSync(p)) {
return res.status(404).json({ error: 'not found' })
}
rmSync(p, { recursive: true, force: true })
res.json({ ok: true })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// POST /api/workspace/rename — 重命名文件或目录
app.post('/api/workspace/rename', authMiddleware, (req, res) => {
try {
let { path: srcPath, newName } = req.body || {}
if (!srcPath || !newName) return res.status(400).json({ error: 'path and newName required' })
if (!isAbsolute(srcPath)) srcPath = join(WORKSPACE_ROOT, srcPath)
srcPath = normalize(srcPath)
if (srcPath.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (!existsSync(srcPath)) {
return res.status(404).json({ error: 'not found' })
}
const destPath = normalize(join(dirname(srcPath), newName))
if (destPath.includes('..')) {
return res.status(403).json({ error: 'invalid newName' })
}
if (existsSync(destPath)) {
return res.status(409).json({ error: 'already exists' })
}
renameSync(srcPath, destPath)
res.json({ ok: true, path: destPath })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// POST /api/workspace/copy — 复制文件或目录
app.post('/api/workspace/copy', authMiddleware, (req, res) => {
try {
let { sourcePath, targetPath } = req.body || {}
if (!sourcePath || !targetPath) return res.status(400).json({ error: 'sourcePath and targetPath required' })
if (!isAbsolute(sourcePath)) sourcePath = join(WORKSPACE_ROOT, sourcePath)
if (!isAbsolute(targetPath)) targetPath = join(WORKSPACE_ROOT, targetPath)
sourcePath = normalize(sourcePath)
targetPath = normalize(targetPath)
if (sourcePath.includes('..') || targetPath.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (!existsSync(sourcePath)) {
return res.status(404).json({ error: 'source not found' })
}
if (existsSync(targetPath)) {
return res.status(409).json({ error: 'target already exists' })
}
cpSync(sourcePath, targetPath, { recursive: true })
res.json({ ok: true, path: targetPath })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// POST /api/workspace/move — 移动文件或目录
app.post('/api/workspace/move', authMiddleware, (req, res) => {
try {
let { sourcePath, targetPath } = req.body || {}
if (!sourcePath || !targetPath) return res.status(400).json({ error: 'sourcePath and targetPath required' })
if (!isAbsolute(sourcePath)) sourcePath = join(WORKSPACE_ROOT, sourcePath)
if (!isAbsolute(targetPath)) targetPath = join(WORKSPACE_ROOT, targetPath)
sourcePath = normalize(sourcePath)
targetPath = normalize(targetPath)
if (sourcePath.includes('..') || targetPath.includes('..')) {
return res.status(403).json({ error: 'invalid path' })
}
if (!existsSync(sourcePath)) {
return res.status(404).json({ error: 'source not found' })
}
if (existsSync(targetPath)) {
return res.status(409).json({ error: 'target already exists' })
}
try {
renameSync(sourcePath, targetPath)
} catch (err) {
if (err.code === 'EXDEV') {
cpSync(sourcePath, targetPath, { recursive: true })
rmSync(sourcePath, { recursive: true, force: true })
} else {
throw err
}
}
res.json({ ok: true, path: targetPath })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// POST /api/upload — 上传文件到指定 session 的 cwd(F-14)
// body: multipart/form-data, fields: file, session_name (optional)
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
// 找到目标 session 的 cwd,否则存 WORKSPACE_ROOT
let cwd = WORKSPACE_ROOT
try {
const sessionName = req.body?.session_name || ''
const windows = execSync(`tmux list-windows -t ${TMUX_SESSION} -F "#I:#W:#{pane_current_path}"`).toString().trim().split('\n')
for (const line of windows) {
const parts = line.split(':')
const name = parts[1]
const path = parts.slice(2).join(':')
if (sessionName && name === sessionName) { cwd = path; break }
// 如果没指定 session,用 active window
if (!sessionName) {
const activeLines = execSync(`tmux list-windows -t ${TMUX_SESSION} -F "#I:#W:#{pane_current_path}:#{window_active}"`).toString().trim().split('\n')
for (const al of activeLines) {
const ap = al.split(':')
if (ap[ap.length - 1]?.trim() === '1') { cwd = ap.slice(2, ap.length - 1).join(':'); break }
}
break
}
}
} catch {}
if (!existsSync(cwd)) cwd = WORKSPACE_ROOT
cb(null, cwd)
},
filename: (req, file, cb) => {
// 保留原始文件名,避免冲突加时间戳前缀
const safe = file.originalname.replace(/[^a-zA-Z0-9._-]/g, '_')
cb(null, safe)
},
}),
limits: { fileSize: 50 * 1024 * 1024 }, // 50MB
})
app.post('/api/upload', authMiddleware, (req, res, next) => {
upload.single('file')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message })
if (!req.file) return res.status(400).json({ error: 'no file' })
const filePath = req.file.path
res.json({ ok: true, path: filePath, filename: req.file.filename, size: req.file.size })
})
})
// ---- F-21: 文件上传 API(上传到当前 workspace 的 data/uploads/)----
// 读取指定 session 的 uploads 目录
// 优先级:NEXUS_CWD 环境变量 > tmux pane_current_path > WORKSPACE_ROOT
function getWorkspaceUploadsDir(session = TMUX_SESSION) {
let cwd
try {
const out = execSync(`tmux show-environment -t ${session} NEXUS_CWD 2>/dev/null`).toString().trim()
const m = out.match(/^NEXUS_CWD=(.+)$/)
if (m) cwd = m[1]
} catch {}
if (!cwd) {
try {
cwd = execSync(`tmux display-message -t ${session} -p '#{pane_current_path}' 2>/dev/null`).toString().trim()
} catch {}
}
if (!cwd) cwd = WORKSPACE_ROOT
return join(cwd, 'data', 'uploads')
}
const fileUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 100 * 1024 * 1024 } // 100MB
})
// POST /api/files/upload — 上传文件到当前 workspace/data/uploads/日期/
// Query: overwrite=1 强制覆盖已存在的文件
app.post('/api/files/upload', authMiddleware, (req, res, next) => {
fileUpload.single('file')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message })
if (!req.file) return res.status(400).json({ error: 'no file' })
const dateDir = new Date().toISOString().slice(0, 10)
const uploadsDir = getWorkspaceUploadsDir(req.query.session || TMUX_SESSION)
const uploadDir = join(uploadsDir, dateDir)
if (!existsSync(uploadDir)) mkdirSync(uploadDir, { recursive: true })
// 使用前端传递的原始文件名(避免 multer 解析编码问题)
const originalName = req.body.originalName || req.file.originalname
// 清理文件名:只保留合法字符,中文保留
const safe = originalName.replace(/[<>:"|?*\\/\x00-\x1f]/g, '_')
const filePath = join(uploadDir, safe)
const overwrite = req.query.overwrite === '1'
// 检查文件是否已存在
if (!overwrite && existsSync(filePath)) {
return res.status(409).json({
error: 'file exists',
filename: safe,
message: `文件 "${safe}" 已存在`
})
}
// 写入文件
try {
writeFileSync(filePath, req.file.buffer)
const url = `/api/files/content?path=${encodeURIComponent(filePath)}`
const responseData = {
ok: true,
filename: safe,
url,
fullPath: filePath,
size: req.file.size,
originalName: originalName
}
console.log('[Upload]', safe, '→', filePath)
res.json(responseData)
} catch (writeErr) {
res.status(500).json({ error: writeErr.message })
}
})
})
// GET /api/files/content?path=... — 访问/下载已上传的文件(路径自描述,无状态)
app.get('/api/files/content', authMiddleware, (req, res) => {
const filePath = req.query.path
if (!filePath || typeof filePath !== 'string') return res.status(400).json({ error: 'path required' })
const normalized = normalize(filePath)
const uploadsDir = getWorkspaceUploadsDir()
const allowed = normalized.startsWith(WORKSPACE_ROOT) || normalized.startsWith(uploadsDir)
if (!allowed) return res.status(403).json({ error: 'access denied' })
if (!existsSync(normalized)) return res.status(404).json({ error: 'file not found' })
res.sendFile(normalized)
})
// GET /api/files — 列出当前 workspace 上传的文件(按日期分组)
app.get('/api/files', authMiddleware, (req, res) => {
try {
const uploadsDir = getWorkspaceUploadsDir(req.query.session || TMUX_SESSION)
const result = []
if (!existsSync(uploadsDir)) return res.json(result)
const dateDirs = readdirSync(uploadsDir, { withFileTypes: true })
.filter(e => e.isDirectory())
.map(e => e.name)
.sort((a, b) => b.localeCompare(a)) // 降序,最新的在前
for (const dateDir of dateDirs) {
const dirPath = join(uploadsDir, dateDir)
const files = readdirSync(dirPath, { withFileTypes: true })
.filter(e => e.isFile())
.map(e => {
const fullPath = join(dirPath, e.name)
const stat = statSync(fullPath)
return {
name: e.name,
url: `/api/files/content?path=${encodeURIComponent(fullPath)}`,
fullPath,
size: stat.size,
created: stat.mtimeMs,
}
})
.sort((a, b) => b.created - a.created)
if (files.length > 0) {
result.push({ date: dateDir, files })
}
}
res.json(result)
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// DELETE /api/files/all — 删除当前 workspace 所有上传的文件
app.delete('/api/files/all', authMiddleware, (req, res) => {
try {
const uploadsDir = getWorkspaceUploadsDir(req.query.session || TMUX_SESSION)
if (!existsSync(uploadsDir)) return res.json({ ok: true, deletedCount: 0 })
const dateDirs = readdirSync(uploadsDir, { withFileTypes: true })
.filter(e => e.isDirectory())
let deletedCount = 0
for (const dateDir of dateDirs) {
const dirPath = join(uploadsDir, dateDir.name)
const files = readdirSync(dirPath, { withFileTypes: true })
.filter(e => e.isFile())
for (const file of files) {
const filePath = join(dirPath, file.name)
try {
unlinkSync(filePath)
deletedCount++
} catch {}
}
// 尝试删除空目录
try {
rmdirSync(dirPath)
} catch {}
}
res.json({ ok: true, deletedCount })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// DELETE /api/files/content?path=... — 删除指定文件(路径自描述)
app.delete('/api/files/content', authMiddleware, (req, res) => {
const filePath = req.query.path
if (!filePath || typeof filePath !== 'string') return res.status(400).json({ error: 'path required' })
const normalized = normalize(filePath)
if (!normalized.startsWith(WORKSPACE_ROOT)) return res.status(403).json({ error: 'access denied' })
try {
if (existsSync(normalized)) {
unlinkSync(normalized)
res.json({ ok: true })
} else {
res.status(404).json({ error: 'file not found' })
}
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// POST /api/sessions/:id/rename — 重命名窗口
app.post('/api/sessions/:id/rename', authMiddleware, (req, res) => {
const index = req.params.id
const session = req.query.session || TMUX_SESSION
const { name } = req.body || {}
if (!name) return res.status(400).json({ error: 'name required' })
// window 名允许 Unicode(中日韩等),仅过滤控制字符和 tmux target separator ':'
// 之前的 /[^a-zA-Z0-9._-]/→'-' 会把中文全部变成 '-',导致"我的频道" → "----"
const safeName = String(name).replace(/[\r\n\t\0:]/g, '').trim().slice(0, 50)
if (!safeName) return res.status(400).json({ error: 'name required' })
try {
execFileSync('tmux', ['rename-window', '-t', `${session}:${index}`, '--', safeName], { stdio: 'pipe' })
res.json({ ok: true, name: safeName })
} catch (err) {
res.status(500).json({ error: err.message })
}
})
// GET /api/sessions/:id/output — 获取窗口最后输出(F-15 状态卡片)
app.get('/api/sessions/:id/output', authMiddleware, (req, res) => {
const windowIndex = parseInt(req.params.id, 10);
const session = req.query.session || TMUX_SESSION;
const entry = ptyMap.get(ptyKey(session, windowIndex));
if (!entry) return res.json({ connected: false, output: '', clients: 0 });
res.json({
connected: true,
output: entry.lastOutput.slice(-2000), // 最后 2KB
clients: entry.clients.size,
idleMs: Date.now() - entry.lastActivity,
});
});
// GET /api/sessions/:id/scrollback — fetch tmux scrollback history (works in alternate screen too)
app.get('/api/sessions/:id/scrollback', authMiddleware, (req, res) => {
const windowIndex = parseInt(req.params.id, 10)
const session = req.query.session || TMUX_SESSION
const lines = Math.min(parseInt(req.query.lines || '3000', 10), 10000)
exec(`tmux capture-pane -e -p -S -${lines} -t ${session}:${windowIndex} 2>/dev/null`, (err, stdout) => {
if (err) return res.status(500).json({ error: err.message })
// trim trailing spaces tmux pads to pane width
const content = stdout.split('\n').map(l => l.trimEnd()).join('\n')
res.json({ content })
})
})
// GET /api/config — 服务端配置信息(供前端初始化用)
app.get('/api/config', authMiddleware, (req, res) => {
res.json({ tmuxSession: TMUX_SESSION, workspaceRoot: WORKSPACE_ROOT })
})
// GET /api/tmux-sessions — 列出所有 tmux session(F-18)
app.get('/api/tmux-sessions', authMiddleware, (req, res) => {
exec('tmux list-sessions -F "#{session_name}|#{session_windows}|#{session_attached}"', (err, stdout) => {
if (err) return res.json([{ name: TMUX_SESSION, windows: 0, attached: false }])
const sessions = stdout.trim().split('\n').filter(Boolean).map(line => {
const [name, windows, attached] = line.split('|')
return { name, windows: Number(windows), attached: Number(attached) > 0 }
})
res.json(sessions)
})
})
// POST /api/launch-iterm — 在本机启动 iTerm2 并用 tmux -CC 集成模式接管指定 session
// 仅在 server 与 iTerm2 同机时有意义(macOS only)。
app.post('/api/launch-iterm', authMiddleware, (req, res) => {
if (process.platform !== 'darwin') {
return res.status(400).json({ error: 'launch-iterm requires macOS host' })
}
const session = req.body?.session
if (!session || typeof session !== 'string') {
return res.status(400).json({ error: 'session required' })
}
if (/["'\\`$]/.test(session)) {
return res.status(400).json({ error: 'invalid session name' })
}
try {