forked from ZgDaniel/cc-web
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.js
More file actions
12399 lines (11629 loc) · 455 KB
/
Copy pathserver.js
File metadata and controls
12399 lines (11629 loc) · 455 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
const http = require('http');
const https = require('https');
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const { spawn, execFile } = require('child_process');
const { WebSocketServer } = require('ws');
const {
createAgentRuntime,
withClaudeOneMillionContext,
withoutClaudeOneMillionContext,
} = require('./lib/agent-runtime');
const { createCodexRolloutStore } = require('./lib/codex-rollouts');
const { getStaticHeadlessCapabilities } = require('./lib/runtime-capabilities');
const { PiRpcClient } = require('./lib/pi-rpc-client');
const { getPiSessionFiles, parsePiSessionFile, summarizePiSessionFile } = require('./lib/pi-sessions');
const { CodexAppServerClient } = require('./lib/codex-app-server-client');
const { ClaudeStreamClient } = require('./lib/claude-stream-client');
const { buildVersionedEndpointUrl, detectConfiguredEndpoint } = require('./lib/api-endpoint');
const PACKAGE_VERSION = require('./package.json').version || 'unknown';
// Load .env
const envPath = path.join(__dirname, '.env');
if (fs.existsSync(envPath)) {
for (const line of fs.readFileSync(envPath, 'utf8').split(/\r?\n/)) {
const m = line.match(/^([^#=]+)=(.*)$/);
if (!m) continue;
const key = m[1].trim();
let val = String(m[2] || '').trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith('\'') && val.endsWith('\''))) {
val = val.slice(1, -1);
}
if (key && !process.env[key]) process.env[key] = val;
}
}
const PORT = parseInt(process.env.PORT) || 8001;
const HOST = String(process.env.HOST || '').trim() || '0.0.0.0';
const DEFAULT_WS_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
const requestedWsMaxPayload = Number.parseInt(process.env.CC_WEB_WS_MAX_PAYLOAD || '', 10);
const WS_MAX_PAYLOAD_BYTES = Number.isFinite(requestedWsMaxPayload) && requestedWsMaxPayload > 0
? Math.min(Math.max(requestedWsMaxPayload, 64 * 1024), 32 * 1024 * 1024)
: DEFAULT_WS_MAX_PAYLOAD_BYTES;
const PI_TRANSPORT = String(process.env.CC_WEB_PI_TRANSPORT || 'rpc').trim().toLowerCase() === 'headless'
? 'headless'
: 'rpc';
const CODEX_TRANSPORT = String(process.env.CC_WEB_CODEX_TRANSPORT || 'app-server').trim().toLowerCase() === 'exec'
? 'exec'
: 'app-server';
const CLAUDE_TRANSPORT = String(process.env.CC_WEB_CLAUDE_TRANSPORT || 'stream-json').trim().toLowerCase() === 'headless'
? 'headless'
: 'stream-json';
const requestedPiRpcIdleMinutes = Number.parseInt(process.env.CC_WEB_PI_RPC_IDLE_TIMEOUT_MINUTES || '', 10);
const PI_RPC_IDLE_TIMEOUT_MINUTES = Number.isFinite(requestedPiRpcIdleMinutes) && requestedPiRpcIdleMinutes > 0
? Math.min(Math.max(requestedPiRpcIdleMinutes, 1), 24 * 60)
: 30;
const PI_RPC_IDLE_TIMEOUT_MS = PI_RPC_IDLE_TIMEOUT_MINUTES * 60 * 1000;
const requestedMaxPiRpcRuntimes = Number.parseInt(process.env.CC_WEB_PI_RPC_MAX_RUNTIMES || '', 10);
const MAX_PI_RPC_RUNTIMES = Number.isFinite(requestedMaxPiRpcRuntimes) && requestedMaxPiRpcRuntimes > 0
? Math.min(Math.max(requestedMaxPiRpcRuntimes, 1), 64)
: 8;
const requestedCodexAppIdleMinutes = Number.parseInt(process.env.CC_WEB_CODEX_APP_IDLE_TIMEOUT_MINUTES || '', 10);
const CODEX_APP_IDLE_TIMEOUT_MINUTES = Number.isFinite(requestedCodexAppIdleMinutes) && requestedCodexAppIdleMinutes > 0
? Math.min(Math.max(requestedCodexAppIdleMinutes, 1), 24 * 60)
: 30;
const CODEX_APP_IDLE_TIMEOUT_MS = CODEX_APP_IDLE_TIMEOUT_MINUTES * 60 * 1000;
const requestedMaxCodexAppRuntimes = Number.parseInt(process.env.CC_WEB_CODEX_APP_MAX_RUNTIMES || '', 10);
const MAX_CODEX_APP_RUNTIMES = Number.isFinite(requestedMaxCodexAppRuntimes) && requestedMaxCodexAppRuntimes > 0
? Math.min(Math.max(requestedMaxCodexAppRuntimes, 1), 64)
: 8;
const requestedClaudeStreamIdleMinutes = Number.parseInt(process.env.CC_WEB_CLAUDE_STREAM_IDLE_TIMEOUT_MINUTES || '', 10);
const CLAUDE_STREAM_IDLE_TIMEOUT_MINUTES = Number.isFinite(requestedClaudeStreamIdleMinutes) && requestedClaudeStreamIdleMinutes > 0
? Math.min(Math.max(requestedClaudeStreamIdleMinutes, 1), 24 * 60)
: 30;
const CLAUDE_STREAM_IDLE_TIMEOUT_MS = CLAUDE_STREAM_IDLE_TIMEOUT_MINUTES * 60 * 1000;
const requestedMaxClaudeStreamRuntimes = Number.parseInt(process.env.CC_WEB_CLAUDE_STREAM_MAX_RUNTIMES || '', 10);
const MAX_CLAUDE_STREAM_RUNTIMES = Number.isFinite(requestedMaxClaudeStreamRuntimes) && requestedMaxClaudeStreamRuntimes > 0
? Math.min(Math.max(requestedMaxClaudeStreamRuntimes, 1), 64)
: 8;
/**
* Resolve a CLI binary path robustly.
* Parent shells / IDE launchers sometimes set CLAUDE_PATH to a stale absolute path
* (e.g. missing ~/.volta/bin/claude) while the real binary lives in ~/.local/bin.
*/
function isExecutablePath(filePath) {
if (!filePath) return false;
try {
fs.accessSync(filePath, fs.constants.F_OK);
const st = fs.statSync(filePath);
// Accept regular files and symlinks-to-files (stat follows links).
if (!st.isFile()) return false;
// On Windows, X_OK is unreliable; existence is enough for spawn.
if (process.platform === 'win32') return true;
fs.accessSync(filePath, fs.constants.X_OK);
return true;
} catch {
return false;
}
}
function whichOnPath(commandName, pathEnv = process.env.PATH) {
const name = String(commandName || '').trim();
if (!name || name.includes('/') || name.includes('\\')) return null;
const dirs = String(pathEnv || '').split(path.delimiter).filter(Boolean);
const exts = process.platform === 'win32'
? (String(process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean))
: [''];
for (const dir of dirs) {
for (const ext of exts) {
const candidate = path.join(dir, name + (ext && !name.toLowerCase().endsWith(ext.toLowerCase()) ? ext : ''));
if (isExecutablePath(candidate)) return candidate;
}
}
return null;
}
function resolveCliBinary(envValue, defaultName, extraCandidates = []) {
const home = process.env.HOME || process.env.USERPROFILE || '';
const requested = String(envValue || '').trim() || defaultName;
const baseName = path.basename(requested.replace(/\\/g, '/')) || defaultName;
const requestedHasPath = path.isAbsolute(requested) || requested.includes('/') || requested.includes('\\');
const candidates = [];
// 1) Explicit env value (absolute or relative path)
if (requested) {
candidates.push(path.isAbsolute(requested)
? requested
: requestedHasPath
? path.resolve(__dirname, requested)
: requested);
}
// 2) Well-known install locations (Claude Code installer uses ~/.local/bin)
if (home) {
candidates.push(
path.join(home, '.local', 'bin', baseName),
path.join(home, '.volta', 'bin', baseName),
path.join(home, '.npm-global', 'bin', baseName),
path.join(home, '.yarn', 'bin', baseName),
path.join(home, '.cargo', 'bin', baseName),
);
}
candidates.push(
path.join('/usr/local/bin', baseName),
path.join('/opt/homebrew/bin', baseName),
);
for (const extra of extraCandidates) {
if (extra) candidates.push(extra);
}
const seen = new Set();
for (const candidate of candidates) {
const resolved = path.isAbsolute(candidate) ? candidate : null;
// Absolute candidates: check existence
if (resolved) {
if (seen.has(resolved)) continue;
seen.add(resolved);
if (isExecutablePath(resolved)) {
if (requested !== resolved && requestedHasPath) {
// Stale absolute env path — fall through quietly, log later at boot.
}
return resolved;
}
continue;
}
}
// 3) Search PATH for bare command name
const fromPath = whichOnPath(baseName, process.env.PATH);
if (fromPath) return fromPath;
// 4) Keep bare name so spawn can still try (and surface a clear ENOENT)
return baseName;
}
// Prefer env when valid; otherwise recover common real install locations.
const CLAUDE_PATH = resolveCliBinary(process.env.CLAUDE_PATH, 'claude');
const CODEX_PATH = resolveCliBinary(process.env.CODEX_PATH, 'codex');
const PI_PATH = resolveCliBinary(process.env.PI_PATH, 'pi');
const CONFIG_DIR = process.env.CC_WEB_CONFIG_DIR || path.join(__dirname, 'config');
const SESSIONS_DIR = process.env.CC_WEB_SESSIONS_DIR || path.join(__dirname, 'sessions');
const PUBLIC_DIR = process.env.CC_WEB_PUBLIC_DIR || path.join(__dirname, 'public');
const LOGS_DIR = process.env.CC_WEB_LOGS_DIR || path.join(__dirname, 'logs');
const ATTACHMENTS_DIR = path.join(SESSIONS_DIR, '_attachments');
const ATTACHMENT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024;
const MAX_MESSAGE_ATTACHMENTS = 4;
const IMAGE_MIME_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
const NOTIFY_CONFIG_PATH = path.join(CONFIG_DIR, 'notify.json');
const AUTH_CONFIG_PATH = path.join(CONFIG_DIR, 'auth.json');
const MODEL_CONFIG_PATH = path.join(CONFIG_DIR, 'model.json');
const CODEX_CONFIG_PATH = path.join(CONFIG_DIR, 'codex.json');
const PI_CONFIG_PATH = path.join(CONFIG_DIR, 'pi.json');
const PROJECTS_CONFIG_PATH = path.join(CONFIG_DIR, 'projects.json');
const BRIDGE_RUNTIME_PATH = path.join(CONFIG_DIR, 'bridge-runtime.json');
const BRIDGE_STATE_PATH = path.join(CONFIG_DIR, 'bridge-state.json');
const TUNNEL_STATE_PATH = path.join(CONFIG_DIR, 'tunnel-state.json');
const TUNNEL_SCRIPT_PATH = path.join(__dirname, 'lib', 'cf-tunnel.js');
const TUNNEL_START_TIMEOUT_MS = 30000;
const CLAUDE_SETTINGS_BACKUP_PATH = path.join(CONFIG_DIR, 'claude-settings-backup.json');
const CLAUDE_RUNTIME_SETTINGS_PATH = path.join(CONFIG_DIR, 'claude-runtime-settings.json');
const BRIDGE_SCRIPT_PATH = path.join(__dirname, 'lib', 'local-api-bridge.js');
const PUBLIC_ROOT = path.resolve(PUBLIC_DIR);
const USER_HOME = process.env.HOME || process.env.USERPROFILE || '';
const BROWSE_ROOTS = (USER_HOME ? [USER_HOME] : [process.cwd()]).map((root) => {
const resolved = path.resolve(root);
try {
return fs.realpathSync(resolved);
} catch {
return resolved;
}
});
const AUTH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const AUTH_TOKEN_CLEANUP_MS = 60 * 60 * 1000;
const HISTORY_CHUNK_BUFFER_LIMIT = 512 * 1024;
const HISTORY_CHUNK_RETRY_MS = 16;
const ATTACHMENT_CLEANUP_THROTTLE_MS = 30 * 60 * 1000;
const BRIDGE_START_TIMEOUT_MS = 5000;
const HTTP_BODY_MAX_BYTES = 2 * 1024 * 1024;
const AUTH_LOCK_WINDOW_MS = 15 * 60 * 1000;
const AUTH_MAX_FAILURES = 5;
const PASSWORD_SALT_BYTES = 16;
const PASSWORD_HASH_BYTES = 64;
const MAX_AUTO_COMPACT_RETRIES = 2;
const SESSION_LIST_CACHE_TTL_MS = 300;
const FILE_TAIL_DEBOUNCE_MS = 40;
const FILE_TAIL_MAX_READ_BYTES = 8 * 1024 * 1024;
const IMPORTED_SESSION_IDS_CACHE_TTL_MS = 2000;
const JSONL_HEAD_READ_BYTES = 128 * 1024;
const JSONL_TAIL_READ_BYTES = 128 * 1024;
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
'X-XSS-Protection': '0',
'Cross-Origin-Resource-Policy': 'same-origin',
'Content-Security-Policy': "default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com; script-src 'self' https://cdnjs.cloudflare.com; font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com; frame-ancestors 'none'; base-uri 'none'",
};
fs.mkdirSync(SESSIONS_DIR, { recursive: true });
fs.mkdirSync(LOGS_DIR, { recursive: true });
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.mkdirSync(ATTACHMENTS_DIR, { recursive: true });
const jsonConfigCache = new Map();
const authAttemptByIp = new Map();
function cloneJson(value) {
if (value === undefined) return undefined;
return JSON.parse(JSON.stringify(value));
}
function readCachedJsonConfig(filePath) {
try {
if (!fs.existsSync(filePath)) return null;
const stat = fs.statSync(filePath);
const cached = jsonConfigCache.get(filePath);
if (cached && cached.mtimeMs === stat.mtimeMs) {
return cloneJson(cached.value);
}
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
jsonConfigCache.set(filePath, { mtimeMs: stat.mtimeMs, value: cloneJson(parsed) });
return cloneJson(parsed);
} catch {
return null;
}
}
function writeJsonAtomic(filePath, value) {
const tempPath = `${filePath}.tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
fs.writeFileSync(tempPath, JSON.stringify(value, null, 2));
fs.renameSync(tempPath, filePath);
}
function writeCachedJsonConfig(filePath, value) {
writeJsonAtomic(filePath, value);
try {
const stat = fs.statSync(filePath);
jsonConfigCache.set(filePath, { mtimeMs: stat.mtimeMs, value: cloneJson(value) });
} catch {
jsonConfigCache.set(filePath, { mtimeMs: null, value: cloneJson(value) });
}
}
function deleteCachedJsonConfig(filePath) {
jsonConfigCache.delete(filePath);
try {
fs.unlinkSync(filePath);
} catch {}
}
function writeHeadWithSecurity(res, statusCode, headers = {}) {
res.writeHead(statusCode, { ...SECURITY_HEADERS, ...headers });
}
// === Process Lifecycle Logger ===
const LOG_FILE = path.join(LOGS_DIR, 'process.log');
const LOG_MAX_SIZE = 2 * 1024 * 1024; // 2MB per file
function plog(level, event, data = {}) {
const entry = {
ts: new Date().toISOString(),
level,
event,
...data,
};
const line = JSON.stringify(entry) + '\n';
try {
// Simple rotation: if file > 2MB, rename to .old and start fresh
try {
const stat = fs.statSync(LOG_FILE);
if (stat.size > LOG_MAX_SIZE) {
const oldFile = LOG_FILE.replace('.log', '.old.log');
try { fs.unlinkSync(oldFile); } catch {}
fs.renameSync(LOG_FILE, oldFile);
}
} catch {}
fs.appendFileSync(LOG_FILE, line);
} catch {}
}
// === Notification System ===
function loadNotifyConfig() {
const cached = readCachedJsonConfig(NOTIFY_CONFIG_PATH);
if (cached) return cached;
// First run: migrate from .env PUSHPLUS_TOKEN
const token = process.env.PUSHPLUS_TOKEN || '';
const config = {
provider: token ? 'pushplus' : 'off',
pushplus: { token },
telegram: { botToken: '', chatId: '' },
serverchan: { sendKey: '' },
feishu: { webhook: '' },
qqbot: { qmsgKey: '' },
};
saveNotifyConfig(config);
return config;
}
function saveNotifyConfig(config) {
writeCachedJsonConfig(NOTIFY_CONFIG_PATH, config);
}
function maskToken(str) {
if (!str || str.length <= 8) return str ? '****' : '';
return str.slice(0, 4) + '****' + str.slice(-4);
}
function validateFeishuWebhook(rawUrl) {
try {
const parsed = new URL(String(rawUrl || '').trim());
if (parsed.protocol !== 'https:') {
return { ok: false, error: '飞书 Webhook 必须使用 HTTPS' };
}
const host = parsed.hostname.toLowerCase();
const hostAllowed = host === 'feishu.cn'
|| host.endsWith('.feishu.cn')
|| host === 'larksuite.com'
|| host.endsWith('.larksuite.com');
if (!hostAllowed) {
return { ok: false, error: '飞书 Webhook 域名不合法' };
}
return { ok: true };
} catch {
return { ok: false, error: '飞书 Webhook URL 无效' };
}
}
function getNotifyConfigMasked() {
const config = loadNotifyConfig();
return {
provider: config.provider,
pushplus: { token: maskToken(config.pushplus?.token) },
telegram: { botToken: maskToken(config.telegram?.botToken), chatId: config.telegram?.chatId || '' },
serverchan: { sendKey: maskToken(config.serverchan?.sendKey) },
feishu: { webhook: maskToken(config.feishu?.webhook) },
qqbot: { qmsgKey: maskToken(config.qqbot?.qmsgKey) },
};
}
function sendNotification(title, content) {
const config = loadNotifyConfig();
if (!config.provider || config.provider === 'off') return Promise.resolve({ ok: true, skipped: true });
return new Promise((resolve) => {
let url, data;
let isFormData = false;
switch (config.provider) {
case 'pushplus': {
if (!config.pushplus?.token) return resolve({ ok: false, error: 'PushPlus token 未配置' });
url = 'https://www.pushplus.plus/send';
data = JSON.stringify({ token: config.pushplus.token, title, content, template: 'txt' });
break;
}
case 'telegram': {
if (!config.telegram?.botToken || !config.telegram?.chatId) return resolve({ ok: false, error: 'Telegram botToken 或 chatId 未配置' });
url = `https://api.telegram.org/bot${config.telegram.botToken}/sendMessage`;
data = JSON.stringify({ chat_id: config.telegram.chatId, text: `${title}\n\n${content}` });
break;
}
case 'serverchan': {
if (!config.serverchan?.sendKey) return resolve({ ok: false, error: 'Server酱 sendKey 未配置' });
url = `https://sctapi.ftqq.com/${config.serverchan.sendKey}.send`;
data = JSON.stringify({ title, desp: content });
break;
}
case 'feishu': {
if (!config.feishu?.webhook) return resolve({ ok: false, error: '飞书 Webhook 未配置' });
const feishuValidation = validateFeishuWebhook(config.feishu.webhook);
if (!feishuValidation.ok) return resolve({ ok: false, error: feishuValidation.error });
url = config.feishu.webhook;
data = JSON.stringify({ msg_type: 'text', content: { text: `${title}\n\n${content}` } });
break;
}
case 'qqbot': {
if (!config.qqbot?.qmsgKey) return resolve({ ok: false, error: 'Qmsg Key 未配置' });
url = `https://qmsg.zendee.cn/send/${config.qqbot.qmsgKey}`;
data = `msg=${encodeURIComponent(`${title}\n\n${content}`)}`;
isFormData = true;
break;
}
default:
return resolve({ ok: false, error: `未知通知方式: ${config.provider}` });
}
const parsed = new URL(url);
const contentType = isFormData ? 'application/x-www-form-urlencoded' : 'application/json';
const reqOptions = {
method: 'POST',
headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data) },
};
const req = https.request(parsed, reqOptions, (res) => {
let body = '';
res.on('data', (c) => body += c);
res.on('end', () => {
plog('INFO', 'notify_response', { provider: config.provider, status: res.statusCode, body: body.slice(0, 200) });
resolve({ ok: res.statusCode >= 200 && res.statusCode < 300, status: res.statusCode, body: body.slice(0, 200) });
});
});
req.on('error', (e) => {
plog('WARN', 'notify_error', { provider: config.provider, error: e.message });
resolve({ ok: false, error: e.message });
});
req.setTimeout(10000, () => req.destroy(new Error('notification timeout')));
req.write(data);
req.end();
});
}
// Load config on startup (ensures migration)
loadNotifyConfig();
// === Auth Config ===
function generateRandomPassword(length = 12) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
const bytes = crypto.randomBytes(length);
for (let i = 0; i < length; i++) {
result += chars[bytes[i] % chars.length];
}
return result;
}
function hashPassword(password) {
const salt = crypto.randomBytes(PASSWORD_SALT_BYTES).toString('hex');
const hash = crypto.scryptSync(String(password || ''), salt, PASSWORD_HASH_BYTES).toString('hex');
return `scrypt:${salt}:${hash}`;
}
function isPasswordHashFormat(stored) {
const parts = String(stored || '').split(':');
return parts.length === 3 && parts[0] === 'scrypt' && parts[1] && /^[a-f0-9]+$/i.test(parts[2]);
}
function verifyPasswordHash(password, stored) {
if (!isPasswordHashFormat(stored)) return false;
try {
const [, salt, expectedHex] = String(stored).split(':');
const derivedHex = crypto.scryptSync(String(password || ''), salt, PASSWORD_HASH_BYTES).toString('hex');
return timingSafeStringEqual(derivedHex, expectedHex);
} catch {
return false;
}
}
function normalizeAuthConfig(raw) {
const mustChange = !!raw?.mustChange;
if (isPasswordHashFormat(raw?.passwordHash)) {
return { passwordHash: String(raw.passwordHash), mustChange };
}
if (typeof raw?.password === 'string' && raw.password) {
return { passwordHash: hashPassword(raw.password), mustChange };
}
return null;
}
function loadAuthConfig() {
// Priority 1: config/auth.json exists
try {
if (fs.existsSync(AUTH_CONFIG_PATH)) {
const rawConfig = JSON.parse(fs.readFileSync(AUTH_CONFIG_PATH, 'utf8'));
const normalized = normalizeAuthConfig(rawConfig);
if (normalized) {
if (!isPasswordHashFormat(rawConfig?.passwordHash) || rawConfig?.password) {
saveAuthConfig(normalized);
plog('INFO', 'auth_password_migrated_to_hash', {});
}
return normalized;
}
}
} catch {}
// Priority 2: .env has CC_WEB_PASSWORD → migrate
const envPw = process.env.CC_WEB_PASSWORD;
if (envPw && envPw !== 'changeme') {
const config = { passwordHash: hashPassword(envPw), mustChange: false };
saveAuthConfig(config);
return config;
}
// Priority 3: Generate random password
const pw = generateRandomPassword(12);
const config = { passwordHash: hashPassword(pw), mustChange: true };
saveAuthConfig(config);
console.log('========================================');
console.log(' 自动生成初始密码: ' + pw);
console.log(' 首次登录后将要求修改密码');
console.log('========================================');
return config;
}
function saveAuthConfig(config) {
const normalized = normalizeAuthConfig(config);
if (!normalized) return;
writeCachedJsonConfig(AUTH_CONFIG_PATH, normalized);
}
function validatePasswordStrength(pw) {
if (!pw || pw.length < 8) {
return { valid: false, message: '密码长度至少 8 位' };
}
let types = 0;
if (/[a-z]/.test(pw)) types++;
if (/[A-Z]/.test(pw)) types++;
if (/[0-9]/.test(pw)) types++;
if (/[^a-zA-Z0-9]/.test(pw)) types++;
if (types < 2) {
return { valid: false, message: '密码需包含至少 2 种字符类型(大写/小写/数字/特殊字符)' };
}
return { valid: true, message: '' };
}
let authConfig = loadAuthConfig();
let PASSWORD_HASH = authConfig.passwordHash || '';
const activeTokens = new Map();
function timingSafeStringEqual(left, right) {
const leftBuf = Buffer.from(String(left ?? ''), 'utf8');
const rightBuf = Buffer.from(String(right ?? ''), 'utf8');
const maxLen = Math.max(leftBuf.length, rightBuf.length, 1);
const paddedLeft = Buffer.alloc(maxLen);
const paddedRight = Buffer.alloc(maxLen);
leftBuf.copy(paddedLeft);
rightBuf.copy(paddedRight);
return crypto.timingSafeEqual(paddedLeft, paddedRight) && leftBuf.length === rightBuf.length;
}
function hasConfiguredPassword() {
return !!PASSWORD_HASH;
}
function verifyConfiguredPassword(inputPassword) {
if (!hasConfiguredPassword()) return false;
return verifyPasswordHash(inputPassword, PASSWORD_HASH);
}
function getWsClientIp(req) {
const forwarded = String(req?.headers?.['x-forwarded-for'] || '').split(',')[0].trim();
return forwarded || req?.socket?.remoteAddress || 'unknown';
}
function getAuthLockState(ip, now = Date.now()) {
const state = authAttemptByIp.get(ip);
if (!state) return { locked: false, remainingMs: 0, count: 0 };
if (state.lockedUntil && state.lockedUntil > now) {
return { locked: true, remainingMs: state.lockedUntil - now, count: state.count || 0 };
}
if (state.lockedUntil && state.lockedUntil <= now) {
authAttemptByIp.delete(ip);
}
return { locked: false, remainingMs: 0, count: 0 };
}
function clearAuthFailures(ip) {
if (!ip) return;
authAttemptByIp.delete(ip);
}
function recordAuthFailure(ip, now = Date.now()) {
const prev = authAttemptByIp.get(ip) || { count: 0, firstAt: now, lockedUntil: 0 };
const count = (prev.firstAt + AUTH_LOCK_WINDOW_MS < now) ? 1 : (prev.count + 1);
const firstAt = (prev.firstAt + AUTH_LOCK_WINDOW_MS < now) ? now : prev.firstAt;
const lockedUntil = count >= AUTH_MAX_FAILURES ? now + AUTH_LOCK_WINDOW_MS : 0;
const next = { count, firstAt, lockedUntil };
authAttemptByIp.set(ip, next);
return {
locked: lockedUntil > now,
remainingMs: lockedUntil > now ? (lockedUntil - now) : 0,
count,
};
}
function rememberActiveToken(token, now = Date.now()) {
if (!token) return null;
activeTokens.set(token, now + AUTH_TOKEN_TTL_MS);
return token;
}
function hasActiveToken(token, now = Date.now()) {
if (!token) return false;
const expiresAt = activeTokens.get(token);
if (!expiresAt) return false;
if (expiresAt <= now) {
activeTokens.delete(token);
return false;
}
activeTokens.set(token, now + AUTH_TOKEN_TTL_MS);
return true;
}
function cleanupExpiredTokens(now = Date.now()) {
for (const [token, expiresAt] of activeTokens) {
if (expiresAt <= now) activeTokens.delete(token);
}
}
function cleanupAuthAttempts(now = Date.now()) {
for (const [ip, state] of authAttemptByIp) {
if (!state) {
authAttemptByIp.delete(ip);
continue;
}
const expired = state.lockedUntil ? state.lockedUntil <= now : (state.firstAt + AUTH_LOCK_WINDOW_MS <= now);
if (expired) authAttemptByIp.delete(ip);
}
}
function clearPendingSlashCommand(sessionId, expected) {
const current = pendingSlashCommands.get(sessionId);
if (!current) return;
if (!expected || current === expected) pendingSlashCommands.delete(sessionId);
}
// Pending slash command metadata: sessionId -> { kind: string }
const pendingSlashCommands = new Map();
// Slash commands cache: per-agent discovered commands from CLI init events
const SLASH_COMMAND_DESCRIPTIONS = {
// Webcoding platform commands (server-side handled)
model: '查看/切换模型(Webcoding 平台)',
effort: '查看/切换推理强度(Webcoding 平台)',
thinking: '查看/切换 Pi 思考级别(Webcoding 平台)',
mode: '查看/切换权限模式(Webcoding 平台)',
compact: '压缩上下文(Webcoding 平台)',
'web-help': '显示 Webcoding 平台帮助与已发现的斜杠命令',
// Claude CLI native commands
clear: '清除当前会话(含上下文)',
cost: '查看会话费用/统计',
help: '显示 CLI 帮助',
debug: '调试模式',
simplify: '精简代码',
batch: '批量处理',
review: '代码审查',
'security-review': '安全审查',
init: '初始化项目',
context: '查看上下文',
heapdump: '堆内存快照',
insights: '洞察分析',
goal: '设置目标条件(/goal <条件>)',
usage: '查看用量',
'reload-skills': '重新加载 skills',
run: '运行 skill',
verify: '验证结果',
'team-onboarding': '团队引导',
// Claude skills (user-installed) — descriptions are best-effort; new skills show their raw name
'update-config': '更新配置',
loop: '循环执行',
'claude-api': 'Claude API 开发',
'web-access': '联网访问',
opencli: 'OpenCLI 社交操作',
'frontend-design': '前端设计',
// Claude plugin commands
'claude-hud:setup': '配置 HUD 状态栏',
'claude-hud:configure': '配置 HUD 显示',
'ralph-loop:help': 'Ralph Loop 帮助',
'ralph-loop:cancel-ralph': '取消 Ralph Loop',
'ralph-loop:ralph-loop': '启动 Ralph Loop',
// Codex CLI built-in interactive commands
status: '查看当前模型、审批和 Token 使用量',
fork: '分支当前对话到新线程',
new: '开始新的对话',
feedback: '发送反馈日志给维护者',
mcp: '列出已配置的 MCP 工具',
permissions: '控制 Codex 何时请求确认',
personality: '自定义 Codex 的沟通风格',
rename: '重命名线程',
skills: '列出可用技能',
statusline: '配置状态栏显示内容',
ide: '把当前 IDE 上下文加入下一条提示',
keymap: '配置 TUI 快捷键',
vim: '切换 TUI Vim 编辑模式',
'setup-default-sandbox': '配置 Windows 提升权限沙箱',
'sandbox-add-read-dir': '为 Windows 沙箱增加可读目录',
agent: '切换当前子 Agent 线程',
subagents: '查看或切换子 Agent 线程',
apps: '浏览可用 Apps / Connectors',
plugins: '浏览和管理插件',
hooks: '查看和管理生命周期 Hooks',
archive: '归档当前线程',
delete: '永久删除当前线程',
copy: '复制最近一条 Codex 回复',
diff: '查看当前 Git 变更',
exit: '退出 Codex TUI',
quit: '退出 Codex TUI',
experimental: '配置实验功能',
approve: '重试最近一次被自动审查拒绝的操作',
memories: '配置 Codex Memories',
import: '导入外部 Agent 配置与历史',
logout: '退出 Codex 登录',
mention: '把文件或目录加入下一条提示',
fast: '切换支持模型的 Fast 服务层级',
plan: '切换 Plan 模式',
ps: '查看当前线程的后台终端',
stop: '停止当前线程的后台终端',
app: '在 ChatGPT 桌面应用中继续当前线程',
side: '开启不打断主线程的临时对话',
btw: '开启不打断主线程的临时对话',
raw: '切换 TUI 原始滚动模式',
resume: '恢复已保存的 Codex 线程',
'debug-config': '显示 Codex 配置层与策略诊断',
title: '配置终端窗口标题',
theme: '选择 TUI 代码高亮主题',
pets: '选择或隐藏 TUI Pet',
pet: '选择或隐藏 TUI Pet',
// Codex skills (user-installed) — discovered at runtime from ~/.codex/skills/
imagegen: 'AI 图像生成',
'openai-docs': 'OpenAI 官方文档查询',
'plugin-creator': '创建 Codex 插件',
'skill-creator': '创建 Codex 技能',
'skill-installer': '安装 Codex 技能',
pdf: 'PDF 文件处理',
slides: 'PowerPoint 演示文稿',
spreadsheets: 'Excel 电子表格',
'computer-use': 'macOS 桌面控制',
};
/** Codex slash commands whose interactive TUI surface has no Web/App Server equivalent. */
const CODEX_TUI_ONLY_COMMANDS = new Set([
'ide', 'keymap', 'vim', 'setup-default-sandbox', 'sandbox-add-read-dir',
'agent', 'subagents', 'apps', 'plugins', 'hooks', 'clear', 'archive', 'delete', 'copy', 'diff',
'exit', 'quit', 'experimental', 'approve', 'memories', 'import', 'feedback', 'init', 'logout',
'mcp', 'mention', 'fast', 'plan', 'goal', 'permissions', 'personality', 'ps', 'stop',
'fork', 'new', 'app', 'side', 'btw', 'raw', 'resume', 'rename', 'skills', 'status', 'usage',
'debug-config', 'statusline', 'title', 'theme', 'pets', 'pet',
]);
const CODEX_APP_PLATFORM_COMMANDS = new Set([
'fork', 'new', 'permissions', 'personality', 'rename', 'status', 'usage', 'ps', 'stop',
'mcp', 'skills', 'goal',
]);
const PI_RPC_PLATFORM_COMMANDS = new Set(['fork', 'clone', 'thinking']);
const PI_RPC_PLATFORM_SLASH_COMMANDS = [
{ name: 'fork', desc: '从当前 Pi 活动分支创建新的 Web 会话' },
{ name: 'clone', desc: '复制当前 Pi 活动分支到新的 Web 会话' },
{ name: 'thinking', desc: SLASH_COMMAND_DESCRIPTIONS.thinking },
];
/** Platform-handled slash commands (not CLI passthrough). */
const PLATFORM_SLASH_COMMANDS = [
{ name: 'model', desc: SLASH_COMMAND_DESCRIPTIONS.model },
{ name: 'effort', desc: SLASH_COMMAND_DESCRIPTIONS.effort },
{ name: 'mode', desc: SLASH_COMMAND_DESCRIPTIONS.mode },
{ name: 'compact', desc: SLASH_COMMAND_DESCRIPTIONS.compact },
{ name: 'web-help', desc: SLASH_COMMAND_DESCRIPTIONS['web-help'] },
];
/** Honest labels for Webcoding permission modes (match actual CLI flags). */
const PERMISSION_MODE_META = {
yolo: {
label: 'YOLO',
short: '跳过审批与沙箱限制',
claude: 'Claude: --permission-mode bypassPermissions',
codex: 'Codex: approvalPolicy=never + danger-full-access',
pi: 'Pi: --approve(信任项目本地扩展/技能)',
},
default: {
label: '默认',
short: '受限写入;支持时在网页中请求审批',
claude: 'Claude: 默认权限模式;stream-json 支持网页审批',
codex: 'Codex: App Server on-request + workspace-write',
pi: 'Pi: --no-approve(忽略项目本地文件自动信任)',
},
plan: {
label: 'Plan',
short: '规划/只读模式(按当前 Agent 原生能力映射)',
claude: 'Claude: --permission-mode plan',
codex: 'Codex: Plan 协作模式 + read-only 沙箱',
pi: 'Pi: --tools read,grep,find,ls(只读工具集)',
},
};
function agentDisplayName(agent) {
const normalized = normalizeAgent(agent);
if (normalized === 'codex') return 'Codex';
if (normalized === 'pi') return 'Pi';
return 'Claude';
}
function formatPermissionModeHelp(agent, mode) {
const meta = PERMISSION_MODE_META[mode] || PERMISSION_MODE_META.yolo;
const normalized = normalizeAgent(agent);
const detail = normalized === 'codex'
? meta.codex
: normalized === 'pi'
? meta.pi
: meta.claude;
return `${meta.label} — ${meta.short}\n ${detail}`;
}
const slashCommandsCache = {
claude: { commands: null, discoveredAt: 0 }, // normalized: [{ name, desc }]
codex: { commands: null, discoveredAt: 0 },
pi: { commands: null, discoveredAt: 0 },
};
const CLAUDE_SLASH_DISCOVERY_TTL_MS = 5 * 60 * 1000;
let claudeSlashDiscoveryPromise = null;
function normalizeSlashCommandName(raw) {
if (raw == null) return '';
if (typeof raw === 'object') {
const fromObj = raw.name || raw.command || raw.cmd || raw.id || '';
return normalizeSlashCommandName(fromObj);
}
let name = String(raw).trim();
if (!name) return '';
if (name.startsWith('/')) name = name.slice(1);
// Keep plugin-style names like "claude-hud:setup"
return name;
}
function extractSlashCommandDescription(raw, name) {
if (raw && typeof raw === 'object') {
const fromObj = raw.description || raw.desc || raw.summary || raw.help || '';
if (String(fromObj).trim()) return String(fromObj).trim();
}
if (name && SLASH_COMMAND_DESCRIPTIONS[name]) return SLASH_COMMAND_DESCRIPTIONS[name];
return name || '';
}
/**
* Normalize heterogeneous CLI discovery payloads into { name, desc }[].
* Accepts strings, or objects with name/description fields.
*/
function normalizeDiscoveredSlashCommands(commands) {
if (!Array.isArray(commands)) return [];
const seen = new Set();
const out = [];
for (const raw of commands) {
const name = normalizeSlashCommandName(raw);
if (!name || seen.has(name)) continue;
seen.add(name);
const source = (raw && typeof raw === 'object' && raw.source)
? String(raw.source)
: '';
out.push({
name,
desc: extractSlashCommandDescription(raw, name),
...(source ? { source } : {}),
});
}
return out;
}
function classifySlashCommand(agent, name, sourceHint = '') {
const normalizedAgent = normalizeAgent(agent);
const key = normalizeSlashCommandName(name);
if (!key) {
return { availability: 'unknown', execution: 'passthrough', reason: '' };
}
if (PLATFORM_SLASH_COMMANDS.some((c) => c.name === key)) {
return {
availability: 'platform',
execution: 'platform',
reason: '由 Webcoding 平台处理,不透传 CLI',
};
}
if (
normalizedAgent === 'codex'
&& CODEX_TRANSPORT === 'app-server'
&& CODEX_APP_PLATFORM_COMMANDS.has(key)
) {
return {
availability: 'platform',
execution: 'platform',
reason: '由 Webcoding 通过 Codex App Server 处理',
};
}
if (
normalizedAgent === 'pi'
&& PI_TRANSPORT === 'rpc'
&& PI_RPC_PLATFORM_COMMANDS.has(key)
) {
return {
availability: 'platform',
execution: 'platform',
reason: '由 Webcoding 通过 Pi RPC 处理',
};
}
if (normalizedAgent === 'codex' && CODEX_TUI_ONLY_COMMANDS.has(key)) {
return {
availability: 'tui-only',
execution: 'blocked',
reason: CODEX_TRANSPORT === 'app-server'
? '该命令依赖 Codex 交互式 TUI,当前 App Server 没有等价网页接口'
: '该命令依赖 Codex 交互式 TUI,exec 协议不支持',
};
}
// Custom/unified Codex: if managed runtime cannot see user content, do not advertise as runnable.
if (normalizedAgent === 'codex') {
const source = String(sourceHint || '');
const needsPrompts = source === 'codex-prompts' || key.startsWith('prompts:');
const needsSkills = source === 'codex-skills';
const needsPlugins = source === 'codex-plugin';
if (needsPrompts && !isCodexOverlayMountOk('prompts')) {
return {
availability: 'runtime-unavailable',
execution: 'blocked',
reason: 'Codex custom runtime 未成功挂载 prompts;子进程看不到该命令',
};
}
if (needsSkills && !isCodexOverlayMountOk('skills')) {
return {
availability: 'runtime-unavailable',
execution: 'blocked',
reason: 'Codex custom runtime 未成功挂载 skills;子进程看不到该技能',
};
}
if (needsPlugins && !isCodexOverlayMountOk('plugins')) {
return {
availability: 'runtime-unavailable',
execution: 'blocked',
reason: 'Codex custom runtime 未成功挂载 plugins;子进程看不到该插件命令',
};
}
if (needsPrompts) {
return {
availability: 'passthrough',
execution: 'passthrough',
reason: 'Codex 自定义 prompt(~/.codex/prompts)',
};
}
}
return {
availability: 'passthrough',
execution: 'passthrough',
reason: '',
};
}
function buildSlashCommandList(agent) {
const normalizedAgent = normalizeAgent(agent);
const cache = slashCommandsCache[normalizedAgent];
const cliCommands = (cache && Array.isArray(cache.commands)) ? cache.commands : [];
const defaultCliSource = normalizedAgent === 'claude'
? 'claude-cli'
: normalizedAgent === 'pi'
? 'pi-cli'
: 'codex-cli';
const out = [];
const seen = new Set();
const platformCommands = normalizedAgent === 'pi' && PI_TRANSPORT === 'rpc'
? [...PLATFORM_SLASH_COMMANDS, ...PI_RPC_PLATFORM_SLASH_COMMANDS]
: PLATFORM_SLASH_COMMANDS;
// 1) Platform controls first (always available in Webcoding)
for (const entry of platformCommands) {
const name = entry.name;
if (!name || seen.has(name)) continue;
seen.add(name);
const classified = classifySlashCommand(normalizedAgent, name, 'webcoding');
out.push({
cmd: `/${name}`,
desc: entry.desc || SLASH_COMMAND_DESCRIPTIONS[name] || name,
source: 'webcoding',