cc-viewer 1.9.31 → 1.9.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  // 整体显示大小已弃用 CSS zoom:Electron 改用 webFrame.setZoomFactor(首屏抢占见
22
22
  // electron/tab-content-preload.js),纯浏览器交由用户用浏览器自带快捷键缩放,故此处不再设 zoom。
23
23
  </script>
24
- <script type="module" crossorigin src="./assets/index-CRRKIWWQ.js"></script>
24
+ <script type="module" crossorigin src="./assets/index-BQAck4ag.js"></script>
25
25
  <link rel="modulepreload" crossorigin href="./assets/vendor-antd-C5Wsfsxn.js">
26
26
  <link rel="modulepreload" crossorigin href="./assets/vendor-codemirror-DPXDhteu.js">
27
27
  <link rel="modulepreload" crossorigin href="./assets/vendor-mdxeditor-DLPCj_fe.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.31",
3
+ "version": "1.9.33",
4
4
  "description": "Claude Code logging, visualization, and management toolkit — launch a web viewer alongside Claude Code with full request/response tracing, proxy, and mobile support",
5
5
  "license": "MIT",
6
6
  "main": "server.js",
@@ -0,0 +1,29 @@
1
+ // ACCESS_TOKEN handoff contract shared by server.js (consumer) and lib/restart.js
2
+ // (producer). This module is itself dependency-free so the detached restart-helper.js
3
+ // process (which loads lib/restart.js) can import it cheaply, with no server graph.
4
+ // INTERNAL handoff channel only — NOT a supported user setting. takeInheritedAccessToken
5
+ // trusts any well-shaped value in this var, so exporting it in a shell would pin the LAN
6
+ // token across manual starts (defeating per-boot rotation). Set only by the restart helper.
7
+ export const ACCESS_TOKEN_ENV = 'CCV_ACCESS_TOKEN';
8
+ // Exact shape of the token server.js generates: randomBytes(16).toString('hex').
9
+ export const ACCESS_TOKEN_RE = /^[a-f0-9]{32}$/;
10
+
11
+ /** Single source of truth for "is this value a well-formed ACCESS_TOKEN?" — shared by the
12
+ * producer (lib/restart.js write/spawn sides) and the consumer (takeInheritedAccessToken)
13
+ * so the shape rule can never drift between the two ends of the handoff. */
14
+ export function isValidAccessToken(value) {
15
+ return typeof value === 'string' && ACCESS_TOKEN_RE.test(value);
16
+ }
17
+
18
+ /**
19
+ * Read-and-strip the self-update handoff token from `env` (default process.env).
20
+ * Destructive by design: the value must not survive into children spawned later
21
+ * (the claude PTY/SDK process, shells). Malformed or absent values return null so
22
+ * the caller falls back to a fresh random token.
23
+ */
24
+ export function takeInheritedAccessToken(env = process.env) {
25
+ if (!env || typeof env !== 'object') return null;
26
+ const raw = env[ACCESS_TOKEN_ENV];
27
+ try { delete env[ACCESS_TOKEN_ENV]; } catch { /* frozen env object */ }
28
+ return isValidAccessToken(raw) ? raw : null;
29
+ }
@@ -1,7 +1,8 @@
1
1
  // Password-based LAN auth — pure logic, heavily unit-tested.
2
2
  //
3
3
  // cc-viewer's original LAN gate is URL `?token=<32-hex>` (server.js ACCESS_TOKEN,
4
- // random per boot, never persisted). This module adds an OPTIONAL second path:
4
+ // random per boot — preserved only across an in-app self-update restart via the
5
+ // restart handoff — never persisted). This module adds an OPTIONAL second path:
5
6
  // a password that, once verified, is stored in a cookie (value = ACCESS_TOKEN).
6
7
  // Both paths coexist — token and cookie are equivalent.
7
8
  //
