@kenhkl/agent-moss 0.17.45 → 0.17.46
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/cli.js +1164 -239
- package/dist/engine/coordinator.js +1042 -170
- package/dist/rules/inline_rules.json +2 -2
- package/dist/rules/l1_rules.json +182 -204
- package/dist/rules/l2_rules.json +6 -6
- package/dist/rules/mc_rules.json +3 -45
- package/dist/rules/script_rules.json +6 -6
- package/dist/server.js +1127 -210
- package/dist/skills/file_access_guard.md +4 -2
- package/dist/static/index.html +537 -96
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -1759,7 +1759,8 @@ function getSensitivePathsForOs(osType) {
|
|
|
1759
1759
|
credential: r.credential === true ? true : void 0,
|
|
1760
1760
|
readOnly: r.readOnly === true ? true : void 0,
|
|
1761
1761
|
denyMode: r.denyMode || void 0,
|
|
1762
|
-
dirDelOnly: r.dirDelOnly === true ? true : void 0
|
|
1762
|
+
dirDelOnly: r.dirDelOnly === true ? true : void 0,
|
|
1763
|
+
askOnMatch: r.askOnMatch === true ? true : void 0
|
|
1763
1764
|
};
|
|
1764
1765
|
const scope = _scopeOf(r.os, r.path);
|
|
1765
1766
|
if (scope === "home") home.push(entry);
|
|
@@ -1865,15 +1866,15 @@ function isScriptGeneratedTarget(targetPath, writtenScripts, shellRuns) {
|
|
|
1865
1866
|
if (!script.detail.includes(base)) continue;
|
|
1866
1867
|
const scriptName = path2.basename(script.path);
|
|
1867
1868
|
if (!scriptName) continue;
|
|
1868
|
-
if (shellRuns.some((
|
|
1869
|
+
if (shellRuns.some((run2) => run2.index > script.index && run2.command.includes(scriptName))) {
|
|
1869
1870
|
return true;
|
|
1870
1871
|
}
|
|
1871
1872
|
}
|
|
1872
1873
|
return false;
|
|
1873
1874
|
}
|
|
1874
1875
|
function parseHeadTailLimit(seg) {
|
|
1875
|
-
const
|
|
1876
|
-
if (
|
|
1876
|
+
const firstWord2 = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
|
|
1877
|
+
if (firstWord2 !== "head" && firstWord2 !== "tail") return null;
|
|
1877
1878
|
const m = seg.match(HEAD_TAIL_LIMIT_RE);
|
|
1878
1879
|
return m ? Number(m[1]) : 10;
|
|
1879
1880
|
}
|
|
@@ -1906,17 +1907,17 @@ function historyReadCoverage(histType, histDetailRaw, readKeywords, writeKeyword
|
|
|
1906
1907
|
for (const rawSeg of segments) {
|
|
1907
1908
|
const seg = rawSeg.trim();
|
|
1908
1909
|
if (!seg) continue;
|
|
1909
|
-
const
|
|
1910
|
+
const firstWord2 = seg.split(/\s+/)[0]?.toLowerCase() || "";
|
|
1910
1911
|
const paths = extractFilePaths(seg);
|
|
1911
1912
|
if (paths.length === 0) continue;
|
|
1912
|
-
if (SHELL_FULL_READ_CMDS.includes(
|
|
1913
|
+
if (SHELL_FULL_READ_CMDS.includes(firstWord2)) {
|
|
1913
1914
|
if (hasTruncatingPipe) addPartial(paths, parseHeadTailLimitForPipeline(segments));
|
|
1914
1915
|
else for (const p of paths) full.add(p);
|
|
1915
|
-
} else if (
|
|
1916
|
+
} else if (firstWord2 === "head" || firstWord2 === "tail") {
|
|
1916
1917
|
addPartial(paths, parseHeadTailLimit(seg));
|
|
1917
|
-
} else if (SHELL_PARTIAL_READ_CMDS.includes(
|
|
1918
|
+
} else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord2)) {
|
|
1918
1919
|
addPartial(paths, null);
|
|
1919
|
-
} else if (
|
|
1920
|
+
} else if (firstWord2 === "sed") {
|
|
1920
1921
|
if (SED_INPLACE_RE.test(seg)) continue;
|
|
1921
1922
|
const m = seg.match(SED_RANGE_RE);
|
|
1922
1923
|
if (m) {
|
|
@@ -1999,8 +2000,8 @@ function appendOnlyTargets(actionDetailRaw, osType) {
|
|
|
1999
2000
|
const p = m[1] || m[2] || m[3];
|
|
2000
2001
|
if (p) out.add(p);
|
|
2001
2002
|
}
|
|
2002
|
-
const
|
|
2003
|
-
if (
|
|
2003
|
+
const firstWord2 = seg.split(/\s+/)[0]?.toLowerCase() || "";
|
|
2004
|
+
if (firstWord2 === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
|
|
2004
2005
|
for (const p of extractFilePaths(seg, osType)) out.add(p);
|
|
2005
2006
|
}
|
|
2006
2007
|
}
|
|
@@ -2048,9 +2049,44 @@ function intentKeywordNegated(text, index) {
|
|
|
2048
2049
|
const prefix = text.slice(Math.max(0, index - NEGATION_WINDOW), index);
|
|
2049
2050
|
return NEGATION_WORDS.some((neg) => prefix.includes(neg));
|
|
2050
2051
|
}
|
|
2052
|
+
function isMediaCleanupInWorkdir(text) {
|
|
2053
|
+
const segs = splitCommandSegments(text).map((s) => s.trim()).filter(Boolean);
|
|
2054
|
+
let cdTarget = "";
|
|
2055
|
+
let found = false;
|
|
2056
|
+
for (const seg of segs) {
|
|
2057
|
+
const parts = seg.split(/\s+/);
|
|
2058
|
+
if (!parts.length) continue;
|
|
2059
|
+
const head = parts[0].toLowerCase();
|
|
2060
|
+
if (head === "cd" || head === "pushd") {
|
|
2061
|
+
const target = (parts[1] || "").replace(/^['"]+|['"]+$/g, "");
|
|
2062
|
+
const segPaths = target.split("/").filter(Boolean);
|
|
2063
|
+
cdTarget = target.startsWith("/") && segPaths.length > 0 && !SYSTEM_PATH_FIRST.has(segPaths[0].toLowerCase()) && segPaths.some((p) => WORKDIR_SEGMENTS.has(p.toLowerCase())) ? target : "";
|
|
2064
|
+
continue;
|
|
2065
|
+
}
|
|
2066
|
+
if (head !== "rm" || !cdTarget) continue;
|
|
2067
|
+
const flagStr = parts.slice(1).filter((t) => t.startsWith("-")).join("").toLowerCase();
|
|
2068
|
+
if (flagStr.includes("r") || !flagStr.includes("f")) return false;
|
|
2069
|
+
const targets = parts.slice(1).filter((t) => !t.startsWith("-")).map((t) => t.replace(/^['"]+|['"]+$/g, ""));
|
|
2070
|
+
if (!targets.length) return false;
|
|
2071
|
+
for (let t of targets) {
|
|
2072
|
+
t = t.replace(/\\/g, "/");
|
|
2073
|
+
while (t.startsWith("./")) t = t.slice(2);
|
|
2074
|
+
if (!t || [".", "*", "?"].includes(t)) return false;
|
|
2075
|
+
if (t.startsWith("/") || t.split("/").includes("..")) return false;
|
|
2076
|
+
if (t.includes("*") || t.includes("?")) {
|
|
2077
|
+
if (!MEDIA_GLOB_RE.test(t)) return false;
|
|
2078
|
+
} else if (!MEDIA_FILE_RE.test(t)) {
|
|
2079
|
+
return false;
|
|
2080
|
+
}
|
|
2081
|
+
found = true;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
return found;
|
|
2085
|
+
}
|
|
2051
2086
|
function isBuildArtifactCleanup(actionDetail) {
|
|
2052
2087
|
const text = (actionDetail || "").trim();
|
|
2053
2088
|
if (!text) return false;
|
|
2089
|
+
if (isMediaCleanupInWorkdir(text)) return true;
|
|
2054
2090
|
let foundRm = false;
|
|
2055
2091
|
const targets = [];
|
|
2056
2092
|
for (const raw of splitCommandSegments(text)) {
|
|
@@ -2161,6 +2197,17 @@ function intentMatrixViolation(intents, actionCat) {
|
|
|
2161
2197
|
}
|
|
2162
2198
|
return null;
|
|
2163
2199
|
}
|
|
2200
|
+
function getIntentPatternsForOs(osType) {
|
|
2201
|
+
const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
|
|
2202
|
+
if (effective) {
|
|
2203
|
+
return effective.map((p) => ({
|
|
2204
|
+
...p,
|
|
2205
|
+
allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
|
|
2206
|
+
}));
|
|
2207
|
+
}
|
|
2208
|
+
const accepted = acceptedOsValues(osType);
|
|
2209
|
+
return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
|
|
2210
|
+
}
|
|
2164
2211
|
function resolveIntentText(promptSession, promptHistory, intentKeywords) {
|
|
2165
2212
|
const cur = (promptSession || "").trim().toLowerCase();
|
|
2166
2213
|
if (intentKeywords.some((kw) => cur.includes(kw))) return cur;
|
|
@@ -2250,6 +2297,14 @@ function checkIntentConsistency(input, agentExt) {
|
|
|
2250
2297
|
};
|
|
2251
2298
|
}
|
|
2252
2299
|
if (reasonKey !== null) {
|
|
2300
|
+
let askReason = "";
|
|
2301
|
+
for (const pat of getIntentPatternsForOs(input.osType)) {
|
|
2302
|
+
if (!pat.askOnMatch) continue;
|
|
2303
|
+
if ((pat.intentKeywords || []).some((k) => intentText.includes(String(k).toLowerCase())) && (pat.dangerousActions || []).some((a) => actionDetail.includes(String(a).toLowerCase()))) {
|
|
2304
|
+
askReason = `\u89C4\u5219\u300C${pat.reason}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
|
|
2305
|
+
break;
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2253
2308
|
return {
|
|
2254
2309
|
allowed: false,
|
|
2255
2310
|
reason: INTENT_REASONS[reasonKey] || "\u539F\u59CB\u610F\u56FE\u4E0E\u6267\u884C\u52A8\u4F5C\u4E0D\u4E00\u81F4",
|
|
@@ -2257,7 +2312,8 @@ function checkIntentConsistency(input, agentExt) {
|
|
|
2257
2312
|
riskType: "intent_deviation",
|
|
2258
2313
|
confidence: 85,
|
|
2259
2314
|
source: "logic_rule",
|
|
2260
|
-
violatedLayers: ["L2.1"]
|
|
2315
|
+
violatedLayers: ["L2.1"],
|
|
2316
|
+
...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
|
|
2261
2317
|
};
|
|
2262
2318
|
}
|
|
2263
2319
|
if ((actionCat === "overwrite" || actionCat === "delete") && intents.size === 0) {
|
|
@@ -2319,6 +2375,25 @@ function runLogicCheck(input, opts) {
|
|
|
2319
2375
|
if (comboResult) return comboResult;
|
|
2320
2376
|
return null;
|
|
2321
2377
|
}
|
|
2378
|
+
function computeComboStageHits(detail) {
|
|
2379
|
+
const hits = /* @__PURE__ */ new Set();
|
|
2380
|
+
for (const [stage, pats] of Object.entries(COMBO_STAGES)) {
|
|
2381
|
+
if (pats.some((p) => {
|
|
2382
|
+
p.lastIndex = 0;
|
|
2383
|
+
return p.test(detail);
|
|
2384
|
+
})) hits.add(stage);
|
|
2385
|
+
}
|
|
2386
|
+
return hits;
|
|
2387
|
+
}
|
|
2388
|
+
function comboStageHits(detail) {
|
|
2389
|
+
if (detail.length > 2048) return computeComboStageHits(detail);
|
|
2390
|
+
const cached2 = comboStageHitsCache.get(detail);
|
|
2391
|
+
if (cached2) return cached2;
|
|
2392
|
+
const value = computeComboStageHits(detail);
|
|
2393
|
+
if (comboStageHitsCache.size >= COMBO_STAGE_CACHE_MAX) comboStageHitsCache.clear();
|
|
2394
|
+
comboStageHitsCache.set(detail, value);
|
|
2395
|
+
return value;
|
|
2396
|
+
}
|
|
2322
2397
|
function checkComboChain(actionHistory, actionDetailRaw) {
|
|
2323
2398
|
INLINE_SCRIPT_RE.lastIndex = 0;
|
|
2324
2399
|
if (INLINE_SCRIPT_RE.test(actionDetailRaw)) return null;
|
|
@@ -2327,16 +2402,7 @@ function checkComboChain(actionHistory, actionDetailRaw) {
|
|
|
2327
2402
|
if (h.actionDetail) details.push(h.actionDetail.toLowerCase());
|
|
2328
2403
|
}
|
|
2329
2404
|
details.push(actionDetailRaw.toLowerCase());
|
|
2330
|
-
const seq = details.map((d) =>
|
|
2331
|
-
const hits = /* @__PURE__ */ new Set();
|
|
2332
|
-
for (const [stage, pats] of Object.entries(COMBO_STAGES)) {
|
|
2333
|
-
if (pats.some((p) => {
|
|
2334
|
-
p.lastIndex = 0;
|
|
2335
|
-
return p.test(d);
|
|
2336
|
-
})) hits.add(stage);
|
|
2337
|
-
}
|
|
2338
|
-
return hits;
|
|
2339
|
-
});
|
|
2405
|
+
const seq = details.map((d) => comboStageHits(d));
|
|
2340
2406
|
for (const chain of COMBO_CHAINS) {
|
|
2341
2407
|
const chainStages = chain.stages;
|
|
2342
2408
|
if (!chainStages.length || chain.min_stages <= 0) continue;
|
|
@@ -2443,15 +2509,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2443
2509
|
for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
|
|
2444
2510
|
const trimmed = seg.trim();
|
|
2445
2511
|
if (!trimmed) continue;
|
|
2446
|
-
const
|
|
2447
|
-
if (
|
|
2512
|
+
const firstWord2 = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
|
|
2513
|
+
if (firstWord2 === "cd") {
|
|
2448
2514
|
continue;
|
|
2449
2515
|
}
|
|
2450
2516
|
if (SHELL_ASSIGN_RE.test(trimmed)) {
|
|
2451
2517
|
continue;
|
|
2452
2518
|
}
|
|
2453
|
-
if (
|
|
2454
|
-
} else if (getPlatformTraits(osType).readOnlyCommands.has(
|
|
2519
|
+
if (firstWord2 === "sed" && SED_INPLACE_RE.test(trimmed)) {
|
|
2520
|
+
} else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord2)) {
|
|
2455
2521
|
const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
|
|
2456
2522
|
const segNoDevnull = segUnquoted.replace(DEVNULL_REDIRECT_RE, "");
|
|
2457
2523
|
const segNoQuotes = segNoDevnull.replace(/'[^']*'|"[^"]*"/g, "");
|
|
@@ -2460,15 +2526,15 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2460
2526
|
continue;
|
|
2461
2527
|
}
|
|
2462
2528
|
const segPaths = extractFilePaths(trimmed, osType);
|
|
2463
|
-
const segPathsFiltered =
|
|
2464
|
-
if (SOURCE_ARG_CMDS.has(
|
|
2529
|
+
const segPathsFiltered = firstWord2 === "wget" || firstWord2 === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
|
|
2530
|
+
if (SOURCE_ARG_CMDS.has(firstWord2)) {
|
|
2465
2531
|
if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
|
|
2466
|
-
} else if (
|
|
2532
|
+
} else if (firstWord2 === "tar") {
|
|
2467
2533
|
if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
|
|
2468
2534
|
const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
|
|
2469
2535
|
if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
|
|
2470
2536
|
}
|
|
2471
|
-
} else if (
|
|
2537
|
+
} else if (firstWord2 === "dd") {
|
|
2472
2538
|
const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
|
|
2473
2539
|
const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
|
|
2474
2540
|
const devNullMatches = trimmed.match(/\bof=(\/dev\/\S+)/g);
|
|
@@ -2640,7 +2706,8 @@ function hasValidConsent(actionHistory, aNext) {
|
|
|
2640
2706
|
}
|
|
2641
2707
|
function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, aNext) {
|
|
2642
2708
|
if (!BASH_LIKE_ACTION_TYPES.includes(actionType)) return null;
|
|
2643
|
-
const
|
|
2709
|
+
const pwdRules = runtimeConfigBridge.current?.effectivePasswordRules(osType) ?? PASSWORD_MODIFY_PATTERNS.map((p) => ({ pattern: p, askOnMatch: false }));
|
|
2710
|
+
const pwdPatterns = pwdRules.map((r) => r.pattern);
|
|
2644
2711
|
let isPasswordModify = pwdPatterns.some((p) => p.test(actionDetail));
|
|
2645
2712
|
if (isPasswordModify && !hasExecBypassChain(actionDetail)) {
|
|
2646
2713
|
const noQuotes = actionDetail.replace(ALL_QUOTES_RE, " ");
|
|
@@ -2648,6 +2715,7 @@ function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, a
|
|
|
2648
2715
|
}
|
|
2649
2716
|
if (!isPasswordModify) return null;
|
|
2650
2717
|
if (hasValidConsent(actionHistory, aNext)) return null;
|
|
2718
|
+
const askRule = pwdRules.find((r) => r.askOnMatch && r.pattern.test(actionDetail));
|
|
2651
2719
|
return {
|
|
2652
2720
|
allowed: false,
|
|
2653
2721
|
reason: "\u6267\u884C\u975E\u4EA4\u4E92\u5F0F\u5BC6\u7801\u4FEE\u6539\u547D\u4EE4\uFF0C\u4F46\u5386\u53F2\u6267\u884C\u5E8F\u5217\u4E2D\u672A\u53D1\u73B0\u7528\u6237\u660E\u786E\u6388\u6743\u7684 ask_user_question\uFF08\u987B\u7528\u6237\u6B63\u9762\u56DE\u7B54\u4E14\u4E0E\u672C\u6B21\u64CD\u4F5C\u76F8\u5173\uFF09\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6388\u6743\u7684\u5BC6\u7801\u4FEE\u6539\u98CE\u9669",
|
|
@@ -2655,15 +2723,18 @@ function checkPasswordConsent(actionType, actionDetail, actionHistory, osType, a
|
|
|
2655
2723
|
riskType: "consent_missing",
|
|
2656
2724
|
confidence: 85,
|
|
2657
2725
|
source: "logic_rule",
|
|
2658
|
-
violatedLayers: ["L2.1"]
|
|
2726
|
+
violatedLayers: ["L2.1"],
|
|
2727
|
+
...askRule ? { ask_recommended: true, ask_reason: "\u5BC6\u7801\u4FEE\u6539\u89C4\u5219\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237" } : {}
|
|
2659
2728
|
};
|
|
2660
2729
|
}
|
|
2661
2730
|
function checkUserDeletionConsent(actionType, actionDetail, actionHistory, osType, aNext) {
|
|
2662
2731
|
if (!BASH_LIKE_ACTION_TYPES.includes(actionType)) return null;
|
|
2663
|
-
const
|
|
2732
|
+
const udRules = runtimeConfigBridge.current?.effectiveUserDeletionRules(osType) ?? USER_DELETION_PATTERNS.map((p) => ({ pattern: p, askOnMatch: false }));
|
|
2733
|
+
const udPatterns = udRules.map((r) => r.pattern);
|
|
2664
2734
|
const isUserDeletion = udPatterns.some((p) => p.test(actionDetail));
|
|
2665
2735
|
if (!isUserDeletion) return null;
|
|
2666
2736
|
if (hasValidConsent(actionHistory, aNext)) return null;
|
|
2737
|
+
const askRule = udRules.find((r) => r.askOnMatch && r.pattern.test(actionDetail));
|
|
2667
2738
|
return {
|
|
2668
2739
|
allowed: false,
|
|
2669
2740
|
reason: "\u6267\u884C\u5220\u9664\u7CFB\u7EDF\u7528\u6237\u547D\u4EE4\uFF0C\u4F46\u5386\u53F2\u6267\u884C\u5E8F\u5217\u4E2D\u672A\u53D1\u73B0\u7528\u6237\u660E\u786E\u6388\u6743\u7684 ask_user_question\uFF08\u987B\u7528\u6237\u6B63\u9762\u56DE\u7B54\u4E14\u4E0E\u672C\u6B21\u64CD\u4F5C\u76F8\u5173\uFF09\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6388\u6743\u7684\u7528\u6237\u5220\u9664\u98CE\u9669",
|
|
@@ -2671,7 +2742,8 @@ function checkUserDeletionConsent(actionType, actionDetail, actionHistory, osTyp
|
|
|
2671
2742
|
riskType: "consent_missing",
|
|
2672
2743
|
confidence: 85,
|
|
2673
2744
|
source: "logic_rule",
|
|
2674
|
-
violatedLayers: ["L2.1"]
|
|
2745
|
+
violatedLayers: ["L2.1"],
|
|
2746
|
+
...askRule ? { ask_recommended: true, ask_reason: "\u7528\u6237\u5220\u9664\u89C4\u5219\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237" } : {}
|
|
2675
2747
|
};
|
|
2676
2748
|
}
|
|
2677
2749
|
function containsPrivilegeEscalation(actionDetail) {
|
|
@@ -2765,7 +2837,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
|
|
|
2765
2837
|
violatedLayers: ["L2.1"]
|
|
2766
2838
|
};
|
|
2767
2839
|
}
|
|
2768
|
-
var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
|
|
2840
|
+
var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SCRIPT_FILE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, NEGATION_WORDS, NEGATION_WINDOW, EXPLICIT_READONLY_RE, UPDATE_INTENT_RE, EXPLICIT_NO_DELETE_RE, INTENT_AMBIGUITY_RE, BUILD_ARTIFACT_NAMES, BUILD_ARTIFACT_GLOB_RE, MEDIA_TEMP_EXTS, MEDIA_GLOB_RE, MEDIA_FILE_RE, WORKDIR_SEGMENTS, SYSTEM_PATH_FIRST, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, COMBO_STAGE_CACHE_MAX, comboStageHitsCache, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
|
|
2769
2841
|
var init_logic_rules = __esm({
|
|
2770
2842
|
"src/engine/logic-rules.ts"() {
|
|
2771
2843
|
"use strict";
|
|
@@ -2892,6 +2964,48 @@ var init_logic_rules = __esm({
|
|
|
2892
2964
|
"htmlcov"
|
|
2893
2965
|
]);
|
|
2894
2966
|
BUILD_ARTIFACT_GLOB_RE = /^\*\.(?:pyc|pyo|class|o|obj|d|egg-info)$/i;
|
|
2967
|
+
MEDIA_TEMP_EXTS = "mp4|mov|avi|mkv|webm|flv|wmv|m4v|jpg|jpeg|png|gif|webp|bmp|tif|tiff|wav|mp3|m4a|aac|flac|ogg|tmp|part|log";
|
|
2968
|
+
MEDIA_GLOB_RE = new RegExp(`^[A-Za-z0-9_.-]+\\*\\.(?:${MEDIA_TEMP_EXTS})$`, "i");
|
|
2969
|
+
MEDIA_FILE_RE = new RegExp(`^[A-Za-z0-9_.-]+\\.(?:${MEDIA_TEMP_EXTS})$`, "i");
|
|
2970
|
+
WORKDIR_SEGMENTS = /* @__PURE__ */ new Set([
|
|
2971
|
+
"result",
|
|
2972
|
+
"results",
|
|
2973
|
+
"output",
|
|
2974
|
+
"outputs",
|
|
2975
|
+
"out",
|
|
2976
|
+
"work",
|
|
2977
|
+
"workdir",
|
|
2978
|
+
"work_extract",
|
|
2979
|
+
"tmp",
|
|
2980
|
+
"temp",
|
|
2981
|
+
"cache",
|
|
2982
|
+
".cache",
|
|
2983
|
+
"build",
|
|
2984
|
+
"dist",
|
|
2985
|
+
"target",
|
|
2986
|
+
"extract",
|
|
2987
|
+
"extracted",
|
|
2988
|
+
"clips",
|
|
2989
|
+
"artifacts",
|
|
2990
|
+
"__pycache__"
|
|
2991
|
+
]);
|
|
2992
|
+
SYSTEM_PATH_FIRST = /* @__PURE__ */ new Set([
|
|
2993
|
+
"etc",
|
|
2994
|
+
"usr",
|
|
2995
|
+
"bin",
|
|
2996
|
+
"sbin",
|
|
2997
|
+
"lib",
|
|
2998
|
+
"lib64",
|
|
2999
|
+
"boot",
|
|
3000
|
+
"root",
|
|
3001
|
+
"sys",
|
|
3002
|
+
"proc",
|
|
3003
|
+
"dev",
|
|
3004
|
+
"run",
|
|
3005
|
+
"srv",
|
|
3006
|
+
"home",
|
|
3007
|
+
"var"
|
|
3008
|
+
]);
|
|
2895
3009
|
REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
|
|
2896
3010
|
REFERENCE_LOOKBACK = 3;
|
|
2897
3011
|
EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
|
|
@@ -2913,6 +3027,8 @@ var init_logic_rules = __esm({
|
|
|
2913
3027
|
reason: String(c.reason || "\u68C0\u6D4B\u5230\u7EC4\u5408\u653B\u51FB\u94FE")
|
|
2914
3028
|
}));
|
|
2915
3029
|
})();
|
|
3030
|
+
COMBO_STAGE_CACHE_MAX = 8192;
|
|
3031
|
+
comboStageHitsCache = /* @__PURE__ */ new Map();
|
|
2916
3032
|
CONSENT_TOPIC = /密码|口令|passwd|password|凭据|凭证|用户|账户|账号|userdel|deluser|groupdel/i;
|
|
2917
3033
|
CONSENT_NEGATIVE = /(?:否|不|别|取消|拒绝|停止|终止|算了|\bno\b|\bnope\b|\bcancel\b|\babort\b|\bstop\b|\bdeny\b|\breject\b|\bdecline\b|\bdon'?t\b|\bdo\s+not\b)/i;
|
|
2918
3034
|
CONSENT_AFFIRMATIVE = /(?:是|好|可以|行|嗯|对|确认|同意|继续|执行|删除|删掉|移除|修改|重置|改密|\byes\b|\by\b|\byep\b|\byeah\b|\bok\b|\bokay\b|\bconfirm(?:ed)?\b|\bproceed\b|\bcontinue\b|\bsure\b|\bapprove\b|\baccept\b|\bagree\b|\bdo\s+it\b|\bgo\s+ahead\b)/i;
|
|
@@ -3095,6 +3211,7 @@ var init_skill_loader = __esm({
|
|
|
3095
3211
|
// src/infra/runtime-config.ts
|
|
3096
3212
|
var runtime_config_exports = {};
|
|
3097
3213
|
__export(runtime_config_exports, {
|
|
3214
|
+
BUILTIN_DETECTOR_DEFAULTS: () => BUILTIN_DETECTOR_DEFAULTS,
|
|
3098
3215
|
DEFAULT_LAYERS: () => DEFAULT_LAYERS,
|
|
3099
3216
|
DENY_MODE_LABELS: () => DENY_MODE_LABELS,
|
|
3100
3217
|
addAgentRule: () => addAgentRule,
|
|
@@ -3109,14 +3226,19 @@ __export(runtime_config_exports, {
|
|
|
3109
3226
|
effectiveInjectionKeywords: () => effectiveInjectionKeywords,
|
|
3110
3227
|
effectiveIntentPatterns: () => effectiveIntentPatterns,
|
|
3111
3228
|
effectivePasswordPatterns: () => effectivePasswordPatterns,
|
|
3229
|
+
effectivePasswordRules: () => effectivePasswordRules,
|
|
3112
3230
|
effectiveSensitivePaths: () => effectiveSensitivePaths,
|
|
3113
3231
|
effectiveUserDeletionPatterns: () => effectiveUserDeletionPatterns,
|
|
3232
|
+
effectiveUserDeletionRules: () => effectiveUserDeletionRules,
|
|
3114
3233
|
filterEnabledRules: () => filterEnabledRules,
|
|
3115
3234
|
generateSourceDefaults: () => generateSourceDefaults,
|
|
3116
3235
|
getAgentRules: () => getAgentRules,
|
|
3236
|
+
getBuiltinAskMap: () => getBuiltinAskMap,
|
|
3117
3237
|
getDisabledL2RulesWithSkipL3: () => getDisabledL2RulesWithSkipL3,
|
|
3118
3238
|
getDisabledSkillIds: () => getDisabledSkillIds,
|
|
3119
3239
|
getEnabledAgentExtensions: () => getEnabledAgentExtensions,
|
|
3240
|
+
getEnabledBuiltinDetectors: () => getEnabledBuiltinDetectors,
|
|
3241
|
+
getEnabledBuiltinDetectorsOrCurrent: () => getEnabledBuiltinDetectorsOrCurrent,
|
|
3120
3242
|
getEnabledL1CommandPatterns: () => getEnabledL1CommandPatterns,
|
|
3121
3243
|
getEnabledL1CommandPatternsOrDefault: () => getEnabledL1CommandPatternsOrDefault,
|
|
3122
3244
|
getEnabledL1InjectionKeywords: () => getEnabledL1InjectionKeywords,
|
|
@@ -3125,10 +3247,12 @@ __export(runtime_config_exports, {
|
|
|
3125
3247
|
getEnabledL2IntentPatternsOrDefault: () => getEnabledL2IntentPatternsOrDefault,
|
|
3126
3248
|
getEnabledL2PasswordPatterns: () => getEnabledL2PasswordPatterns,
|
|
3127
3249
|
getEnabledL2PasswordPatternsOrDefault: () => getEnabledL2PasswordPatternsOrDefault,
|
|
3250
|
+
getEnabledL2PasswordRules: () => getEnabledL2PasswordRules,
|
|
3128
3251
|
getEnabledL2SensitivePaths: () => getEnabledL2SensitivePaths,
|
|
3129
3252
|
getEnabledL2SensitivePathsOrDefault: () => getEnabledL2SensitivePathsOrDefault,
|
|
3130
3253
|
getEnabledL2UserDeletionPatterns: () => getEnabledL2UserDeletionPatterns,
|
|
3131
3254
|
getEnabledL2UserDeletionPatternsOrDefault: () => getEnabledL2UserDeletionPatternsOrDefault,
|
|
3255
|
+
getEnabledL2UserDeletionRules: () => getEnabledL2UserDeletionRules,
|
|
3132
3256
|
getEnabledScenarioExtensions: () => getEnabledScenarioExtensions,
|
|
3133
3257
|
getEnvOverrides: () => getEnvOverrides,
|
|
3134
3258
|
getProfileOrDetect: () => getProfileOrDetect,
|
|
@@ -3145,8 +3269,11 @@ __export(runtime_config_exports, {
|
|
|
3145
3269
|
saveRuntimeConfig: () => saveRuntimeConfig,
|
|
3146
3270
|
updateAgentCategoryEnabled: () => updateAgentCategoryEnabled,
|
|
3147
3271
|
updateAgentRuleEnabled: () => updateAgentRuleEnabled,
|
|
3272
|
+
updateCategoryAsk: () => updateCategoryAsk,
|
|
3148
3273
|
updateCategoryEnabled: () => updateCategoryEnabled,
|
|
3274
|
+
updateInjectionTierEnabled: () => updateInjectionTierEnabled,
|
|
3149
3275
|
updateLayerEnabled: () => updateLayerEnabled,
|
|
3276
|
+
updateRuleAsk: () => updateRuleAsk,
|
|
3150
3277
|
updateRuleDenyMode: () => updateRuleDenyMode,
|
|
3151
3278
|
updateRuleEnabled: () => updateRuleEnabled,
|
|
3152
3279
|
updateRuleSkipL3: () => updateRuleSkipL3,
|
|
@@ -3344,23 +3471,22 @@ function getEnabledL1CommandPatterns(runtime, osType) {
|
|
|
3344
3471
|
rules = _mergeUserCustom(rules, runtime, "L1_rules", "pattern");
|
|
3345
3472
|
if (osType) rules = _filterRulesByOs(rules, osType);
|
|
3346
3473
|
return rules.map((r) => ({
|
|
3474
|
+
id: r.id || "",
|
|
3347
3475
|
pattern: r.pattern || "",
|
|
3348
3476
|
risk_level: r.risk_level || "",
|
|
3349
3477
|
risk_type: r.risk_type || "",
|
|
3350
|
-
reason: r.reason || ""
|
|
3478
|
+
reason: r.reason || "",
|
|
3479
|
+
ask_on_match: r.ask_on_match === true
|
|
3351
3480
|
}));
|
|
3352
3481
|
}
|
|
3353
3482
|
function getEnabledL2SensitivePaths(runtime, osType) {
|
|
3354
|
-
|
|
3355
|
-
if (!cat || !cat.rules || cat.rules.length === 0) {
|
|
3356
|
-
cat = runtime.L2_rules?.sensitive_path_access || { category_enabled: true, rules: [] };
|
|
3357
|
-
}
|
|
3483
|
+
const cat = _sensitivePathCategoryOf(runtime) || { category_enabled: true, rules: [] };
|
|
3358
3484
|
let rules = filterEnabledRules(cat.rules || [], cat.category_enabled);
|
|
3359
3485
|
rules = _mergeRulesFromDirs(rules, "sensitive_path_access");
|
|
3360
3486
|
rules = _mergeUserCustom(rules, runtime, ["L1_rules", "L2_rules"], "path");
|
|
3361
3487
|
if (osType) rules = _filterRulesByOs(rules, osType);
|
|
3362
3488
|
return rules.map((r) => {
|
|
3363
|
-
const out = { path: r.path || "", risk_level: r.risk_level || "", desc: r.desc || "", deny_mode: r.deny_mode || "deny_write" };
|
|
3489
|
+
const out = { id: r.id || "", path: r.path || "", risk_level: r.risk_level || "", desc: r.desc || "", deny_mode: r.deny_mode || "deny_write", ask_on_match: r.ask_on_match === true };
|
|
3364
3490
|
if (r.credential) out.credential = true;
|
|
3365
3491
|
if (r.read_only) out.read_only = true;
|
|
3366
3492
|
if (r.dir_del_only) out.dir_del_only = true;
|
|
@@ -3465,7 +3591,8 @@ function _l1CommandPatternsToRules() {
|
|
|
3465
3591
|
reason: p.description,
|
|
3466
3592
|
enabled: true,
|
|
3467
3593
|
builtin: true,
|
|
3468
|
-
os: p.os || "linux"
|
|
3594
|
+
os: p.os || "linux",
|
|
3595
|
+
ask_on_match: p.ask_on_match === true
|
|
3469
3596
|
};
|
|
3470
3597
|
const fp = _ruleFingerprint(rule);
|
|
3471
3598
|
if (seen.has(fp)) continue;
|
|
@@ -3481,6 +3608,7 @@ function _l1InjectionKeywordsToRules() {
|
|
|
3481
3608
|
keyword: kw.keyword,
|
|
3482
3609
|
risk_level: kw.riskLevel,
|
|
3483
3610
|
lang: kw.lang || "en",
|
|
3611
|
+
tier: kw.tier || "",
|
|
3484
3612
|
// 带上条目自己的 os(`all` = 全平台通用),别丢 —— 丢了 Windows 会拿到
|
|
3485
3613
|
// 本不该给它的条目。与 Python `_l1_injection_keywords_to_rules` 对齐。
|
|
3486
3614
|
os: kw.os,
|
|
@@ -3514,7 +3642,8 @@ function _l2SensitivePathsToRules() {
|
|
|
3514
3642
|
skip_l3_on_disabled: true,
|
|
3515
3643
|
enabled: true,
|
|
3516
3644
|
builtin: true,
|
|
3517
|
-
os: os6
|
|
3645
|
+
os: os6,
|
|
3646
|
+
ask_on_match: sp.ask_on_match === true
|
|
3518
3647
|
};
|
|
3519
3648
|
_syncDenyModeFields(rule);
|
|
3520
3649
|
if (sp.dirDelOnly) rule.dir_del_only = true;
|
|
@@ -3537,7 +3666,8 @@ function _l2IntentPatternsToRules() {
|
|
|
3537
3666
|
allow_if_write_intent: pat.allowIfWriteIntent,
|
|
3538
3667
|
skip_l3_on_disabled: true,
|
|
3539
3668
|
enabled: true,
|
|
3540
|
-
builtin: true
|
|
3669
|
+
builtin: true,
|
|
3670
|
+
ask_on_match: pat.askOnMatch === true
|
|
3541
3671
|
}));
|
|
3542
3672
|
}
|
|
3543
3673
|
function _l2PasswordPatternsToRules() {
|
|
@@ -3707,6 +3837,19 @@ function _agentRulesToDefaults() {
|
|
|
3707
3837
|
}
|
|
3708
3838
|
return out;
|
|
3709
3839
|
}
|
|
3840
|
+
function getEnabledBuiltinDetectors(runtime) {
|
|
3841
|
+
const cat = runtime?.L1_rules?.builtin_detectors;
|
|
3842
|
+
if (!cat || typeof cat !== "object") {
|
|
3843
|
+
return new Set(BUILTIN_DETECTOR_DEFAULTS.map((r) => r.id));
|
|
3844
|
+
}
|
|
3845
|
+
if (cat.category_enabled === false) return /* @__PURE__ */ new Set();
|
|
3846
|
+
return new Set(
|
|
3847
|
+
(cat.rules || []).filter((r) => r && r.id && r.enabled !== false && !r.source_removed).map((r) => String(r.id))
|
|
3848
|
+
);
|
|
3849
|
+
}
|
|
3850
|
+
function getEnabledBuiltinDetectorsOrCurrent() {
|
|
3851
|
+
return getEnabledBuiltinDetectors(loadRuntimeConfig());
|
|
3852
|
+
}
|
|
3710
3853
|
function generateSourceDefaults() {
|
|
3711
3854
|
return {
|
|
3712
3855
|
version: 1,
|
|
@@ -3719,7 +3862,8 @@ function generateSourceDefaults() {
|
|
|
3719
3862
|
},
|
|
3720
3863
|
injection_detection: {
|
|
3721
3864
|
category_enabled: true,
|
|
3722
|
-
|
|
3865
|
+
tier_enabled: { strong: true, weak: true },
|
|
3866
|
+
category_desc: "\u53EF\u7591\u6CE8\u5165\u7279\u5F81\uFF08\u53EA\u4F5C\u4E3A L3 \u7EBF\u7D22\uFF0C\u4E0D\u76F4\u63A5\u62E6\u622A\uFF09",
|
|
3723
3867
|
rules: _l1InjectionKeywordsToRules()
|
|
3724
3868
|
},
|
|
3725
3869
|
sensitive_path_access: {
|
|
@@ -3727,6 +3871,11 @@ function generateSourceDefaults() {
|
|
|
3727
3871
|
category_desc: "\u654F\u611F\u8DEF\u5F84\u8BBF\u95EE\u68C0\u6D4B\uFF08deny_both/deny_read/deny_write\uFF09",
|
|
3728
3872
|
rules: _l2SensitivePathsToRules()
|
|
3729
3873
|
},
|
|
3874
|
+
builtin_detectors: {
|
|
3875
|
+
category_enabled: true,
|
|
3876
|
+
category_desc: "\u4EE3\u7801\u5185\u7F6E\u68C0\u6D4B\uFF08\u5371\u9669\u6A21\u5F0F / \u4E3B\u76EE\u5F55\u5220\u9664 / \u6A2A\u5411\u79FB\u52A8 / \u89E3\u7801\u5206\u6790\uFF09",
|
|
3877
|
+
rules: BUILTIN_DETECTOR_DEFAULTS.map((r) => ({ ...r }))
|
|
3878
|
+
},
|
|
3730
3879
|
user_custom: { category_enabled: true, category_desc: "\u7528\u6237\u81EA\u5B9A\u4E49\u547D\u4EE4\u89C4\u5219", rules: [] }
|
|
3731
3880
|
},
|
|
3732
3881
|
L2_rules: {
|
|
@@ -3826,6 +3975,7 @@ function _mergeRuleCategories(userCfg, srcDefaults, layerKey) {
|
|
|
3826
3975
|
const existing = userByFp.get(fp);
|
|
3827
3976
|
const userDisabled = existing.user_disabled === true;
|
|
3828
3977
|
const userSkipL3 = existing.skip_l3_on_disabled;
|
|
3978
|
+
const userAsk = existing.ask_on_match;
|
|
3829
3979
|
const userDenyMode = existing.deny_mode;
|
|
3830
3980
|
const userSourceDeny = existing.source_deny_mode;
|
|
3831
3981
|
Object.keys(existing).forEach((k) => delete existing[k]);
|
|
@@ -3833,6 +3983,7 @@ function _mergeRuleCategories(userCfg, srcDefaults, layerKey) {
|
|
|
3833
3983
|
existing.enabled = !userDisabled;
|
|
3834
3984
|
if (userDisabled) existing.user_disabled = true;
|
|
3835
3985
|
if (userSkipL3 !== void 0) existing.skip_l3_on_disabled = userSkipL3;
|
|
3986
|
+
if (userAsk !== void 0) existing.ask_on_match = userAsk === true;
|
|
3836
3987
|
if (userDenyMode && userSourceDeny && userDenyMode !== userSourceDeny) {
|
|
3837
3988
|
existing.deny_mode = userDenyMode;
|
|
3838
3989
|
}
|
|
@@ -3972,6 +4123,7 @@ function _migrateCategoriesAcrossLayers(cfg, srcLayer, dstLayer, catNames) {
|
|
|
3972
4123
|
const dstCat = dst[catName];
|
|
3973
4124
|
if (!dstCat.category_desc && srcCat.category_desc) dstCat.category_desc = srcCat.category_desc;
|
|
3974
4125
|
if (dstCat.category_enabled === void 0) dstCat.category_enabled = srcCat.category_enabled;
|
|
4126
|
+
if (dstCat.tier_enabled === void 0) dstCat.tier_enabled = { ...srcCat.tier_enabled || {} };
|
|
3975
4127
|
if (srcCat.rules && srcCat.rules.length > 0) {
|
|
3976
4128
|
const dstFps = new Set((dstCat.rules || []).map((r) => _ruleFingerprint(r)));
|
|
3977
4129
|
for (const r of srcCat.rules) {
|
|
@@ -3988,13 +4140,16 @@ function _migrateCategoriesAcrossLayers(cfg, srcLayer, dstLayer, catNames) {
|
|
|
3988
4140
|
function getEnabledL1InjectionKeywords(runtime, osType) {
|
|
3989
4141
|
const cat = runtime.L1_rules?.injection_detection || { category_enabled: true, rules: [] };
|
|
3990
4142
|
let rules = filterEnabledRules(cat.rules || [], cat.category_enabled);
|
|
4143
|
+
const tierEnabled = cat.tier_enabled || {};
|
|
4144
|
+
rules = rules.filter((r) => !r.tier || tierEnabled[r.tier] !== false);
|
|
3991
4145
|
rules = _mergeRulesFromDirs(rules, "injection_detection");
|
|
3992
4146
|
rules = _mergeUserCustom(rules, runtime, "L1_rules", "keyword");
|
|
3993
4147
|
if (osType) rules = _filterRulesByOs(rules, osType);
|
|
3994
4148
|
return rules.map((r) => ({
|
|
3995
4149
|
keyword: r.keyword || "",
|
|
3996
4150
|
risk_level: r.risk_level || "",
|
|
3997
|
-
lang: r.lang || "en"
|
|
4151
|
+
lang: r.lang || "en",
|
|
4152
|
+
tier: String(r.tier || "")
|
|
3998
4153
|
}));
|
|
3999
4154
|
}
|
|
4000
4155
|
function getEnabledL2IntentPatterns(runtime, osType) {
|
|
@@ -4008,9 +4163,40 @@ function getEnabledL2IntentPatterns(runtime, osType) {
|
|
|
4008
4163
|
dangerous_actions: r.dangerous_actions || [],
|
|
4009
4164
|
reason: r.reason || "",
|
|
4010
4165
|
allow_if_write_intent: r.allow_if_write_intent === true,
|
|
4011
|
-
os: r.os
|
|
4166
|
+
os: r.os,
|
|
4167
|
+
id: r.id || "",
|
|
4168
|
+
ask_on_match: r.ask_on_match === true
|
|
4012
4169
|
}));
|
|
4013
4170
|
}
|
|
4171
|
+
function getEnabledL2PasswordRules(runtime) {
|
|
4172
|
+
const cat = runtime.L2_rules?.password_modify_consent || { category_enabled: true, rules: [] };
|
|
4173
|
+
return _mergeUserCustom(
|
|
4174
|
+
_mergeRulesFromDirs(filterEnabledRules(cat.rules || [], cat.category_enabled), "password_modify_consent"),
|
|
4175
|
+
runtime,
|
|
4176
|
+
"L2_rules",
|
|
4177
|
+
"pattern"
|
|
4178
|
+
);
|
|
4179
|
+
}
|
|
4180
|
+
function getEnabledL2UserDeletionRules(runtime) {
|
|
4181
|
+
const cat = runtime.L2_rules?.user_deletion_consent || { category_enabled: true, rules: [] };
|
|
4182
|
+
return _mergeUserCustom(
|
|
4183
|
+
_mergeRulesFromDirs(filterEnabledRules(cat.rules || [], cat.category_enabled), "user_deletion_consent"),
|
|
4184
|
+
runtime,
|
|
4185
|
+
"L2_rules",
|
|
4186
|
+
"pattern"
|
|
4187
|
+
);
|
|
4188
|
+
}
|
|
4189
|
+
function getBuiltinAskMap(runtime) {
|
|
4190
|
+
const cat = runtime?.L1_rules?.builtin_detectors;
|
|
4191
|
+
const out = {};
|
|
4192
|
+
if (!cat || typeof cat !== "object") return out;
|
|
4193
|
+
for (const r of cat.rules || []) {
|
|
4194
|
+
const rid = String(r?.id || "");
|
|
4195
|
+
if (!rid) continue;
|
|
4196
|
+
out[rid] = r.ask_on_match && r.enabled !== false ? `\u89C4\u5219\u300C${r.reason || rid}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237` : "";
|
|
4197
|
+
}
|
|
4198
|
+
return out;
|
|
4199
|
+
}
|
|
4014
4200
|
function getEnabledL2PasswordPatterns(runtime) {
|
|
4015
4201
|
const cat = runtime.L2_rules?.password_modify_consent || { category_enabled: true, rules: [] };
|
|
4016
4202
|
const rules = _mergeUserCustom(
|
|
@@ -4142,7 +4328,8 @@ function effectiveDangerousPatterns(osType) {
|
|
|
4142
4328
|
severity: String(r.risk_level || "medium"),
|
|
4143
4329
|
riskType: String(r.risk_type || ""),
|
|
4144
4330
|
description: String(r.reason || ""),
|
|
4145
|
-
os: String(r.os || "linux").toLowerCase()
|
|
4331
|
+
os: String(r.os || "linux").toLowerCase(),
|
|
4332
|
+
askOnMatch: r.ask_on_match === true
|
|
4146
4333
|
}));
|
|
4147
4334
|
});
|
|
4148
4335
|
}
|
|
@@ -4152,7 +4339,8 @@ function effectiveInjectionKeywords(osType) {
|
|
|
4152
4339
|
return rules.map((r) => ({
|
|
4153
4340
|
keyword: String(r.keyword || ""),
|
|
4154
4341
|
riskLevel: String(r.risk_level || ""),
|
|
4155
|
-
lang: String(r.lang || "en")
|
|
4342
|
+
lang: String(r.lang || "en"),
|
|
4343
|
+
tier: String(r.tier || "")
|
|
4156
4344
|
})).filter((r) => r.keyword);
|
|
4157
4345
|
});
|
|
4158
4346
|
}
|
|
@@ -4167,10 +4355,23 @@ function effectiveSensitivePaths(osType) {
|
|
|
4167
4355
|
readOnly: r.read_only === true ? true : void 0,
|
|
4168
4356
|
dirDelOnly: r.dir_del_only === true ? true : void 0,
|
|
4169
4357
|
denyMode: String(r.deny_mode || ""),
|
|
4170
|
-
os: String(r.os || "linux").toLowerCase()
|
|
4358
|
+
os: String(r.os || "linux").toLowerCase(),
|
|
4359
|
+
askOnMatch: r.ask_on_match === true
|
|
4171
4360
|
}));
|
|
4172
4361
|
});
|
|
4173
4362
|
}
|
|
4363
|
+
function effectivePasswordRules(osType) {
|
|
4364
|
+
return _effective(osType, "password_rules", (rt) => getEnabledL2PasswordRules(rt).map((r) => ({
|
|
4365
|
+
pattern: new RegExp(String(r.pattern || ""), "i"),
|
|
4366
|
+
askOnMatch: r.ask_on_match === true
|
|
4367
|
+
})));
|
|
4368
|
+
}
|
|
4369
|
+
function effectiveUserDeletionRules(osType) {
|
|
4370
|
+
return _effective(osType, "user_deletion_rules", (rt) => getEnabledL2UserDeletionRules(rt).map((r) => ({
|
|
4371
|
+
pattern: new RegExp(String(r.pattern || ""), "i"),
|
|
4372
|
+
askOnMatch: r.ask_on_match === true
|
|
4373
|
+
})));
|
|
4374
|
+
}
|
|
4174
4375
|
function effectiveIntentPatterns(osType) {
|
|
4175
4376
|
return _effective(osType, "intent", (rt) => {
|
|
4176
4377
|
const rules = getEnabledL2IntentPatternsOrDefault(rt, osType);
|
|
@@ -4179,7 +4380,8 @@ function effectiveIntentPatterns(osType) {
|
|
|
4179
4380
|
dangerousActions: r.dangerous_actions || [],
|
|
4180
4381
|
reason: String(r.reason || ""),
|
|
4181
4382
|
os: String(r.os || "linux").toLowerCase(),
|
|
4182
|
-
allowIfWriteIntent: r.allow_if_write_intent === true
|
|
4383
|
+
allowIfWriteIntent: r.allow_if_write_intent === true,
|
|
4384
|
+
askOnMatch: r.ask_on_match === true
|
|
4183
4385
|
}));
|
|
4184
4386
|
});
|
|
4185
4387
|
}
|
|
@@ -4191,8 +4393,15 @@ function effectiveUserDeletionPatterns(osType) {
|
|
|
4191
4393
|
}
|
|
4192
4394
|
function _sensitivePathCategoryOf(runtime) {
|
|
4193
4395
|
const l1 = runtime.L1_rules?.sensitive_path_access;
|
|
4194
|
-
|
|
4195
|
-
|
|
4396
|
+
const l2 = runtime.L2_rules?.sensitive_path_access;
|
|
4397
|
+
const l1Rules = l1?.rules || [];
|
|
4398
|
+
const l2Rules = l2?.rules || [];
|
|
4399
|
+
if (l2Rules.length === 0) return l1;
|
|
4400
|
+
if (l1Rules.length === 0) return l2;
|
|
4401
|
+
const seen = new Set(l1Rules.map((r) => _ruleFingerprint(r)));
|
|
4402
|
+
const merged = { ...l1 };
|
|
4403
|
+
merged.rules = [...l1Rules, ...l2Rules.filter((r) => !seen.has(_ruleFingerprint(r)))];
|
|
4404
|
+
return merged;
|
|
4196
4405
|
}
|
|
4197
4406
|
function _validateSkillId(skillId) {
|
|
4198
4407
|
if (!skillId || !SKILL_ID_RE.test(skillId)) {
|
|
@@ -4228,6 +4437,23 @@ function updateRuleDenyMode(layer, category, ruleId, denyMode) {
|
|
|
4228
4437
|
saveRuntimeConfig(runtime);
|
|
4229
4438
|
return runtime;
|
|
4230
4439
|
}
|
|
4440
|
+
function updateRuleAsk(layer, category, ruleId, askOnMatch) {
|
|
4441
|
+
const runtime = loadRuntimeConfig();
|
|
4442
|
+
const rules = runtime[layer]?.[category]?.rules || [];
|
|
4443
|
+
const r = rules.find((x) => x.id === ruleId);
|
|
4444
|
+
if (r) r.ask_on_match = !!askOnMatch;
|
|
4445
|
+
saveRuntimeConfig(runtime);
|
|
4446
|
+
return runtime;
|
|
4447
|
+
}
|
|
4448
|
+
function updateCategoryAsk(layer, category, askOnMatch) {
|
|
4449
|
+
const runtime = loadRuntimeConfig();
|
|
4450
|
+
const cat = runtime[layer]?.[category];
|
|
4451
|
+
if (cat && typeof cat === "object") {
|
|
4452
|
+
for (const r of cat.rules || []) r.ask_on_match = !!askOnMatch;
|
|
4453
|
+
saveRuntimeConfig(runtime);
|
|
4454
|
+
}
|
|
4455
|
+
return runtime;
|
|
4456
|
+
}
|
|
4231
4457
|
function updateRuleSkipL3(layer, category, ruleId, skipL3) {
|
|
4232
4458
|
const runtime = loadRuntimeConfig();
|
|
4233
4459
|
for (const r of runtime[layer]?.[category]?.rules || []) {
|
|
@@ -4239,6 +4465,13 @@ function updateRuleSkipL3(layer, category, ruleId, skipL3) {
|
|
|
4239
4465
|
saveRuntimeConfig(runtime);
|
|
4240
4466
|
return runtime;
|
|
4241
4467
|
}
|
|
4468
|
+
function updateInjectionTierEnabled(tier, enabled) {
|
|
4469
|
+
const runtime = loadRuntimeConfig();
|
|
4470
|
+
const cat = (runtime.L1_rules ??= {}).injection_detection ??= { category_enabled: true, rules: [] };
|
|
4471
|
+
cat.tier_enabled = { ...cat.tier_enabled || {}, [tier]: enabled };
|
|
4472
|
+
saveRuntimeConfig(runtime);
|
|
4473
|
+
return runtime;
|
|
4474
|
+
}
|
|
4242
4475
|
function updateCategoryEnabled(layer, category, enabled) {
|
|
4243
4476
|
const runtime = loadRuntimeConfig();
|
|
4244
4477
|
const cat = runtime[layer]?.[category];
|
|
@@ -4501,7 +4734,7 @@ function updateScenarioCategoryEnabled(scenarioId, category, enabled) {
|
|
|
4501
4734
|
saveRuntimeConfig(runtime);
|
|
4502
4735
|
return runtime;
|
|
4503
4736
|
}
|
|
4504
|
-
var __dirname4, ENV_RUNTIME_CONFIG_PATH, RUNTIME_CONFIG_DIR, RUNTIME_CONFIG_PATH, LAYER_DISABLE_ENV, DEFAULT_LAYERS, DENY_MODE_LABELS, runtimeConfigCache, _DEDUP_KEYS, hasRuntimeConfigCache, _AGENTS_DIR_PROD, _AGENTS_DIR_DEV, _SCENARIOS_DIR_PROD, _SCENARIOS_DIR_DEV, _effectiveCache, SKILL_ID_RE;
|
|
4737
|
+
var __dirname4, ENV_RUNTIME_CONFIG_PATH, RUNTIME_CONFIG_DIR, RUNTIME_CONFIG_PATH, LAYER_DISABLE_ENV, DEFAULT_LAYERS, DENY_MODE_LABELS, runtimeConfigCache, _DEDUP_KEYS, hasRuntimeConfigCache, _AGENTS_DIR_PROD, _AGENTS_DIR_DEV, _SCENARIOS_DIR_PROD, _SCENARIOS_DIR_DEV, BUILTIN_DETECTOR_DEFAULTS, _effectiveCache, SKILL_ID_RE;
|
|
4505
4738
|
var init_runtime_config = __esm({
|
|
4506
4739
|
"src/infra/runtime-config.ts"() {
|
|
4507
4740
|
"use strict";
|
|
@@ -4552,6 +4785,17 @@ var init_runtime_config = __esm({
|
|
|
4552
4785
|
_AGENTS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "agents");
|
|
4553
4786
|
_SCENARIOS_DIR_PROD = join7(__dirname4, "scenarios");
|
|
4554
4787
|
_SCENARIOS_DIR_DEV = join7(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
|
|
4788
|
+
BUILTIN_DETECTOR_DEFAULTS = [
|
|
4789
|
+
{ id: "builtin_wildcard_delete", reason: "\u901A\u914D\u7B26 + \u6279\u91CF\u5220\u9664\uFF08rm \u914D\u901A\u914D\u7B26\uFF0C\u6392\u9664 /tmp \u7B49\u4E34\u65F6\u76EE\u5F55\u6E05\u7406\uFF09", risk_level: "high", risk_type: "script_execution", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4790
|
+
{ id: "builtin_find_exec_write", reason: "find \u6279\u91CF\u6267\u884C\u5199\u64CD\u4F5C\uFF08find -exec / | xargs \u540E\u63A5 chmod/cp/mv/rm \u7B49\uFF09", risk_level: "high", risk_type: "script_execution", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4791
|
+
{ id: "builtin_redirect_system", reason: "\u91CD\u5B9A\u5411\u8986\u76D6\u5199\u5165\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08/etc\u3001/boot\u3001/proc\uFF09", risk_level: "critical", risk_type: "file_access", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4792
|
+
{ id: "builtin_home_deletion", reason: "\u4E3B\u76EE\u5F55\u9012\u5F52\u5220\u9664\uFF08rm -rf ~ / $HOME \u53CA\u53D8\u91CF\u95F4\u63A5\u5F15\u7528\uFF09", risk_level: "high", risk_type: "home_deletion", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4793
|
+
{ id: "structural_hidden_payload", reason: "\u89E3\u7801\u5206\u6790\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u53EF\u89E3\u7801\u7684\u9690\u85CF\u8F7D\u8377\uFF08Tag/base64/hex/URL\uFF09", risk_level: "high", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4794
|
+
{ id: "structural_bidi_override", reason: "\u89E3\u7801\u5206\u6790\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u53CC\u5411\u63A7\u5236\u7B26\uFF08\u53EF\u80FD\u906E\u6321\u6587\u672C\uFF09", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4795
|
+
{ id: "structural_external_media", reason: "\u7ED3\u6784\u7279\u5F81\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u5916\u90E8\u56FE\u7247\u94FE\u63A5", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4796
|
+
{ id: "structural_persistence", reason: "\u7ED3\u6784\u7279\u5F81\uFF1A\u6307\u4EE4\u6E90\u5199\u5165\u5185\u5BB9\u542B\u6301\u4E45\u5316\u6307\u4EE4\u53E5\u5F0F\uFF08\u6BCF\u5F53\u7528\u6237\u2026\uFF09", risk_level: "medium", risk_type: "prompt_injection", enabled: true, builtin: true, os: "all", ask_on_match: false },
|
|
4797
|
+
{ id: "builtin_lateral_movement", reason: "\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp/rsync \u5230\u975E\u672C\u673A\u4E3B\u673A\uFF09", risk_level: "high", risk_type: "lateral_movement", enabled: true, builtin: true, os: "all", ask_on_match: false }
|
|
4798
|
+
];
|
|
4555
4799
|
_effectiveCache = /* @__PURE__ */ new WeakMap();
|
|
4556
4800
|
SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
|
|
4557
4801
|
registerRuntimeConfigBridge({
|
|
@@ -4563,6 +4807,9 @@ var init_runtime_config = __esm({
|
|
|
4563
4807
|
effectiveIntentPatterns,
|
|
4564
4808
|
effectivePasswordPatterns,
|
|
4565
4809
|
effectiveUserDeletionPatterns,
|
|
4810
|
+
effectivePasswordRules,
|
|
4811
|
+
effectiveUserDeletionRules,
|
|
4812
|
+
builtinAskMap: () => getBuiltinAskMap(loadRuntimeConfig()),
|
|
4566
4813
|
disabledSkillIds: () => getDisabledSkillIds(loadRuntimeConfig())
|
|
4567
4814
|
});
|
|
4568
4815
|
}
|
|
@@ -4824,10 +5071,10 @@ function getCacheOptions() {
|
|
|
4824
5071
|
let enabled = true;
|
|
4825
5072
|
let maxSize = 1e3;
|
|
4826
5073
|
const cfg = loadConfigFile(resolveConfigPath());
|
|
4827
|
-
const
|
|
4828
|
-
if (
|
|
4829
|
-
if (typeof
|
|
4830
|
-
if (typeof
|
|
5074
|
+
const cache4 = cfg?.cache;
|
|
5075
|
+
if (cache4 && typeof cache4 === "object") {
|
|
5076
|
+
if (typeof cache4.enabled === "boolean") enabled = cache4.enabled;
|
|
5077
|
+
if (typeof cache4.max_size === "number" && cache4.max_size > 0) maxSize = cache4.max_size;
|
|
4831
5078
|
}
|
|
4832
5079
|
if (process.env.AGENT_MOSS_DISABLE_CACHE === "1") enabled = false;
|
|
4833
5080
|
return { enabled, maxSize };
|
|
@@ -5423,6 +5670,194 @@ var init_written_content_analyzer = __esm({
|
|
|
5423
5670
|
}
|
|
5424
5671
|
});
|
|
5425
5672
|
|
|
5673
|
+
// src/engine/structural-analyzer.ts
|
|
5674
|
+
function decodeTagPayload(text) {
|
|
5675
|
+
const payloads = [];
|
|
5676
|
+
let current = [];
|
|
5677
|
+
let afterFlag = false;
|
|
5678
|
+
let prevCp = 0;
|
|
5679
|
+
const flush = () => {
|
|
5680
|
+
if (current.length && !afterFlag) payloads.push(current.join(""));
|
|
5681
|
+
current = [];
|
|
5682
|
+
afterFlag = false;
|
|
5683
|
+
};
|
|
5684
|
+
for (const ch of text || "") {
|
|
5685
|
+
const cp = ch.codePointAt(0);
|
|
5686
|
+
if (cp >= TAG_MIN && cp <= TAG_MAX) {
|
|
5687
|
+
if (!current.length) afterFlag = prevCp === 127988;
|
|
5688
|
+
current.push(String.fromCharCode(cp - 917504));
|
|
5689
|
+
} else if (cp === TAG_CANCEL) {
|
|
5690
|
+
flush();
|
|
5691
|
+
} else {
|
|
5692
|
+
flush();
|
|
5693
|
+
}
|
|
5694
|
+
prevCp = cp;
|
|
5695
|
+
}
|
|
5696
|
+
flush();
|
|
5697
|
+
return payloads;
|
|
5698
|
+
}
|
|
5699
|
+
function decodeBase32(value) {
|
|
5700
|
+
const clean = value.replace(/=+$/, "").toUpperCase();
|
|
5701
|
+
let bits = 0;
|
|
5702
|
+
let acc = 0;
|
|
5703
|
+
const out = [];
|
|
5704
|
+
for (const ch of clean) {
|
|
5705
|
+
const idx = B32_ALPHABET.indexOf(ch);
|
|
5706
|
+
if (idx < 0) return "";
|
|
5707
|
+
acc = acc << 5 | idx;
|
|
5708
|
+
bits += 5;
|
|
5709
|
+
if (bits >= 8) {
|
|
5710
|
+
bits -= 8;
|
|
5711
|
+
out.push(acc >> bits & 255);
|
|
5712
|
+
}
|
|
5713
|
+
}
|
|
5714
|
+
return Buffer.from(out).toString("utf8");
|
|
5715
|
+
}
|
|
5716
|
+
function decodeHexDump(text) {
|
|
5717
|
+
const out = [];
|
|
5718
|
+
for (const m of text.matchAll(XXD_LINE_RE)) {
|
|
5719
|
+
const hex = m[1].replace(/\s+/g, "");
|
|
5720
|
+
try {
|
|
5721
|
+
out.push(Buffer.from(hex, "hex").toString("utf8"));
|
|
5722
|
+
} catch {
|
|
5723
|
+
}
|
|
5724
|
+
}
|
|
5725
|
+
for (const m of text.match(OD_HEX_RE) || []) {
|
|
5726
|
+
const hex = m.replace(/\s+/g, "");
|
|
5727
|
+
if (hex.length % 2) continue;
|
|
5728
|
+
try {
|
|
5729
|
+
out.push(Buffer.from(hex, "hex").toString("utf8"));
|
|
5730
|
+
} catch {
|
|
5731
|
+
}
|
|
5732
|
+
}
|
|
5733
|
+
return out;
|
|
5734
|
+
}
|
|
5735
|
+
function decodeUnicodeEscapes(value) {
|
|
5736
|
+
return value.replace(
|
|
5737
|
+
/\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{8})/g,
|
|
5738
|
+
(_all, a, b) => String.fromCodePoint(parseInt(a || b, 16))
|
|
5739
|
+
);
|
|
5740
|
+
}
|
|
5741
|
+
function decodeHtmlEntities(value) {
|
|
5742
|
+
return value.replace(
|
|
5743
|
+
/&#(x?)([0-9a-fA-F]+);/g,
|
|
5744
|
+
(_all, x, n) => String.fromCodePoint(parseInt(n, x ? 16 : 10))
|
|
5745
|
+
);
|
|
5746
|
+
}
|
|
5747
|
+
function looksText(value) {
|
|
5748
|
+
if (value.trim().length < 4) return false;
|
|
5749
|
+
let printable = 0;
|
|
5750
|
+
for (const c of value) {
|
|
5751
|
+
if (c >= " " && c !== "\x7F") printable++;
|
|
5752
|
+
else if (c === "\r" || c === "\n" || c === " ") printable++;
|
|
5753
|
+
}
|
|
5754
|
+
return printable / Math.max(value.length, 1) >= 0.9;
|
|
5755
|
+
}
|
|
5756
|
+
function decodePayloads(text, opts = {}) {
|
|
5757
|
+
const out = [];
|
|
5758
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5759
|
+
const add = (encoding, value) => {
|
|
5760
|
+
if (looksText(value) && !seen.has(value)) {
|
|
5761
|
+
seen.add(value);
|
|
5762
|
+
out.push({ encoding, decoded: value });
|
|
5763
|
+
}
|
|
5764
|
+
};
|
|
5765
|
+
for (const p of decodeTagPayload(text)) add("tag", p);
|
|
5766
|
+
for (const m of text.match(HEX_ESC_RE) || []) {
|
|
5767
|
+
try {
|
|
5768
|
+
const bytes = m.replace(/\\x/g, "").match(/../g).map((h) => parseInt(h, 16));
|
|
5769
|
+
add("hex", Buffer.from(bytes).toString("utf8"));
|
|
5770
|
+
} catch {
|
|
5771
|
+
}
|
|
5772
|
+
}
|
|
5773
|
+
for (const m of text.match(UNICODE_ESC_RE) || []) {
|
|
5774
|
+
try {
|
|
5775
|
+
add("unicode_escape", decodeUnicodeEscapes(m));
|
|
5776
|
+
} catch {
|
|
5777
|
+
}
|
|
5778
|
+
}
|
|
5779
|
+
for (const m of text.match(PCT_RE) || []) {
|
|
5780
|
+
try {
|
|
5781
|
+
add("url", decodeURIComponent(m));
|
|
5782
|
+
} catch {
|
|
5783
|
+
}
|
|
5784
|
+
}
|
|
5785
|
+
for (const m of text.match(B64_RE) || []) {
|
|
5786
|
+
try {
|
|
5787
|
+
const raw = Buffer.from(m + "=".repeat((4 - m.length % 4) % 4), "base64");
|
|
5788
|
+
add("base64", raw.toString("utf8"));
|
|
5789
|
+
} catch {
|
|
5790
|
+
}
|
|
5791
|
+
}
|
|
5792
|
+
for (const m of text.match(B64URL_RE) || []) {
|
|
5793
|
+
try {
|
|
5794
|
+
const norm = m.replace(/-/g, "+").replace(/_/g, "/");
|
|
5795
|
+
const raw = Buffer.from(norm + "=".repeat((4 - norm.length % 4) % 4), "base64");
|
|
5796
|
+
add("base64url", raw.toString("utf8"));
|
|
5797
|
+
} catch {
|
|
5798
|
+
}
|
|
5799
|
+
}
|
|
5800
|
+
for (const m of text.match(B32_RE) || []) add("base32", decodeBase32(m));
|
|
5801
|
+
for (const v of decodeHexDump(text)) add("hex_dump", v);
|
|
5802
|
+
if (opts.includeHtml) {
|
|
5803
|
+
for (const m of text.match(HTML_ENTITY_RE) || []) {
|
|
5804
|
+
try {
|
|
5805
|
+
add("html_entity", decodeHtmlEntities(m));
|
|
5806
|
+
} catch {
|
|
5807
|
+
}
|
|
5808
|
+
}
|
|
5809
|
+
}
|
|
5810
|
+
return out;
|
|
5811
|
+
}
|
|
5812
|
+
function findStructuralSignals(content) {
|
|
5813
|
+
const text = content || "";
|
|
5814
|
+
const findings = [];
|
|
5815
|
+
for (const p of decodePayloads(text)) {
|
|
5816
|
+
findings.push({
|
|
5817
|
+
kind: "hidden_payload",
|
|
5818
|
+
sample: `[${p.encoding}] ${p.decoded.slice(0, 120)}`,
|
|
5819
|
+
riskLevel: "medium",
|
|
5820
|
+
decoded: p.decoded
|
|
5821
|
+
});
|
|
5822
|
+
}
|
|
5823
|
+
const bidi = text.match(BIDI_RE);
|
|
5824
|
+
if (bidi) findings.push({ kind: "bidi_override", sample: JSON.stringify(bidi[0]), riskLevel: "medium" });
|
|
5825
|
+
const media = text.match(EXTERNAL_MEDIA_RE);
|
|
5826
|
+
if (media) findings.push({ kind: "external_media", sample: media[0].slice(0, 120), riskLevel: "medium" });
|
|
5827
|
+
const persist = text.match(PERSISTENCE_RE);
|
|
5828
|
+
if (persist) findings.push({ kind: "persistence_phrase", sample: persist[0].slice(0, 120), riskLevel: "medium" });
|
|
5829
|
+
return findings;
|
|
5830
|
+
}
|
|
5831
|
+
var TAG_MIN, TAG_MAX, TAG_CANCEL, BIDI_RE, EXTERNAL_MEDIA_RE, PERSISTENCE_RE, B64_RE, B64URL_RE, B32_RE, HEX_ESC_RE, UNICODE_ESC_RE, PCT_RE, XXD_LINE_RE, OD_HEX_RE, HTML_ENTITY_RE, B32_ALPHABET, SIGNAL_TO_DETECTOR;
|
|
5832
|
+
var init_structural_analyzer = __esm({
|
|
5833
|
+
"src/engine/structural-analyzer.ts"() {
|
|
5834
|
+
"use strict";
|
|
5835
|
+
init_esm_shims();
|
|
5836
|
+
TAG_MIN = 917536;
|
|
5837
|
+
TAG_MAX = 917630;
|
|
5838
|
+
TAG_CANCEL = 917631;
|
|
5839
|
+
BIDI_RE = /[\u202a-\u202e]/;
|
|
5840
|
+
EXTERNAL_MEDIA_RE = /!\[[^\]]*\]\(\s*(?:https?:)?\/\/[^)\s]+|<img\b[^>]*\bsrc\s*=\s*["']?(?:https?:)?\/\//i;
|
|
5841
|
+
PERSISTENCE_RE = /(?:每当|每次|以后每次|今后每次|从现在起每次)[^。\n]{0,20}(?:用户|你)|from now on,?\s*(?:whenever|each time|every time)|whenever the user|each time the user/i;
|
|
5842
|
+
B64_RE = /[A-Za-z0-9+/]{8,}={0,2}/g;
|
|
5843
|
+
B64URL_RE = /[A-Za-z0-9_-]{16,}={0,2}/g;
|
|
5844
|
+
B32_RE = /[A-Z2-7]{12,}={0,6}/g;
|
|
5845
|
+
HEX_ESC_RE = /(?:\\x[0-9a-fA-F]{2}){4,}/g;
|
|
5846
|
+
UNICODE_ESC_RE = /(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}){4,}/g;
|
|
5847
|
+
PCT_RE = /(?:%[0-9A-Fa-f]{2}){4,}/g;
|
|
5848
|
+
XXD_LINE_RE = /^\s*[0-9a-fA-F]{4,8}:\s+([0-9a-fA-F]{2,4}(?:[ ]+[0-9a-fA-F]{2,4})*)/gm;
|
|
5849
|
+
OD_HEX_RE = /(?:(?<![0-9a-fA-F])[0-9a-fA-F]{2}[ \t]+){15,}[0-9a-fA-F]{2}/g;
|
|
5850
|
+
HTML_ENTITY_RE = /(?:&#x?[0-9a-fA-F]+;){4,}/g;
|
|
5851
|
+
B32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
5852
|
+
SIGNAL_TO_DETECTOR = {
|
|
5853
|
+
hidden_payload: "structural_hidden_payload",
|
|
5854
|
+
bidi_override: "structural_bidi_override",
|
|
5855
|
+
external_media: "structural_external_media",
|
|
5856
|
+
persistence_phrase: "structural_persistence"
|
|
5857
|
+
};
|
|
5858
|
+
}
|
|
5859
|
+
});
|
|
5860
|
+
|
|
5426
5861
|
// src/engine/heuristic.ts
|
|
5427
5862
|
import { posix } from "path";
|
|
5428
5863
|
function _effectiveDangerousPatterns(osType) {
|
|
@@ -5569,11 +6004,18 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
|
|
|
5569
6004
|
const deob = normalizeShellObfuscation(scanDetail);
|
|
5570
6005
|
if (deob !== scanDetail) scanCommands.push(`${actionType}: ${deob}`, deob);
|
|
5571
6006
|
let top = null;
|
|
6007
|
+
const loopbackOnly = allUrlsLoopback(actionDetail) && !LOOPBACK_DATA_GUARD_RE.test(actionDetail);
|
|
6008
|
+
const boundedLoop = isBoundedLoop(scanDetail);
|
|
5572
6009
|
for (const rule of _effectiveDangerousPatterns(osType)) {
|
|
5573
6010
|
if (scanCommands.some((c) => rule.pattern.test(c))) {
|
|
6011
|
+
if (loopbackOnly && rule.riskType === "data_exfiltration") continue;
|
|
6012
|
+
if (boundedLoop && rule.riskType === "resource_exhaustion" && (rule.description || "").includes("\u65E0\u9650\u5FAA\u73AF")) continue;
|
|
5574
6013
|
if (!top || severityRank(rule.severity) > severityRank(top.sev)) {
|
|
5575
6014
|
top = { sev: rule.severity, type: rule.riskType, desc: rule.description };
|
|
5576
6015
|
}
|
|
6016
|
+
if (rule.askOnMatch && !top.ask) {
|
|
6017
|
+
top.ask = `\u89C4\u5219\u300C${rule.description}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
|
|
6018
|
+
}
|
|
5577
6019
|
}
|
|
5578
6020
|
}
|
|
5579
6021
|
const toJudgment = (hit) => ({
|
|
@@ -5583,13 +6025,22 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
|
|
|
5583
6025
|
riskType: hit.type,
|
|
5584
6026
|
confidence: 95,
|
|
5585
6027
|
source: "heuristic",
|
|
5586
|
-
violatedLayers: ["L1.1"]
|
|
6028
|
+
violatedLayers: ["L1.1"],
|
|
6029
|
+
...hit.ask ? { ask_recommended: true, ask_reason: hit.ask } : {}
|
|
5587
6030
|
});
|
|
5588
6031
|
if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
|
|
5589
6032
|
const rmResolved = checkRmResolvedTargets(scanDetail);
|
|
5590
6033
|
if (rmResolved) return rmResolved;
|
|
5591
6034
|
return top ? toJudgment(top) : null;
|
|
5592
6035
|
}
|
|
6036
|
+
function isBoundedLoop(text) {
|
|
6037
|
+
const loops = (text.match(LOOP_START_RE) || []).length;
|
|
6038
|
+
const breaks = (text.match(LOOP_EXIT_RE) || []).length;
|
|
6039
|
+
return loops > 0 && breaks >= loops && !LOOP_SIDE_EFFECT_RE.test(text);
|
|
6040
|
+
}
|
|
6041
|
+
function isDbQueryCommand(text) {
|
|
6042
|
+
return DB_QUERY_CMD_RE.test(text || "");
|
|
6043
|
+
}
|
|
5593
6044
|
function allUrlsLoopback(actionDetail) {
|
|
5594
6045
|
const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
|
|
5595
6046
|
if (!hosts || hosts.length === 0) return false;
|
|
@@ -5609,6 +6060,49 @@ function stripEchoParamsForUserRules(actionDetail) {
|
|
|
5609
6060
|
return `${head} ` + (cut >= 0 ? rest.slice(cut) : "");
|
|
5610
6061
|
}).join(" ");
|
|
5611
6062
|
}
|
|
6063
|
+
function extractDecodedPayloads(actionType, detail, handledWrite) {
|
|
6064
|
+
if (!getEnabledBuiltinDetectorsOrCurrent().has("structural_hidden_payload")) return [];
|
|
6065
|
+
const source = injectionScanSource(actionType, detail, handledWrite);
|
|
6066
|
+
if (!source) return [];
|
|
6067
|
+
let content = detail || "";
|
|
6068
|
+
if (handledWrite) {
|
|
6069
|
+
const payload = extractWritePayload(actionType, content);
|
|
6070
|
+
if (payload) content = payload.content;
|
|
6071
|
+
}
|
|
6072
|
+
return decodePayloads(content, { includeHtml: source === "instruction" }).map((p) => ({ source, encoding: p.encoding, decoded: p.decoded }));
|
|
6073
|
+
}
|
|
6074
|
+
function detectDecoded(payload) {
|
|
6075
|
+
const enabled = getEnabledBuiltinDetectorsOrCurrent();
|
|
6076
|
+
const hits = [];
|
|
6077
|
+
const cmd = scanDangerousCommandPatterns("bash", payload);
|
|
6078
|
+
if (cmd) hits.push(cmd);
|
|
6079
|
+
const pat = checkDangerousPatterns("bash", payload, enabled);
|
|
6080
|
+
if (pat) hits.push(pat);
|
|
6081
|
+
if (enabled.has("builtin_home_deletion")) {
|
|
6082
|
+
const home = checkHomeDeletion("bash", payload);
|
|
6083
|
+
if (home) hits.push(home);
|
|
6084
|
+
}
|
|
6085
|
+
if (enabled.has("builtin_lateral_movement")) {
|
|
6086
|
+
const lateral = checkLateralMovement(payload);
|
|
6087
|
+
if (lateral) hits.push(lateral);
|
|
6088
|
+
}
|
|
6089
|
+
const path10 = checkSensitivePath(payload, "/", null, void 0);
|
|
6090
|
+
if (path10) hits.push(path10);
|
|
6091
|
+
const inj = checkInjectionKeywords(payload.toLowerCase());
|
|
6092
|
+
if (inj.length) {
|
|
6093
|
+
hits.push({
|
|
6094
|
+
allowed: false,
|
|
6095
|
+
reason: `\u89E3\u7801\u5185\u5BB9\u542B\u6CE8\u5165\u5173\u952E\u8BCD: ${inj.map((h) => h.keyword).join(", ")}`,
|
|
6096
|
+
riskLevel: "medium",
|
|
6097
|
+
riskType: "prompt_injection",
|
|
6098
|
+
confidence: 90,
|
|
6099
|
+
source: "heuristic",
|
|
6100
|
+
violatedLayers: ["L1.1"]
|
|
6101
|
+
});
|
|
6102
|
+
}
|
|
6103
|
+
if (!hits.length) return null;
|
|
6104
|
+
return hits.reduce((a, b) => severityRank(b.riskLevel) > severityRank(a.riskLevel) ? b : a);
|
|
6105
|
+
}
|
|
5612
6106
|
function runHeuristicCheck(input) {
|
|
5613
6107
|
const command = `${input.aNext.actionType}: ${input.aNext.actionDetail}`;
|
|
5614
6108
|
const matched = [];
|
|
@@ -5683,11 +6177,22 @@ function runHeuristicCheck(input) {
|
|
|
5683
6177
|
const exemptKeygen = isSshKeygenGenerate(input.aNext.actionDetail);
|
|
5684
6178
|
const pwGuardOff = hasExecBypassChain(input.aNext.actionDetail);
|
|
5685
6179
|
const noQuotes = pwGuardOff ? null : input.aNext.actionDetail.replace(ALL_QUOTES_RE, " ");
|
|
6180
|
+
const boundedLoop = isBoundedLoop(scanDetail);
|
|
6181
|
+
const loopbackExfilSkip = urlsAllLoopback && !LOOPBACK_DATA_GUARD_RE.test(input.aNext.actionDetail);
|
|
6182
|
+
let askReason = "";
|
|
5686
6183
|
for (const rule of _effectiveDangerousPatterns(input.osType)) {
|
|
5687
6184
|
if (scanCommands.some((c) => rule.pattern.test(c))) {
|
|
6185
|
+
if (loopbackExfilSkip && rule.riskType === "data_exfiltration") continue;
|
|
5688
6186
|
if (exemptKeygen && rule.riskType === "file_access") continue;
|
|
6187
|
+
if (boundedLoop && rule.riskType === "resource_exhaustion" && (rule.description || "").includes("\u65E0\u9650\u5FAA\u73AF")) {
|
|
6188
|
+
matched.push("\u68C0\u6D4B\u5230\u5FAA\u73AF\u4F46\u5B58\u5728\u7EC8\u6B62\u6761\u4EF6\uFF08break/return\uFF09\uFF0C\u964D\u7EA7\u4EA4 L2/L3");
|
|
6189
|
+
continue;
|
|
6190
|
+
}
|
|
5689
6191
|
if (noQuotes !== null && QUOTED_SAFE_PASSWORD_PATTERN_SOURCES.has(rule.pattern.source) && !rule.pattern.test(noQuotes)) continue;
|
|
5690
6192
|
matched.push(rule.description);
|
|
6193
|
+
if (rule.askOnMatch && !askReason) {
|
|
6194
|
+
askReason = `\u89C4\u5219\u300C${rule.description}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237`;
|
|
6195
|
+
}
|
|
5691
6196
|
if (severityRank(rule.severity) > severityRank(highestSeverity)) {
|
|
5692
6197
|
highestSeverity = rule.severity;
|
|
5693
6198
|
topRiskType = rule.riskType;
|
|
@@ -5714,9 +6219,15 @@ function runHeuristicCheck(input) {
|
|
|
5714
6219
|
}
|
|
5715
6220
|
}
|
|
5716
6221
|
}
|
|
5717
|
-
const
|
|
6222
|
+
const enabledBuiltin = getEnabledBuiltinDetectorsOrCurrent();
|
|
6223
|
+
const injectionSource = injectionScanSource(
|
|
6224
|
+
input.aNext.actionType,
|
|
6225
|
+
input.aNext.actionDetail,
|
|
6226
|
+
handledWrite
|
|
6227
|
+
);
|
|
6228
|
+
const injectionText = injectionSource ? input.aNext.actionDetail.toLowerCase() : "";
|
|
5718
6229
|
let pythonWalkOnerrorOnly = false;
|
|
5719
|
-
if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=")
|
|
6230
|
+
if (injectionSource === "output" && isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=")) {
|
|
5720
6231
|
pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
|
|
5721
6232
|
}
|
|
5722
6233
|
const injectionHits = checkInjectionKeywords(
|
|
@@ -5725,6 +6236,9 @@ function runHeuristicCheck(input) {
|
|
|
5725
6236
|
input.osType,
|
|
5726
6237
|
pythonWalkOnerrorOnly
|
|
5727
6238
|
);
|
|
6239
|
+
for (const h of injectionHits) {
|
|
6240
|
+
if (h.riskLevel === "high" || h.riskLevel === "critical") h.riskLevel = "medium";
|
|
6241
|
+
}
|
|
5728
6242
|
if (injectionHits.length > 0) {
|
|
5729
6243
|
const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
|
|
5730
6244
|
matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
|
|
@@ -5733,12 +6247,28 @@ function runHeuristicCheck(input) {
|
|
|
5733
6247
|
highestRiskType = "prompt_injection";
|
|
5734
6248
|
}
|
|
5735
6249
|
}
|
|
6250
|
+
if (injectionSource) {
|
|
6251
|
+
const payload = handledWrite ? extractWritePayload(input.aNext.actionType, input.aNext.actionDetail) : null;
|
|
6252
|
+
const content = payload ? payload.content : input.aNext.actionDetail;
|
|
6253
|
+
for (const finding of findStructuralSignals(content)) {
|
|
6254
|
+
const det = SIGNAL_TO_DETECTOR[finding.kind];
|
|
6255
|
+
if (!det || !enabledBuiltin.has(det)) continue;
|
|
6256
|
+
if (finding.kind === "hidden_payload") continue;
|
|
6257
|
+
if (injectionSource !== "instruction") continue;
|
|
6258
|
+
const level = finding.riskLevel;
|
|
6259
|
+
matched.push(`\u7ED3\u6784\u7279\u5F81: ${finding.kind}`);
|
|
6260
|
+
if (severityRank(level) > severityRank(highestSeverity)) {
|
|
6261
|
+
highestSeverity = level;
|
|
6262
|
+
highestRiskType = "prompt_injection";
|
|
6263
|
+
}
|
|
6264
|
+
}
|
|
6265
|
+
}
|
|
5736
6266
|
const actionTypeL = input.aNext.actionType.toLowerCase();
|
|
5737
6267
|
const detailL = input.aNext.actionDetail.toLowerCase();
|
|
5738
6268
|
const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
|
|
5739
|
-
const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
|
|
6269
|
+
const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL, enabledBuiltin);
|
|
5740
6270
|
const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
|
|
5741
|
-
const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
|
|
6271
|
+
const homeResult = handledWrite || !enabledBuiltin.has("builtin_home_deletion") ? null : checkHomeDeletion(actionTypeL, detailL);
|
|
5742
6272
|
const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
|
|
5743
6273
|
if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
|
|
5744
6274
|
const rmResolved = checkRmResolvedTargets(scanDetail);
|
|
@@ -5749,16 +6279,22 @@ function runHeuristicCheck(input) {
|
|
|
5749
6279
|
for (const r of mergeResults) {
|
|
5750
6280
|
if (severityRank(r.riskLevel) > severityRank(best.riskLevel)) best = r;
|
|
5751
6281
|
}
|
|
5752
|
-
if (severityRank(highestSeverity)
|
|
5753
|
-
|
|
6282
|
+
if (highestRiskType && severityRank(highestSeverity) >= severityRank(best.riskLevel)) {
|
|
6283
|
+
const out = {
|
|
5754
6284
|
allowed: false,
|
|
5755
6285
|
reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${matched.join(", ")}`,
|
|
5756
6286
|
riskLevel: highestSeverity,
|
|
5757
6287
|
riskType: highestRiskType,
|
|
5758
6288
|
confidence: 95,
|
|
5759
6289
|
source: "heuristic",
|
|
5760
|
-
violatedLayers: ["L1.1"]
|
|
6290
|
+
violatedLayers: ["L1.1"],
|
|
6291
|
+
...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
|
|
5761
6292
|
};
|
|
6293
|
+
if (best === pathResult && pathResult?.deniedReadPath) {
|
|
6294
|
+
out.deniedReadPath = pathResult.deniedReadPath;
|
|
6295
|
+
if (pathResult.isCredential) out.isCredential = true;
|
|
6296
|
+
}
|
|
6297
|
+
return out;
|
|
5762
6298
|
}
|
|
5763
6299
|
if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
|
|
5764
6300
|
best = { ...best, deniedReadPath: pathResult.deniedReadPath };
|
|
@@ -5773,11 +6309,14 @@ function runHeuristicCheck(input) {
|
|
|
5773
6309
|
riskType: highestRiskType,
|
|
5774
6310
|
confidence: 95,
|
|
5775
6311
|
source: "heuristic",
|
|
5776
|
-
violatedLayers: ["L1.1"]
|
|
6312
|
+
violatedLayers: ["L1.1"],
|
|
6313
|
+
...askReason ? { ask_recommended: true, ask_reason: askReason } : {}
|
|
5777
6314
|
};
|
|
5778
6315
|
}
|
|
5779
|
-
|
|
5780
|
-
|
|
6316
|
+
if (enabledBuiltin.has("builtin_lateral_movement")) {
|
|
6317
|
+
const lateralResult = checkLateralMovement(detailL);
|
|
6318
|
+
if (lateralResult) return lateralResult;
|
|
6319
|
+
}
|
|
5781
6320
|
return null;
|
|
5782
6321
|
}
|
|
5783
6322
|
function onlyPythonWalkOnerrorKeywords(command) {
|
|
@@ -5796,6 +6335,52 @@ function onlyPythonWalkOnerrorKeywords(command) {
|
|
|
5796
6335
|
const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
|
|
5797
6336
|
return walkKws.length > 0;
|
|
5798
6337
|
}
|
|
6338
|
+
function shellWriteTargets(command) {
|
|
6339
|
+
const out = [];
|
|
6340
|
+
INSTRUCTION_WRITE_RE.lastIndex = 0;
|
|
6341
|
+
let m;
|
|
6342
|
+
while ((m = INSTRUCTION_WRITE_RE.exec(command || "")) !== null) out.push(m[2]);
|
|
6343
|
+
return out;
|
|
6344
|
+
}
|
|
6345
|
+
function isDataDocPath(path10) {
|
|
6346
|
+
const i = String(path10 || "").lastIndexOf(".");
|
|
6347
|
+
return i >= 0 && DATA_DOC_EXTS.has(String(path10).slice(i).toLowerCase());
|
|
6348
|
+
}
|
|
6349
|
+
function isTextOutputCommand(command) {
|
|
6350
|
+
const text = command || "";
|
|
6351
|
+
if (isLiteralTextCommand(text)) return true;
|
|
6352
|
+
if (/\b(?:python3?|perl|ruby|node|php|lua)\b[^;|&\n]*\s-(?:c|e)\b/i.test(text)) return true;
|
|
6353
|
+
for (const seg of splitCommandSegments2(text)) {
|
|
6354
|
+
const parts = seg.trim().split(/\s+/);
|
|
6355
|
+
if (!parts.length) continue;
|
|
6356
|
+
const head = parts[0].toLowerCase();
|
|
6357
|
+
if (head === "echo" || head === "printf") return true;
|
|
6358
|
+
if (head === "cat" && seg.includes("<<")) return true;
|
|
6359
|
+
if (head === "tee" && shellWriteTargets(seg).length === 0) return true;
|
|
6360
|
+
}
|
|
6361
|
+
return false;
|
|
6362
|
+
}
|
|
6363
|
+
function injectionScanSource(actionType, raw, handledWrite) {
|
|
6364
|
+
const at = (actionType || "").toLowerCase();
|
|
6365
|
+
const text = raw || "";
|
|
6366
|
+
if (isSearchActionType(at)) return "";
|
|
6367
|
+
if (isDbQueryCommand(text)) return "";
|
|
6368
|
+
if (handledWrite) {
|
|
6369
|
+
const payload = extractWritePayload(at, text);
|
|
6370
|
+
const path10 = payload ? payload.path : "";
|
|
6371
|
+
if (path10 && isInstructionTarget(path10)) return "instruction";
|
|
6372
|
+
if (isDataDocument(at, text)) return "";
|
|
6373
|
+
return "output";
|
|
6374
|
+
}
|
|
6375
|
+
if (["bash", "executebash", "terminal-executebash"].includes(at)) {
|
|
6376
|
+
const targets = shellWriteTargets(text);
|
|
6377
|
+
if (targets.some((t) => isInstructionTarget(t))) return "instruction";
|
|
6378
|
+
if (targets.length > 0 && targets.every(isDataDocPath)) return "";
|
|
6379
|
+
if (isTextOutputCommand(text)) return "output";
|
|
6380
|
+
return "";
|
|
6381
|
+
}
|
|
6382
|
+
return "";
|
|
6383
|
+
}
|
|
5799
6384
|
function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
|
|
5800
6385
|
const hits = [];
|
|
5801
6386
|
const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
|
|
@@ -6056,6 +6641,9 @@ function isSearchActionType(actionType) {
|
|
|
6056
6641
|
const at = actionType.toLowerCase();
|
|
6057
6642
|
return SEARCH_ACTION_PREFIXES.some((p) => at.startsWith(p)) || SEARCH_ACTION_EXACT.includes(at);
|
|
6058
6643
|
}
|
|
6644
|
+
function askMeta(on, desc) {
|
|
6645
|
+
return on ? { ask_recommended: true, ask_reason: `\u89C4\u5219\u300C${desc || ""}\u300D\u5DF2\u6807\u8BB0\u4E3A\u547D\u4E2D\u540E\u5EFA\u8BAE\u8BE2\u95EE\u7528\u6237` } : {};
|
|
6646
|
+
}
|
|
6059
6647
|
function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
6060
6648
|
const expandedCwd = cwd.replace(/^~/, process.env.HOME || "/home/user");
|
|
6061
6649
|
const { root: rootPaths, home: homePaths, credential: credentialPaths } = getSensitivePathsForOs(osType);
|
|
@@ -6071,7 +6659,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6071
6659
|
if (part.startsWith("(?!")) return part;
|
|
6072
6660
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6073
6661
|
}).join("");
|
|
6074
|
-
const re = path10.startsWith(".") || path10.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
6662
|
+
const re = path10.startsWith(".") || path10.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}${TEMPLATE_SUFFIX_LA}\\b`, "i") : new RegExp(`\\b${escaped}${TEMPLATE_SUFFIX_LA}\\b`, "i");
|
|
6075
6663
|
return re.test(text);
|
|
6076
6664
|
};
|
|
6077
6665
|
const pathMatchesAny = (path10) => pathScanTexts.some((t) => pathMatches(t, path10));
|
|
@@ -6090,6 +6678,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6090
6678
|
confidence: 90,
|
|
6091
6679
|
source: "heuristic",
|
|
6092
6680
|
violatedLayers: ["L1.1"],
|
|
6681
|
+
...askMeta(sp.askOnMatch === true, sp.desc),
|
|
6093
6682
|
deniedReadPath: sp.path
|
|
6094
6683
|
};
|
|
6095
6684
|
}
|
|
@@ -6104,6 +6693,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6104
6693
|
confidence: 90,
|
|
6105
6694
|
source: "heuristic",
|
|
6106
6695
|
violatedLayers: ["L1.1"],
|
|
6696
|
+
...askMeta(sp.askOnMatch === true, sp.desc),
|
|
6107
6697
|
isCredential: !!sp.credential,
|
|
6108
6698
|
deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
|
|
6109
6699
|
};
|
|
@@ -6134,6 +6724,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6134
6724
|
confidence: 90,
|
|
6135
6725
|
source: "heuristic",
|
|
6136
6726
|
violatedLayers: ["L1.1"],
|
|
6727
|
+
...askMeta(sp.askOnMatch === true, sp.desc),
|
|
6137
6728
|
isCredential: !!sp.credential
|
|
6138
6729
|
};
|
|
6139
6730
|
}
|
|
@@ -6146,6 +6737,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6146
6737
|
confidence: 90,
|
|
6147
6738
|
source: "heuristic",
|
|
6148
6739
|
violatedLayers: ["L1.1"],
|
|
6740
|
+
...askMeta(sp.askOnMatch === true, sp.desc),
|
|
6149
6741
|
isCredential: !!sp.credential
|
|
6150
6742
|
};
|
|
6151
6743
|
}
|
|
@@ -6162,6 +6754,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6162
6754
|
confidence: 90,
|
|
6163
6755
|
source: "heuristic",
|
|
6164
6756
|
violatedLayers: ["L1.1"],
|
|
6757
|
+
...askMeta(sp.askOnMatch === true, sp.desc),
|
|
6165
6758
|
isCredential: !!sp.credential,
|
|
6166
6759
|
deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
|
|
6167
6760
|
};
|
|
@@ -6192,9 +6785,10 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6192
6785
|
}
|
|
6193
6786
|
}
|
|
6194
6787
|
}
|
|
6788
|
+
const templateSuffix = TEMPLATE_SUFFIX_LA;
|
|
6195
6789
|
for (const cp of credentialPaths) {
|
|
6196
6790
|
const escaped = cp.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6197
|
-
const re = cp.path.startsWith(".") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`) : new RegExp(`\\b${escaped}\\b`);
|
|
6791
|
+
const re = cp.path.startsWith(".") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}${templateSuffix}\\b`) : new RegExp(`\\b${escaped}${templateSuffix}\\b`);
|
|
6198
6792
|
if (re.test(command)) {
|
|
6199
6793
|
return {
|
|
6200
6794
|
allowed: false,
|
|
@@ -6204,6 +6798,7 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6204
6798
|
confidence: 90,
|
|
6205
6799
|
source: "heuristic",
|
|
6206
6800
|
violatedLayers: ["L1.1"],
|
|
6801
|
+
...askMeta(cp.askOnMatch === true, cp.desc),
|
|
6207
6802
|
isCredential: true,
|
|
6208
6803
|
deniedReadPath: cp.path
|
|
6209
6804
|
};
|
|
@@ -6260,6 +6855,14 @@ function homeEscapeTarget(seg) {
|
|
|
6260
6855
|
}
|
|
6261
6856
|
return false;
|
|
6262
6857
|
}
|
|
6858
|
+
function builtinAsk(ruleId) {
|
|
6859
|
+
try {
|
|
6860
|
+
const reason = runtimeConfigBridge.current?.builtinAskMap()?.[ruleId];
|
|
6861
|
+
return reason ? { ask_recommended: true, ask_reason: reason } : {};
|
|
6862
|
+
} catch {
|
|
6863
|
+
return {};
|
|
6864
|
+
}
|
|
6865
|
+
}
|
|
6263
6866
|
function checkHomeDeletion(actionType, actionDetail) {
|
|
6264
6867
|
if (actionType !== "bash" && actionType !== "executebash" && actionType !== "terminal-executebash") return null;
|
|
6265
6868
|
const segs = actionDetail.split(/&&|\|\||;|\n/).map((s) => s.trim()).filter(Boolean);
|
|
@@ -6273,7 +6876,8 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
6273
6876
|
riskType: "script_execution",
|
|
6274
6877
|
confidence: 90,
|
|
6275
6878
|
source: "heuristic",
|
|
6276
|
-
violatedLayers: ["L1.1"]
|
|
6879
|
+
violatedLayers: ["L1.1"],
|
|
6880
|
+
...builtinAsk("builtin_home_deletion")
|
|
6277
6881
|
};
|
|
6278
6882
|
}
|
|
6279
6883
|
}
|
|
@@ -6304,7 +6908,8 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
6304
6908
|
riskType: "script_execution",
|
|
6305
6909
|
confidence: 90,
|
|
6306
6910
|
source: "heuristic",
|
|
6307
|
-
violatedLayers: ["L1.1"]
|
|
6911
|
+
violatedLayers: ["L1.1"],
|
|
6912
|
+
...builtinAsk("builtin_home_deletion")
|
|
6308
6913
|
};
|
|
6309
6914
|
}
|
|
6310
6915
|
}
|
|
@@ -6314,18 +6919,34 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
6314
6919
|
function escapeRegExp(s) {
|
|
6315
6920
|
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6316
6921
|
}
|
|
6922
|
+
function dirTargetIsDirectory(text, dirPath) {
|
|
6923
|
+
const low = text.toLowerCase();
|
|
6924
|
+
const dpath = dirPath.toLowerCase();
|
|
6925
|
+
let idx = low.indexOf(dpath);
|
|
6926
|
+
while (idx >= 0) {
|
|
6927
|
+
const tail = low.slice(idx + dpath.length);
|
|
6928
|
+
if (!tail || /^[\s'"\\);|&)>]/.test(tail)) return true;
|
|
6929
|
+
if (tail.startsWith("/*") || tail.startsWith("/.")) return true;
|
|
6930
|
+
if (tail.startsWith("/")) {
|
|
6931
|
+
const rest = tail.slice(1);
|
|
6932
|
+
if (!rest || /^[\s'"\\);|&)>]/.test(rest)) return true;
|
|
6933
|
+
}
|
|
6934
|
+
idx = low.indexOf(dpath, idx + 1);
|
|
6935
|
+
}
|
|
6936
|
+
return false;
|
|
6937
|
+
}
|
|
6317
6938
|
function isDeleteActionForDir(command, dirPath) {
|
|
6318
6939
|
const low = command.toLowerCase();
|
|
6319
6940
|
const dpath = dirPath.toLowerCase();
|
|
6320
|
-
if (new RegExp(`\\b(?:rm|unlink|rmdir)\\b[^&|;]*?${escapeRegExp(dpath)}`, "i").test(low)) {
|
|
6941
|
+
if (new RegExp(`\\b(?:rm|unlink|rmdir)\\b[^&|;]*?${escapeRegExp(dpath)}`, "i").test(low) && dirTargetIsDirectory(low, dpath)) {
|
|
6321
6942
|
return true;
|
|
6322
6943
|
}
|
|
6323
|
-
if (new RegExp(`(?:\u5220\u9664|\u79FB\u9664)[^\\n;|&]*?${escapeRegExp(dpath)}`).test(low)) {
|
|
6944
|
+
if (new RegExp(`(?:\u5220\u9664|\u79FB\u9664)[^\\n;|&]*?${escapeRegExp(dpath)}`).test(low) && dirTargetIsDirectory(low, dpath)) {
|
|
6324
6945
|
return true;
|
|
6325
6946
|
}
|
|
6326
6947
|
for (const seg of low.split(/&&|\|\||;|\n/)) {
|
|
6327
6948
|
const fw = (seg.trim().split(/\s+/)[0] || "").toLowerCase();
|
|
6328
|
-
if ((fw === "rm" || fw === "unlink" || fw === "rmdir") && seg
|
|
6949
|
+
if ((fw === "rm" || fw === "unlink" || fw === "rmdir") && dirTargetIsDirectory(seg, dpath)) {
|
|
6329
6950
|
return true;
|
|
6330
6951
|
}
|
|
6331
6952
|
}
|
|
@@ -6336,7 +6957,7 @@ function isArchiveReadOfDir(command, dirPath) {
|
|
|
6336
6957
|
const dpath = dirPath.toLowerCase();
|
|
6337
6958
|
for (const seg of low.split(/&&|\|\||;|\n/)) {
|
|
6338
6959
|
const s = seg.trim();
|
|
6339
|
-
if (!s || !s
|
|
6960
|
+
if (!s || !dirTargetIsDirectory(s, dpath)) continue;
|
|
6340
6961
|
const parts = s.split(/\s+/);
|
|
6341
6962
|
const fw = parts[0] || "";
|
|
6342
6963
|
if (fw === "zip") return true;
|
|
@@ -6346,7 +6967,7 @@ function isArchiveReadOfDir(command, dirPath) {
|
|
|
6346
6967
|
}
|
|
6347
6968
|
if (fw === "cp" || fw === "rsync") {
|
|
6348
6969
|
const segPaths = s.match(/[/~][^\s;|&><'"]*/g) || [];
|
|
6349
|
-
if (segPaths[0]
|
|
6970
|
+
if (segPaths[0] && dirTargetIsDirectory(segPaths[0], dpath)) return true;
|
|
6350
6971
|
}
|
|
6351
6972
|
}
|
|
6352
6973
|
return false;
|
|
@@ -6358,15 +6979,16 @@ function isSshKeygenGenerate(command) {
|
|
|
6358
6979
|
if (/(?:^|\s)-\S*[ylpB]\S*/.test(low)) return false;
|
|
6359
6980
|
return true;
|
|
6360
6981
|
}
|
|
6361
|
-
function checkDangerousPatterns(actionType, actionDetail) {
|
|
6982
|
+
function checkDangerousPatterns(actionType, actionDetail, enabledBuiltin) {
|
|
6362
6983
|
if (actionType === "file_write" || actionType === "file_edit") return null;
|
|
6984
|
+
const on = (id) => !enabledBuiltin || enabledBuiltin.has(id);
|
|
6363
6985
|
const scan = stripSearchPatternLiterals(stripHeredocContent(stripShellDocsOnly(actionDetail)));
|
|
6364
6986
|
const isTempPath = TEMP_DIRS2.some(
|
|
6365
6987
|
(td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
|
|
6366
6988
|
) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
|
|
6367
6989
|
const wildcardDeleteRe = /(?:\brm\b|\b(r?mdir|del|delete|remove|rmdir|unlink)\b|\b删除\b|\b移除\b)[\s\S]{0,40}?[*?]|[*?][\s\S]{0,40}?\b(?:rm|del|delete|remove|rmdir|unlink)\b|rm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+\S*[*?]/i;
|
|
6368
6990
|
const scanNoSpecials = scan.replace(/\$(?:\?|\$|!|#|\{[?$!#]\})/g, " ");
|
|
6369
|
-
if (!isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
6991
|
+
if (on("builtin_wildcard_delete") && !isTempPath && !isBuildArtifactCleanup(actionDetail) && wildcardDeleteRe.test(scanNoSpecials)) {
|
|
6370
6992
|
return {
|
|
6371
6993
|
allowed: false,
|
|
6372
6994
|
reason: "\u68C0\u6D4B\u5230\u901A\u914D\u7B26\u7ED3\u5408\u5220\u9664\u64CD\u4F5C\uFF0C\u53EF\u80FD\u9020\u6210\u6279\u91CF\u8BEF\u5220",
|
|
@@ -6374,12 +6996,13 @@ function checkDangerousPatterns(actionType, actionDetail) {
|
|
|
6374
6996
|
riskType: "script_execution",
|
|
6375
6997
|
confidence: 90,
|
|
6376
6998
|
source: "heuristic",
|
|
6377
|
-
violatedLayers: ["L1.1"]
|
|
6999
|
+
violatedLayers: ["L1.1"],
|
|
7000
|
+
...builtinAsk("builtin_wildcard_delete")
|
|
6378
7001
|
};
|
|
6379
7002
|
}
|
|
6380
|
-
const findWriteMatch = actionDetail.match(
|
|
7003
|
+
const findWriteMatch = on("builtin_find_exec_write") ? actionDetail.match(
|
|
6381
7004
|
/\bfind\b.*?(?:(?:^|\s)-exec(?:dir)?\s+(chmod|chown|cp|mv|rm|dd|tee|truncate|mkfs|shred|rmdir|unlink)\b|(?:^|\s)\|\s*xargs\s+(?:sed\s+-[a-zA-Z]*i|chmod|chown|cp|mv|rm|dd|tee|truncate|mkfs|shred|rmdir|unlink)\b)/i
|
|
6382
|
-
);
|
|
7005
|
+
) : null;
|
|
6383
7006
|
if (findWriteMatch) {
|
|
6384
7007
|
const cmdHit = findWriteMatch[1] || "xargs";
|
|
6385
7008
|
return {
|
|
@@ -6389,10 +7012,11 @@ function checkDangerousPatterns(actionType, actionDetail) {
|
|
|
6389
7012
|
riskType: "script_execution",
|
|
6390
7013
|
confidence: 90,
|
|
6391
7014
|
source: "heuristic",
|
|
6392
|
-
violatedLayers: ["L1.1"]
|
|
7015
|
+
violatedLayers: ["L1.1"],
|
|
7016
|
+
...builtinAsk("builtin_find_exec_write")
|
|
6393
7017
|
};
|
|
6394
7018
|
}
|
|
6395
|
-
if (/>\s*['"]?\/etc\//.test(actionDetail) || />\s*['"]?\/boot\//.test(actionDetail) || />\s*['"]?\/proc\//.test(actionDetail)) {
|
|
7019
|
+
if (on("builtin_redirect_system") && (/>\s*['"]?\/etc\//.test(actionDetail) || />\s*['"]?\/boot\//.test(actionDetail) || />\s*['"]?\/proc\//.test(actionDetail))) {
|
|
6396
7020
|
return {
|
|
6397
7021
|
allowed: false,
|
|
6398
7022
|
reason: "\u68C0\u6D4B\u5230\u91CD\u5B9A\u5411\u8986\u76D6\u5199\u5165\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55",
|
|
@@ -6400,7 +7024,8 @@ function checkDangerousPatterns(actionType, actionDetail) {
|
|
|
6400
7024
|
riskType: "file_access",
|
|
6401
7025
|
confidence: 95,
|
|
6402
7026
|
source: "heuristic",
|
|
6403
|
-
violatedLayers: ["L1.1"]
|
|
7027
|
+
violatedLayers: ["L1.1"],
|
|
7028
|
+
...builtinAsk("builtin_redirect_system")
|
|
6404
7029
|
};
|
|
6405
7030
|
}
|
|
6406
7031
|
if (/>\s*\/dev\/(sd|hd|nvme|vd|loop|mem|kmsg|port|zero|random|urandom|full|core)/i.test(actionDetail)) {
|
|
@@ -6502,13 +7127,14 @@ function checkLateralMovement(actionDetail) {
|
|
|
6502
7127
|
riskType: "lateral_movement",
|
|
6503
7128
|
confidence: 80,
|
|
6504
7129
|
source: "heuristic",
|
|
6505
|
-
violatedLayers: ["L1.1"]
|
|
7130
|
+
violatedLayers: ["L1.1"],
|
|
7131
|
+
...builtinAsk("builtin_lateral_movement")
|
|
6506
7132
|
};
|
|
6507
7133
|
}
|
|
6508
7134
|
}
|
|
6509
7135
|
return null;
|
|
6510
7136
|
}
|
|
6511
|
-
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
7137
|
+
var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, LOOP_EXIT_RE, LOOP_START_RE, DB_QUERY_CMD_RE, LOOP_SIDE_EFFECT_RE, LOOPBACK_DATA_GUARD_RE, TEMPLATE_SUFFIX_LA, INSTRUCTION_WRITE_RE, DATA_DOC_EXTS, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SEARCH_OPTION_WITH_ARG, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
|
|
6512
7138
|
var init_heuristic = __esm({
|
|
6513
7139
|
"src/engine/heuristic.ts"() {
|
|
6514
7140
|
"use strict";
|
|
@@ -6520,6 +7146,8 @@ var init_heuristic = __esm({
|
|
|
6520
7146
|
init_runtime_config_bridge();
|
|
6521
7147
|
init_rules_loader();
|
|
6522
7148
|
init_written_content_analyzer();
|
|
7149
|
+
init_inline_analyzer();
|
|
7150
|
+
init_structural_analyzer();
|
|
6523
7151
|
init_logic_rules();
|
|
6524
7152
|
INJECTION_KEYWORDS = (() => {
|
|
6525
7153
|
const kws = loadL1().injection_detection || [];
|
|
@@ -6542,6 +7170,30 @@ var init_heuristic = __esm({
|
|
|
6542
7170
|
HEURISTIC_RULES = loadHeuristicRules();
|
|
6543
7171
|
LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
|
|
6544
7172
|
TEMP_DIRS2 = HEURISTIC_RULES.temp_dirs ?? [];
|
|
7173
|
+
LOOP_EXIT_RE = /\bbreak\b/gi;
|
|
7174
|
+
LOOP_START_RE = /\bwhile\s+(?:true\b|1\b|:)|until\s+false\b|\bfor\s*\(\s*;/gi;
|
|
7175
|
+
DB_QUERY_CMD_RE = /\b(?:sqlite3|psql|mysql|mariadb|sqlplus)\b|\bpython(?:3(?:\.\d+)?)?\s+-c\b[\s\S]{0,4096}?\b(?:execute|executemany)\s*\(/i;
|
|
7176
|
+
LOOP_SIDE_EFFECT_RE = /\b(?:rm|rmdir|unlink|shred|dd|mkfs\w*|chmod|chown|curl|wget|nc|ncat|socat|ssh|scp|rsync|kill|pkill|killall|shutdown|reboot|systemctl|sudo|mount)\b|\/dev\/tcp|\bos\.(?:system|popen|fork|exec\w*)\b|\bsubprocess\b|>\s*\/(?:etc|dev|proc|sys|boot)\//i;
|
|
7177
|
+
LOOPBACK_DATA_GUARD_RE = /\$|`|\bcat\b|@|-[TF]\b/;
|
|
7178
|
+
TEMPLATE_SUFFIX_LA = "(?!\\.(?:example|template|sample|dist)(?![A-Za-z0-9_-]))";
|
|
7179
|
+
INSTRUCTION_WRITE_RE = /(?:>>?|\btee\b(?:\s+-a)?)\s*(['"]?)([^\s;|&'"<>]+)/gi;
|
|
7180
|
+
DATA_DOC_EXTS = /* @__PURE__ */ new Set([
|
|
7181
|
+
".md",
|
|
7182
|
+
".txt",
|
|
7183
|
+
".rst",
|
|
7184
|
+
".html",
|
|
7185
|
+
".htm",
|
|
7186
|
+
".json",
|
|
7187
|
+
".yaml",
|
|
7188
|
+
".yml",
|
|
7189
|
+
".csv",
|
|
7190
|
+
".xml",
|
|
7191
|
+
".css",
|
|
7192
|
+
".ini",
|
|
7193
|
+
".conf",
|
|
7194
|
+
".log",
|
|
7195
|
+
".sql"
|
|
7196
|
+
]);
|
|
6545
7197
|
PATH_CONTEXT_TRIGGER_RE = /(?:^|[;&|]\s*)(?:rm|rmdir|unlink|ln|mv|cp|dd|truncate|shred|chmod|chown)\b/i;
|
|
6546
7198
|
HOME_PREFIX_RE = /(?:~|~(?=\/)|\$HOME\b|\$\{HOME\}|\/home\/[a-z0-9_.-]+)/gi;
|
|
6547
7199
|
PY_EXEC_IO_RE = /os\.system|os\.popen|subprocess|eval\s*\(|exec\s*\(|__import__|open\s*\(|socket|urllib|requests\.|shutil|os\.(?:remove|unlink|rename|makedirs?|listdir|scandir|walk|chmod|chown|kill|environ)|iterdir|glob\s*\(|path\(/i;
|
|
@@ -6587,8 +7239,99 @@ var init_heuristic = __esm({
|
|
|
6587
7239
|
}
|
|
6588
7240
|
});
|
|
6589
7241
|
|
|
7242
|
+
// src/engine/shell-alias-resolver.ts
|
|
7243
|
+
import { spawnSync } from "child_process";
|
|
7244
|
+
import { existsSync as existsSync11, statSync as statSync5 } from "fs";
|
|
7245
|
+
import { homedir as homedir4 } from "os";
|
|
7246
|
+
import { join as join11 } from "path";
|
|
7247
|
+
function rcFiles() {
|
|
7248
|
+
return [
|
|
7249
|
+
join11(homedir4(), ".bashrc"),
|
|
7250
|
+
join11(homedir4(), ".bash_profile"),
|
|
7251
|
+
join11(homedir4(), ".profile"),
|
|
7252
|
+
"/etc/bash.bashrc",
|
|
7253
|
+
"/etc/profile"
|
|
7254
|
+
];
|
|
7255
|
+
}
|
|
7256
|
+
function rcSignature() {
|
|
7257
|
+
return rcFiles().map((p) => {
|
|
7258
|
+
try {
|
|
7259
|
+
return String(statSync5(p).mtimeMs);
|
|
7260
|
+
} catch {
|
|
7261
|
+
return "0";
|
|
7262
|
+
}
|
|
7263
|
+
}).join("|");
|
|
7264
|
+
}
|
|
7265
|
+
function minimalEnv() {
|
|
7266
|
+
const keep = ["HOME", "USER", "LOGNAME", "SHELL", "PATH", "LANG", "LC_ALL", "TERM"];
|
|
7267
|
+
const env2 = {};
|
|
7268
|
+
for (const k of keep) if (process.env[k] !== void 0) env2[k] = process.env[k];
|
|
7269
|
+
env2.TERM = env2.TERM || "dumb";
|
|
7270
|
+
return env2;
|
|
7271
|
+
}
|
|
7272
|
+
function firstWord(command) {
|
|
7273
|
+
const m = (command || "").match(FIRST_WORD_RE);
|
|
7274
|
+
return m ? m[1] : "";
|
|
7275
|
+
}
|
|
7276
|
+
function run(shell, script, word, cwd) {
|
|
7277
|
+
try {
|
|
7278
|
+
const r = spawnSync(shell, ["-ic", script, "_", word], {
|
|
7279
|
+
timeout: PROBE_TIMEOUT_MS,
|
|
7280
|
+
cwd: cwd || void 0,
|
|
7281
|
+
env: minimalEnv(),
|
|
7282
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
7283
|
+
encoding: "utf8"
|
|
7284
|
+
});
|
|
7285
|
+
return r.stdout || "";
|
|
7286
|
+
} catch {
|
|
7287
|
+
return "";
|
|
7288
|
+
}
|
|
7289
|
+
}
|
|
7290
|
+
function resolveCommandPrefix(command, cwd = "") {
|
|
7291
|
+
if (process.env.AGENT_MOSS_SHELL_ALIAS_RESOLVE !== "1") return null;
|
|
7292
|
+
if (process.platform === "win32") return null;
|
|
7293
|
+
const word = firstWord(command);
|
|
7294
|
+
if (!word || word.includes("/")) return null;
|
|
7295
|
+
let shell = process.env.SHELL || "/bin/bash";
|
|
7296
|
+
if (!existsSync11(shell)) shell = "/bin/bash";
|
|
7297
|
+
const key = `${process.env.HOME || ""}|${shell}|${word}`;
|
|
7298
|
+
const sig = rcSignature();
|
|
7299
|
+
const cached2 = cache3.get(key);
|
|
7300
|
+
if (cached2 && cached2.sig === sig) return cached2.value;
|
|
7301
|
+
const out = run(shell, 'alias -- "$1" 2>/dev/null; type -a -- "$1" 2>/dev/null', word, cwd);
|
|
7302
|
+
let resolution = null;
|
|
7303
|
+
for (const raw of out.split("\n")) {
|
|
7304
|
+
const line = raw.trim();
|
|
7305
|
+
const m = line.match(/^alias\s+\S+=(.*)$/);
|
|
7306
|
+
if (m) {
|
|
7307
|
+
const value = m[1].trim().replace(/^['"]|['"]$/g, "");
|
|
7308
|
+
const rest = command.trim().slice(word.length).trim();
|
|
7309
|
+
resolution = { word, kind: "alias", expansion: `${value} ${rest}`.trim() };
|
|
7310
|
+
break;
|
|
7311
|
+
}
|
|
7312
|
+
if (new RegExp(`\\b${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s+is\\s+a\\s+(?:shell\\s+)?function\\b`).test(line)) {
|
|
7313
|
+
const body = run(shell, 'declare -f -- "$1" 2>/dev/null', word, cwd).trim();
|
|
7314
|
+
if (body) resolution = { word, kind: "function", expansion: `${body}
|
|
7315
|
+
${command}` };
|
|
7316
|
+
break;
|
|
7317
|
+
}
|
|
7318
|
+
}
|
|
7319
|
+
cache3.set(key, { sig, value: resolution });
|
|
7320
|
+
return resolution;
|
|
7321
|
+
}
|
|
7322
|
+
var PROBE_TIMEOUT_MS, FIRST_WORD_RE, cache3;
|
|
7323
|
+
var init_shell_alias_resolver = __esm({
|
|
7324
|
+
"src/engine/shell-alias-resolver.ts"() {
|
|
7325
|
+
"use strict";
|
|
7326
|
+
init_esm_shims();
|
|
7327
|
+
PROBE_TIMEOUT_MS = 2e3;
|
|
7328
|
+
FIRST_WORD_RE = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*([^\s;|&()]+)/;
|
|
7329
|
+
cache3 = /* @__PURE__ */ new Map();
|
|
7330
|
+
}
|
|
7331
|
+
});
|
|
7332
|
+
|
|
6590
7333
|
// src/engine/template-loader.ts
|
|
6591
|
-
import { readFileSync as readFileSync10, existsSync as
|
|
7334
|
+
import { readFileSync as readFileSync10, existsSync as existsSync12 } from "fs";
|
|
6592
7335
|
import { resolve as resolve8, dirname as dirname9 } from "path";
|
|
6593
7336
|
import { fileURLToPath as fileURLToPath9 } from "url";
|
|
6594
7337
|
function loadTemplates() {
|
|
@@ -6602,7 +7345,7 @@ function loadTemplates() {
|
|
|
6602
7345
|
}
|
|
6603
7346
|
for (const file of TEMPLATE_FILES) {
|
|
6604
7347
|
const filePath = resolve8(dir, file);
|
|
6605
|
-
if (
|
|
7348
|
+
if (existsSync12(filePath)) {
|
|
6606
7349
|
const key = file.replace(".txt", "").replace("_template", "");
|
|
6607
7350
|
cachedTemplates[key] = readFileSync10(filePath, "utf-8");
|
|
6608
7351
|
}
|
|
@@ -6625,7 +7368,7 @@ var init_template_loader = __esm({
|
|
|
6625
7368
|
|
|
6626
7369
|
// src/engine/script-analyzer.ts
|
|
6627
7370
|
import { readFileSync as readFileSync11 } from "fs";
|
|
6628
|
-
import { resolve as resolve9, join as
|
|
7371
|
+
import { resolve as resolve9, join as join12 } from "path";
|
|
6629
7372
|
function emptyResult() {
|
|
6630
7373
|
return { scriptPath: "", scriptContent: "", matchedKeywords: [], lineCount: 0, isSuspicious: false, error: "", riskLevel: "", riskReason: "" };
|
|
6631
7374
|
}
|
|
@@ -6678,7 +7421,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
|
|
|
6678
7421
|
}
|
|
6679
7422
|
function readScriptContent(scriptPath, maxLines = 500) {
|
|
6680
7423
|
try {
|
|
6681
|
-
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ?
|
|
7424
|
+
const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join12(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve9(scriptPath);
|
|
6682
7425
|
const raw = readFileSync11(expandedPath, "utf-8");
|
|
6683
7426
|
const lines = raw.split("\n").slice(0, maxLines);
|
|
6684
7427
|
return { content: lines.join("\n"), lineCount: lines.length, error: "" };
|
|
@@ -10114,6 +10857,7 @@ function emptyNode(pathStr, depth) {
|
|
|
10114
10857
|
l1RiskType: "",
|
|
10115
10858
|
l1Reason: "",
|
|
10116
10859
|
l1MatchedPatterns: [],
|
|
10860
|
+
l1AskReason: "",
|
|
10117
10861
|
l2Hit: false,
|
|
10118
10862
|
l2ViolatedRule: "",
|
|
10119
10863
|
l2RiskLevel: "",
|
|
@@ -10306,6 +11050,7 @@ var init_tracker = __esm({
|
|
|
10306
11050
|
node.l1RiskType = l1.riskType;
|
|
10307
11051
|
node.l1Reason = l1.reason;
|
|
10308
11052
|
node.l1MatchedPatterns = l1.matchedPatterns || [];
|
|
11053
|
+
node.l1AskReason = l1.askReason || "";
|
|
10309
11054
|
if (l1.riskLevel === "critical") {
|
|
10310
11055
|
this.result.hasCritical = true;
|
|
10311
11056
|
if (!this.result.firstHitNode) this.result.firstHitNode = node;
|
|
@@ -10358,9 +11103,9 @@ var init_tracker = __esm({
|
|
|
10358
11103
|
});
|
|
10359
11104
|
|
|
10360
11105
|
// src/engine/script-content-analyzer.ts
|
|
10361
|
-
import { statSync as
|
|
10362
|
-
import { resolve as resolve11, join as
|
|
10363
|
-
import { homedir as
|
|
11106
|
+
import { statSync as statSync7, existsSync as existsSync14 } from "fs";
|
|
11107
|
+
import { resolve as resolve11, join as join14, isAbsolute as isAbsolute5 } from "path";
|
|
11108
|
+
import { homedir as homedir6 } from "os";
|
|
10364
11109
|
function emptyChain() {
|
|
10365
11110
|
return {
|
|
10366
11111
|
nodes: [],
|
|
@@ -10471,8 +11216,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
10471
11216
|
if (looksLikeScriptPath(tok)) {
|
|
10472
11217
|
try {
|
|
10473
11218
|
const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
|
|
10474
|
-
if (
|
|
10475
|
-
const stat =
|
|
11219
|
+
if (existsSync14(resolved)) {
|
|
11220
|
+
const stat = statSync7(resolved);
|
|
10476
11221
|
if (stat.isFile()) return resolved;
|
|
10477
11222
|
}
|
|
10478
11223
|
} catch {
|
|
@@ -10485,8 +11230,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
10485
11230
|
const p = m[1];
|
|
10486
11231
|
try {
|
|
10487
11232
|
const resolved = resolvePath2(p);
|
|
10488
|
-
if (
|
|
10489
|
-
const stat =
|
|
11233
|
+
if (existsSync14(resolved)) {
|
|
11234
|
+
const stat = statSync7(resolved);
|
|
10490
11235
|
if (stat.isFile()) return resolved;
|
|
10491
11236
|
}
|
|
10492
11237
|
} catch {
|
|
@@ -10501,8 +11246,8 @@ function extractInlineScriptPath(actionDetail) {
|
|
|
10501
11246
|
let resolved;
|
|
10502
11247
|
try {
|
|
10503
11248
|
resolved = resolvePath2(p);
|
|
10504
|
-
if (
|
|
10505
|
-
const stat =
|
|
11249
|
+
if (existsSync14(resolved)) {
|
|
11250
|
+
const stat = statSync7(resolved);
|
|
10506
11251
|
if (stat.isFile()) return resolved;
|
|
10507
11252
|
}
|
|
10508
11253
|
} catch {
|
|
@@ -10542,7 +11287,7 @@ function shlexSplit(s) {
|
|
|
10542
11287
|
function resolvePath2(p) {
|
|
10543
11288
|
let expanded = p;
|
|
10544
11289
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
10545
|
-
expanded =
|
|
11290
|
+
expanded = join14(homedir6(), expanded.slice(1));
|
|
10546
11291
|
}
|
|
10547
11292
|
return resolve11(expanded);
|
|
10548
11293
|
}
|
|
@@ -10569,6 +11314,31 @@ function scanExtensionPatterns(ext, content) {
|
|
|
10569
11314
|
}
|
|
10570
11315
|
return null;
|
|
10571
11316
|
}
|
|
11317
|
+
function scanSensitiveSegments(content, cwd, ext, osType) {
|
|
11318
|
+
let prefilter = null;
|
|
11319
|
+
try {
|
|
11320
|
+
const { root, home, credential } = getSensitivePathsForOs(osType);
|
|
11321
|
+
const prefixes = [];
|
|
11322
|
+
for (const sp of [...root, ...home, ...credential]) {
|
|
11323
|
+
const prefix = String(sp.path || "").split("(")[0].trim();
|
|
11324
|
+
if (prefix) prefixes.push(prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
11325
|
+
}
|
|
11326
|
+
if (prefixes.length) prefilter = new RegExp(prefixes.join("|"), "i");
|
|
11327
|
+
} catch {
|
|
11328
|
+
}
|
|
11329
|
+
let best = null;
|
|
11330
|
+
for (const raw of content.split(/&&|\|\||;|\n/)) {
|
|
11331
|
+
const seg = raw.trim();
|
|
11332
|
+
if (!seg) continue;
|
|
11333
|
+
if (prefilter && !prefilter.test(seg)) continue;
|
|
11334
|
+
const j = checkSensitivePath(seg, cwd, ext, osType);
|
|
11335
|
+
if (!j || j.allowed) continue;
|
|
11336
|
+
if (!best || (LEVEL_ORDER2[j.riskLevel] || 0) > (LEVEL_ORDER2[best.riskLevel] || 0)) {
|
|
11337
|
+
best = { riskLevel: j.riskLevel, riskType: j.riskType, reason: j.reason, askReason: j.ask_reason };
|
|
11338
|
+
}
|
|
11339
|
+
}
|
|
11340
|
+
return best;
|
|
11341
|
+
}
|
|
10572
11342
|
function scanScriptChainWithL2(chain, input) {
|
|
10573
11343
|
for (const node of chain.nodes) {
|
|
10574
11344
|
if (node.error || !node.preprocessedContent) continue;
|
|
@@ -10631,31 +11401,21 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
10631
11401
|
isInline = true;
|
|
10632
11402
|
}
|
|
10633
11403
|
if (resolvedPath && !isAbsolute5(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
10634
|
-
resolvedPath =
|
|
11404
|
+
resolvedPath = join14(input.cwd || process.cwd(), resolvedPath);
|
|
10635
11405
|
}
|
|
10636
11406
|
const l1Adapter = (content) => {
|
|
11407
|
+
const candidates = [];
|
|
10637
11408
|
const extHit = scanExtensionPatterns(ext, content);
|
|
10638
|
-
if (extHit) {
|
|
10639
|
-
return {
|
|
10640
|
-
hit: true,
|
|
10641
|
-
riskLevel: extHit.riskLevel,
|
|
10642
|
-
riskType: extHit.riskType,
|
|
10643
|
-
reason: extHit.reason,
|
|
10644
|
-
matchedPatterns: []
|
|
10645
|
-
};
|
|
10646
|
-
}
|
|
11409
|
+
if (extHit) candidates.push({ riskLevel: extHit.riskLevel, riskType: extHit.riskType, reason: extHit.reason });
|
|
10647
11410
|
const j = scanDangerousCommandPatterns("bash", content, input.osType);
|
|
10648
|
-
if (j && !j.allowed) {
|
|
10649
|
-
|
|
10650
|
-
|
|
10651
|
-
|
|
10652
|
-
|
|
10653
|
-
|
|
10654
|
-
|
|
10655
|
-
|
|
10656
|
-
};
|
|
10657
|
-
}
|
|
10658
|
-
return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
|
|
11411
|
+
if (j && !j.allowed) candidates.push({ riskLevel: j.riskLevel, riskType: j.riskType, reason: j.reason, askReason: j.ask_reason });
|
|
11412
|
+
const spHit = scanSensitiveSegments(content, input.cwd || process.cwd(), ext, input.osType);
|
|
11413
|
+
if (spHit) candidates.push(spHit);
|
|
11414
|
+
if (candidates.length === 0) {
|
|
11415
|
+
return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
|
|
11416
|
+
}
|
|
11417
|
+
const best = candidates.reduce((a, b) => (LEVEL_ORDER2[b.riskLevel] || 0) > (LEVEL_ORDER2[a.riskLevel] || 0) ? b : a);
|
|
11418
|
+
return { hit: true, riskLevel: best.riskLevel, riskType: best.riskType, reason: best.reason, matchedPatterns: [], askReason: best.askReason };
|
|
10659
11419
|
};
|
|
10660
11420
|
const tracker = new RecursiveTracker(
|
|
10661
11421
|
l1Adapter,
|
|
@@ -11232,17 +11992,17 @@ __export(token_stats_exports, {
|
|
|
11232
11992
|
resetTokenStats: () => resetTokenStats,
|
|
11233
11993
|
resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
|
|
11234
11994
|
});
|
|
11235
|
-
import { readFileSync as readFileSync14, writeFileSync as writeFileSync2, existsSync as
|
|
11995
|
+
import { readFileSync as readFileSync14, writeFileSync as writeFileSync2, existsSync as existsSync15, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync8 } from "fs";
|
|
11236
11996
|
function getStatsPath() {
|
|
11237
11997
|
const envPath = process.env[ENV_STATS_PATH];
|
|
11238
11998
|
if (envPath) return envPath;
|
|
11239
11999
|
return getTokenStatsPath();
|
|
11240
12000
|
}
|
|
11241
12001
|
function loadAllRecords(statsPath) {
|
|
11242
|
-
if (!
|
|
12002
|
+
if (!existsSync15(statsPath)) return [];
|
|
11243
12003
|
let sig = "";
|
|
11244
12004
|
try {
|
|
11245
|
-
const st =
|
|
12005
|
+
const st = statSync8(statsPath);
|
|
11246
12006
|
sig = `${st.mtimeMs}:${st.size}`;
|
|
11247
12007
|
} catch {
|
|
11248
12008
|
return [];
|
|
@@ -11265,7 +12025,7 @@ function loadAllRecords(statsPath) {
|
|
|
11265
12025
|
function saveRecords(statsPath, records) {
|
|
11266
12026
|
try {
|
|
11267
12027
|
const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
|
|
11268
|
-
if (dir && !
|
|
12028
|
+
if (dir && !existsSync15(dir)) mkdirSync3(dir, { recursive: true });
|
|
11269
12029
|
const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
|
|
11270
12030
|
try {
|
|
11271
12031
|
writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
|
|
@@ -11277,7 +12037,7 @@ function saveRecords(statsPath, records) {
|
|
|
11277
12037
|
}
|
|
11278
12038
|
}
|
|
11279
12039
|
try {
|
|
11280
|
-
const st =
|
|
12040
|
+
const st = statSync8(statsPath);
|
|
11281
12041
|
_recordsCache = {
|
|
11282
12042
|
path: statsPath,
|
|
11283
12043
|
sig: `${st.mtimeMs}:${st.size}`,
|
|
@@ -11414,7 +12174,7 @@ function getTokenTrend(days = 0, startDate, endDate) {
|
|
|
11414
12174
|
}
|
|
11415
12175
|
function resetTokenStats() {
|
|
11416
12176
|
const statsPath = getStatsPath();
|
|
11417
|
-
if (
|
|
12177
|
+
if (existsSync15(statsPath)) {
|
|
11418
12178
|
try {
|
|
11419
12179
|
unlinkSync2(statsPath);
|
|
11420
12180
|
} catch {
|
|
@@ -11830,23 +12590,37 @@ async function analyzeWithLLM(prompt, config) {
|
|
|
11830
12590
|
}
|
|
11831
12591
|
const attemptStart = performance.now();
|
|
11832
12592
|
try {
|
|
11833
|
-
const
|
|
11834
|
-
|
|
11835
|
-
|
|
11836
|
-
|
|
11837
|
-
|
|
11838
|
-
|
|
11839
|
-
|
|
11840
|
-
|
|
11841
|
-
|
|
11842
|
-
|
|
11843
|
-
|
|
11844
|
-
|
|
12593
|
+
const baseBudget = config.maxTokens || 1024;
|
|
12594
|
+
const escalatedBudget = Math.min(Math.max(baseBudget * 4, 16384), 32768);
|
|
12595
|
+
let response = null;
|
|
12596
|
+
let content = "";
|
|
12597
|
+
let finishReason;
|
|
12598
|
+
let usage = null;
|
|
12599
|
+
for (const budget of Array.from(/* @__PURE__ */ new Set([baseBudget, escalatedBudget]))) {
|
|
12600
|
+
response = await client.chat.completions.create({
|
|
12601
|
+
model: config.model,
|
|
12602
|
+
temperature: config.temperature || 0.1,
|
|
12603
|
+
max_tokens: budget,
|
|
12604
|
+
messages: [
|
|
12605
|
+
{ role: "system", content: "\u53EA\u8F93\u51FA\u7EAF JSON\uFF0C\u4E0D\u8981\u5305\u542B markdown \u6807\u8BB0\u3001\u4EE3\u7801\u5757\u6216\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002" },
|
|
12606
|
+
{ role: "user", content: prompt }
|
|
12607
|
+
],
|
|
12608
|
+
signal: abortController.signal,
|
|
12609
|
+
// 私有化网关的额外参数(关思考等)原样透传;空则不传。
|
|
12610
|
+
...config.extraBody && Object.keys(config.extraBody).length ? { extra_body: config.extraBody } : {}
|
|
12611
|
+
});
|
|
12612
|
+
const msg = response.choices[0]?.message;
|
|
12613
|
+
content = msg?.content ?? "";
|
|
12614
|
+
finishReason = response.choices[0]?.finish_reason;
|
|
12615
|
+
usage = response.usage;
|
|
12616
|
+
const hasReasoning = ["reasoning", "reasoning_content", "thinking"].some((k) => typeof msg?.[k] === "string" && msg[k].length > 0);
|
|
12617
|
+
if (content || finishReason !== "length" || budget === escalatedBudget || !hasReasoning) break;
|
|
12618
|
+
console.warn(
|
|
12619
|
+
`[AgentMoss] LLM \u63A8\u7406\u8017\u5C3D token\uFF08max_tokens=${budget}\uFF09\uFF0C\u6309\u63A8\u7406\u6A21\u578B\u7B56\u7565\u63D0\u5347\u5230 ${escalatedBudget} \u91CD\u8BD5\u4E00\u6B21\uFF08model=${config.model}\uFF09\u2014\u2014\u975E\u63A8\u7406\u6A21\u578B\u4E0D\u4F1A\u89E6\u53D1\u6B64\u8DEF\u5F84`
|
|
12620
|
+
);
|
|
12621
|
+
}
|
|
11845
12622
|
const message = response.choices[0]?.message;
|
|
11846
|
-
let content = message?.content ?? "";
|
|
11847
|
-
const finishReason = response.choices[0]?.finish_reason;
|
|
11848
12623
|
const fieldLengths = responseFieldLengths(message);
|
|
11849
|
-
const usage = response.usage;
|
|
11850
12624
|
if (!content) {
|
|
11851
12625
|
const { text: fallback, field } = reasoningFallbackWithField(message);
|
|
11852
12626
|
if (fallback) {
|
|
@@ -12002,9 +12776,9 @@ var init_llm_analyzer = __esm({
|
|
|
12002
12776
|
});
|
|
12003
12777
|
|
|
12004
12778
|
// src/brain/rule-store.ts
|
|
12005
|
-
import { existsSync as
|
|
12006
|
-
import { join as
|
|
12007
|
-
import { homedir as
|
|
12779
|
+
import { existsSync as existsSync16, readFileSync as readFileSync15, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
|
|
12780
|
+
import { join as join15 } from "path";
|
|
12781
|
+
import { homedir as homedir7 } from "os";
|
|
12008
12782
|
function getRulesPath() {
|
|
12009
12783
|
const envPath = process.env[ENV_RULES_PATH];
|
|
12010
12784
|
if (envPath) return envPath;
|
|
@@ -12022,7 +12796,7 @@ var init_rule_store = __esm({
|
|
|
12022
12796
|
"src/brain/rule-store.ts"() {
|
|
12023
12797
|
"use strict";
|
|
12024
12798
|
init_esm_shims();
|
|
12025
|
-
DEFAULT_RULES_PATH =
|
|
12799
|
+
DEFAULT_RULES_PATH = join15(homedir7(), ".agentmoss", "brain", "rules.json");
|
|
12026
12800
|
ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
|
|
12027
12801
|
STATUS_DRAFT = "draft";
|
|
12028
12802
|
STATUS_APPROVED = "approved";
|
|
@@ -12039,7 +12813,7 @@ var init_rule_store = __esm({
|
|
|
12039
12813
|
this.data = this.load();
|
|
12040
12814
|
}
|
|
12041
12815
|
load() {
|
|
12042
|
-
if (!
|
|
12816
|
+
if (!existsSync16(this.path)) {
|
|
12043
12817
|
return { version: 1, rules: [], pattern_candidates: [] };
|
|
12044
12818
|
}
|
|
12045
12819
|
try {
|
|
@@ -12637,9 +13411,9 @@ var init_reviewer = __esm({
|
|
|
12637
13411
|
});
|
|
12638
13412
|
|
|
12639
13413
|
// src/brain/skill-manager.ts
|
|
12640
|
-
import { existsSync as
|
|
12641
|
-
import { homedir as
|
|
12642
|
-
import { join as
|
|
13414
|
+
import { existsSync as existsSync17, mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
13415
|
+
import { homedir as homedir8 } from "os";
|
|
13416
|
+
import { join as join16 } from "path";
|
|
12643
13417
|
import { randomUUID } from "crypto";
|
|
12644
13418
|
function getMetaPath(override) {
|
|
12645
13419
|
return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
|
|
@@ -12649,14 +13423,14 @@ var init_skill_manager = __esm({
|
|
|
12649
13423
|
"src/brain/skill-manager.ts"() {
|
|
12650
13424
|
"use strict";
|
|
12651
13425
|
init_esm_shims();
|
|
12652
|
-
DEFAULT_SKILL_META_PATH =
|
|
13426
|
+
DEFAULT_SKILL_META_PATH = join16(homedir8(), ".agentmoss", "brain", "skill_meta.json");
|
|
12653
13427
|
ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
|
|
12654
13428
|
BrainSkillManager = class {
|
|
12655
13429
|
constructor(skillsDir, metaPath) {
|
|
12656
13430
|
this.skillsDir = skillsDir;
|
|
12657
13431
|
this.metaPath = getMetaPath(metaPath);
|
|
12658
13432
|
try {
|
|
12659
|
-
mkdirSync5(
|
|
13433
|
+
mkdirSync5(join16(this.metaPath, ".."), { recursive: true });
|
|
12660
13434
|
} catch {
|
|
12661
13435
|
}
|
|
12662
13436
|
this.load();
|
|
@@ -12666,7 +13440,7 @@ var init_skill_manager = __esm({
|
|
|
12666
13440
|
skills = [];
|
|
12667
13441
|
metaPath;
|
|
12668
13442
|
load() {
|
|
12669
|
-
if (!
|
|
13443
|
+
if (!existsSync17(this.metaPath)) return;
|
|
12670
13444
|
try {
|
|
12671
13445
|
const data = JSON.parse(readFileSync16(this.metaPath, "utf-8"));
|
|
12672
13446
|
this.skills = data.skills || [];
|
|
@@ -12691,7 +13465,7 @@ var init_skill_manager = __esm({
|
|
|
12691
13465
|
let changed = false;
|
|
12692
13466
|
for (const sk of this.skills) {
|
|
12693
13467
|
if (sk.status !== "active") continue;
|
|
12694
|
-
if (!
|
|
13468
|
+
if (!existsSync17(join16(this.skillsDir, `${sk.name}.md`))) {
|
|
12695
13469
|
sk.status = "stale";
|
|
12696
13470
|
changed = true;
|
|
12697
13471
|
}
|
|
@@ -12702,9 +13476,9 @@ var init_skill_manager = __esm({
|
|
|
12702
13476
|
addSkill(skill) {
|
|
12703
13477
|
const id = skill.id || randomUUID();
|
|
12704
13478
|
const name = skill.name || `brain_${id.slice(0, 8)}`;
|
|
12705
|
-
if (!
|
|
12706
|
-
const mdPath =
|
|
12707
|
-
if (
|
|
13479
|
+
if (!existsSync17(this.skillsDir)) return "";
|
|
13480
|
+
const mdPath = join16(this.skillsDir, `${name}.md`);
|
|
13481
|
+
if (existsSync17(mdPath)) return "";
|
|
12708
13482
|
try {
|
|
12709
13483
|
writeFileSync4(mdPath, skill.content, "utf-8");
|
|
12710
13484
|
} catch {
|
|
@@ -12753,8 +13527,8 @@ var init_skill_manager = __esm({
|
|
|
12753
13527
|
const out = [];
|
|
12754
13528
|
for (const sk of this.skills) {
|
|
12755
13529
|
if (sk.origin_node !== "local" || sk.status !== "active") continue;
|
|
12756
|
-
const mdPath =
|
|
12757
|
-
if (!
|
|
13530
|
+
const mdPath = join16(this.skillsDir, `${sk.name}.md`);
|
|
13531
|
+
if (!existsSync17(mdPath)) continue;
|
|
12758
13532
|
out.push({
|
|
12759
13533
|
name: sk.name,
|
|
12760
13534
|
category: sk.category || "",
|
|
@@ -13227,7 +14001,7 @@ function loadStages() {
|
|
|
13227
14001
|
}
|
|
13228
14002
|
function extractResources(actionDetail) {
|
|
13229
14003
|
const resources = /* @__PURE__ */ new Set();
|
|
13230
|
-
const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "");
|
|
14004
|
+
const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "").replace(WORKDIR_CMD_RE, " ");
|
|
13231
14005
|
PATH_RE.lastIndex = 0;
|
|
13232
14006
|
let m;
|
|
13233
14007
|
while ((m = PATH_RE.exec(text)) !== null) {
|
|
@@ -13243,7 +14017,7 @@ function markStage(actionDetail) {
|
|
|
13243
14017
|
}
|
|
13244
14018
|
function markIntegrity(actionDetail) {
|
|
13245
14019
|
const aps = labelEvent(actionDetail);
|
|
13246
|
-
if (aps.has("download_file")
|
|
14020
|
+
if (aps.has("download_file")) {
|
|
13247
14021
|
return { integrity: "low", isLowSource: true };
|
|
13248
14022
|
}
|
|
13249
14023
|
return { integrity: "medium", isLowSource: false };
|
|
@@ -13368,7 +14142,7 @@ function allNodesFlat(mg) {
|
|
|
13368
14142
|
for (const s of mg.sessions) out.push(...s.nodes);
|
|
13369
14143
|
return out;
|
|
13370
14144
|
}
|
|
13371
|
-
var COMBO_STAGES2, PATH_RE, COMMON_DIR_RESOURCES;
|
|
14145
|
+
var COMBO_STAGES2, PATH_RE, COMMON_DIR_RESOURCES, WORKDIR_CMD_RE;
|
|
13372
14146
|
var init_builder = __esm({
|
|
13373
14147
|
"src/engine/formal-engine/builder.ts"() {
|
|
13374
14148
|
"use strict";
|
|
@@ -13391,6 +14165,7 @@ var init_builder = __esm({
|
|
|
13391
14165
|
"/data",
|
|
13392
14166
|
"/storage"
|
|
13393
14167
|
]);
|
|
14168
|
+
WORKDIR_CMD_RE = /\b(?:cd|pushd|mkdir)\s+(?:-[^\s;&|]+\s+)*[^\s;&|]+/gi;
|
|
13394
14169
|
}
|
|
13395
14170
|
});
|
|
13396
14171
|
|
|
@@ -14045,7 +14820,7 @@ var init_properties = __esm({
|
|
|
14045
14820
|
TOOL_REGISTRY = null;
|
|
14046
14821
|
COMPUTE_RE = /subprocess|os\.system|shell\s*=\s*True|\beval\(|\bexec\(|bash\s+[^\s]|sh\s+-c|python3?\s+|node\s+|\btimeout\s+|nohup\s+|\b\.\/[\w./-]+/i;
|
|
14047
14822
|
STRONG_COMPUTE_TYPES = new Set(FORMAL_RULES.compute_action_types ?? []);
|
|
14048
|
-
DL_OR_LOW_RE = /curl\s+.*-o\b|wget\s+.*\s+-O\b|curl\s+.*\|\s*(bash|sh|python)|wget\s+.*\|\s*(bash|sh|python)|git\s+clone|docker\s+pull|pip\s+install|npm\s+install|base64\s+-d/i;
|
|
14823
|
+
DL_OR_LOW_RE = /curl\s+.*-o\b|wget\s+.*\s+-O\b|curl\s+.*\|\s*(bash|sh|python)|wget\s+.*\|\s*(bash|sh|python)|git\s+clone|docker\s+pull|(?:pip3?(?:\.\d+)?|python[0-9.]*\s+-m\s+pip)\s+install|(?:npm|yarn|pnpm)\s+(?:i|install|add)|(?:base64|base32)\s+-d|openssl\s+base64\s+-d/i;
|
|
14049
14824
|
DATA_SOURCE_READ_RE = /\b(?:cat|head|tail|less|more|sed|awk|grep|strings|base64|xxd|od|dd)\b|\b(?:open|read_text|read_bytes)\s*\(/i;
|
|
14050
14825
|
ALL_PROPERTIES = [
|
|
14051
14826
|
{ id: "cross-session-chain", check: checkCrossSessionChain, shortName: "P1" },
|
|
@@ -15441,6 +16216,9 @@ async function runAnalysis(input) {
|
|
|
15441
16216
|
isLayerEnabled("scenario_rules_enabled") ? getScenarioExtensionsMulti(input.scenarioId || process.env.AGENT_MOSS_SCENARIO || "") : null
|
|
15442
16217
|
);
|
|
15443
16218
|
const degradedNotes = [];
|
|
16219
|
+
let decodedPayloads = [];
|
|
16220
|
+
let aliasResolution = null;
|
|
16221
|
+
const decodeHints = [];
|
|
15444
16222
|
let scriptChain = null;
|
|
15445
16223
|
if (input.aNext.actionType.toLowerCase() === "bash" && getDeployRole() === "host") {
|
|
15446
16224
|
degradedNotes.push("script_content_deferred_to_sandbox: AGENT_MOSS_DEPLOY_ROLE=host");
|
|
@@ -15476,11 +16254,63 @@ async function runAnalysis(input) {
|
|
|
15476
16254
|
riskType: node.l1RiskType,
|
|
15477
16255
|
confidence: 90,
|
|
15478
16256
|
source: "heuristic_script_scan",
|
|
15479
|
-
violatedLayers: ["L1.2"]
|
|
16257
|
+
violatedLayers: ["L1.2"],
|
|
16258
|
+
...node.l1AskReason ? { ask_recommended: true, ask_reason: node.l1AskReason } : {}
|
|
16259
|
+
};
|
|
16260
|
+
}
|
|
16261
|
+
}
|
|
16262
|
+
}
|
|
16263
|
+
}
|
|
16264
|
+
try {
|
|
16265
|
+
const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
16266
|
+
decodedPayloads = extractDecodedPayloads(
|
|
16267
|
+
input.aNext.actionType,
|
|
16268
|
+
input.aNext.actionDetail,
|
|
16269
|
+
handledWrite
|
|
16270
|
+
);
|
|
16271
|
+
if (input.aNext.actionType.toLowerCase() === "bash") {
|
|
16272
|
+
aliasResolution = resolveCommandPrefix(input.aNext.actionDetail, input.cwd || "");
|
|
16273
|
+
}
|
|
16274
|
+
if (heuristicEnabled) {
|
|
16275
|
+
for (const p of decodedPayloads) {
|
|
16276
|
+
const l1 = detectDecoded(p.decoded);
|
|
16277
|
+
if (!l1) continue;
|
|
16278
|
+
if (l1.allowed !== false) continue;
|
|
16279
|
+
const level = p.source === "instruction" ? l1.riskLevel : "medium";
|
|
16280
|
+
if (level === "high" || level === "critical") {
|
|
16281
|
+
return {
|
|
16282
|
+
allowed: false,
|
|
16283
|
+
reason: `\u89E3\u7801\u5206\u6790\uFF08${p.encoding} \u7F16\u7801\uFF09\uFF1A${l1.reason}`,
|
|
16284
|
+
riskLevel: level,
|
|
16285
|
+
riskType: l1.riskType,
|
|
16286
|
+
confidence: 95,
|
|
16287
|
+
source: "decode_engine",
|
|
16288
|
+
violatedLayers: ["L1.3"],
|
|
16289
|
+
...l1.ask_reason ? { ask_recommended: true, ask_reason: l1.ask_reason } : {}
|
|
15480
16290
|
};
|
|
15481
16291
|
}
|
|
16292
|
+
decodeHints.push(`[${p.encoding}/${p.source}] ${l1.reason}`);
|
|
15482
16293
|
}
|
|
15483
16294
|
}
|
|
16295
|
+
} catch {
|
|
16296
|
+
}
|
|
16297
|
+
if (heuristicEnabled && aliasResolution) {
|
|
16298
|
+
const l1 = detectDecoded(aliasResolution.expansion);
|
|
16299
|
+
if (l1 && l1.allowed === false && (l1.riskLevel === "high" || l1.riskLevel === "critical")) {
|
|
16300
|
+
return {
|
|
16301
|
+
allowed: false,
|
|
16302
|
+
reason: `\u522B\u540D/\u51FD\u6570\u5C55\u5F00\uFF08${aliasResolution.word}\uFF09\uFF1A${l1.reason}`,
|
|
16303
|
+
riskLevel: l1.riskLevel,
|
|
16304
|
+
riskType: l1.riskType,
|
|
16305
|
+
confidence: 90,
|
|
16306
|
+
source: "alias_engine",
|
|
16307
|
+
violatedLayers: ["L1.4"],
|
|
16308
|
+
...l1.ask_reason ? { ask_recommended: true, ask_reason: l1.ask_reason } : {}
|
|
16309
|
+
};
|
|
16310
|
+
}
|
|
16311
|
+
if (l1 && l1.allowed === false) {
|
|
16312
|
+
decodeHints.push(`[alias/${aliasResolution.kind}] ${l1.reason}`);
|
|
16313
|
+
}
|
|
15484
16314
|
}
|
|
15485
16315
|
const brainStore = getBrainStore(input.osType);
|
|
15486
16316
|
if (brainStore) {
|
|
@@ -15696,6 +16526,48 @@ async function runAnalysis(input) {
|
|
|
15696
16526
|
}
|
|
15697
16527
|
}
|
|
15698
16528
|
}
|
|
16529
|
+
if (decodedPayloads.length > 0 && isLogicRulesEnabled()) {
|
|
16530
|
+
for (const p of decodedPayloads) {
|
|
16531
|
+
const l2 = runLogicCheck(
|
|
16532
|
+
{ ...input, aNext: { actionType: "bash", actionDetail: p.decoded } },
|
|
16533
|
+
{ agentExt }
|
|
16534
|
+
);
|
|
16535
|
+
if (!l2 || l2.allowed !== false) continue;
|
|
16536
|
+
const level = p.source === "instruction" ? l2.riskLevel : "medium";
|
|
16537
|
+
if (level === "high" || level === "critical") {
|
|
16538
|
+
return {
|
|
16539
|
+
allowed: false,
|
|
16540
|
+
reason: `\u89E3\u7801\u5206\u6790\uFF08${p.encoding} \u7F16\u7801\uFF09\uFF1A${l2.reason}`,
|
|
16541
|
+
riskLevel: level,
|
|
16542
|
+
riskType: l2.riskType,
|
|
16543
|
+
confidence: 90,
|
|
16544
|
+
source: "decode_engine",
|
|
16545
|
+
violatedLayers: ["L2.4"]
|
|
16546
|
+
};
|
|
16547
|
+
}
|
|
16548
|
+
decodeHints.push(`[${p.encoding}/${p.source}] ${l2.reason}`);
|
|
16549
|
+
}
|
|
16550
|
+
}
|
|
16551
|
+
if (isLogicRulesEnabled() && aliasResolution) {
|
|
16552
|
+
const l2 = runLogicCheck(
|
|
16553
|
+
{ ...input, aNext: { actionType: "bash", actionDetail: aliasResolution.expansion } },
|
|
16554
|
+
{ agentExt }
|
|
16555
|
+
);
|
|
16556
|
+
if (l2 && l2.allowed === false && (l2.riskLevel === "high" || l2.riskLevel === "critical")) {
|
|
16557
|
+
return {
|
|
16558
|
+
allowed: false,
|
|
16559
|
+
reason: `\u522B\u540D/\u51FD\u6570\u5C55\u5F00\uFF08${aliasResolution.word}\uFF09\uFF1A${l2.reason}`,
|
|
16560
|
+
riskLevel: l2.riskLevel,
|
|
16561
|
+
riskType: l2.riskType,
|
|
16562
|
+
confidence: 90,
|
|
16563
|
+
source: "alias_engine",
|
|
16564
|
+
violatedLayers: ["L2.5"]
|
|
16565
|
+
};
|
|
16566
|
+
}
|
|
16567
|
+
if (l2 && l2.allowed === false) {
|
|
16568
|
+
decodeHints.push(`[alias/${aliasResolution.kind}] ${l2.reason}`);
|
|
16569
|
+
}
|
|
16570
|
+
}
|
|
15699
16571
|
if (brainStore) {
|
|
15700
16572
|
const brainL2 = checkBrainRules(brainStore, {
|
|
15701
16573
|
layer: 2,
|
|
@@ -15749,6 +16621,9 @@ async function runAnalysis(input) {
|
|
|
15749
16621
|
}
|
|
15750
16622
|
} catch {
|
|
15751
16623
|
}
|
|
16624
|
+
if (decodeHints.length > 0) {
|
|
16625
|
+
skipL3Hints += "\n\u89E3\u7801\u5206\u6790\u7EBF\u7D22\uFF1A\n- " + decodeHints.join("\n- ");
|
|
16626
|
+
}
|
|
15752
16627
|
let llmResult;
|
|
15753
16628
|
try {
|
|
15754
16629
|
const pathContext = buildPathContext(input.aNext.actionDetail);
|
|
@@ -15831,6 +16706,8 @@ var init_coordinator = __esm({
|
|
|
15831
16706
|
"use strict";
|
|
15832
16707
|
init_esm_shims();
|
|
15833
16708
|
init_heuristic();
|
|
16709
|
+
init_written_content_analyzer();
|
|
16710
|
+
init_shell_alias_resolver();
|
|
15834
16711
|
init_logic_rules();
|
|
15835
16712
|
init_platform_traits();
|
|
15836
16713
|
init_shell_split();
|
|
@@ -16009,7 +16886,7 @@ init_paths();
|
|
|
16009
16886
|
import { cors } from "hono/cors";
|
|
16010
16887
|
import { logger } from "hono/logger";
|
|
16011
16888
|
import net from "net";
|
|
16012
|
-
import { existsSync as
|
|
16889
|
+
import { existsSync as existsSync23, writeFileSync as writeFileSync7, renameSync as renameSync3, mkdirSync as mkdirSync10 } from "fs";
|
|
16013
16890
|
import { dirname as dirname16 } from "path";
|
|
16014
16891
|
|
|
16015
16892
|
// src/package-json.ts
|
|
@@ -16187,9 +17064,9 @@ var ReviewResponseSchema = z.object({
|
|
|
16187
17064
|
init_esm_shims();
|
|
16188
17065
|
init_security_policy();
|
|
16189
17066
|
init_coordinator();
|
|
16190
|
-
import { existsSync as
|
|
17067
|
+
import { existsSync as existsSync20, readFileSync as readFileSync19 } from "fs";
|
|
16191
17068
|
import { tmpdir as tmpdir3 } from "os";
|
|
16192
|
-
import { join as
|
|
17069
|
+
import { join as join20, resolve as resolve12 } from "path";
|
|
16193
17070
|
|
|
16194
17071
|
// src/engine/types.ts
|
|
16195
17072
|
init_esm_shims();
|
|
@@ -16210,10 +17087,10 @@ init_security_policy();
|
|
|
16210
17087
|
init_paths();
|
|
16211
17088
|
init_config();
|
|
16212
17089
|
import { createHash as createHash7 } from "crypto";
|
|
16213
|
-
import { existsSync as
|
|
17090
|
+
import { existsSync as existsSync19, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
|
|
16214
17091
|
import { tmpdir as tmpdir2 } from "os";
|
|
16215
|
-
import { join as
|
|
16216
|
-
var CACHE_DIR =
|
|
17092
|
+
import { join as join19 } from "path";
|
|
17093
|
+
var CACHE_DIR = join19(tmpdir2(), "agent_moss_policy_cache");
|
|
16217
17094
|
var cacheDirOverride = null;
|
|
16218
17095
|
function cacheDir() {
|
|
16219
17096
|
return cacheDirOverride ?? CACHE_DIR;
|
|
@@ -16222,7 +17099,7 @@ function safeCacheDir() {
|
|
|
16222
17099
|
const dir = cacheDir();
|
|
16223
17100
|
if (ensurePrivateDir(dir)) return dir;
|
|
16224
17101
|
try {
|
|
16225
|
-
const fallback =
|
|
17102
|
+
const fallback = join19(getDataRoot(), "policy_cache");
|
|
16226
17103
|
if (ensurePrivateDir(fallback)) {
|
|
16227
17104
|
console.warn(`[AgentMoss] \u7F13\u5B58\u76EE\u5F55 ${dir} \u4E0D\u5B89\u5168\uFF08\u88AB\u5176\u4ED6\u7528\u6237\u62E5\u6709\u6216\u4E3A\u7B26\u53F7\u94FE\u63A5\uFF09\uFF0C\u5DF2\u56DE\u9000\u5230 ${fallback}`);
|
|
16228
17105
|
return fallback;
|
|
@@ -16244,7 +17121,7 @@ var PolicyCache = class {
|
|
|
16244
17121
|
cacheFilePath(sessionId, promptSession) {
|
|
16245
17122
|
const promptHash = createHash7("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
16246
17123
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
16247
|
-
return
|
|
17124
|
+
return join19(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
16248
17125
|
}
|
|
16249
17126
|
/** 取缓存:内存 → 文件;未命中返回 null。 */
|
|
16250
17127
|
get(sessionId, promptSession) {
|
|
@@ -16257,7 +17134,7 @@ var PolicyCache = class {
|
|
|
16257
17134
|
return hit;
|
|
16258
17135
|
}
|
|
16259
17136
|
const file = this.cacheFilePath(sessionId, promptSession);
|
|
16260
|
-
if (
|
|
17137
|
+
if (existsSync19(file) && !lstatSync2(file).isSymbolicLink()) {
|
|
16261
17138
|
try {
|
|
16262
17139
|
const policy = readFileSync18(file, "utf-8");
|
|
16263
17140
|
this.remember(key, policy);
|
|
@@ -16275,7 +17152,7 @@ var PolicyCache = class {
|
|
|
16275
17152
|
try {
|
|
16276
17153
|
const dir = safeCacheDir();
|
|
16277
17154
|
const sub = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
16278
|
-
if (!ensurePrivateDir(
|
|
17155
|
+
if (!ensurePrivateDir(join19(dir, sub))) return;
|
|
16279
17156
|
writePrivateText(file, policy);
|
|
16280
17157
|
} catch {
|
|
16281
17158
|
}
|
|
@@ -16301,12 +17178,12 @@ var PolicyCache = class {
|
|
|
16301
17178
|
if (k.startsWith(`${sessionId}::`)) this.memory.delete(k);
|
|
16302
17179
|
}
|
|
16303
17180
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
16304
|
-
const dir =
|
|
17181
|
+
const dir = join19(cacheDir(), safeSessionId);
|
|
16305
17182
|
try {
|
|
16306
|
-
if (
|
|
17183
|
+
if (existsSync19(dir)) {
|
|
16307
17184
|
for (const f of readdirSync6(dir)) {
|
|
16308
17185
|
try {
|
|
16309
|
-
unlinkSync5(
|
|
17186
|
+
unlinkSync5(join19(dir, f));
|
|
16310
17187
|
} catch {
|
|
16311
17188
|
}
|
|
16312
17189
|
}
|
|
@@ -16318,11 +17195,11 @@ var PolicyCache = class {
|
|
|
16318
17195
|
clear() {
|
|
16319
17196
|
this.memory.clear();
|
|
16320
17197
|
try {
|
|
16321
|
-
if (
|
|
17198
|
+
if (existsSync19(cacheDir())) {
|
|
16322
17199
|
for (const sessionDir of readdirSync6(cacheDir())) {
|
|
16323
|
-
const dir =
|
|
17200
|
+
const dir = join19(cacheDir(), sessionDir);
|
|
16324
17201
|
try {
|
|
16325
|
-
for (const f of readdirSync6(dir)) unlinkSync5(
|
|
17202
|
+
for (const f of readdirSync6(dir)) unlinkSync5(join19(dir, f));
|
|
16326
17203
|
rmdirSync(dir);
|
|
16327
17204
|
} catch {
|
|
16328
17205
|
}
|
|
@@ -16409,7 +17286,7 @@ ${safe(policy, 2e3)}`);
|
|
|
16409
17286
|
|
|
16410
17287
|
// src/engine/analyzer.ts
|
|
16411
17288
|
import { parse as parseToml } from "smol-toml";
|
|
16412
|
-
var POLICY_OUTPUT_DIR =
|
|
17289
|
+
var POLICY_OUTPUT_DIR = join20(tmpdir3(), "agent_moss");
|
|
16413
17290
|
var policyOutputDirOverride = null;
|
|
16414
17291
|
function policyOutputDir() {
|
|
16415
17292
|
return policyOutputDirOverride ?? POLICY_OUTPUT_DIR;
|
|
@@ -16448,7 +17325,7 @@ function savePolicyToFile(sessionId, policyToml) {
|
|
|
16448
17325
|
return null;
|
|
16449
17326
|
}
|
|
16450
17327
|
const safeName = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
16451
|
-
const filepath =
|
|
17328
|
+
const filepath = join20(outDir, `${safeName}.toml`);
|
|
16452
17329
|
writePrivateText(filepath, policyToml);
|
|
16453
17330
|
return filepath;
|
|
16454
17331
|
} catch (err) {
|
|
@@ -16487,11 +17364,11 @@ function loadPolicyMappingDoc() {
|
|
|
16487
17364
|
const dir = resolveAssetDir(__dirname, "templates");
|
|
16488
17365
|
if (dir) {
|
|
16489
17366
|
const p = resolve12(dir, "policy_mapping.md");
|
|
16490
|
-
if (
|
|
17367
|
+
if (existsSync20(p)) return readFileSync19(p, "utf-8");
|
|
16491
17368
|
}
|
|
16492
17369
|
for (const cand of assetDirCandidates(__dirname, "templates")) {
|
|
16493
17370
|
const p = resolve12(cand, "policy_mapping.md");
|
|
16494
|
-
if (
|
|
17371
|
+
if (existsSync20(p)) return readFileSync19(p, "utf-8");
|
|
16495
17372
|
}
|
|
16496
17373
|
return "";
|
|
16497
17374
|
}
|
|
@@ -16602,9 +17479,9 @@ async function analyzeInner(input, mossLog) {
|
|
|
16602
17479
|
mossLog.logResult("Deny", denied.reason);
|
|
16603
17480
|
return withL3(denied, judgment);
|
|
16604
17481
|
}
|
|
16605
|
-
const
|
|
17482
|
+
const cache4 = getDefaultCache();
|
|
16606
17483
|
mossLog.startStep("step2_cache_lookup");
|
|
16607
|
-
const cached2 =
|
|
17484
|
+
const cached2 = cache4.get(input.sessionId, input.promptSession);
|
|
16608
17485
|
if (cached2 !== null) {
|
|
16609
17486
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u547D\u4E2D");
|
|
16610
17487
|
savePolicyToFile(input.sessionId, cached2);
|
|
@@ -16615,7 +17492,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
16615
17492
|
if (!isPolicyGenEnabled()) {
|
|
16616
17493
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0CPolicy \u751F\u6210\u5DF2\u7981\u7528");
|
|
16617
17494
|
mossLog.startStep("step2_default_policy");
|
|
16618
|
-
|
|
17495
|
+
cache4.put(input.sessionId, input.promptSession, DEFAULT_READONLY_POLICY);
|
|
16619
17496
|
savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
|
|
16620
17497
|
const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
|
|
16621
17498
|
mossLog.endStep("step2_default_policy", "\u4F7F\u7528\u9ED8\u8BA4\u6700\u5C0F\u6743\u9650 Policy");
|
|
@@ -16624,7 +17501,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
16624
17501
|
}
|
|
16625
17502
|
if (judgment.source === "whitelist_bypass") {
|
|
16626
17503
|
mossLog.endStep("step2_cache_lookup", "\u7F13\u5B58\u672A\u547D\u4E2D\uFF0C\u767D\u540D\u5355\u5DE5\u5177");
|
|
16627
|
-
|
|
17504
|
+
cache4.put(input.sessionId, input.promptSession, DEFAULT_READONLY_POLICY);
|
|
16628
17505
|
savePolicyToFile(input.sessionId, DEFAULT_READONLY_POLICY);
|
|
16629
17506
|
const res = allowResult(DEFAULT_READONLY_POLICY, judgment);
|
|
16630
17507
|
mossLog.logResult("Allow", res.reason, DEFAULT_READONLY_POLICY);
|
|
@@ -16634,7 +17511,7 @@ async function analyzeInner(input, mossLog) {
|
|
|
16634
17511
|
mossLog.startStep("step2_generate_policy");
|
|
16635
17512
|
try {
|
|
16636
17513
|
const policy = await generatePolicyWithLLM(input.sessionId, input.promptSession);
|
|
16637
|
-
|
|
17514
|
+
cache4.put(input.sessionId, input.promptSession, policy);
|
|
16638
17515
|
savePolicyToFile(input.sessionId, policy);
|
|
16639
17516
|
mossLog.endStep("step2_generate_policy", "Policy \u751F\u6210\u5E76\u7F13\u5B58\u6210\u529F");
|
|
16640
17517
|
const res = allowResult(policy, judgment);
|
|
@@ -16774,6 +17651,21 @@ init_formal_engine();
|
|
|
16774
17651
|
init_stateful();
|
|
16775
17652
|
init_circuit_breaker();
|
|
16776
17653
|
|
|
17654
|
+
// src/infra/os-type.ts
|
|
17655
|
+
init_esm_shims();
|
|
17656
|
+
function currentOsType() {
|
|
17657
|
+
const env2 = String(process.env.AGENT_MOSS_OS_TYPE || "").trim().toLowerCase();
|
|
17658
|
+
if (env2) {
|
|
17659
|
+
if (["hmos", "openharmony", "hongmeng", "harmony"].includes(env2)) return "harmony";
|
|
17660
|
+
if (["darwin", "mac", "macosx", "osx", "macos"].includes(env2)) return "macos";
|
|
17661
|
+
if (env2 === "windows") return "windows";
|
|
17662
|
+
return "linux";
|
|
17663
|
+
}
|
|
17664
|
+
if (process.platform === "win32") return "windows";
|
|
17665
|
+
if (process.platform === "darwin") return "macos";
|
|
17666
|
+
return "linux";
|
|
17667
|
+
}
|
|
17668
|
+
|
|
16777
17669
|
// src/engine/formal-engine/pattern_miner.ts
|
|
16778
17670
|
init_esm_shims();
|
|
16779
17671
|
init_rules_loader();
|
|
@@ -17087,7 +17979,7 @@ function poolsSnapshot() {
|
|
|
17087
17979
|
|
|
17088
17980
|
// src/routes.ts
|
|
17089
17981
|
init_metrics();
|
|
17090
|
-
import { join as
|
|
17982
|
+
import { join as join22, dirname as dirname14 } from "path";
|
|
17091
17983
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
17092
17984
|
var __dirname9 = dirname14(fileURLToPath11(import.meta.url));
|
|
17093
17985
|
async function healthRoute(c) {
|
|
@@ -17156,7 +18048,7 @@ async function analyzeRoute(c) {
|
|
|
17156
18048
|
}
|
|
17157
18049
|
let osType = req.os_type;
|
|
17158
18050
|
if (!osType) {
|
|
17159
|
-
osType =
|
|
18051
|
+
osType = currentOsType();
|
|
17160
18052
|
}
|
|
17161
18053
|
const _principal = principalOf(c.req.raw.headers, new URL(c.req.url).pathname);
|
|
17162
18054
|
const [_boundOk, agentId] = bindAgent(_principal, req.agent_id || req.metadata?.agent_type || "");
|
|
@@ -17647,7 +18539,7 @@ function getBrainRuleStore() {
|
|
|
17647
18539
|
return new BrainRuleStore();
|
|
17648
18540
|
}
|
|
17649
18541
|
function getBrainSkillManager() {
|
|
17650
|
-
const dir = resolveAssetDir(__dirname9, "skills") ??
|
|
18542
|
+
const dir = resolveAssetDir(__dirname9, "skills") ?? join22(__dirname9, "..", "..", "agent_moss", "skills");
|
|
17651
18543
|
return new BrainSkillManager(dir);
|
|
17652
18544
|
}
|
|
17653
18545
|
async function brainRulesRoute(c) {
|
|
@@ -17750,13 +18642,14 @@ init_rules_loader();
|
|
|
17750
18642
|
init_asset_dir();
|
|
17751
18643
|
init_rules_mode();
|
|
17752
18644
|
init_edition_scope();
|
|
18645
|
+
init_logic_rules();
|
|
17753
18646
|
import { Hono } from "hono";
|
|
17754
18647
|
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
17755
|
-
import { readFileSync as readFileSync21, existsSync as
|
|
17756
|
-
import { join as
|
|
18648
|
+
import { readFileSync as readFileSync21, existsSync as existsSync22, unlinkSync as unlinkSync6 } from "fs";
|
|
18649
|
+
import { join as join23, dirname as dirname15 } from "path";
|
|
17757
18650
|
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
17758
18651
|
var __dirname10 = dirname15(fileURLToPath12(import.meta.url));
|
|
17759
|
-
var STATIC_DIR =
|
|
18652
|
+
var STATIC_DIR = join23(__dirname10, "static");
|
|
17760
18653
|
var CONSOLE_TOKEN_ENV = "AGENT_MOSS_CONSOLE_TOKEN";
|
|
17761
18654
|
function getConsoleToken() {
|
|
17762
18655
|
return process.env[CONSOLE_TOKEN_ENV] || "";
|
|
@@ -17808,8 +18701,8 @@ function createConsoleRouter() {
|
|
|
17808
18701
|
console2.use("/api/*", authMiddleware());
|
|
17809
18702
|
console2.use("/api/*", builtinOnlyReadOnlyMiddleware());
|
|
17810
18703
|
const serveIndex = (c) => {
|
|
17811
|
-
const indexFile =
|
|
17812
|
-
if (
|
|
18704
|
+
const indexFile = join23(STATIC_DIR, "index.html");
|
|
18705
|
+
if (existsSync22(indexFile)) {
|
|
17813
18706
|
return c.html(readFileSync21(indexFile, "utf-8"));
|
|
17814
18707
|
}
|
|
17815
18708
|
return c.html("<h1>AgentMoss Policy Console</h1><p>Frontend not built. Use /console/api/* endpoints.</p>");
|
|
@@ -17840,7 +18733,6 @@ function createConsoleRouter() {
|
|
|
17840
18733
|
"mc-ltl-001": "\u5148\u8BFB\u53D6\u4E86\u51ED\u636E/\u5BC6\u94A5\uFF0C\u4E4B\u540E\u51FA\u73B0\u7F51\u7EDC\u5916\u4F20",
|
|
17841
18734
|
"mc-ltl-002": "\u5148\u4E0B\u8F7D/\u83B7\u53D6\u4E86\u6587\u4EF6\uFF0C\u4E4B\u540E\u6267\u884C\u4E86\u6587\u4EF6",
|
|
17842
18735
|
"mc-ltl-003": "\u5148\u7981\u7528\u4E86\u5B89\u5168\u9632\u62A4\uFF0C\u4E4B\u540E\u51FA\u73B0\u7834\u574F\u6027\u64CD\u4F5C\uFF08\u6267\u884C/\u5220\u9664/\u63D0\u6743\uFF09",
|
|
17843
|
-
"mc-ltl-004": "\u5148\u51FA\u73B0\u63D0\u793A\u8BCD\u6CE8\u5165\uFF0C\u4E4B\u540E\u51FA\u73B0\u654F\u611F\u64CD\u4F5C\uFF08\u5916\u4F20/\u5199\u6587\u4EF6/\u6267\u884C\uFF09",
|
|
17844
18736
|
"mc-ltl-005": "\u5148\u8BFB\u53D6\u51ED\u636E\uFF0C\u4E4B\u540E\u51FA\u73B0\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp \u5230\u8FDC\u7A0B\uFF09",
|
|
17845
18737
|
"mc-ltl-006": "\u5148\u63A5\u89E6\u654F\u611F\u6570\u636E\uFF0C\u4E4B\u540E\u6E05\u9664\u65E5\u5FD7",
|
|
17846
18738
|
"mc-ltl-007": "\u5148\u63D0\u6743\uFF0C\u4E4B\u540E\u5B89\u88C5\u6301\u4E45\u5316\u540E\u95E8",
|
|
@@ -17881,7 +18773,6 @@ function createConsoleRouter() {
|
|
|
17881
18773
|
"mc-ltl-001": "\u5148\u8BFB\u53D6\u4E86\u51ED\u636E/\u5BC6\u94A5\uFF0C\u4E4B\u540E\u51FA\u73B0\u7F51\u7EDC\u5916\u4F20",
|
|
17882
18774
|
"mc-ltl-002": "\u5148\u4E0B\u8F7D/\u83B7\u53D6\u4E86\u6587\u4EF6\uFF0C\u4E4B\u540E\u6267\u884C\u4E86\u6587\u4EF6",
|
|
17883
18775
|
"mc-ltl-003": "\u5148\u7981\u7528\u4E86\u5B89\u5168\u9632\u62A4\uFF0C\u4E4B\u540E\u51FA\u73B0\u7834\u574F\u6027\u64CD\u4F5C\uFF08\u6267\u884C/\u5220\u9664/\u63D0\u6743\uFF09",
|
|
17884
|
-
"mc-ltl-004": "\u5148\u51FA\u73B0\u63D0\u793A\u8BCD\u6CE8\u5165\uFF0C\u4E4B\u540E\u51FA\u73B0\u654F\u611F\u64CD\u4F5C\uFF08\u5916\u4F20/\u5199\u6587\u4EF6/\u6267\u884C\uFF09",
|
|
17885
18776
|
"mc-ltl-005": "\u5148\u8BFB\u53D6\u51ED\u636E\uFF0C\u4E4B\u540E\u51FA\u73B0\u6A2A\u5411\u79FB\u52A8\uFF08ssh/scp \u5230\u8FDC\u7A0B\uFF09",
|
|
17886
18777
|
"mc-ltl-006": "\u5148\u63A5\u89E6\u654F\u611F\u6570\u636E\uFF0C\u4E4B\u540E\u6E05\u9664\u65E5\u5FD7",
|
|
17887
18778
|
"mc-ltl-007": "\u5148\u63D0\u6743\uFF0C\u4E4B\u540E\u5B89\u88C5\u6301\u4E45\u5316\u540E\u95E8",
|
|
@@ -17931,6 +18822,14 @@ function createConsoleRouter() {
|
|
|
17931
18822
|
const rc = updateRuleEnabled(b.layer, b.category, b.rule_id, b.enabled);
|
|
17932
18823
|
return c.json(withL22View(rc));
|
|
17933
18824
|
});
|
|
18825
|
+
console2.put("/api/rules/tier_enabled", async (c) => {
|
|
18826
|
+
const b = await c.req.json();
|
|
18827
|
+
if (!["strong", "weak"].includes(b.tier)) {
|
|
18828
|
+
return c.json({ detail: `\u65E0\u6548\u7684 tier: ${b.tier}` }, 400);
|
|
18829
|
+
}
|
|
18830
|
+
const rc = updateInjectionTierEnabled(b.tier, b.enabled);
|
|
18831
|
+
return c.json(withL22View(rc));
|
|
18832
|
+
});
|
|
17934
18833
|
console2.put("/api/rules/deny_mode", async (c) => {
|
|
17935
18834
|
const b = await c.req.json();
|
|
17936
18835
|
if (!["deny_write", "deny_read", "deny_both"].includes(b.deny_mode)) {
|
|
@@ -17939,6 +18838,16 @@ function createConsoleRouter() {
|
|
|
17939
18838
|
const rc = updateRuleDenyMode(b.layer, b.category, b.rule_id, b.deny_mode);
|
|
17940
18839
|
return c.json(withL22View(rc));
|
|
17941
18840
|
});
|
|
18841
|
+
console2.put("/api/rules/ask", async (c) => {
|
|
18842
|
+
const b = await c.req.json();
|
|
18843
|
+
const rc = updateRuleAsk(b.layer, b.category, b.rule_id, b.ask_on_match === true);
|
|
18844
|
+
return c.json(withL22View(rc));
|
|
18845
|
+
});
|
|
18846
|
+
console2.put("/api/categories/ask", async (c) => {
|
|
18847
|
+
const b = await c.req.json();
|
|
18848
|
+
const rc = updateCategoryAsk(b.layer, b.category, b.ask_on_match === true);
|
|
18849
|
+
return c.json(withL22View(rc));
|
|
18850
|
+
});
|
|
17942
18851
|
console2.put("/api/rules/skip_l3", async (c) => {
|
|
17943
18852
|
const b = await c.req.json();
|
|
17944
18853
|
const rc = updateRuleSkipL3(b.layer, b.category, b.rule_id, b.skip_l3_on_disabled);
|
|
@@ -17951,7 +18860,8 @@ function createConsoleRouter() {
|
|
|
17951
18860
|
});
|
|
17952
18861
|
console2.post("/api/rules", async (c) => {
|
|
17953
18862
|
const b = await c.req.json();
|
|
17954
|
-
const
|
|
18863
|
+
const layer = b.category === "sensitive_path_access" ? "L1_rules" : b.layer;
|
|
18864
|
+
const rc = addCustomRule(layer, b.category, {
|
|
17955
18865
|
pattern: b.pattern,
|
|
17956
18866
|
risk_level: b.risk_level,
|
|
17957
18867
|
risk_type: b.risk_type,
|
|
@@ -18005,14 +18915,14 @@ function createConsoleRouter() {
|
|
|
18005
18915
|
if (!/^[A-Za-z0-9_-]+$/.test(skillId)) {
|
|
18006
18916
|
return c.json({ detail: "\u975E\u6CD5 skill id" }, 400);
|
|
18007
18917
|
}
|
|
18008
|
-
const userPath =
|
|
18918
|
+
const userPath = join23(dirname15(getRuntimeConfigPath()), "agent_moss_skills", `${skillId}.md`);
|
|
18009
18919
|
const builtinDir = resolveAssetDir(__dirname10, "skills");
|
|
18010
18920
|
const candidates = [
|
|
18011
18921
|
...isRuntimeConfigDisabled() ? [] : [userPath],
|
|
18012
|
-
builtinDir ?
|
|
18922
|
+
builtinDir ? join23(builtinDir, `${skillId}.md`) : ""
|
|
18013
18923
|
].filter(Boolean);
|
|
18014
18924
|
for (const p of candidates) {
|
|
18015
|
-
if (
|
|
18925
|
+
if (existsSync22(p)) {
|
|
18016
18926
|
return c.json({ skill_id: skillId, path: p, content: readFileSync21(p, "utf-8") });
|
|
18017
18927
|
}
|
|
18018
18928
|
}
|
|
@@ -18109,7 +19019,14 @@ function createConsoleRouter() {
|
|
|
18109
19019
|
});
|
|
18110
19020
|
console2.get("/api/config", (c) => {
|
|
18111
19021
|
const rc = displayRuntimeConfig();
|
|
18112
|
-
|
|
19022
|
+
const osType = currentOsType();
|
|
19023
|
+
return c.json({
|
|
19024
|
+
...rc,
|
|
19025
|
+
L2_2: getL22View(),
|
|
19026
|
+
builtin_only: isBuiltinOnly(),
|
|
19027
|
+
rules_mode: getRulesMode(),
|
|
19028
|
+
platform: { os_type: osType, accepted_os: acceptedOsValues(osType) }
|
|
19029
|
+
});
|
|
18113
19030
|
});
|
|
18114
19031
|
console2.get("/api/env-overrides", (c) => {
|
|
18115
19032
|
return c.json({ overrides: getEnvOverrides() });
|
|
@@ -18118,7 +19035,7 @@ function createConsoleRouter() {
|
|
|
18118
19035
|
const defaults = generateSourceDefaults();
|
|
18119
19036
|
try {
|
|
18120
19037
|
const p = getRuntimeConfigPath();
|
|
18121
|
-
if (
|
|
19038
|
+
if (existsSync22(p)) unlinkSync6(p);
|
|
18122
19039
|
} catch {
|
|
18123
19040
|
}
|
|
18124
19041
|
return c.json(withL22View(defaults));
|
|
@@ -18177,7 +19094,7 @@ function logDeploymentSelfCheck() {
|
|
|
18177
19094
|
console.log("\u5C42\u7EA7\u5F00\u5173: " + layerKeys.map((k) => `${k}=${isLayerEnabled(k) ? "on" : "OFF"}`).join(" "));
|
|
18178
19095
|
if (!builtinOnly) {
|
|
18179
19096
|
try {
|
|
18180
|
-
const dirs = rulesDirs().filter((d) =>
|
|
19097
|
+
const dirs = rulesDirs().filter((d) => existsSync23(d));
|
|
18181
19098
|
if (dirs.length > 0) {
|
|
18182
19099
|
console.log(`\u89C4\u5219\u76EE\u5F55: ${dirs.join(", ")}\uFF08\u53EA\u8BFB\u5176\u4E2D ${OVERRIDE_FILENAME} / ${EXTRA_FILENAME}\uFF09`);
|
|
18183
19100
|
}
|
|
@@ -18523,7 +19440,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
18523
19440
|
},
|
|
18524
19441
|
serve: async () => {
|
|
18525
19442
|
failFastOnAuthError();
|
|
18526
|
-
const { mkdirSync: mkdirSync11, existsSync:
|
|
19443
|
+
const { mkdirSync: mkdirSync11, existsSync: existsSync24, unlinkSync: unlinkSync7 } = await import("fs");
|
|
18527
19444
|
const { dirname: dirname17 } = await import("path");
|
|
18528
19445
|
const dir = dirname17(socketPath);
|
|
18529
19446
|
if (dir) {
|
|
@@ -18532,7 +19449,7 @@ async function startUnixSocketServer(socketPath = "/var/run/agent_moss/agent_mos
|
|
|
18532
19449
|
} catch {
|
|
18533
19450
|
}
|
|
18534
19451
|
}
|
|
18535
|
-
if (
|
|
19452
|
+
if (existsSync24(socketPath)) {
|
|
18536
19453
|
const { connect } = await import("net");
|
|
18537
19454
|
const inUse = await new Promise((resolve13) => {
|
|
18538
19455
|
const probe = connect(socketPath);
|