cc-viewer 1.9.21 → 1.9.22

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-CocpEURl.js"></script>
24
+ <script type="module" crossorigin src="./assets/index-DoFyHmPM.js"></script>
25
25
  <link rel="modulepreload" crossorigin href="./assets/vendor-antd-I6I2F7Rv.js">
26
26
  <link rel="modulepreload" crossorigin href="./assets/vendor-codemirror-Zkm6UHQg.js">
27
27
  <link rel="modulepreload" crossorigin href="./assets/vendor-mdxeditor-CC09MDyZ.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.21",
3
+ "version": "1.9.22",
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",
package/server/i18n.js CHANGED
@@ -647,6 +647,86 @@ const i18nData = {
647
647
  "tr": " ⚠️ CCV_BASE_PATH \"{value}\" \"/\" ile başlamalıdır — yok sayıldı. Örnek: \"/proxy/\"",
648
648
  "uk": " ⚠️ CCV_BASE_PATH \"{value}\" має починатися з \"/\" — проігноровано. Приклад: \"/proxy/\""
649
649
  },
650
+ "baseUrl.invalid": {
651
+ "zh": " ⚠️ CCV_BASE_URL \"{value}\" 无法解析或使用了不支持的 scheme(支持 http(s)://、ws(s)://、host/path 或 /path 写法),已忽略并回退到 CCV_BASE_PATH。",
652
+ "en": " ⚠️ CCV_BASE_URL \"{value}\" is invalid or uses an unsupported scheme (use http(s)://, ws(s)://, host/path, or /path) — ignored; falling back to CCV_BASE_PATH.",
653
+ "zh-TW": " ⚠️ CCV_BASE_URL \"{value}\" 無法解析或使用了不支援的 scheme(支援 http(s)://、ws(s)://、host/path 或 /path 寫法),已忽略並回退到 CCV_BASE_PATH。",
654
+ "ko": " ⚠️ CCV_BASE_URL \"{value}\"을(를) 해석할 수 없거나 지원하지 않는 scheme입니다(http(s)://, ws(s)://, host/path 또는 /path 형식 사용) — 무시하고 CCV_BASE_PATH로 되돌립니다.",
655
+ "ja": " ⚠️ CCV_BASE_URL \"{value}\" は解析できないか、未対応の scheme です(http(s)://、ws(s)://、host/path、/path 形式を使用)— 無視し、CCV_BASE_PATH にフォールバックします。",
656
+ "de": " ⚠️ CCV_BASE_URL \"{value}\" ist ungültig oder verwendet ein nicht unterstütztes Schema (http(s)://, ws(s)://, host/path oder /path verwenden) — ignoriert; Rückfall auf CCV_BASE_PATH.",
657
+ "es": " ⚠️ CCV_BASE_URL \"{value}\" no es válida o usa un esquema no admitido (use http(s)://, ws(s)://, host/path o /path) — ignorada; se recurre a CCV_BASE_PATH.",
658
+ "fr": " ⚠️ CCV_BASE_URL « {value} » est invalide ou utilise un schéma non pris en charge (utilisez http(s)://, ws(s)://, host/path ou /path) — ignorée ; retour à CCV_BASE_PATH.",
659
+ "it": " ⚠️ CCV_BASE_URL \"{value}\" non è valida o usa uno schema non supportato (usa http(s)://, ws(s)://, host/path o /path) — ignorata; ripiego su CCV_BASE_PATH.",
660
+ "da": " ⚠️ CCV_BASE_URL \"{value}\" er ugyldig eller bruger et ikke-understøttet skema (brug http(s)://, ws(s)://, host/path eller /path) — ignoreret; falder tilbage på CCV_BASE_PATH.",
661
+ "pl": " ⚠️ CCV_BASE_URL \"{value}\" jest nieprawidłowy lub używa nieobsługiwanego schematu (użyj http(s)://, ws(s)://, host/path lub /path) — zignorowano; powrót do CCV_BASE_PATH.",
662
+ "ru": " ⚠️ CCV_BASE_URL \"{value}\" недействителен или использует неподдерживаемую схему (используйте http(s)://, ws(s)://, host/path или /path) — проигнорировано; возврат к CCV_BASE_PATH.",
663
+ "ar": " ⚠️ CCV_BASE_URL \"{value}\" غير صالح أو يستخدم مخططًا غير مدعوم (استخدم http(s):// أو ws(s):// أو host/path أو /path) — تم التجاهل؛ الرجوع إلى CCV_BASE_PATH.",
664
+ "no": " ⚠️ CCV_BASE_URL \"{value}\" er ugyldig eller bruker et ikke-støttet skjema (bruk http(s)://, ws(s)://, host/path eller /path) — ignorert; faller tilbake til CCV_BASE_PATH.",
665
+ "pt-BR": " ⚠️ CCV_BASE_URL \"{value}\" é inválida ou usa um esquema não suportado (use http(s)://, ws(s)://, host/path ou /path) — ignorada; revertendo para CCV_BASE_PATH.",
666
+ "th": " ⚠️ CCV_BASE_URL \"{value}\" ไม่ถูกต้องหรือใช้ scheme ที่ไม่รองรับ (ใช้ http(s)://, ws(s)://, host/path หรือ /path) — ถูกละเว้น กลับไปใช้ CCV_BASE_PATH",
667
+ "tr": " ⚠️ CCV_BASE_URL \"{value}\" geçersiz veya desteklenmeyen bir şema kullanıyor (http(s)://, ws(s)://, host/path veya /path kullanın) — yoksayıldı; CCV_BASE_PATH değerine geri dönülüyor.",
668
+ "uk": " ⚠️ CCV_BASE_URL \"{value}\" недійсний або використовує непідтримувану схему (використовуйте http(s)://, ws(s)://, host/path або /path) — проігноровано; повернення до CCV_BASE_PATH."
669
+ },
670
+ "baseUrl.queryFragmentIgnored": {
671
+ "zh": " ⚠️ CCV_BASE_URL \"{value}\" 中的查询串/锚点已忽略(只使用 scheme、host 与 path)。",
672
+ "en": " ⚠️ CCV_BASE_URL \"{value}\": query string / fragment ignored (only scheme, host, and path are used).",
673
+ "zh-TW": " ⚠️ CCV_BASE_URL \"{value}\" 中的查詢串/錨點已忽略(只使用 scheme、host 與 path)。",
674
+ "ko": " ⚠️ CCV_BASE_URL \"{value}\": 쿼리 문자열/프래그먼트는 무시됩니다(scheme, host, path만 사용).",
675
+ "ja": " ⚠️ CCV_BASE_URL \"{value}\": クエリ文字列/フラグメントは無視されます(scheme、host、path のみ使用)。",
676
+ "de": " ⚠️ CCV_BASE_URL \"{value}\": Query-String/Fragment ignoriert (nur Schema, Host und Pfad werden verwendet).",
677
+ "es": " ⚠️ CCV_BASE_URL \"{value}\": cadena de consulta/fragmento ignorados (solo se usan esquema, host y ruta).",
678
+ "fr": " ⚠️ CCV_BASE_URL « {value} » : chaîne de requête/fragment ignorés (seuls le schéma, l'hôte et le chemin sont utilisés).",
679
+ "it": " ⚠️ CCV_BASE_URL \"{value}\": query string/frammento ignorati (vengono usati solo schema, host e percorso).",
680
+ "da": " ⚠️ CCV_BASE_URL \"{value}\": forespørgselsstreng/fragment ignoreret (kun skema, vært og sti bruges).",
681
+ "pl": " ⚠️ CCV_BASE_URL \"{value}\": ciąg zapytania/fragment zignorowane (używany jest tylko schemat, host i ścieżka).",
682
+ "ru": " ⚠️ CCV_BASE_URL \"{value}\": строка запроса/фрагмент проигнорированы (используются только схема, хост и путь).",
683
+ "ar": " ⚠️ CCV_BASE_URL \"{value}\": تم تجاهل سلسلة الاستعلام/الجزء (يُستخدم فقط المخطط والمضيف والمسار).",
684
+ "no": " ⚠️ CCV_BASE_URL \"{value}\": spørrestreng/fragment ignorert (kun skjema, vert og sti brukes).",
685
+ "pt-BR": " ⚠️ CCV_BASE_URL \"{value}\": query string/fragmento ignorados (apenas esquema, host e caminho são usados).",
686
+ "th": " ⚠️ CCV_BASE_URL \"{value}\": ละเว้น query string/fragment (ใช้เฉพาะ scheme, host และ path)",
687
+ "tr": " ⚠️ CCV_BASE_URL \"{value}\": sorgu dizesi/parça yoksayıldı (yalnızca şema, ana bilgisayar ve yol kullanılır).",
688
+ "uk": " ⚠️ CCV_BASE_URL \"{value}\": рядок запиту/фрагмент проігноровано (використовуються лише схема, хост і шлях)."
689
+ },
690
+ "baseUrl.overridesBasePath": {
691
+ "zh": " ℹ️ CCV_BASE_URL 与 CCV_BASE_PATH 同时设置,CCV_BASE_URL 优先(CCV_BASE_PATH 被忽略)。",
692
+ "en": " ℹ️ Both CCV_BASE_URL and CCV_BASE_PATH are set; CCV_BASE_URL takes precedence (CCV_BASE_PATH is ignored).",
693
+ "zh-TW": " ℹ️ CCV_BASE_URL 與 CCV_BASE_PATH 同時設定,CCV_BASE_URL 優先(CCV_BASE_PATH 被忽略)。",
694
+ "ko": " ℹ️ CCV_BASE_URL과 CCV_BASE_PATH가 모두 설정되어 있습니다. CCV_BASE_URL이 우선합니다(CCV_BASE_PATH는 무시됨).",
695
+ "ja": " ℹ️ CCV_BASE_URL と CCV_BASE_PATH の両方が設定されています。CCV_BASE_URL が優先されます(CCV_BASE_PATH は無視されます)。",
696
+ "de": " ℹ️ CCV_BASE_URL und CCV_BASE_PATH sind beide gesetzt; CCV_BASE_URL hat Vorrang (CCV_BASE_PATH wird ignoriert).",
697
+ "es": " ℹ️ CCV_BASE_URL y CCV_BASE_PATH están definidas; CCV_BASE_URL tiene prioridad (CCV_BASE_PATH se ignora).",
698
+ "fr": " ℹ️ CCV_BASE_URL et CCV_BASE_PATH sont toutes deux définies ; CCV_BASE_URL est prioritaire (CCV_BASE_PATH est ignorée).",
699
+ "it": " ℹ️ CCV_BASE_URL e CCV_BASE_PATH sono entrambe impostate; CCV_BASE_URL ha la precedenza (CCV_BASE_PATH viene ignorata).",
700
+ "da": " ℹ️ Både CCV_BASE_URL og CCV_BASE_PATH er sat; CCV_BASE_URL har forrang (CCV_BASE_PATH ignoreres).",
701
+ "pl": " ℹ️ Ustawiono zarówno CCV_BASE_URL, jak i CCV_BASE_PATH; CCV_BASE_URL ma pierwszeństwo (CCV_BASE_PATH jest ignorowana).",
702
+ "ru": " ℹ️ Заданы и CCV_BASE_URL, и CCV_BASE_PATH; приоритет у CCV_BASE_URL (CCV_BASE_PATH игнорируется).",
703
+ "ar": " ℹ️ تم تعيين كل من CCV_BASE_URL و CCV_BASE_PATH؛ الأولوية لـ CCV_BASE_URL (يتم تجاهل CCV_BASE_PATH).",
704
+ "no": " ℹ️ Både CCV_BASE_URL og CCV_BASE_PATH er satt; CCV_BASE_URL har forrang (CCV_BASE_PATH ignoreres).",
705
+ "pt-BR": " ℹ️ CCV_BASE_URL e CCV_BASE_PATH estão definidas; CCV_BASE_URL tem precedência (CCV_BASE_PATH é ignorada).",
706
+ "th": " ℹ️ ตั้งค่าทั้ง CCV_BASE_URL และ CCV_BASE_PATH; CCV_BASE_URL มีความสำคัญกว่า (CCV_BASE_PATH จะถูกละเว้น)",
707
+ "tr": " ℹ️ Hem CCV_BASE_URL hem CCV_BASE_PATH ayarlı; CCV_BASE_URL önceliklidir (CCV_BASE_PATH yoksayılır).",
708
+ "uk": " ℹ️ Задано і CCV_BASE_URL, і CCV_BASE_PATH; пріоритет має CCV_BASE_URL (CCV_BASE_PATH ігнорується)."
709
+ },
710
+ "server.startedExternal": {
711
+ "zh": " ➜ External: {url}",
712
+ "en": " ➜ External: {url}",
713
+ "zh-TW": " ➜ External: {url}",
714
+ "ko": " ➜ External: {url}",
715
+ "ja": " ➜ External: {url}",
716
+ "de": " ➜ External: {url}",
717
+ "es": " ➜ External: {url}",
718
+ "fr": " ➜ External: {url}",
719
+ "it": " ➜ External: {url}",
720
+ "da": " ➜ External: {url}",
721
+ "pl": " ➜ External: {url}",
722
+ "ru": " ➜ External: {url}",
723
+ "ar": " ➜ External: {url}",
724
+ "no": " ➜ External: {url}",
725
+ "pt-BR": " ➜ External: {url}",
726
+ "th": " ➜ External: {url}",
727
+ "tr": " ➜ External: {url}",
728
+ "uk": " ➜ External: {url}"
729
+ },
650
730
  "server.auth.loginTitle": {
651
731
  "zh": "请输入访问密码",
652
732
  "en": "Enter access password",
@@ -3095,14 +3175,18 @@ export function getLang() {
3095
3175
  return currentLang;
3096
3176
  }
3097
3177
 
3178
+ // Single-pass interpolation: a param value that itself contains '{otherKey}' must NOT be
3179
+ // re-substituted (e.g. basePath '/arca/.../session/{token}/' must survive the later {token}
3180
+ // param pass). Per-key replaceAll loops rewrite earlier insertions; a regex callback resolves
3181
+ // each placeholder exactly once against the ORIGINAL template text.
3182
+ function interpolate(text, params) {
3183
+ return text.replace(/\{([A-Za-z0-9_]+)\}/g, (m, k) =>
3184
+ Object.prototype.hasOwnProperty.call(params, k) ? String(params[k]) : m);
3185
+ }
3186
+
3098
3187
  export function t(key, params) {
3099
- let text = locales[currentLang]?.[key] || locales['en'][key] || key;
3100
- if (params) {
3101
- for (const [k, v] of Object.entries(params)) {
3102
- text = text.replaceAll(`{${k}}`, v);
3103
- }
3104
- }
3105
- return text;
3188
+ const text = locales[currentLang]?.[key] || locales['en'][key] || key;
3189
+ return params ? interpolate(text, params) : text;
3106
3190
  }
3107
3191
 
3108
3192
  /**
@@ -3111,13 +3195,8 @@ export function t(key, params) {
3111
3195
  * without mutating shared state. Falls back to en → key.
3112
3196
  */
3113
3197
  export function tFor(key, lang, params) {
3114
- let text = locales[lang]?.[key] || locales['en'][key] || key;
3115
- if (params) {
3116
- for (const [k, v] of Object.entries(params)) {
3117
- text = text.replaceAll(`{${k}}`, v);
3118
- }
3119
- }
3120
- return text;
3198
+ const text = locales[lang]?.[key] || locales['en'][key] || key;
3199
+ return params ? interpolate(text, params) : text;
3121
3200
  }
3122
3201
 
3123
3202
  /**
@@ -1492,6 +1492,9 @@ export function setupInterceptor() {
1492
1492
  response = await _originalFetch.call(this, _fetchUrl, _fetchOpts);
1493
1493
  } catch (err) {
1494
1494
  if (streamingBucket) _resetStreamingBucket();
1495
+ // The request will never produce a completion — release its v2 in-flight
1496
+ // count so the session isn't permanently blocked from shard rotation.
1497
+ if (_v2Handle) { try { _v2Writer.releaseHandle(_v2Handle); } catch { /* best-effort */ } _v2Handle = null; }
1495
1498
  throw err;
