cc-viewer 1.9.34 → 1.9.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/cli.js +355 -59
  2. package/dist/assets/{App-CjP88gbM.css → App-BJIeZQK0.css} +1 -1
  3. package/dist/assets/App-C_S65Ygt.js +2 -0
  4. package/dist/assets/{ArchivePreview-dQkBQGgg.js → ArchivePreview-ezRMkut5.js} +1 -1
  5. package/dist/assets/{AudioPreview-B6gJoe0v.js → AudioPreview-MxQVazDj.js} +1 -1
  6. package/dist/assets/{MdxEditorPanel-COJDASLB.js → MdxEditorPanel-CmG2jyvK.js} +1 -1
  7. package/dist/assets/{Mobile-Cq04x2pS.js → Mobile-BerOQqT4.js} +1 -1
  8. package/dist/assets/{ProxyStatsModal-BRtZRf0B.js → ProxyStatsModal-dqlP2r2c.js} +1 -1
  9. package/dist/assets/{SubtitlePreview-C67JiAyR.js → SubtitlePreview-CHRRgV95.js} +1 -1
  10. package/dist/assets/index-DBmXRTLE.js +2 -0
  11. package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +2 -0
  12. package/dist/index.html +1 -1
  13. package/package.json +1 -1
  14. package/server/i18n.js +4 -0
  15. package/server/interceptor.js +114 -25
  16. package/server/lib/anthropic-auth-placeholder.js +147 -0
  17. package/server/lib/continuation-args.js +25 -0
  18. package/server/lib/im/im-bridge-core.js +59 -14
  19. package/server/lib/im/im-permissions.js +48 -0
  20. package/server/lib/im/im-process-manager.js +6 -5
  21. package/server/lib/im-deny.js +4 -1
  22. package/server/lib/interceptor-core.js +51 -0
  23. package/server/lib/proxy-session-registry.js +156 -0
  24. package/server/lib/scheduled-task-executor.js +6 -3
  25. package/server/lib/sdk-manager.js +376 -88
  26. package/server/lib/session-start-bridge.js +7 -1
  27. package/server/lib/update-job.js +3 -3
  28. package/server/lib/v2/session-select.js +18 -2
  29. package/server/lib/v2/v2-writer.js +249 -21
  30. package/server/proxy.js +15 -7
  31. package/server/pty-manager.js +62 -41
  32. package/server/routes/events.js +16 -4
  33. package/server/routes/preferences.js +108 -24
  34. package/server/routes/resume.js +271 -27
  35. package/server/routes/update.js +15 -2
  36. package/server/routes/workspaces.js +112 -29
  37. package/server/server.js +60 -10
  38. package/dist/assets/App-CZ0L1Cvm.js +0 -2
  39. package/dist/assets/index-Cb1Ur9uR.js +0 -2
  40. package/dist/assets/seqResourceLoaders-BQo28rrY.js +0 -2