@@ -0,0 +1,68 @@
1
+ // Shared directory-listing sort comparator. Used by /api/files (project view)
2
+ // and /api/target-files (CLAUDE.md / skill / memory browser). Pure functions
3
+ // so the rules can be unit-tested without a server.
4
+ //
5
+ // Ordering contract:
6
+ // - directories always come before files (regardless of the requested key);
7
+ // - null / non-finite metric values (stat failure, directories' size) sort
8
+ // AFTER real values;
9
+ // - `name` is the stable tie-breaker so re-sorting the same listing is
10
+ // deterministic;
11
+ // - `order` reverses only the metric comparison, not the directory-first
12
+ // rule (directories stay on top even in desc).
13
+
14
+ const SORT_KEYS = new Set(['name', 'size', 'mtime']);
15
+ const ORDERS = new Set(['asc', 'desc']);
16
+
17
+ export function normalizeSortParams(searchParams) {
18
+ const sortRaw = (searchParams && searchParams.get && searchParams.get('sort')) || '';
19
+ const orderRaw = (searchParams && searchParams.get && searchParams.get('order')) || '';
20
+ const sort = SORT_KEYS.has(sortRaw) ? sortRaw : 'name';
21
+ const order = ORDERS.has(orderRaw) ? orderRaw : 'asc';
22
+ return { sort, order };
23
+ }
24
+
25
+ function compareName(a, b) {
26
+ return String(a.name).localeCompare(String(b.name));
27
+ }
28
+
29
+ // `sort` is one of 'name' | 'size' | 'mtime'; `order` is 'asc' | 'desc'.
30
+ // Ordering rules:
31
+ // - Directories always rank before files (order does not flip this).
32
+ // - Within each kind, the metric (or name) is reversed when order is desc —
33
+ // matching the file-manager convention the user expects when clicking a
34
+ // column header twice. The sidebar tree never sends a sort param, so the
35
+ // tree's listing always stays in name-asc via the default call; the grid's
36
+ // non-default sort is isolated under its own cache key (see
37
+ // fileBrowserPrefs.dirCacheKey).
38
+ // - Null / non-finite metrics always rank last (never flipped by order),
39
+ // with name as tie-breaker.
40
+ export function compareEntries(sort, order) {
41
+ const metricKey = sort === 'mtime' ? 'mtimeMs' : sort;
42
+ const desc = order === 'desc';
43
+ return (a, b) => {
44
+ const aDir = a.type === 'directory';
45
+ const bDir = b.type === 'directory';
46
+ if (aDir !== bDir) return aDir ? -1 : 1;
47
+ if (aDir) {
48
+ const cmp = compareName(a, b);
49
+ return desc ? -cmp : cmp;
50
+ }
51
+ if (sort === 'name') {
52
+ const cmp = compareName(a, b);
53
+ return desc ? -cmp : cmp;
54
+ }
55
+ // Files: nulls last, then metric asc/desc, then name asc.
56
+ const aNum = typeof a[metricKey] === 'number' && Number.isFinite(a[metricKey]);
57
+ const bNum = typeof b[metricKey] === 'number' && Number.isFinite(b[metricKey]);
58
+ if (aNum && bNum) {
59
+ const av = a[metricKey];
60
+ const bv = b[metricKey];
61
+ if (av !== bv) return desc ? bv - av : av - bv;
62
+ return compareName(a, b);
63
+ }
64
+ if (aNum) return -1;
65
+ if (bNum) return 1;
66
+ return compareName(a, b);
67
+ };
68
+ }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
3
3
  import { dirname } from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { restartFromHelper, waitForExit } from './restart.js';
