cc-viewer 1.9.21 → 1.9.23
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/README.md +2 -1
- package/cli.js +50 -14
- package/dist/assets/{App-C4f2Dpy9.js → App-DEA3HoZr.js} +2 -2
- package/dist/assets/{MdxEditorPanel-D7aQDQJp.js → MdxEditorPanel-CTAS2DJv.js} +1 -1
- package/dist/assets/{Mobile-D9ekLQFS.js → Mobile-CgVpXvs2.js} +1 -1
- package/dist/assets/{ProxyStatsModal-CWpgyVKI.js → ProxyStatsModal-C4sl-cuB.js} +1 -1
- package/dist/assets/index-CS47d9oh.js +2 -0
- package/dist/assets/seqResourceLoaders-CORH46PN.js +2 -0
- package/dist/assets/seqResourceLoaders-v4YzKhTS.css +41 -0
- package/dist/index.html +1 -1
- package/findcc.js +4 -4
- package/node_modules/@ccv/core/src/contentFilter.js +4 -1
- package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
- package/package.json +1 -1
- package/server/i18n.js +97 -14
- package/server/interceptor.js +6 -0
- package/server/lib/async-write-queue.js +18 -0
- package/server/lib/auth.js +11 -3
- package/server/lib/base-path.js +89 -18
- package/server/lib/base-url.js +209 -0
- package/server/lib/ensure-hooks.js +134 -2
- package/server/lib/im/im-bridge-core.js +16 -0
- package/server/lib/log-management.js +21 -1
- package/server/lib/plugin-runtime.js +24 -5
- package/server/lib/scheduled-task-executor.js +14 -2
- package/server/lib/scheduled-task-store.js +129 -18
- package/server/lib/sdk-manager.js +113 -11
- package/server/lib/v2/adapter.js +147 -15
- package/server/lib/v2/conversation-store.js +9 -0
- package/server/lib/v2/journal.js +35 -0
- package/server/lib/v2/layout.js +67 -1
- package/server/lib/v2/live-feed.js +15 -0
- package/server/lib/v2/replay.js +11 -3
- package/server/lib/v2/session-select.js +34 -2
- package/server/lib/v2/shard-manager.js +249 -0
- package/server/lib/v2/v2-writer.js +252 -6
- package/server/pty-manager.js +103 -4
- package/server/routes/events.js +75 -4
- package/server/routes/logs.js +47 -16
- package/server/routes/misc.js +15 -5
- package/server/routes/scheduled-tasks.js +13 -0
- package/server/server.js +123 -23
- package/dist/assets/index-CocpEURl.js +0 -2
- package/dist/assets/seqResourceLoaders-BhiCEaUt.js +0 -2
- package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
package/server/lib/base-path.js
CHANGED
|
@@ -1,34 +1,105 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
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
|
-
//
|
|
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
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
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
|
-
//
|
|
27
|
-
// slice(length - 1)
|
|
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
|
-
//
|
|
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
|
|
33
|
-
|
|
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
|
+
}
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* Register AskUserQuestion and permission approval hooks into ~/.claude/settings.json.
|
|
3
3
|
* Shared between cli.js and electron/tab-worker.js.
|
|
4
4
|
*/
|
|
5
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from 'node:fs';
|
|
6
|
-
import { resolve } from 'node:path';
|
|
5
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, statSync, chmodSync } from 'node:fs';
|
|
6
|
+
import { resolve, join } from 'node:path';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
7
8
|
import { randomBytes } from 'node:crypto';
|
|
8
9
|
import { getClaudeConfigDir } from '../../findcc.js';
|
|
9
10
|
import { SERVER_LIB } from '../_paths.js';
|
|
@@ -385,3 +386,134 @@ export function ensureHooks() {
|
|
|
385
386
|
console.warn('[CC Viewer] Failed to ensure hooks:', err.message);
|
|
386
387
|
}
|
|
387
388
|
}
|
|
389
|
+
|
|
390
|
+
// ─── .claude.json path resolution + onboarding/trust initialization ───
|
|
391
|
+
// Claude Code's global config file lives at a location that depends on whether
|
|
392
|
+
// CLAUDE_CONFIG_DIR is set and whether a `.config.json` override exists:
|
|
393
|
+
// 1. `<configDir>/.config.json` — highest precedence when it exists
|
|
394
|
+
// 2. `<configDir>/.claude.json` — custom config dir (e.g. CodeFuse engine cc dir)
|
|
395
|
+
// 3. `~/.claude.json` — default (home dir, NOT ~/.claude/.claude.json)
|
|
396
|
+
// Getting this wrong means the trust/onboarding write lands in a file Claude
|
|
397
|
+
// never reads, and the process stays blocked on the "Yes, I trust this folder" page.
|
|
398
|
+
export function resolveClaudeJsonPath(configDir) {
|
|
399
|
+
const expand = (d) => (typeof d === 'string' && d.startsWith('~/')) ? join(homedir(), d.slice(2)) : d;
|
|
400
|
+
const defaultDir = resolve(getClaudeConfigDir());
|
|
401
|
+
const dir = resolve(expand(configDir) || defaultDir);
|
|
402
|
+
const dotConfig = join(dir, '.config.json');
|
|
403
|
+
if (existsSync(dotConfig)) return dotConfig;
|
|
404
|
+
const explicitCustomDir = !!configDir && dir !== defaultDir;
|
|
405
|
+
const parentEnvSet = !!(process.env.CLAUDE_CONFIG_DIR && process.env.CLAUDE_CONFIG_DIR.trim() !== '');
|
|
406
|
+
if (explicitCustomDir || parentEnvSet) return join(dir, '.claude.json');
|
|
407
|
+
return resolve(defaultDir, '..', '.claude.json');
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Ensure Claude Code's onboarding and trust state are pre-seeded in .claude.json
|
|
412
|
+
* so the process never blocks on interactive confirmation dialogs ("Yes, I accept"
|
|
413
|
+
* / "Yes, I trust this folder"). This is critical for headless IM workers where
|
|
414
|
+
* no human is present to press Enter.
|
|
415
|
+
*
|
|
416
|
+
* Fields written (idempotent, never overwrites user data):
|
|
417
|
+
* - `hasCompletedOnboarding: true` — skips the first-run onboarding flow
|
|
418
|
+
* - `trustedFolders[workspacePath] = true` — skips the directory trust dialog
|
|
419
|
+
* - `projects[workspacePath].hasTrustDialogAccepted = true` — newer Claude builds
|
|
420
|
+
* may key trust off this per-project field instead of (or in addition to)
|
|
421
|
+
* `trustedFolders`
|
|
422
|
+
*
|
|
423
|
+
* Safety invariant: if the target file exists but is unreadable/corrupt, we
|
|
424
|
+
* NEVER write back — a blind overwrite would destroy the user's projects,
|
|
425
|
+
* mcpServers, oauthAccount, etc. (same rule as ensureApiKeyApproved).
|
|
426
|
+
*
|
|
427
|
+
* Writes are atomic (tmp file + rename) and preserve the original file mode.
|
|
428
|
+
*/
|
|
429
|
+
export function ensureOnboardingAndTrust({ configDir, workspacePath } = {}) {
|
|
430
|
+
try {
|
|
431
|
+
const claudeJsonPath = resolveClaudeJsonPath(configDir || getClaudeConfigDir());
|
|
432
|
+
let claudeJson = null;
|
|
433
|
+
if (existsSync(claudeJsonPath)) {
|
|
434
|
+
try {
|
|
435
|
+
claudeJson = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
|
|
436
|
+
if (!claudeJson || typeof claudeJson !== 'object' || Array.isArray(claudeJson)) {
|
|
437
|
+
console.warn(`[cc-viewer] ${claudeJsonPath} is not a JSON object, skipping onboarding/trust write`);
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
} catch (err) {
|
|
441
|
+
// P0 safety rule: unreadable/corrupt file → never overwrite.
|
|
442
|
+
console.warn(`[cc-viewer] ${claudeJsonPath} is unreadable/unparseable (${err.message}), skipping onboarding/trust write to avoid overwriting user config`);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
} else {
|
|
446
|
+
claudeJson = {}; // first run: safe to start from empty object
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
let dirty = false;
|
|
450
|
+
// 1) hasCompletedOnboarding: skip the "Yes, I accept" first-run dialog.
|
|
451
|
+
if (claudeJson.hasCompletedOnboarding !== true) {
|
|
452
|
+
claudeJson.hasCompletedOnboarding = true;
|
|
453
|
+
dirty = true;
|
|
454
|
+
}
|
|
455
|
+
// 2) bypassPermissionsModeAccepted: skip the "Bypass Permissions mode" warning
|
|
456
|
+
// that appears when --dangerously-skip-permissions is used on a fresh config.
|
|
457
|
+
// IM workers always launch with this flag, so this is required to prevent
|
|
458
|
+
// the hang from moving from the trust page to the bypass page.
|
|
459
|
+
if (claudeJson.bypassPermissionsModeAccepted !== true) {
|
|
460
|
+
claudeJson.bypassPermissionsModeAccepted = true;
|
|
461
|
+
dirty = true;
|
|
462
|
+
}
|
|
463
|
+
// 3) trustedFolders: skip the "Do you trust this folder" dialog.
|
|
464
|
+
// NOTE: Claude Code 2.1.199 does not actually read this field (verified
|
|
465
|
+
// against the binary); it is written for forward compatibility only.
|
|
466
|
+
// Normalize the key the same way Claude does: path.normalize + forward
|
|
467
|
+
// slashes on Windows, NFC on all platforms.
|
|
468
|
+
if (workspacePath) {
|
|
469
|
+
const normPath = resolve(workspacePath).replace(/\\/g, '/').normalize('NFC');
|
|
470
|
+
const trusted = claudeJson.trustedFolders && typeof claudeJson.trustedFolders === 'object' && !Array.isArray(claudeJson.trustedFolders)
|
|
471
|
+
? claudeJson.trustedFolders
|
|
472
|
+
: {};
|
|
473
|
+
if (!trusted[normPath]) {
|
|
474
|
+
trusted[normPath] = true;
|
|
475
|
+
claudeJson.trustedFolders = trusted;
|
|
476
|
+
dirty = true;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
// 4) projects[workspacePath].hasTrustDialogAccepted: the field Claude Code
|
|
480
|
+
// 2.1.199 actually checks (verified against the binary). This is the
|
|
481
|
+
// operative trust mechanism. Same normalization as above.
|
|
482
|
+
if (workspacePath) {
|
|
483
|
+
const normPath = resolve(workspacePath).replace(/\\/g, '/').normalize('NFC');
|
|
484
|
+
if (!claudeJson.projects || typeof claudeJson.projects !== 'object' || Array.isArray(claudeJson.projects)) {
|
|
485
|
+
claudeJson.projects = {};
|
|
486
|
+
}
|
|
487
|
+
const proj = claudeJson.projects[normPath];
|
|
488
|
+
if (!proj || typeof proj !== 'object' || Array.isArray(proj)) {
|
|
489
|
+
claudeJson.projects[normPath] = { hasTrustDialogAccepted: true };
|
|
490
|
+
dirty = true;
|
|
491
|
+
} else if (proj.hasTrustDialogAccepted !== true) {
|
|
492
|
+
proj.hasTrustDialogAccepted = true;
|
|
493
|
+
dirty = true;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if (dirty) {
|
|
498
|
+
// Atomic write: tmp file + rename, preserving original file mode.
|
|
499
|
+
// Create the tmp file with the target permissions from the start (0o600 for
|
|
500
|
+
// a new file — .claude.json may contain credentials), so the content is
|
|
501
|
+
// never briefly world-readable between write and chmod.
|
|
502
|
+
const tmpPath = `${claudeJsonPath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
|
|
503
|
+
try {
|
|
504
|
+
let targetMode = 0o600; // safe default for a new file holding credentials
|
|
505
|
+
try {
|
|
506
|
+
targetMode = statSync(claudeJsonPath).mode & 0o777;
|
|
507
|
+
} catch { /* file doesn't exist yet — use safe default */ }
|
|
508
|
+
writeFileSync(tmpPath, JSON.stringify(claudeJson, null, 2), { encoding: 'utf-8', mode: targetMode });
|
|
509
|
+
renameSyncWithRetry(tmpPath, claudeJsonPath);
|
|
510
|
+
} catch (err) {
|
|
511
|
+
try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch { /* ignore */ }
|
|
512
|
+
throw err;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
} catch (err) {
|
|
516
|
+
console.warn('[cc-viewer] Failed to ensure onboarding/trust in .claude.json:', err.message);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
@@ -606,6 +606,22 @@ function drainQueue(inst) {
|
|
|
606
606
|
void sendReply(inst, item, tr(inst, 'noSession'));
|
|
607
607
|
continue;
|
|
608
608
|
}
|
|
609
|
+
// Boot-state gate: when the Claude PTY is blocked on an interactive dialog
|
|
610
|
+
// (trust confirmation, onboarding), fail fast with a clear error instead of
|
|
611
|
+
// letting the message sit until the 120s timeout. This turns a silent hang
|
|
612
|
+
// into an actionable diagnostic.
|
|
613
|
+
// NOTE: 'exited' is NOT handled here — the !st.running check above already
|
|
614
|
+
// catches exited PTYs and replies 'noSession'. This gate only covers the
|
|
615
|
+
// "running but blocked on a dialog" case.
|
|
616
|
+
if (typeof d.getPtyBootState === 'function') {
|
|
617
|
+
const bootState = d.getPtyBootState();
|
|
618
|
+
if (bootState === 'blocked-on-trust' || bootState === 'blocked-on-onboarding') {
|
|
619
|
+
inst.queue.shift();
|
|
620
|
+
audit(inst, 'startup-blocked', { conversationId: item.conversationId, bootState });
|
|
621
|
+
void sendReply(inst, item, tr(inst, 'startupError'));
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
609
625
|
inst.queue.shift();
|
|
610
626
|
const cfg = d.getConfig();
|
|
611
627
|
const skipPerm = d.getPtySkipPermissions();
|
|
@@ -2,7 +2,7 @@ import { existsSync, realpathSync, readdirSync, readFileSync, statSync, mkdirSyn
|
|
|
2
2
|
import { readFile, stat, readdir } from 'node:fs/promises';
|
|
3
3
|
import { join, sep, dirname, basename } from 'node:path';
|
|
4
4
|
import { reconstructEntries } from '@ccv/core/delta-reconstructor';
|
|
5
|
-
import { sanitizePathComponent } from './v2/layout.js';
|
|
5
|
+
import { sanitizePathComponent, dirSizeSync, listShards } from './v2/layout.js';
|
|
6
6
|
import { listV2Sessions } from './v2/adapter.js';
|
|
7
7
|
import { summarizeSessionPage } from './v2/session-list.js';
|
|
8
8
|
import { listSessionIds } from './v2/replay.js';
|
|
@@ -142,6 +142,11 @@ export function listV2LogsPage(logDir, project, { page = 1, pageSize = 50 } = {}
|
|
|
142
142
|
if (!existsSync(projectDir)) return out;
|
|
143
143
|
|
|
144
144
|
// Cheap pass: order candidates by startTs without paying per-session folds.
|
|
145
|
+
// Sharding (2026-11): frozen shards live INSIDE the session dir under
|
|
146
|
+
// `parts/<N>/`, so sessions/ enumerates ONLY live sessions (the parts subtree
|
|
147
|
+
// is invisible one level down) and `dirSizeSync`/`summarizeSession` already
|
|
148
|
+
// include the archived bytes — no cross-root folding needed. The shard COUNT
|
|
149
|
+
// comes from a one-level readdir of each session's parts/ dir below.
|
|
145
150
|
const candidates = [];
|
|
146
151
|
for (const dirName of listSessionIds(projectDir)) {
|
|
147
152
|
let meta = null;
|
|
@@ -149,6 +154,13 @@ export function listV2LogsPage(logDir, project, { page = 1, pageSize = 50 } = {}
|
|
|
149
154
|
if (meta && meta.leader) continue; // teammate — folded into its leader's row
|
|
150
155
|
candidates.push({ dirName, startTs: (meta && meta.startTs) || '' });
|
|
151
156
|
}
|
|
157
|
+
// Frozen-shard count per base dirName (cheap: one readdir of parts/, via the
|
|
158
|
+
// layout-owned enumerator so the numeric-name rule lives in exactly one place).
|
|
159
|
+
const shardCountByBase = new Map();
|
|
160
|
+
for (const c of candidates) {
|
|
161
|
+
const count = listShards(join(projectDir, 'sessions', c.dirName)).length;
|
|
162
|
+
if (count > 0) shardCountByBase.set(c.dirName, count);
|
|
163
|
+
}
|
|
152
164
|
// Newest first; dirName tiebreak matches listV2Logs' file tiebreak for stability.
|
|
153
165
|
candidates.sort((a, b) => b.startTs.localeCompare(a.startTs) || b.dirName.localeCompare(a.dirName));
|
|
154
166
|
out.total = candidates.length;
|
|
@@ -161,13 +173,18 @@ export function listV2LogsPage(logDir, project, { page = 1, pageSize = 50 } = {}
|
|
|
161
173
|
if (s.leader) continue;
|
|
162
174
|
if (s.size === 0) continue;
|
|
163
175
|
if (s.discard) continue; // quota-probe orphans: never listed
|
|
176
|
+
const shards = shardCountByBase.get(c.dirName) || 0;
|
|
164
177
|
out.items.push({
|
|
165
178
|
file: `v2:${project}/${s.sid}`,
|
|
166
179
|
kind: 'v2',
|
|
167
180
|
timestamp: compactLocalTs(s.startTs),
|
|
181
|
+
// s.size (dirSizeSync) already spans the parts/ shard archive — the whole
|
|
182
|
+
// session dir is one folder on disk.
|
|
168
183
|
size: s.size,
|
|
169
184
|
turns: s.turns,
|
|
170
185
|
preview: s.preview || [],
|
|
186
|
+
// 1 + frozen count = total shards (active + archived); 1 when unsharded.
|
|
187
|
+
shards: 1 + shards,
|
|
171
188
|
});
|
|
172
189
|
}
|
|
173
190
|
return out;
|
|
@@ -331,6 +348,9 @@ export function deleteLogFiles(logDir, files, opts = {}) {
|
|
|
331
348
|
let target = join(recycleDir, ref.sessionId);
|
|
332
349
|
if (existsSync(target)) target = `${target}-${now()}`;
|
|
333
350
|
renameSync(realPath, target);
|
|
351
|
+
// Sharding (2026-11): the frozen shards live INSIDE the session dir
|
|
352
|
+
// (parts/<N>/), so the rename above already carried them — nothing to
|
|
353
|
+
// cascade, no orphans.
|
|
334
354
|
results.push({ file, ok: true, movedTo: target });
|
|
335
355
|
} catch (err) {
|
|
336
356
|
results.push({ file, error: err.message });
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
createRestartBackoff,
|
|
25
25
|
} from './plugin-service-manager.js';
|
|
26
26
|
import { createProxyTracker, createPluginAgent, proxyHttpRequest, proxyUpgrade } from './plugin-proxy.js';
|
|
27
|
+
import { wireBasePath } from './base-url.js';
|
|
27
28
|
import { reportSwallowed } from './error-report.js';
|
|
28
29
|
|
|
29
30
|
const ACTIVATE_TIMEOUT_MS = 2000;
|
|
@@ -137,20 +138,38 @@ function notifyError(rt, err, info) {
|
|
|
137
138
|
|
|
138
139
|
function currentMountTarget(rt) {
|
|
139
140
|
if (!rt.child || !rt.status.port) return null;
|
|
140
|
-
|
|
141
|
-
const basePath = (_ctx?.basePath || '').replace(/\/$/, '');
|
|
142
|
-
const externalPrefix = `${basePath}${rt.entry.service.prefix}`;
|
|
141
|
+
const p = mountPrefixes(rt);
|
|
143
142
|
return {
|
|
144
143
|
name: rt.name,
|
|
145
144
|
port: rt.status.port,
|
|
146
145
|
secret: rt.child.secret,
|
|
147
|
-
externalPrefix,
|
|
148
|
-
cookiePath:
|
|
146
|
+
externalPrefix: p.externalPrefix,
|
|
147
|
+
cookiePath: p.cookiePath,
|
|
149
148
|
protocol: _ctx?.protocol || 'http',
|
|
150
149
|
agent: rt.agent,
|
|
151
150
|
};
|
|
152
151
|
}
|
|
153
152
|
|
|
153
|
+
// externalPrefix (Location / x-forwarded-prefix) stays LITERAL; cookiePath must be the WIRE
|
|
154
|
+
// form because browsers compare cookie paths against the percent-encoded request pathname.
|
|
155
|
+
// basePath is injectable for tests; production callers leave it to the server-injected ctx.
|
|
156
|
+
function mountPrefixes(rt, basePath = _ctx?.basePath || '') {
|
|
157
|
+
// basePath always has a trailing slash (normalizeBasePath) - strip it before joining to avoid '//plugins/x'
|
|
158
|
+
const literal = basePath.replace(/\/$/, '');
|
|
159
|
+
// wireBasePath needs the trailing-slash form (it falls back to literal otherwise), so
|
|
160
|
+
// serialize BEFORE stripping the slash. A base containing '{token}'-style characters
|
|
161
|
+
// arrives percent-encoded ('%7Btoken%7D') — a literal cookie Path would never be sent back.
|
|
162
|
+
const wire = wireBasePath(basePath).replace(/\/$/, '');
|
|
163
|
+
return {
|
|
164
|
+
externalPrefix: `${literal}${rt.entry.service.prefix}`,
|
|
165
|
+
cookiePath: `${wire}${rt.entry.service.prefix}/`,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Test-only export: the wire-cookie contract above regressed once (slash stripped before
|
|
170
|
+
// serializing → silent literal fallback), so the pure mapping is exposed for unit tests.
|
|
171
|
+
export const _mountPrefixesForTest = mountPrefixes;
|
|
172
|
+
|
|
154
173
|
// ---- mount table ----
|
|
155
174
|
|
|
156
175
|
function findMountByPath(pathname) {
|
|
@@ -11,6 +11,13 @@
|
|
|
11
11
|
// Result contract:
|
|
12
12
|
// inject → { status:'dispatched' } | { status:'failed', reason }
|
|
13
13
|
// spawn → { status:'completed', sessionId, durationMs } | { status:'error', reason, error? }
|
|
14
|
+
//
|
|
15
|
+
// The stored task.prompt is the RAW user text; the UltraPlan template wrapper and the
|
|
16
|
+
// quoted attachment paths are assembled HERE at fire time (assembleScheduledPrompt,
|
|
17
|
+
// shared with the web hosts via @ccv/core) so the stored prompt stays editable and
|
|
18
|
+
// summaries/toasts stay human-readable.
|
|
19
|
+
|
|
20
|
+
import { assembleScheduledPrompt } from '@ccv/core/ultraplanTemplates';
|
|
14
21
|
|
|
15
22
|
/**
|
|
16
23
|
* @param {object} task the claimed task (has .mode/.prompt/.cwd/.project/.schedule)
|
|
@@ -25,8 +32,13 @@
|
|
|
25
32
|
* }
|
|
26
33
|
*/
|
|
27
34
|
export async function executeScheduledTask(task, claim, io) {
|
|
28
|
-
|
|
29
|
-
|
|
35
|
+
// Assemble once: template wrapper + quoted attachment paths + raw prompt text.
|
|
36
|
+
// An empty assembly (no text, no attachments) means there is nothing to dispatch.
|
|
37
|
+
const prompt = assembleScheduledPrompt(task);
|
|
38
|
+
if (!prompt) return { status: 'failed', reason: 'invalid_prompt' };
|
|
39
|
+
const resolved = { ...task, prompt };
|
|
40
|
+
if (task.mode === 'spawn') return _spawn(resolved, claim, io);
|
|
41
|
+
return io.isSdkMode ? _injectSdk(resolved, io) : _injectPty(resolved, io);
|
|
30
42
|
}
|
|
31
43
|
|
|
32
44
|
async function _injectSdk(task, io) {
|