@@ -0,0 +1,48 @@
1
+ // IM worker 的 permissions.deny 防御层(PTY 与 SDK 两条启动路径共用)。
2
+ //
3
+ // IM worker 恒以 skip-permissions / bypassPermissions 运行,权限安全由三层组成:
4
+ // 1. 发送人白名单(im-bridge-core access control);
5
+ // 2. CCV_IM_DENY=1 的 IM 硬拦截(可靠的执行层):PTY 走 perm-bridge.js 的 settings PreToolUse
6
+ // hook;SDK worker 因子进程剥离 CCV_IM_DENY/CCVIEWER_PORT 使该 settings bridge 休眠,且
7
+ // bypass 下 CLI 不调 canUseTool(CLAUDE_SDK_CAN_USE_TOOL_SHADOWED),故权威层是 sdk-manager
8
+ // 挂载的 in-process PreToolUse hook —— 两条路径共用同一个 evaluateImDeny 纯函数判定;
9
+ // 3. 本文件注入的 permissions.deny —— CLI 侧的 best-effort 纵深防御。
10
+ // 注意:deny 只收紧不放松(优先级最高),不会破坏用户既有 permissions。真正可靠的执行层是第 2 层。
11
+ // 该数组曾是 pty-manager.js 的内联块;SDK worker(runImSdkMode)需要同一份规则,故抽成共享 helper。
12
+ import { homedir } from 'node:os';
13
+
14
+ /**
15
+ * 返回要合并进 per-spawn settings 的对象。仅当 CCV_IM_DENY === '1' 时返回
16
+ * { permissions: { deny: [...] } },否则返回 {}(调用方直接展开即可)。
17
+ */
18
+ export function buildImDenySettings() {
19
+ if (process.env.CCV_IM_DENY !== '1') return {};
20
+ const home = homedir();
21
+ return {
22
+ permissions: {
23
+ deny: [
24
+ 'Bash(sudo:*)', 'Bash(rm -rf:*)', 'Bash(rm -fr:*)',
25
+ 'Bash(git push:*)', 'Bash(npm publish:*)', 'Bash(ssh:*)', 'Bash(scp:*)',
26
+ `Read(${home}/.ssh/**)`, `Edit(${home}/.ssh/**)`, `Write(${home}/.ssh/**)`,
27
+ `Read(${home}/.aws/**)`, `Edit(${home}/.aws/**)`, `Write(${home}/.aws/**)`,
28
+ // File-precise: protect the deny mechanism itself (settings/hooks), the IM
29
+ // credential store (preferences.json), and the credential vault (credentials.json +
30
+ // master.key), but do not block all of ~/.claude — the worker's working directory
31
+ // sits under ~/.claude/cc-viewer/IM_<id>/ and must stay writable.
32
+ `Edit(${home}/.claude/settings.json)`, `Write(${home}/.claude/settings.json)`,
33
+ `Edit(${home}/.claude/settings.local.json)`, `Write(${home}/.claude/settings.local.json)`,
34
+ `Edit(${home}/.claude/cc-viewer/preferences.json)`, `Write(${home}/.claude/cc-viewer/preferences.json)`,
35
+ // preferences.json 现承载定时任务定义(含 prompt);运行历史/旧版任务文件同理拒读拒写。
36
+ `Read(${home}/.claude/cc-viewer/preferences.json)`,
37
+ `Read(${home}/.claude/cc-viewer/scheduled-task-runs.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-task-runs.json)`, `Write(${home}/.claude/cc-viewer/scheduled-task-runs.json)`,
38
+ `Read(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Write(${home}/.claude/cc-viewer/scheduled-tasks.json)`,
39
+ `Read(${home}/.claude/cc-viewer/credentials.json)`, `Edit(${home}/.claude/cc-viewer/credentials.json)`, `Write(${home}/.claude/cc-viewer/credentials.json)`,
40
+ `Read(${home}/.claude/cc-viewer/master.key)`, `Edit(${home}/.claude/cc-viewer/master.key)`, `Write(${home}/.claude/cc-viewer/master.key)`,
41
+ // Backup copies of the vault (cc-viewer-config-backups/<ts>/) hold the same decryption
42
+ // kit (credentials.json + master.key) — deny the whole subtree or an IM worker could read
43
+ // a rolled backup and decrypt every secret.
44
+ `Read(${home}/.claude/cc-viewer-config-backups/**)`, `Edit(${home}/.claude/cc-viewer-config-backups/**)`, `Write(${home}/.claude/cc-viewer-config-backups/**)`,
45
+ ],
46
+ },
47
+ };
48
+ }
@@ -1,9 +1,9 @@
1
1
  // IM 进程管理(父进程侧)—— 由主交互式 ccv 调用,负责把每个启用的 IM 作为 detached 常驻
2
- // 子进程拉起 / 停止 / 查询状态 / 启动时 reconcile。worker 自身(cli.js runImMode)持有 im.lock;
3
- // 本模块只读锁 + 探活 + spawn/kill。
2
+ // 子进程拉起 / 停止 / 查询状态 / 启动时 reconcile。worker 自身(cli.js runImSdkMode / `--im-sdk`,
3
+ // `--im-pty` 为 legacy PTY 排障口)持有 im.lock;本模块只读锁 + 探活 + spawn/kill。
4
4
  //