@@ -13,10 +13,23 @@ process.stderr.on('error', () => {});
13
13
  export async function runRestartHelper({ stateFile = process.argv[2], configFile = process.argv[3], config, install = installStagedUpdate, restart = restartFromHelper, log = console.error } = {}) {
14
14
  let staged;
15
15
  try {
16
- config ||= readRestartConfig(configFile);
16
+ // Read the config in its own try/catch: it now carries the live ACCESS_TOKEN, and a raw
17
+ // JSON.parse error message can embed a ~20-char snippet of the offending input — which
18
+ // would then be persisted to update-state.json.error and logged. Rethrow a fixed message.
19
+ if (!config) {
20
+ try { config = readRestartConfig(configFile); }
21
+ catch { throw new Error('Invalid restart config'); }
22
+ }
17
23
  if (!Number.isInteger(config.pid) || config.pid <= 0 || !Array.isArray(config.args) || typeof config.cwd !== 'string' || typeof config.cliPath !== 'string' || !/^\d+\.\d+\.\d+$/.test(config.version)) throw new Error('Invalid arguments');
18
24
  staged = JSON.parse(readFileSync(stateFile, 'utf8'));
19
25
  if (staged.version !== config.version) throw new Error('Staged update does not match the requested version');
26
+ // The config now carries the live ACCESS_TOKEN handoff — erase the file as soon
27
+ // as it has been read into memory. The finally-block rm stays as the safety net,
28
+ // and the in-memory `config` still backs the install-failure restore path below.
29
+ if (configFile) {
30
+ try { rmSync(configFile, { force: true }); }
31
+ catch (err) { log(`[CC Viewer] Failed to remove restart config (holds the access token): ${err.message}`); }
32
+ }
20
33
  mkdirSync(dirname(RESTART_READY_FILE), { recursive: true, mode: 0o700 });
21
34
  writeFileSync(RESTART_READY_FILE, JSON.stringify({ token: config.token }), { mode: 0o600 });
22
35
  await waitForExit(config.pid);
@@ -52,7 +65,8 @@ export async function runRestartHelper({ stateFile = process.argv[2], configFile
52
65
  } finally {
53
66
  if (configFile) {
54
67
  const { rm } = await import('node:fs/promises');
55
- await rm(configFile, { force: true }).catch(() => {});
68
+ // Best-effort safety net; the file may hold the live token, so surface a failure.
69
+ await rm(configFile, { force: true }).catch((err) => log(`[CC Viewer] Failed to clean up restart config: ${err.message}`));
56
70
  }
57
71
  }
58
72
  }
@@ -4,17 +4,23 @@ import { randomUUID } from 'node:crypto';
4
4
  import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
5
5
  import { dirname } from 'node:path';
6
6
  import { isPidAlive } from './pid-alive.js';
7
+ import { ACCESS_TOKEN_ENV, isValidAccessToken } from './access-token.js';
7
8
  import { UPDATE_STATE_FILE, RESTART_CONFIG_FILE, RESTART_READY_FILE } from './update-job.js';
8
9
 
9
10
  export const RESTART_HELPER_PATH = fileURLToPath(new URL('./restart-helper.js', import.meta.url));
10
11
 
11
- export async function launchRestart({ pid = process.pid, args, cwd, version, cliPath, spawnImpl = spawn, timeoutMs = 5000 } = {}) {
12
+ export async function launchRestart({ pid = process.pid, args, cwd, version, cliPath, accessToken, spawnImpl = spawn, timeoutMs = 5000 } = {}) {
12
13
  if (!Number.isInteger(pid) || pid <= 0 || !Array.isArray(args) || typeof cwd !== 'string' || typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version) || typeof cliPath !== 'string') {
13
14
  throw new Error('Invalid restart configuration');
14
15
  }
15
16
  const token = randomUUID();
17
+ // accessToken = the CURRENT ACCESS_TOKEN (the LAN gate), forwarded so the
18
+ // replacement accepts the token an already-open page is still using. Omitted
19
+ // when absent/malformed — never throws, a bad handoff must not block an update.
20
+ const config = { pid, args, cwd, version, cliPath, token };
21
+ if (isValidAccessToken(accessToken)) config.accessToken = accessToken;
16
22
  await mkdir(dirname(RESTART_CONFIG_FILE), { recursive: true, mode: 0o700 });
17
- await writeFile(RESTART_CONFIG_FILE, JSON.stringify({ pid, args, cwd, version, cliPath, token }), { mode: 0o600 });
23
+ await writeFile(RESTART_CONFIG_FILE, JSON.stringify(config), { mode: 0o600 });
18
24
  await rm(RESTART_READY_FILE, { force: true });
19
25
  let child;
20
26
  try {
@@ -72,7 +78,12 @@ export async function waitForExit(pid, { alive = isPidAlive, sleep = (ms) => new
72
78
 
73
79
  export async function restartFromHelper(config, { spawnImpl = spawn, wait = waitForExit } = {}) {
74
80
  await wait(config.pid);
75
- const child = spawnImpl(process.execPath, [config.cliPath, ...config.args], { cwd: config.cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: false, env: { ...process.env, CCV_NO_OPEN: '1' } });
81
+ const env = { ...process.env, CCV_NO_OPEN: '1' };
82
+ // Forward the previous ACCESS_TOKEN so the replacement accepts the token an
83
+ // already-open page is still using; drop any stale handoff when none is valid.
84
+ if (isValidAccessToken(config.accessToken)) env[ACCESS_TOKEN_ENV] = config.accessToken;
85
+ else delete env[ACCESS_TOKEN_ENV];
86
+ const child = spawnImpl(process.execPath, [config.cliPath, ...config.args], { cwd: config.cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: false, env });
76
87
  child.stdout?.on('data', (chunk) => { try { process.stdout.write(chunk); } catch { } });
77
88
  child.stderr?.on('data', (chunk) => { try { process.stderr.write(chunk); } catch { } });
78
89
  console.error(`[CC Viewer] Restarted in the background with PID ${child.pid}. Stop it with: kill ${child.pid}`);
@@ -16,6 +16,7 @@ import { getClaudeConfigDir } from '../../findcc.js';
16
16
  import { _projectName } from '../interceptor.js';
17
17
  import { isAdminReq } from '../lib/is-admin.js';
18
18
  import { isSameOriginBrowserRequest } from '../lib/same-origin.js';
19
+ import { normalizeSortParams, compareEntries } from '../lib/file-sort.js';
19
20
  import {
20
21
  targetError, errnoToStatus, realDirectory, checkedDirectory, insidePath,
21
22
  targetRelPath, resolveTargetRoot,
@@ -773,7 +774,7 @@ function fileContentPost(req, res, parsedUrl, isLocal) {
773
774
  });
774
775
  }
775
776
 
776
- function listTargetDirectory(rootReal, segments, deps, requireReadable = true) {
777
+ function listTargetDirectory(rootReal, segments, deps, requireReadable = true, sortOpts = null) {
777
778
  const dirReal = requireReadable
778
779
  ? checkedDirectory(segments.length ? join(rootReal, ...segments) : rootReal, 'Directory')
779
780
  : realDirectory(segments.length ? join(rootReal, ...segments) : rootReal, 'Directory');
@@ -806,11 +807,19 @@ function listTargetDirectory(rootReal, segments, deps, requireReadable = true) {
806
807
  let st;
807
808
  try { st = statSync(policy.real); } catch (err) { reportSwallowed('targetFiles.entry.stat', err); continue; }
808
809
  if (!st.isDirectory() && !st.isFile()) continue;
809
- entries.push({ name: entry.name, type: st.isDirectory() ? 'directory' : 'file', absPath: policy.real });
810
+ const type = st.isDirectory() ? 'directory' : 'file';
811
+ entries.push({
812
+ name: entry.name,
813
+ type,
814
+ absPath: policy.real,
815
+ size: type === 'file' ? st.size : null,
816
+ mtimeMs: st.mtimeMs,
817
+ });
810
818
  }
811
- entries.sort((a, b) => a.type !== b.type
812
- ? (a.type === 'directory' ? -1 : 1)
813
- : a.name.localeCompare(b.name));
819
+ const cmp = sortOpts
820
+ ? compareEntries(sortOpts.sort, sortOpts.order)
821
+ : compareEntries('name', 'asc');
822
+ entries.sort(cmp);
814
823
  return entries;
815
824
  }
816
825
 
@@ -832,9 +841,14 @@ function targetFiles(req, res, parsedUrl, isLocal, deps) {
832
841
  const rawPath = parsedUrl.searchParams.get('path');
833
842
  const requestedSegments = targetRelPath(rawPath);
834
843
  const segments = requestedSegments === null ? scope.targetPath.split('/').filter(Boolean) : requestedSegments;
835
- const entries = listTargetDirectory(scope.rootReal, segments, deps, segments.length > 0 || scope.rootKind !== 'home');
844
+ // Optional ?sort=name|size|mtime&order=asc|desc. The primary listing (the
845
+ // grid the user is looking at) honors the requested order; the ancestors
846
+ // chain — which the sidebar tree reads — is always name/asc so the tree
847
+ // order stays stable across user-driven grid re-sorts.
848
+ const sortOpts = normalizeSortParams(parsedUrl.searchParams);
849
+ const entries = listTargetDirectory(scope.rootReal, segments, deps, segments.length > 0 || scope.rootKind !== 'home', sortOpts);
836
850
  const rootEntries = requestedSegments === null && segments.length > 0
837
- ? listTargetDirectory(scope.rootReal, [], deps, scope.rootKind === 'project')
851
+ ? listTargetDirectory(scope.rootReal, [], deps, scope.rootKind === 'project', sortOpts)
838
852
  : entries;
839
853
  const targetEntries = requestedSegments === null
840
854
  ? entries.filter(entry => insidePath(entry.absPath, join(scope.rootReal, ...segments)))
@@ -847,7 +861,8 @@ function targetFiles(req, res, parsedUrl, isLocal, deps) {
847
861
  // segments. We deliberately DO NOT use path.relative(targetPath, rawPath)
848
862
  // here — that helper happily produces "../.." for sibling branches, which
849
863
  // would pollute the cache with pseudo-paths and re-list directories the
850
- // user never navigated into.
864
+ // user never navigated into. Ancestors always list in default name/asc so
865
+ // the tree row order stays stable while the grid applies user sorting.
851
866
  const chainSegments = requestedSegments === null ? targetSegments : segments;
852
867
  // Request-scoped memo: targetFiles lists the same directory multiple times
853
868
  // (entries + ancestors chain often share prefixes), so we cache by dir key
@@ -855,7 +870,7 @@ function targetFiles(req, res, parsedUrl, isLocal, deps) {
855
870
  const listMemo = new Map();
856
871
  const listOnce = (segs, requireReadable) => {
857
872
  const key = segs.join('/') + (requireReadable ? '|r' : '|n');
858
- if (!listMemo.has(key)) listMemo.set(key, listTargetDirectory(scope.rootReal, segs, deps, requireReadable));
873
+ if (!listMemo.has(key)) listMemo.set(key, listTargetDirectory(scope.rootReal, segs, deps, requireReadable, null));
859
874
  return listMemo.get(key);
860
875
  };
861
876
  const ancestorCount = Math.max(0, chainSegments.length - (requestedSegments === null ? 0 : 1));
@@ -8,7 +8,10 @@ import { homedir, tmpdir } from 'node:os';
8
8
  import { execFile } from 'node:child_process';
9
9
  import { bumpWorkspacesVersion, isReadAllowed } from '../lib/file-access-policy.js';
10
10
  import { isPathContained, validateImportDir, renameSyncWithRetry } from '../lib/file-api.js';
11
+ import { normalizeSortParams, compareEntries } from '../lib/file-sort.js';
11
12
  import { reportSwallowed } from '../lib/error-report.js';
13
+ import { isAdminReq } from '../lib/is-admin.js';
14
+ import { isSameOriginBrowserRequest } from '../lib/same-origin.js';
12
15
  import { viewRootOrReply } from '../lib/view-root.js';
13
16
  import { revealInOs, openTerminalAt } from '../lib/os-open.js';
14
17
  import { loadWorkspaces } from '../workspace-registry.js';
@@ -290,26 +293,44 @@ async function files(req, res, parsedUrl, isLocal, deps) {
290
293
  const cwd = _viewRootOrReply(req, res, parsedUrl);
291
294
  if (!cwd) return;
292
295
  const targetDir = join(cwd, reqPath);
296
+ // Address-bar / list-view / sort-driven listings all read sort+order here.
297
+ // Defaults preserve the historical "directories first, name asc" behavior.
298
+ const { sort, order } = normalizeSortParams(parsedUrl.searchParams);
293
299
  try {
294
300
  const entries = readdirSync(targetDir, { withFileTypes: true });
295
301
  const items = entries
296
302
  .filter(e => !deps.IGNORED_PATTERNS.has(e.name))
297
303
  .map(e => {
298
- // Dirent.isDirectory() 不解引用 symlink —— 对指向目录的 symlink 也返回 false。
299
- // 需要对 symlink 单独 statSync(follow link)才能拿到真实类型,否则前端会把
300
- // symlink-to-dir 当成文件渲染,不可展开。断链时 fallback 到 file,避免单个
301
- // 坏链接让整个目录返回 404。
304
+ // Dirent.isDirectory() does not dereference symlinks — a symlink pointing
305
+ // at a directory also returns false. A symlink needs its own statSync
306
+ // (following the link) to learn the real type, otherwise the client would
307
+ // render a symlink-to-dir as a file and refuse to expand it. Broken links
308
+ // fall back to 'file' so one bad entry cannot 404 the whole listing.
309
+ // Files and directories take their size/mtimeMs from the same stat call,
310
+ // avoiding a second syscall for symlinks.
302
311
  let type = e.isDirectory() ? 'directory' : 'file';
312
+ let stat = null;
303
313
  if (e.isSymbolicLink()) {
304
- try { type = statSync(join(targetDir, e.name)).isDirectory() ? 'directory' : 'file'; }
314
+ try {
315
+ stat = statSync(join(targetDir, e.name));
316
+ type = stat.isDirectory() ? 'directory' : 'file';
317
+ }
305
318
  catch { type = 'file'; }
319
+ } else {
320
+ // Always stat so the list view and size/mtime sorts have data. A
321
+ // single failing entry must not 404 the whole listing — degrade to
322
+ // null metrics instead (broken symlink, EACCES race, etc.).
323
+ try { stat = statSync(join(targetDir, e.name)); }
324
+ catch (err) { if (err && err.code !== 'ENOENT') reportSwallowed('filesFs.entry.stat', err); }
306
325
  }
307
- return { name: e.name, type };
326
+ return {
327
+ name: e.name,
328
+ type,
329
+ size: stat && type === 'file' ? stat.size : null,
330
+ mtimeMs: stat ? stat.mtimeMs : null,
331
+ };
308
332
  })
309
- .sort((a, b) => {
310
- if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
311
- return a.name.localeCompare(b.name);
312
- });
333
+ .sort(compareEntries(sort, order));
313
334
  // 使用 git check-ignore 批量检测被 .gitignore 忽略的文件
314
335
  let gitIgnoredSet = new Set();
315
336
  try {
@@ -727,17 +748,59 @@ function resolvePath(req, res, parsedUrl, isLocal, deps) {
727
748
  return;
728
749
  }
729
750
  try {
751
+ const cwd = _viewRootOrReply(req, res, parsedUrl, parsed.project, parsed.instance);
752
+ if (!cwd) return;
753
+ // Address-bar absolute path branch: { absolutePath } resolves a host
754
+ // absolute path against the viewed root and returns the project-relative
755
+ // relPath the browser navigates with. The existing { path } branch is
756
+ // unchanged (pure string join; never stats, never rejects missing paths).
757
+ if (typeof parsed.absolutePath === 'string') {
758
+ // SECURITY: the absolute branch is a host-filesystem existence oracle
759
+ // (it stats the path and distinguishes 404 / 400-outside / 403-EACCES).
760
+ // Hold it to the same bar as /api/target-resolve-path — admin + a
761
+ // same-origin browser request — because the global
762
+ // Access-Control-Allow-Origin: * would otherwise let any web page
763
+ // probe the loopback server for arbitrary host paths.
764
+ if (!isAdminReq(req, isLocal) || !isSameOriginBrowserRequest(req, parsedUrl)) {
765
+ res.writeHead(403, { 'Content-Type': 'application/json' });
766
+ res.end(JSON.stringify({ error: 'forbidden' }));
767
+ return;
768
+ }
769
+ const abs = parsed.absolutePath;
770
+ if (abs.length === 0 || abs.length > 4096 || /[\x00-\x1f]/.test(abs) || !isAbsoluteHostPath(abs)) {
771
+ res.writeHead(400, { 'Content-Type': 'application/json' });
772
+ res.end(JSON.stringify({ error: 'Invalid path' }));
773
+ return;
774
+ }
775
+ let real;
776
+ // realpathSync.native returns the on-disk casing on case-insensitive
777
+ // filesystems (macOS APFS / Windows NTFS); the JS implementation keeps
778
+ // the input casing, which would make the containment check below
779
+ // reject legitimate in-root paths spelled with different casing.
780
+ try { real = realpathSync.native(abs); } catch (err) {
781
+ const status = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
782
+ res.writeHead(status, { 'Content-Type': 'application/json' });
783
+ res.end(JSON.stringify({ error: status === 404 ? 'Path not found' : 'Invalid path' }));
784
+ return;
785
+ }
786
+ const realCwd = realpathSync.native(cwd);
787
+ if (real !== realCwd && !real.startsWith(realCwd + sep)) {
788
+ res.writeHead(400, { 'Content-Type': 'application/json' });
789
+ res.end(JSON.stringify({ error: 'Path traversal not allowed' }));
790
+ return;
791
+ }
792
+ const st = statSync(real);
793
+ const relPath = real === realCwd ? '' : real.slice(realCwd.length + 1).split(sep).join('/');
794
+ res.writeHead(200, { 'Content-Type': 'application/json' });
795
+ res.end(JSON.stringify({ ok: true, fullPath: real, relPath, type: st.isDirectory() ? 'directory' : 'file' }));
796
+ return;
797
+ }
730
798
  const relPath = parsed.path || '';
731
799
  if (relPath.startsWith('/') || relPath.includes('..')) {
732
800
  res.writeHead(400, { 'Content-Type': 'application/json' });
733
801
  res.end(JSON.stringify({ error: 'Invalid path' }));
734
802
  return;
735
803
  }
736
- // Resolve a project-relative path against the same viewed root used by
737
- // reveal/open. Registered projects and live instances use the shared
738
- // resolver, so same-name projects cannot silently fall back to the bound cwd.
739
- const cwd = _viewRootOrReply(req, res, parsedUrl, parsed.project, parsed.instance);
740
- if (!cwd) return;
741
804
  const fullPath = relPath ? join(cwd, relPath) : cwd;
742
805
  res.writeHead(200, { 'Content-Type': 'application/json' });
743
806
  res.end(JSON.stringify({ ok: true, fullPath }));
@@ -748,6 +811,13 @@ function resolvePath(req, res, parsedUrl, isLocal, deps) {
748
811
  });
749
812
  }
750
813
 
814
+ // Host-absolute path probe for the address-bar branch above: POSIX (/foo) and
815
+ // Windows drive-letter (C:\foo / C:/foo) spellings. UNC (\\server\share) is
816
+ // refused — the browser has no business resolving network shares.
817
+ function isAbsoluteHostPath(p) {
818
+ return p.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(p);
819
+ }
820
+
751
821
  // Lightweight existence probe for the chat markdown code-span feature: the web
752
822
  // client batches path-looking inline code spans here and only renders them
753
823
  // clickable when the file provably exists. Uniform {exists:false} for every
@@ -180,6 +180,36 @@ function targetOpenTerminal(req, res, parsedUrl, isLocal, deps) {
180
180
  // ─── resolve to absolute path (for copy-path / attach-to-chat) ──────────────
181
181
  function targetResolvePath(req, res, parsedUrl, isLocal, deps) {
182
182
  withBody(req, res, parsedUrl, isLocal, deps, (parsed, scope) => {
183
+ // Address-bar absolute path branch: resolve a host absolute path against
184
+ // the navigation root, returning the navigation-root-relative relPath the
185
+ // browser navigates with. Existing { path } behavior is unchanged.
186
+ if (typeof parsed.absolutePath === 'string') {
187
+ const abs = parsed.absolutePath;
188
+ const isAbs = abs.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(abs);
189
+ if (!abs || abs.length > 4096 || /[\x00-\x1f]/.test(abs) || !isAbs) {
190
+ throw targetError(400, 'Invalid path');
191
+ }
192
+ let real;
193
+ // realpathSync.native returns the on-disk casing on case-insensitive
194
+ // filesystems (macOS APFS / Windows NTFS), matching how scope.rootReal
195
+ // was derived; the JS implementation would keep the input casing and
196
+ // make the containment check below reject legitimate in-root paths.
197
+ try { real = realpathSync.native(abs); } catch (err) { throw targetError(errnoToStatus(err), 'Path not found'); }
198
+ if (!insidePath(real, scope.rootReal)) throw targetError(403, 'Path outside navigation root');
199
+ // Match the read route's policy backstop (listTargetDirectory filters
200
+ // each entry through isReadAllowed): the resolve endpoint must not
201
+ // become an existence/type oracle for read-denied paths like ~/.ssh.
202
+ // The navigation root itself is exempt — it is already the user's
203
+ // visible anchor and may live outside the read-allowlist roots.
204
+ if (real !== scope.rootReal) {
205
+ const policy = isReadAllowed(real);
206
+ if (!policy.ok) throw targetError(403, 'Path not allowed');
207
+ }
208
+ const st = statSync(real);
209
+ const rel = real === scope.rootReal ? '' : real.slice(scope.rootReal.length + 1).split(/[\\/]/).join('/');
210
+ send(res, 200, { ok: true, fullPath: real, relPath: rel, type: st.isDirectory() ? 'directory' : 'file' });
211
+ return;
212
+ }
183
213
  const segments = parsed.path ? requiredTargetRelPath(parsed.path) : [];
184
214
  const full = segments.length ? join(scope.rootReal, ...segments) : scope.rootReal;
185
215
  send(res, 200, { ok: true, fullPath: full });
package/server/server.js CHANGED
@@ -55,6 +55,7 @@ import * as imCore from './lib/im/im-bridge-core.js';
55
55
  import * as imProcMgr from './lib/im/im-process-manager.js';
56
56
  import * as chatQueue from './lib/chat-queue.js';
57
57
  import { reportSwallowed } from './lib/error-report.js';
58
+ import { takeInheritedAccessToken } from './lib/access-token.js';
58
59
  import { cancelAutoApproveState } from './lib/auto-approve.js';
59
60
  import { cancelAskAutoAnswerState, replayAskAutoAnswerFields } from './lib/ask-auto-answer.js';
60
61
  import { initScheduledTaskScheduler, startScheduledTaskScheduler, stopScheduledTaskScheduler } from './lib/scheduled-task-scheduler.js';
@@ -407,8 +408,15 @@ const MAX_PORT = parseInt(process.env.CCV_MAX_PORT) || 7049;
407
408
  // 主进程默认仍绑 0.0.0.0 以支持手机/局域网访问。
408
409
  const HOST = process.env.CCV_HOST || '0.0.0.0';
409
410
 
410
- // 局域网访问 token(本地 127.0.0.1 免验证)
411
- const ACCESS_TOKEN = randomBytes(16).toString('hex');
411
+ // 局域网访问 token(本地 127.0.0.1 免验证)。
412
+ // Self-update handoff: the restart helper passes the previous boot's token via
413
+ // CCV_ACCESS_TOKEN so an already-open page (?token= URL, /api/version-info poll,
414
+ // ccv_auth cookie) keeps working across the in-app restart. Consumed-and-deleted
415
+ // at module evaluation, trusted only in the exact shape this server generates;
416
+ // absent/malformed falls back to a fresh random token. Never stored in
417
+ // preferences.json — only handed transiently through restart-config.json on an
418
+ // in-app self-update — and still rotated on a manual restart.
419
+ const ACCESS_TOKEN = takeInheritedAccessToken() || randomBytes(16).toString('hex');
412
420
  // Internal token used ONLY for bridge → server calls (env-leaked to the spawned
413
421
  // claude process via pty-manager). Separate from ACCESS_TOKEN so the LAN URL
414
422
  // token can't double as a bridge auth bypass for same-host CSRF (round-3 P1).
@@ -436,8 +444,9 @@ if (process.env.CCV_USE_PASSWORD === '1') {
436
444
  saveAuthConfig({ enabled: true, password }, { scope, projectDir: AUTH_PROJECT });
437
445
  authConfig = loadAuthConfig(AUTH_PROJECT);
438
446
  }
439
- // 钩子已消费完毕:清掉这两个 env,避免明文密码随 {...process.env} 泄漏进 spawn 出的 Claude 子进程
440
- // (与刻意不把 ACCESS_TOKEN 放进 env 的策略一致)。此后无人再读它们(仅上面这段读取)。
447
+ // 钩子已消费完毕:清掉这两个 env,避免明文密码随 {...process.env} 泄漏进 spawn 出的 Claude 子进程。
448
+ // ACCESS_TOKEN 同理:自更新交接用的 CCV_ACCESS_TOKEN 已在上面 takeInheritedAccessToken() 读取即删除,
449
+ // 此后运行期进程 env 中不再保留该 token,spawn 出的 Claude 子进程也拿不到。此后无人再读它们(仅上面这段读取)。
441
450
  delete process.env.CCV_USE_PASSWORD;
442
451
  delete process.env.CCV_PASSWORD;
443
452