1496
1499
  }
1497
1500
 
@@ -1706,6 +1709,9 @@ export function setupInterceptor() {
1706
1709
  }
1707
1710
  } catch (err) {
1708
1711
  _resetStreamingBucket();
1712
+ // The stream died before producing a completion — release the
1713
+ // v2 in-flight count so shard rotation isn't permanently blocked.
1714
+ if (_v2Handle) { try { _v2Writer.releaseHandle(_v2Handle); } catch { /* best-effort */ } _v2Handle = null; }
1709
1715
  controller.error(err);
1710
1716
  }
1711
1717
  }
@@ -26,6 +26,7 @@ export class AsyncWriteQueue {
26
26
  // typeof 防御:字符串 "1000" 能通过 > 0 协转检查,但后续字节比较会退化为字典序
27
27
  this._highWaterMark = (typeof opts.highWaterMark === 'number' && opts.highWaterMark > 0)
28
28
  ? opts.highWaterMark : HIGH_WATER_MARK;
29
+ this._idleCbs = []; // one-shot drain-complete listeners (shard rotation)
29
30
  }
30
31
 
31
32
  _getPath() {
@@ -34,6 +35,10 @@ export class AsyncWriteQueue {
34
35
 
35
36
  get filePath() { return this._getPath(); }
36
37
  get pendingBytes() { return this._pendingBytes; }
38
+ /** True when no bytes are queued and no drain is in flight — a synchronous
39
+ * rename of a target path is safe only at this point (a chunked drain
40
+ * re-opens the path per chunk). Used by v2 shard rotation. */
41
+ get isIdle() { return this._pendingBytes === 0 && !this._draining; }
37
42
 
38
43
  append(data, onDone) {
39
44
  return this.appendTo(this._getPath(), data, onDone);
@@ -164,5 +169,18 @@ export class AsyncWriteQueue {
164
169
 
165
170
  for (const resolve of this._flushResolvers) resolve();
166
171
  this._flushResolvers.length = 0;
172
+ // Drain-complete callbacks (v2 shard rotation): a rotation armed while the
173
+ // queue was busy re-runs here, at the true idle point.
174
+ for (const cb of this._idleCbs.splice(0)) {
175
+ try { cb(); } catch { /* a listener must never break the drain path */ }
176
+ }
177
+ }
178
+
179
+ /** Register a one-shot callback fired the next time the queue goes idle
180
+ * (queue empty + no drain in flight). Fires SYNCHRONOUSLY if already idle. */
181
+ onIdle(cb) {
182
+ if (typeof cb !== 'function') return;
183
+ if (this._queue.length === 0 && !this._draining) { try { cb(); } catch {} return; }
184
+ this._idleCbs.push(cb);
167
185
  }
168
186
  }
@@ -295,11 +295,14 @@ function escapeHtml(s) {
295
295
  /**
296
296
  * Self-contained login page (inline CSS + JS, references NO /assets — static assets
297
297
  * are auth-exempt but we don't want to surface the SPA bundle to unauthenticated
298
- * remotes). On submit it POSTs to /api/auth/login and reloads on success.
298
+ * remotes). On submit it POSTs to <basePath>api/auth/login and reloads on success.
299
299
  *
300
300
  * `lang` is a resolved locale code (caller derives it from Accept-Language).
301
+ * `basePath` is the effective deployment prefix (CCV_BASE_URL/CCV_BASE_PATH), normalized
302
+ * with a trailing slash ('' at root): a prefix-preserving reverse proxy would otherwise
303
+ * route the hardcoded '/api/auth/login' POST nowhere near ccv.
301
304
  */
302
- export function renderLoginPage({ lang = 'en', error = false } = {}) {
305
+ export function renderLoginPage({ lang = 'en', error = false, basePath = '' } = {}) {
303
306
  const dir = lang === 'ar' ? 'rtl' : 'ltr';
304
307
  const title = escapeHtml(tFor('server.auth.loginTitle', lang));
305
308
  const placeholder = escapeHtml(tFor('server.auth.loginPlaceholder', lang));
@@ -307,6 +310,11 @@ export function renderLoginPage({ lang = 'en', error = false } = {}) {
307
310
  const errMsg = escapeHtml(tFor('server.auth.loginError', lang));
308
311
  const toggleLabel = escapeHtml(tFor('server.auth.togglePassword', lang));
309
312
  const errStyle = error ? '' : ' style="display:none"';
313
+ // Login POST target: always root-absolute. basePath carries its own trailing slash; without
314
+ // a prefix fall back to '/api/auth/login' — the login page is served for ANY HTML navigation
315
+ // path (deep links included) and a relative 'api/auth/login' would resolve against the
316
+ // document URL and miss the endpoint. JS string escape: \ -> \\, " -> \", </ -> <\/ .
317
+ const jsSafeBase = String(basePath || '/').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/<\//g, '<\\/');
310
318
  return `<!DOCTYPE html>
311
319
  <html lang="${escapeHtml(lang)}" dir="${dir}" data-theme="dark">
312
320
  <head>
@@ -387,7 +395,7 @@ export function renderLoginPage({ lang = 'en', error = false } = {}) {
387
395
  f.addEventListener('submit', function (ev) {
388
396
  ev.preventDefault();
389
397
  b.disabled = true; e.style.display = 'none';
390
- fetch('/api/auth/login', {
398
+ fetch("${jsSafeBase}api/auth/login", {
391
399
  method: 'POST',
392
400
  headers: { 'Content-Type': 'application/json' },
393
401
  body: JSON.stringify({ password: p.value })
@@ -1,34 +1,105 @@
1
- // CCV_BASE_PATH(反向代理子路径部署)的统一 normalize / validate / strip。
2
- // 纯函数,无副作用,server.js(HTTP 剥离 / <base> 注入 / WS upgrade)与 cli.js(启动 URL
3
- // 打印)共用,消除各处复制粘贴的 normalize 逻辑。vite.config.js 不复用(构建期 base 有
4
- // `undefined→'/'` 的三态语义,与运行时"未设=无前缀"不同,见该文件注释)。
1
+ // Unified normalize / validate / strip for CCV_BASE_PATH (reverse-proxy sub-path deployment).
2
+ // Pure functions, no side effects; shared by server.js (HTTP strip / <base> injection /
3
+ // WS upgrade) and cli.js (startup URL printing) so the normalize logic lives in exactly one
4
+ // place. vite.config.js deliberately does NOT reuse this (build-time base has a three-state
5
+ // `undefined → '/'` semantic that differs from runtime "unset = no prefix" — see that file).
5
6
 
6
- // 规范化 basePath:未设 / 空串 / 根 '/' → ''(无前缀);其余补尾斜杠('/proxy' → '/proxy/')。
7
- // 尾斜杠是 startsWith 匹配的防歧义关键('/proxy/' 不会误命中 '/proxyextra/x')。
8
- // 缺前导 '/' 的非法值('proxy/x')也返回 ''(忽略)——否则注入段会产出相对 <base> 破坏页面;
9
- // 告警由 validateBasePath 在启动期负责。
7
+ // Normalize basePath: unset / empty / root '/' → '' (no prefix); anything else gets a trailing
8
+ // slash ('/proxy' → '/proxy/'). The trailing slash is the anti-ambiguity key for startsWith
9
+ // matching ('/proxy/' never mis-hits '/proxyextra/x'). Invalid values missing the leading '/'
10
+ // ('proxy/x') also return '' (ignored) — otherwise the injected segment would produce a
11
+ // relative <base> and break the page; the startup warning is validateBasePath's job.
12
+ // Backslashes are rejected for the same reason as in parseBaseUrl: WHATWG resolution treats
13
+ // '/\evil.com/x' as protocol-relative, which would make the injected <base> cross-origin.
10
14
  export function normalizeBasePath(raw) {
11
- if (!raw || raw === '/' || !raw.startsWith('/')) return '';
12
- // 剥裸换行符:含 \n/\r 的值会把 index.html 注入的 JS 字符串断成语法错误(页面级 DoS)
15
+ if (!raw || raw === '/' || !raw.startsWith('/') || raw.includes('\\')) return '';
16
+ // Strip raw CR/LF: a value containing \n/\r would break the JS string injected into
17
+ // index.html into a syntax error (page-level DoS).
13
18
  return raw.replace(/[\r\n]/g, '').replace(/\/?$/, '/');
14
19
  }
15
20
 
16
- // 校验 + 规范化。非空但缺前导 '/'(如 'proxy/x')属配置错误:startsWith 永不命中、剥离
17
- // 静默失效。不自动补 '/' —— 自动修正会掩盖与代理侧前缀的错配,更难排查;这里选择
18
- // 忽略(按无前缀工作)并返回 i18n key 供启动期 console.warn。
21
+ // Validate + normalize. A non-empty value missing the leading '/' (e.g. 'proxy/x') is a
22
+ // configuration error: startsWith never matches and stripping silently does nothing. We do
23
+ // NOT auto-prepend '/' — auto-fixing would hide a mismatch with the proxy-side prefix and be
24
+ // harder to diagnose; instead the value is ignored (behave as no-prefix) and an i18n key is
25
+ // returned for the startup console.warn. A value containing a backslash is rejected outright
26
+ // (see normalizeBasePath) rather than silently ignored.
19
27
  export function validateBasePath(raw) {
20
28
  if (raw && raw !== '/' && !raw.startsWith('/')) {
21
29
  return { ok: false, normalized: '', warning: 'basePath.missingLeadingSlash' };
22
30
  }
31
+ if (raw && raw.includes('\\')) {
32
+ return { ok: false, normalized: '', warning: 'basePath.missingLeadingSlash' };
33
+ }
23
34
  return { ok: true, normalized: normalizeBasePath(raw), warning: null };
24
35
  }
25
36
 
26
- // 从请求 pathname 剥掉 basePath 前缀,保证结果带前导 '/'(路由表按 '/api/...' 匹配)。
27
- // slice(length - 1) 让 normalizedBase 的尾斜杠留作结果的前导斜杠:
37
+ // Strip the basePath prefix from a request pathname, guaranteeing a leading '/' on the result
38
+ // (route tables match '/api/...'). slice(length - 1) keeps the matched prefix's trailing slash
39
+ // as the result's leading slash:
28
40
  // stripBasePath('/proxy/api/x', '/proxy/') → '/api/x'
29
41
  // stripBasePath('/proxy/', '/proxy/') → '/'
30
- // 不匹配(含裸前缀 '/proxy' 无尾斜杠的访问)原样返回,由调用方按 SPA/404 处理。
42
+ // Request pathnames are always serialized by new URL (safeParseRequestUrl / browsers alike),
43
+ // so literal-prefix characters like '{token}' arrive percent-encoded ('%7Btoken%7D') — matching
44
+ // therefore uses the encoded forms from wireBasePathVariants, while injection
45
+ // (<base>/window.__CCV_BASE_PATH__) keeps the literal form. A non-matching path is returned
46
+ // unchanged and the caller handles it as SPA/404. A bare prefix (no trailing slash, e.g.
47
+ // '/proxy' or its encoded form) is treated as the prefix root → '/': together with the
48
+ // injected <base href>, relative assets resolve correctly and a shared link missing the
49
+ // trailing slash no longer white-screens/404s. The equality check is exact — '/proxyextra'
50
+ // is not affected.
51
+
52
+ // Serialize a literal basePath to wire form (the request-pathname shape): new URL
53
+ // percent-encodes WHATWG path characters like '{'/'}' ('/session/{token}/' →
54
+ // '/session/%7Btoken%7D/'). Every comparison against an already-parsed request path (prefix
55
+ // stripping, plugin cookie Path, ...) MUST use this form; the literal form is only for
56
+ // <base href>/JS injection. A value containing '?#' would have its trailing slash eaten by URL
57
+ // parsing ('/a?x/' → '/a') — such a config can never match a request anyway, so we fall back
58
+ // to the literal form to preserve the old behavior (never over-strip adjacent paths).
59
+ export function wireBasePath(normalizedBase) {
60
+ if (!normalizedBase) return '';
61
+ if (/[?#]/.test(normalizedBase)) return normalizedBase;
62
+ try {
63
+ const wire = new URL(`http://ccv-base${normalizedBase}`).pathname;
64
+ // The trailing slash is the key to startsWith disambiguation and the slice leading-slash
65
+ // semantic; if it was lost, fall back (defensive).
66
+ return wire.endsWith('/') ? wire : normalizedBase;
67
+ } catch {
68
+ return normalizedBase;
69
+ }
70
+ }
71
+
72
+ // Match candidates: the wire form plus percent-escape case variants. Some proxies re-case
73
+ // individual escapes (%7B → %7b or back), and new URL preserves the incoming case, so ANY
74
+ // per-triplet case combination can arrive — generate all 2^N combinations (N is the number of
75
+ // escapes, typically 2 for '{token}'). With no escapes this dedupes to a single element.
76
+ export function wireBasePathVariants(normalizedBase) {
77
+ const wire = wireBasePath(normalizedBase);
78
+ if (!wire) return [];
79
+ const triplets = [...wire.matchAll(/%([0-9A-Fa-f]{2})/g)];
80
+ if (triplets.length === 0) return [wire];
81
+ const seen = new Set();
82
+ const out = [];
83
+ const walk = (prefix, idx) => {
84
+ if (idx === triplets.length) {
85
+ const candidate = prefix + wire.slice(triplets[idx - 1].index + 3);
86
+ if (!seen.has(candidate)) { seen.add(candidate); out.push(candidate); }
87
+ return;
88
+ }
89
+ const t = triplets[idx];
90
+ const literal = wire.slice(idx === 0 ? 0 : triplets[idx - 1].index + 3, t.index);
91
+ walk(prefix + literal + t[0].toLowerCase(), idx + 1);
92
+ walk(prefix + literal + t[0].toUpperCase(), idx + 1);
93
+ };
94
+ walk('', 0);
95
+ return out;
96
+ }
97
+
31
98
  export function stripBasePath(pathname, normalizedBase) {
32
- if (!normalizedBase || !pathname.startsWith(normalizedBase)) return pathname;
33
- return pathname.slice(normalizedBase.length - 1) || '/';
99
+ if (!normalizedBase) return pathname;
100
+ for (const base of wireBasePathVariants(normalizedBase)) {
101
+ if (pathname.startsWith(base)) return pathname.slice(base.length - 1) || '/';
102
+ if (pathname === base.slice(0, -1)) return '/';
103
+ }
104
+ return pathname;
34
105
  }
@@ -0,0 +1,209 @@
1
+ // CCV_BASE_URL (cloud / reverse-proxy deployment behind a public URL): parse + URL building.
2
+ // Pure functions, no side effects. Callers read env fresh on every call — server.js deliberately
3
+ // re-reads base-path config per request (tests flip env without restarting the server).
4
+ //
5
+ // Accepted forms:
6
+ // 1. host[:port][/path] arca-sandbox-office.alipay.com/arca/api/v1/session/{token}
7
+ // 2. /path /arca/api/v1/session/{token}
8
+ // 3. scheme://host[:port][/path] https://arca-sandbox-office.alipay.com/arca/api/v1/session/{token}
9
+ // ws:// and wss:// are accepted aliases: ws -> http, wss -> https (WS URLs are derived).
10
+ //
11
+ // The path is split by hand instead of using `new URL(...).pathname` on purpose: WHATWG URL
12
+ // parsing percent-encodes `{`/`}` in special-scheme paths, which would corrupt the literal
13
+ // `{token}` session segment into `%7Btoken%7D` for <base href>/window.__CCV_BASE_PATH__ injection
14
+ // (the wire-encoded form is derived separately for request matching — see wireBasePath).
15
+ // Manual splitting also avoids `new URL('http://' + '//path')`-style authority misdetection.
16
+ import { normalizeBasePath } from './base-path.js';
17
+
18
+ // wireBasePath / wireBasePathVariants live in base-path.js (the path-utility home); re-exported
19
+ // here so base-url consumers (plugin-runtime cookie Path) have a single import site.
20
+ export { wireBasePath, wireBasePathVariants } from './base-path.js';
21
+
22
+ const SCHEME_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\//;
23
+ // hostname | bracketed IPv6, optional numeric port; no userinfo, no non-ASCII (use punycode).
24
+ const AUTHORITY_RE = /^(?:\[([0-9a-fA-F:.]+)\]|([A-Za-z0-9._-]+))(?::(\d{1,5}))?$/;
25
+
26
+ const EMPTY = Object.freeze({ ok: true, scheme: null, host: null, port: null, basePath: '', warning: null });
27
+
28
+ function invalid() {
29
+ return { ok: false, scheme: null, host: null, port: null, basePath: '', warning: 'baseUrl.invalid' };
30
+ }
31
+
32
+ /** Trim + strip CRLF so a hostile/mangled env value cannot inject lines into logs or JS. */
33
+ export function sanitizeBaseUrlValue(raw) {
34
+ if (raw == null) return '';
35
+ return String(raw).trim().replace(/[\r\n]/g, '');
36
+ }
37
+
38
+ /**
39
+ * Parse a CCV_BASE_URL value.
40
+ * @returns {{
41
+ * ok: boolean, // false = value ignored, caller falls back to CCV_BASE_PATH
42
+ * scheme: 'http'|'https'|null, // normalized; null = user omitted the scheme
43
+ * host: string|null, // lowercased hostname, IPv6 keeps brackets, no port
44
+ * port: number|null,
45
+ * basePath: string, // normalized ('/a/b/' or '' for root), braces kept literal
46
+ * warning: string|null, // i18n key (baseUrl.invalid / baseUrl.queryFragmentIgnored)
47
+ * }}
48
+ */
49
+ export function parseBaseUrl(raw) {
50
+ let text = sanitizeBaseUrlValue(raw);
51
+ if (!text) return { ...EMPTY };
52
+
53
+ let scheme = null;
54
+ const m = SCHEME_RE.exec(text);
55
+ if (m) {
56
+ const proto = m[1].toLowerCase();
57
+ if (proto === 'http' || proto === 'ws') scheme = 'http';
58
+ else if (proto === 'https' || proto === 'wss') scheme = 'https';
59
+ else return invalid();
60
+ text = text.slice(m[0].length);
61
+ }
62
+
63
+ // Query/fragment are never part of a mounted prefix or a generated base URL.
64
+ let warning = null;
65
+ const cut = text.search(/[?#]/);
66
+ if (cut !== -1) {
67
+ text = text.slice(0, cut);
68
+ warning = 'baseUrl.queryFragmentIgnored';
69
+ }
70
+ // A value that carried a scheme but nothing after it ('https://', 'https://?x=1') is a
71
+ // configuration error, not "no prefix" — surface it so resolveBaseConfig can fall back.
72
+ if (m && !text) return invalid();
73
+ // A query/fragment-only value ('?x=1', '#f') is a configuration error too: accepting it as
74
+ // "valid, no prefix" would silently override a configured CCV_BASE_PATH with nothing.
75
+ if (!m && cut !== -1 && !text) return invalid();
76
+ if (!text) return { ...EMPTY, warning };
77
+
78
+ let host = null;
79
+ let port = null;
80
+ let pathRaw = '';
81
+ // Exactly one leading '/' means path-only. '//...' is a protocol-relative authority and is
82
+ // parsed as host — injecting it as a path would produce a cross-origin <base href="//evil">.
83
+ if (text.startsWith('/') && !text.startsWith('//')) {
84
+ pathRaw = text;
85
+ } else {
86
+ const authorityPart = text.startsWith('//') ? text.slice(2) : text;
87
+ const slash = authorityPart.indexOf('/');
88
+ const authority = slash === -1 ? authorityPart : authorityPart.slice(0, slash);
89
+ pathRaw = slash === -1 ? '' : authorityPart.slice(slash);
90
+ if (!authority || authority.includes('@') || authority === '*') return invalid();
91
+ const am = AUTHORITY_RE.exec(authority);
92
+ if (!am) return invalid();
93
+ if (am[3] !== undefined) {
94
+ const p = Number(am[3]);
95
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return invalid();
96
+ port = p;
97
+ }
98
+ host = am[1] !== undefined ? `[${am[1].toLowerCase()}]` : am[2].toLowerCase();
99
+ }
100
+
101
+ // The path is used verbatim in HTML/JS injection, so whitespace, control characters and
102
+ // backslashes are rejected rather than silently diverging from the wire-encoded request
103
+ // pathname. A '//' path would inject a protocol-relative <base href="//..."> (cross-origin);
104
+ // a backslash is rejected for the same reason — WHATWG URL resolution treats '/\evil.com/x'
105
+ // like '//evil.com/x', turning every relative API call (token appended) into a cross-origin
106
+ // request. C0 controls are rejected as well (they would reach the startup console raw).
107
+ if (/\s/.test(pathRaw) || /[\\\u0000-\u001f\u007f]/.test(pathRaw) || pathRaw.startsWith('//')) return invalid();
108
+
109
+ // normalizeBasePath: '' for root, adds the trailing slash that disambiguates startsWith,
110
+ // and strips CRLF from the path itself. Braces ({token}) stay literal.
111
+ return { ok: true, scheme, host, port, basePath: normalizeBasePath(pathRaw), warning };
112
+ }
113
+
114
+ /**
115
+ * Merge CCV_BASE_URL (preferred) and legacy CCV_BASE_PATH into the one effective config.
116
+ *
117
+ * Rules:
118
+ * - CCV_BASE_URL unset/blank -> CCV_BASE_PATH (unchanged back-compat)
119
+ * - CCV_BASE_URL invalid -> CCV_BASE_PATH + 'baseUrl.invalid' warning
120
+ * - CCV_BASE_URL valid (even host-only) -> CCV_BASE_URL wins outright; a host-only form
121
+ * authoritatively means "no prefix" and does NOT
122
+ * fall back to CCV_BASE_PATH
123
+ * - both set and CCV_BASE_URL valid -> + 'baseUrl.overridesBasePath' warning
124
+ *
125
+ * @param {NodeJS.ProcessEnv} [env]
126
+ * @returns {{ basePath: string, scheme: 'http'|'https'|null, host: string|null,
127
+ * port: number|null, source: 'baseUrl'|'basePath'|'none',
128
+ * warning: string|null, warningValue: string }}
129
+ */
130
+ export function resolveBaseConfig(env = process.env) {
131
+ const rawBasePath = env.CCV_BASE_PATH;
132
+ const sanitized = sanitizeBaseUrlValue(env.CCV_BASE_URL);
133
+ const legacyBasePath = normalizeBasePath(rawBasePath);
134
+
135
+ if (!sanitized) {
136
+ return {
137
+ basePath: legacyBasePath, scheme: null, host: null, port: null,
138
+ source: legacyBasePath ? 'basePath' : 'none', warning: null, warningValue: '',
139
+ };
140
+ }
141
+
142
+ const parsed = parseBaseUrl(sanitized);
143
+ if (!parsed.ok) {
144
+ return {
145
+ basePath: legacyBasePath, scheme: null, host: null, port: null,
146
+ source: legacyBasePath ? 'basePath' : 'none',
147
+ warning: 'baseUrl.invalid', warningValue: sanitized,
148
+ };
149
+ }
150
+
151
+ return {
152
+ basePath: parsed.basePath, scheme: parsed.scheme, host: parsed.host, port: parsed.port,
153
+ source: 'baseUrl',
154
+ warning: parsed.warning || (legacyBasePath ? 'baseUrl.overridesBasePath' : null),
155
+ warningValue: sanitized,
156
+ };
157
+ }
158
+
159
+ /** Hostname to add to the Host-header allowlist (lowercased, port-free, IPv6 bracketed), or null. */
160
+ export function baseUrlAllowedHost(env = process.env) {
161
+ const parsed = parseBaseUrl(env.CCV_BASE_URL);
162
+ return parsed.ok && parsed.host ? parsed.host : null;
163
+ }
164
+
165
+ /** First hop of X-Forwarded-Proto when it is http/https; null otherwise. */
166
+ export function forwardedProto(req) {
167
+ const raw = req?.headers?.['x-forwarded-proto'];
168
+ if (typeof raw !== 'string') return null;
169
+ const first = raw.split(',')[0].trim().toLowerCase();
170
+ return first === 'http' || first === 'https' ? first : null;
171
+ }
172
+
173
+ /**
174
+ * Scheme for user-facing URLs when CCV_BASE_URL carries a host.
175
+ * Priority: explicit scheme in CCV_BASE_URL -> request X-Forwarded-Proto -> https.
176
+ * Defaulting to https is deliberate: a host-based cloud deployment is normally TLS-terminated
177
+ * in front of ccv, and the proxy should send X-Forwarded-Proto. WS URLs are derived by the
178
+ * caller (https -> wss, http -> ws).
179
+ */
180
+ export function resolveExternalScheme({ scheme = null, req = null } = {}) {
181
+ if (scheme === 'http' || scheme === 'https') return scheme;
182
+ return forwardedProto(req) || 'https';
183
+ }
184
+
185
+ /** `{scheme}://{host}[:{port}]{basePath}[?token=...]`; empty basePath renders as '/'. */
186
+ export function buildExternalUrl({ scheme = 'https', host, port = null, basePath = '', token = null } = {}) {
187
+ if (!host) return null;
188
+ const authority = port ? `${host}:${port}` : host;
189
+ const path = basePath || '/';
190
+ const query = token ? `?token=${encodeURIComponent(token)}` : '';
191
+ return `${scheme === 'http' ? 'http' : 'https'}://${authority}${path}${query}`;
192
+ }
193
+
194
+ /**
195
+ * One-liner for the four call sites (startup log, auto-open, cli print ×2, /api/local-url):
196
+ * build the public URL from a resolveBaseConfig() result, or null when the config has no host.
197
+ * Scheme: explicit in CCV_BASE_URL > this request's X-Forwarded-Proto (pass req when available)
198
+ * > https. Always carries ccv's own ACCESS_TOKEN — a remote URL without it is a 403 dead link.
199
+ */
200
+ export function externalUrlFromConfig(cfg, { token = null, req = null } = {}) {
201
+ if (!cfg?.host) return null;
202
+ return buildExternalUrl({
203
+ scheme: resolveExternalScheme({ scheme: cfg.scheme, req }),
204
+ host: cfg.host,
205
+ port: cfg.port,
206
+ basePath: cfg.basePath,
207
+ token,
208
+ });
209
+ }