5
5
  // 设计:detached + unref(主 ccv 关闭后 worker 仍在线);停止时杀**进程组**清理 worker 的
6
- // Claude PTY + proxy 等孙进程;env 用「前缀剥离 + 白名单回填」杜绝 CCV_*/CCVIEWER_* 泄漏。
6
+ // Claude 会话 + proxy 等孙进程;env 用「前缀剥离 + 白名单回填」杜绝 CCV_*/CCVIEWER_* 泄漏。
7
7
  // v1 不做常驻 supervisor(reconcile-on-startup + 配置保存即驱动 已覆盖主路径,且避免多主进程互斗)。
8
8
  import { spawn as nodeSpawn, execSync } from 'node:child_process';
9
9
  import { openSync, closeSync, mkdirSync } from 'node:fs';
@@ -54,7 +54,8 @@ export function buildChildEnv(id, base = process.env) {
54
54
  }
55
55
 
56
56
  /**
57
- * 以 detached 子进程拉起一个 IM worker:`node cli.js --im <id> --no-open`,cwd=IM_<id>/。
57
+ * 以 detached 子进程拉起一个 IM worker:`node cli.js --im-sdk <id> --no-open`,cwd=IM_<id>/。
58
+ * (SDK worker 是默认形态;cli.js 把裸 `--im` 也映射为 SDK,`--im-pty` 为隐藏排障口。)
58
59
  * @param {string} id
59
60
  * @param {{ spawnImpl?: Function }} [opts] 测试可注入 spawnImpl
60
61
  * @returns {{ pid:number|undefined, dir:string, outLog:string }}
@@ -86,7 +87,7 @@ export function spawnImProcess(id, opts = {}) {
86
87
  stdio = ['ignore', fd, fd];
87
88
  } catch { /* 无法开日志文件时退化为 ignore */ }
88
89
 
89
- const child = spawnImpl(resolveNodeBinary(), [CLI_JS, '--im', id, '--no-open'], {
90
+ const child = spawnImpl(resolveNodeBinary(), [CLI_JS, '--im-sdk', id, '--no-open'], {
90
91
  cwd: dir,
91
92
  env: buildChildEnv(id),
92
93
  stdio,
@@ -94,7 +94,10 @@ export function evaluateImDeny(toolName, toolInput = {}, opts = {}) {
94
94
  return { deny: false };
95
95
  }
96
96
 
97
- if (toolName === 'Read') {
97
+ // Read-class tools: Read (file_path), Grep/Glob (path), NotebookRead (notebook_path).
98
+ // Grep/Glob 的 path 指向被读取的目录/文件 —— 否则 `Grep {path:'~/.ssh'}` 会绕过 Read 路径层
99
+ // 把凭证内容读进上下文再随答复外带(review-security P1-3)。复用同一套读取判定。
100
+ if (toolName === 'Read' || toolName === 'Grep' || toolName === 'Glob' || toolName === 'NotebookRead') {
98
101
  const abs = pathOf(toolInput, home);
99
102
  if (!abs) return { deny: false };
100
103
  if (isVaultFile(abs) || isTaskDataFile(abs)) return { deny: true, reason: 'read of the credential vault / master key' };
@@ -751,3 +751,54 @@ export function isValidRoleValue(v, profilesById) {
751
751
  if (typeof v !== 'string' || !v) return false;
752
752
  return !!(profilesById && typeof profilesById.get === 'function' && profilesById.get(v));
753
753
  }
754
+
755
+ // ─── Per-session (per-instanceKey) proxy resolution ───────────────────────────
756
+ // A session binding is { main, roles:{subagent,teammate} } (see
757
+ // lib/proxy-session-registry.js). These pure functions fold a session binding on top
758
+ // of the process-global profile so a request can be rerouted per session. They are
759
+ // the SINGLE source of truth shared by proxy.js (upstream pick) and the interceptor
760
+ // fetch hook (URL/auth/model rewrite) — the two layers must never diverge.
761
+ //
762
+ // mapped === undefined means "this session has no binding" (PTY / ephemeral / an
763
+ // external caller): the request follows the legacy global profile exactly as before.
764
+ // A present binding with main==='max' means the session explicitly chose Default:
765
+ // return null (no rewrite) and DO NOT follow the global profile afterwards.
766
+
767
+ // Resolve a session's effective MAIN profile.
768
+ // sessionEntry: the binding (or undefined when unbound)
769
+ // profilesById: Map<profileId, profile>
770
+ // legacyMain: the process-global effective main profile (_activeProfile)
771
+ export function resolveSessionMainProfile(sessionEntry, profilesById, legacyMain) {
772
+ if (sessionEntry === undefined || sessionEntry === null) return legacyMain || null;
773
+ const main = sessionEntry.main;
774
+ if (main === 'max') return null; // explicit Default
775
+ if (typeof main === 'string' && main) {
776
+ const hit = profilesById && typeof profilesById.get === 'function' ? profilesById.get(main) : undefined;
777
+ return hit || legacyMain || null; // dangling id → fall back to the legacy global
778
+ }
779
+ return legacyMain || null;
780
+ }
781
+
782
+ // Resolve an effective ROLE profile for a session. Precedence:
783
+ // session role explicit id/'max' (per-session role assignment)
784
+ // session role 'follow' → the SESSION's main (so main+subagent stay together)
785
+ // workspace role id/'max' (legacyRoleIds, when the session has no binding/override)
786
+ // legacyMain
787
+ // 'role' is 'main' | 'subagent' | 'teammate'.
788
+ export function resolveSessionRoleProfile(role, sessionEntry, profilesById, legacyMain, legacyRoleIds) {
789
+ const sessionMain = resolveSessionMainProfile(sessionEntry, profilesById, legacyMain);
790
+ if (role === 'main') return sessionMain;
791
+ const sessionRole = sessionEntry && sessionEntry.roles ? sessionEntry.roles[role] : undefined;
792
+ if (typeof sessionRole === 'string' && sessionRole && sessionRole !== 'follow') {
793
+ if (sessionRole === 'max') return null; // explicit Default for this role
794
+ const hit = profilesById && typeof profilesById.get === 'function' ? profilesById.get(sessionRole) : undefined;
795
+ return hit || sessionMain;
796
+ }
797
+ // session role is 'follow'/absent → follow the session main. When the session has NO
798
+ // binding at all, defer to the legacy workspace role assignment (existing behavior).
799
+ if (sessionEntry === undefined || sessionEntry === null) {
800
+ return resolveRoleProfile(role, legacyRoleIds, profilesById, legacyMain);
801
+ }
802
+ return sessionMain;
803
+ }
804
+
@@ -0,0 +1,156 @@
1
+ // Per-session (per SDK instance) proxy binding. Maps an SDK instanceKey to the
2
+ // session's proxy choice ({ main, roles }) so one session's proxy change never
3
+ // leaks into another session sharing the same ccv process.
4
+ //
5
+ // This is intentionally process-local and IN-MEMORY ONLY: bindings are seeded when
6
+ // a session is registered/activated and dropped when it closes or the process stops.
7
+ // Nothing is persisted — a restart simply has no bindings (matches the product
8
+ // requirement that the choice need not survive a restart).
9
+ //
10
+ // Boundary: this is an L1 lib. It must NOT import sdk-manager (that would eagerly
11
+ // load the Agent SDK in PTY mode) or interceptor (an L2 consumer). interceptor
12
+ // registers a global-default provider here; proxy.js and the fetch hook read the
13
+ // per-request override through interceptor, never from sdk-manager directly.
14
+ import { readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { LOG_DIR } from '../../findcc.js';
17
+ import { reportSwallowed } from './error-report.js';
18
+
19
+ const INSTANCE_KEY_RE = /^ccv-[0-9a-f]+$/;
20
+ const MAX_ENTRIES = 1024; // defensive cap: an unbounded map would be a slow leak
21
+
22
+ // instanceKey -> { main: profileId|'max', roles: { subagent, teammate } }
23
+ // 'max' is the explicit "Default" (no rewrite) value and MUST be stored verbatim —
24
+ // an absent mapping means "not bound" (fall back to the process-global profile),
25
+ // which is a different thing from "this session explicitly chose Default".
26
+ const _byInstance = new Map();
27
+
28
+ let _globalDefaultProvider = null;
29
+ // Returns { main, roles } used to SEED a fresh session's binding — the workspace-effective
30
+ // main (getActiveProfileId: workspace override > profile.json.active) and the workspace's
31
+ // stored role assignments, so a seeded session matches the legacy behavior exactly (same
32
+ // upstream as an unbound request AND the same sub/teammate routing).
33
+ let _seedProvider = null;
34
+
35
+ export function isValidInstanceKey(key) {
36
+ return typeof key === 'string' && INSTANCE_KEY_RE.test(key);
37
+ }
38
+
39
+ // interceptor registers the live global-default reader (profile.json.active) here so
40
+ // seeding can resolve the default without this module importing interceptor (L2).
41
+ export function registerGlobalDefaultProvider(fn) {
42
+ _globalDefaultProvider = typeof fn === 'function' ? fn : null;
43
+ }
44
+
45
+ // interceptor registers the workspace-effective seed reader ({ main, roles }).
46
+ export function registerSeedProvider(fn) {
47
+ _seedProvider = typeof fn === 'function' ? fn : null;
48
+ }
49
+
50
+ // The global default profile id: the registered provider first (live value), then a
51
+ // one-off disk read of profile.json.active (so sdk-manager tests / early boot that
52
+ // haven't registered a provider still resolve), then 'max'.
53
+ export function getGlobalDefaultProfileId() {
54
+ if (_globalDefaultProvider) {
55
+ try {
56
+ const v = _globalDefaultProvider();
57
+ if (typeof v === 'string' && v) return v;
58
+ } catch (err) {
59
+ reportSwallowed('proxy-session-registry.defaultProvider', err);
60
+ }
61
+ }
62
+ try {
63
+ const data = JSON.parse(readFileSync(join(LOG_DIR, 'profile.json'), 'utf8'));
64
+ if (typeof data?.active === 'string' && data.active) return data.active;
65
+ } catch { /* missing/corrupt profile.json → fall through to 'max' */ }
66
+ return 'max';
67
+ }
68
+
69
+ // The seed { main, roles } for a fresh session: the registered seed provider first;
70
+ // falls back to the global default main with follow/follow roles.
71
+ function _seedValue() {
72
+ if (_seedProvider) {
73
+ try {
74
+ const v = _seedProvider();
75
+ if (v && typeof v === 'object' && typeof v.main === 'string' && v.main) {
76
+ return {
77
+ main: v.main,
78
+ roles: {
79
+ subagent: typeof v.roles?.subagent === 'string' && v.roles.subagent ? v.roles.subagent : 'follow',
80
+ teammate: typeof v.roles?.teammate === 'string' && v.roles.teammate ? v.roles.teammate : 'follow',
81
+ },
82
+ };
83
+ }
84
+ } catch (err) {
85
+ reportSwallowed('proxy-session-registry.seedProvider', err);
86
+ }
87
+ }
88
+ return { main: getGlobalDefaultProfileId(), roles: { subagent: 'follow', teammate: 'follow' } };
89
+ }
90
+
91
+ export function getSessionProxy(instanceKey) {
92
+ if (!isValidInstanceKey(instanceKey)) return undefined;
93
+ return _byInstance.get(instanceKey);
94
+ }
95
+
96
+ // Overwrite a session's binding (user-driven change). Unknown keys are dropped;
97
+ // 'max' is a valid explicit Default for main and for each role.
98
+ export function setSessionProxyProfile(instanceKey, { main, roles } = {}) {
99
+ if (!isValidInstanceKey(instanceKey)) return false;
100
+ const entry = {
101
+ main: typeof main === 'string' && main ? main : getGlobalDefaultProfileId(),
102
+ roles: {
103
+ subagent: typeof roles?.subagent === 'string' && roles.subagent ? roles.subagent : 'follow',
104
+ teammate: typeof roles?.teammate === 'string' && roles.teammate ? roles.teammate : 'follow',
105
+ },
106
+ };
107
+ if (_byInstance.size >= MAX_ENTRIES && !_byInstance.has(instanceKey)) {
108
+ // Evict the oldest entry (Map preserves insertion order).
109
+ const oldest = _byInstance.keys().next().value;
110
+ _byInstance.delete(oldest);
111
+ }
112
+ _byInstance.set(instanceKey, entry);
113
+ return true;
114
+ }
115
+
116
+ // Seed a session's binding ONLY when none exists yet (a returning/reattached session
117
+ // must never lose the choice the user already made). Seeds from the workspace-effective
118
+ // main + stored roles (via the seed provider) so a fresh session matches legacy behavior.
119
+ export function seedSessionProxyProfile(instanceKey) {
120
+ if (!isValidInstanceKey(instanceKey)) return false;
121
+ if (_byInstance.has(instanceKey)) return false;
122
+ const seed = _seedValue();
123
+ return setSessionProxyProfile(instanceKey, { main: seed.main, roles: seed.roles });
124
+ }
125
+
126
+ export function clearSessionProxyProfile(instanceKey) {
127
+ return _byInstance.delete(instanceKey);
128
+ }
129
+
130
+ export function clearSessionProxyProfiles() {
131
+ _byInstance.clear();
132
+ }
133
+
134
+ // A deleted profile must not leave a dangling binding behind: drop mappings whose
135
+ // main (or a role) points at a profile that no longer exists. 'max' and 'follow'
136
+ // are always valid. Resolution also falls back at read time, so this is belt+braces.
137
+ export function pruneSessionProxyProfiles(validIds) {
138
+ if (!(validIds instanceof Set)) return;
139
+ const valid = (id) => id === 'max' || id === 'follow' || validIds.has(id);
140
+ for (const [key, entry] of _byInstance) {
141
+ if (!valid(entry.main)) { _byInstance.delete(key); continue; }
142
+ if (!valid(entry.roles.subagent)) entry.roles.subagent = 'follow';
143
+ if (!valid(entry.roles.teammate)) entry.roles.teammate = 'follow';
144
+ }
145
+ }
146
+
147
+ export function listSessionProxyProfiles() {
148
+ return [..._byInstance.entries()].map(([instanceKey, v]) => ({ instanceKey, ...v }));
149
+ }
150
+
151
+ export function __resetSessionProxyProfilesForTests() {
152
+ _byInstance.clear();
153
+ // NOTE: providers (_globalDefaultProvider / _seedProvider) are owned by the registrar
154
+ // (interceptor) and intentionally NOT cleared here — clearing them would silently
155
+ // degrade later seeds to the disk fallback within the same process.
156
+ }
@@ -44,9 +44,12 @@ export async function executeScheduledTask(task, claim, io) {
44
44
  async function _injectSdk(task, io) {
45
45
  const sdk = io.sdk;
46
46
  if (!sdk || !sdk.isSdkAvailable()) return { status: 'failed', reason: 'sdk_unavailable' };
47
- // The resident session is a per-cwd singleton — find the one for the task's cwd.
48
- const target = sdk.listSdkSessions().find(s => io.samePath(s.cwd, task.cwd));
49
- if (!target) return { status: 'failed', reason: 'no_live_session' };
47
+ // A cwd may host several same-cwd sibling sessions (multi-instance, 2026-11): pick the
48
+ // ACTIVE one when it lives in this cwd, else the deterministic (non-fresh) primary, else
49
+ // the most recent — never just the first-registered.
50
+ const matches = sdk.listSdkSessions().filter(s => io.samePath(s.cwd, task.cwd));
51
+ if (!matches.length) return { status: 'failed', reason: 'no_live_session' };
52
+ const target = matches.find(s => s.active) || matches.find(s => s.isFreshKey === false) || matches[matches.length - 1];
50
53
 
51
54
  // Queue-full precheck (P1-4): _sendUserMessage resolves normally even when the queue
52
55
  // rejects the message (broadcasts queue-rejected and returns), so a dispatched verdict