@kangyishuai/dsh-casefile 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -36
- package/README.zh-CN.md +96 -36
- package/lib/actions.js +270 -36
- package/lib/client.js +815 -102
- package/lib/core/brief.js +58 -12
- package/lib/core/ingest-craft.js +2 -2
- package/lib/core/ingest.js +10 -4
- package/lib/core/model.js +17 -1
- package/lib/core/report.js +8 -1
- package/lib/core/store.js +371 -15
- package/lib/service.js +54 -2
- package/lib/tools.js +112 -16
- package/locale/en.json +11 -1
- package/locale/zh.json +11 -1
- package/package.json +1 -1
package/lib/core/brief.js
CHANGED
|
@@ -15,15 +15,59 @@ import { sha256Text } from "./digest.js";
|
|
|
15
15
|
/** 规格包版本。 */
|
|
16
16
|
export const SPEC_VERSION = 1;
|
|
17
17
|
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
/\
|
|
25
|
-
/\
|
|
26
|
-
]
|
|
18
|
+
/**
|
|
19
|
+
* 常见 token 形态(宁可多遮,不可漏)。
|
|
20
|
+
* AUD-CASEFILE-05 补全:Google/Firebase 客户端 key、AWS 临时凭证、npm token、JWT、私钥块,
|
|
21
|
+
* 以及 `password=` / `api_key=` 这类键值形态。
|
|
22
|
+
*/
|
|
23
|
+
const SECRET_PATTERNS = /** @type {const} */ ([
|
|
24
|
+
[/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[redacted]"],
|
|
25
|
+
[/\bghp_[A-Za-z0-9]{20,}\b/gu, "[redacted]"],
|
|
26
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,}\b/gu, "[redacted]"],
|
|
27
|
+
[/\bAKIA[0-9A-Z]{16}\b/gu, "[redacted]"],
|
|
28
|
+
[/\bASIA[0-9A-Z]{16}\b/gu, "[redacted]"],
|
|
29
|
+
[/\bAIza[0-9A-Za-z_-]{20,}\b/gu, "[redacted]"],
|
|
30
|
+
[/\bnpm_[A-Za-z0-9]{20,}\b/gu, "[redacted]"],
|
|
31
|
+
[/\bxox[abp]-[A-Za-z0-9-]{10,}\b/gu, "[redacted]"],
|
|
32
|
+
[/\bBearer\s+[A-Za-z0-9._-]{16,}\b/giu, "[redacted]"],
|
|
33
|
+
[/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu, "[redacted]"],
|
|
34
|
+
[
|
|
35
|
+
/-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z]+)? PRIVATE KEY-----/gu,
|
|
36
|
+
"[redacted]",
|
|
37
|
+
],
|
|
38
|
+
[
|
|
39
|
+
/(\b(?:password|passwd|api[_-]?key|apikey|secret|token)\s*[=:]\s*)(?:"[^"]+"|'[^']+'|[^\s"',;)]{6,})/giu,
|
|
40
|
+
"$1[redacted]",
|
|
41
|
+
],
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 常见系统根目录:这些前缀下的任意路径都按绝对路径遮(AUD-CASEFILE-05)。
|
|
46
|
+
* 覆盖 macOS 的 /Applications /Volumes /Library /System /private,Linux 的 /opt /etc /usr /home /var /tmp 等。
|
|
47
|
+
*/
|
|
48
|
+
const SYSTEM_ROOT_RE = String.raw`\/(?:Users|home|var|tmp|private|Applications|Volumes|opt|etc|Library|usr|System|bin|sbin|dev|proc|boot|root|mnt|media|snap|nix|data|srv|workspace)\/`;
|
|
49
|
+
|
|
50
|
+
/** 路径 token 的终止字符(引号、括号、中文标点、分隔符)。 */
|
|
51
|
+
const PATH_TAIL = String.raw`[^\s"'\x60()(){}<>|、。;,;]+`;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 任意绝对 POSIX 路径 / 未展开的 `~/` 路径(AUD-CASEFILE-05)。
|
|
55
|
+
*
|
|
56
|
+
* 三条分支:
|
|
57
|
+
* 1. `~/…`(未展开的 home,任何一段都遮);
|
|
58
|
+
* 2. 已知系统根目录下的路径(`/Applications`、`/Volumes`、`/etc`、`/usr`…);
|
|
59
|
+
* 3. 带文件扩展名的路径(`/custom/report.har` 这种未知根目录)。
|
|
60
|
+
*
|
|
61
|
+
* 刻意**不**把任意 `/x/y` 都遮掉:`POST /api/todos`、`/auth/token` 这类 API 路由
|
|
62
|
+
* 是规格包要交付的信息,遮掉会把可复算的规格变成 <path> 噪声。
|
|
63
|
+
* 前面的字符限定为非路径字符,避免把 URL(`https://…`)吃掉。
|
|
64
|
+
* @param {string} text
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
function redactAbsolutePaths(text) {
|
|
68
|
+
const pattern = String.raw`(^|[^A-Za-z0-9_:/.-])(?:(?:~\/${PATH_TAIL})|(?:${SYSTEM_ROOT_RE}${PATH_TAIL})|(?:\/${PATH_TAIL}\.(?:[A-Za-z0-9]{1,8})\b(?:${PATH_TAIL})?))`;
|
|
69
|
+
return text.replace(new RegExp(pattern, "gu"), (_match, prefix) => `${prefix}<path>`);
|
|
70
|
+
}
|
|
27
71
|
|
|
28
72
|
/**
|
|
29
73
|
* 脱敏一段文本。
|
|
@@ -34,9 +78,9 @@ const SECRET_PATTERNS = [
|
|
|
34
78
|
export function redactText(text, options = {}) {
|
|
35
79
|
let out = String(text);
|
|
36
80
|
const { home, cwd, extraPaths = [] } = options;
|
|
37
|
-
//
|
|
81
|
+
// 顺序很重要:先把「任意绝对路径」整段抹掉,再按已知根目录兜底替换。
|
|
38
82
|
// 反过来会先替换前缀,留下 `<path>/x.bin` 这种半截路径。
|
|
39
|
-
out = out
|
|
83
|
+
out = redactAbsolutePaths(out);
|
|
40
84
|
out = out.replace(/[A-Za-z]:\\[^\s"'`)]+/g, "<path>");
|
|
41
85
|
/** @param {string | undefined} item @returns {item is string} */
|
|
42
86
|
const isPath = (item) => typeof item === "string" && item.length > 1;
|
|
@@ -44,7 +88,9 @@ export function redactText(text, options = {}) {
|
|
|
44
88
|
for (const path of paths.sort((a, b) => b.length - a.length)) {
|
|
45
89
|
out = out.split(path).join("<path>");
|
|
46
90
|
}
|
|
47
|
-
for (const pattern of SECRET_PATTERNS)
|
|
91
|
+
for (const [pattern, replacement] of SECRET_PATTERNS) {
|
|
92
|
+
out = out.replace(pattern, replacement);
|
|
93
|
+
}
|
|
48
94
|
return out;
|
|
49
95
|
}
|
|
50
96
|
|
package/lib/core/ingest-craft.js
CHANGED
|
@@ -17,8 +17,8 @@ const OPERATION_KINDS = [
|
|
|
17
17
|
["parse", "structure"],
|
|
18
18
|
["string", "string"],
|
|
19
19
|
["js", "behavior"],
|
|
20
|
-
["network", "
|
|
21
|
-
["capture", "
|
|
20
|
+
["network", "har"],
|
|
21
|
+
["capture", "har"],
|
|
22
22
|
["screenshot", "screen"],
|
|
23
23
|
["plist", "structure"],
|
|
24
24
|
["signature", "structure"],
|
package/lib/core/ingest.js
CHANGED
|
@@ -18,13 +18,19 @@
|
|
|
18
18
|
/** 摄入契约版本;形状变化时递增。 */
|
|
19
19
|
export const INGEST_VERSION = 1;
|
|
20
20
|
|
|
21
|
+
// 必须与 core/model.js 的 evidence kind 枚举**完全一致**,否则摄入会被模型层拒绝。
|
|
22
|
+
// (这个不一致是真机跑出来的:Craft 的 capture.network 被映射成 network → invalid-input)
|
|
21
23
|
const EVIDENCE_KINDS = [
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
+
"pseudocode",
|
|
25
|
+
"assembly",
|
|
24
26
|
"string",
|
|
27
|
+
"xref",
|
|
28
|
+
"callgraph",
|
|
29
|
+
"har",
|
|
30
|
+
"process",
|
|
25
31
|
"screen",
|
|
26
|
-
"
|
|
27
|
-
"
|
|
32
|
+
"structure",
|
|
33
|
+
"behavior",
|
|
28
34
|
"other",
|
|
29
35
|
];
|
|
30
36
|
const CLAIM_KINDS = ["structure", "behavior", "string", "other"];
|
package/lib/core/model.js
CHANGED
|
@@ -282,15 +282,31 @@ export function normalizeArtifact(raw) {
|
|
|
282
282
|
};
|
|
283
283
|
}
|
|
284
284
|
|
|
285
|
+
/**
|
|
286
|
+
* 证据种类:已知值原样保留,未知值归 `other` 并把原文记进 `kindRaw`。
|
|
287
|
+
* 背景(AUD-CASEFILE-02):kind 曾是自由字符串,模型写 `docs`/`static-analysis` 时整条证据被拒;
|
|
288
|
+
* 现在工具 schema 已给出 enum,落库层也不再因为"叫不出名字"而丢证据。
|
|
289
|
+
* @param {unknown} value
|
|
290
|
+
* @returns {{ kind: string, kindRaw?: string }}
|
|
291
|
+
*/
|
|
292
|
+
function normalizeEvidenceKind(value) {
|
|
293
|
+
const raw = String(value ?? "").trim();
|
|
294
|
+
if (raw === "") return { kind: "other" };
|
|
295
|
+
if (CLAIM_KINDS.includes(/** @type {any} */ (raw))) return { kind: raw };
|
|
296
|
+
return { kind: "other", kindRaw: raw.slice(0, 64) };
|
|
297
|
+
}
|
|
298
|
+
|
|
285
299
|
/**
|
|
286
300
|
* 规范化一条证据(只投影 REA 的结论)。
|
|
287
301
|
* @param {Record<string, any>} input
|
|
288
302
|
* @returns {Record<string, any>}
|
|
289
303
|
*/
|
|
290
304
|
export function normalizeEvidence(input) {
|
|
305
|
+
const kind = normalizeEvidenceKind(input?.kind);
|
|
291
306
|
return {
|
|
292
307
|
id: newId("ev"),
|
|
293
|
-
kind:
|
|
308
|
+
kind: kind.kind,
|
|
309
|
+
...(kind.kindRaw ? { kindRaw: kind.kindRaw } : {}),
|
|
294
310
|
sourceTool: text(input?.sourceTool ?? "unknown", "sourceTool", { max: 200 }),
|
|
295
311
|
sessionId: input?.sessionId == null ? null : text(input.sessionId, "sessionId", { max: 200 }),
|
|
296
312
|
observedAt:
|
package/lib/core/report.js
CHANGED
|
@@ -152,6 +152,7 @@ export function summarizeProducers(evidence) {
|
|
|
152
152
|
* coverage?: ReturnType<typeof computeCoverage>,
|
|
153
153
|
* stop?: Record<string, any> | null,
|
|
154
154
|
* generatedAt?: string,
|
|
155
|
+
* redaction?: Record<string, any>,
|
|
155
156
|
* }} input
|
|
156
157
|
* @returns {Record<string, any>}
|
|
157
158
|
*/
|
|
@@ -167,6 +168,7 @@ export function buildReport(input) {
|
|
|
167
168
|
return {
|
|
168
169
|
version: 1,
|
|
169
170
|
generatedAt: input.generatedAt ?? nowIso(),
|
|
171
|
+
...(input.redaction == null ? {} : { redaction: input.redaction }),
|
|
170
172
|
project: {
|
|
171
173
|
id: input.project.id,
|
|
172
174
|
title: input.project.title,
|
|
@@ -238,6 +240,7 @@ export function buildReport(input) {
|
|
|
238
240
|
export function renderReportMarkdown(report) {
|
|
239
241
|
const lines = [];
|
|
240
242
|
const percent = (report.coverage.ratio * 100).toFixed(0);
|
|
243
|
+
const redacted = report.redaction?.redacted !== false;
|
|
241
244
|
lines.push(`# 验收报告:${report.project.title}`);
|
|
242
245
|
lines.push("");
|
|
243
246
|
lines.push(`- 项目:\`${report.project.id}\``);
|
|
@@ -355,6 +358,9 @@ export function renderReportMarkdown(report) {
|
|
|
355
358
|
lines.push("");
|
|
356
359
|
lines.push("- 本报告对应上面「最近构建」的实现 digest;实现或原件变化后,旧结论不再有效。");
|
|
357
360
|
lines.push("- 检查结论来自 casefile 的 checker,`unknown` 表示无法判定,不等于通过。");
|
|
361
|
+
lines.push(
|
|
362
|
+
`- 脱敏:${redacted ? "已脱敏(分享前仍建议自己复核一遍)" : "未脱敏(含原始路径与目标标识,分享前请自行处理)"}`,
|
|
363
|
+
);
|
|
358
364
|
lines.push("");
|
|
359
365
|
return lines.join("\n");
|
|
360
366
|
}
|
|
@@ -384,6 +390,7 @@ export function renderReportHtml(report) {
|
|
|
384
390
|
const project = r.project ?? {};
|
|
385
391
|
const counts = r.counts ?? {};
|
|
386
392
|
const coverage = r.coverage ?? {};
|
|
393
|
+
const redacted = r.redaction?.redacted !== false;
|
|
387
394
|
const e = escapeHtml;
|
|
388
395
|
/**
|
|
389
396
|
* @param {unknown[]} cells
|
|
@@ -497,6 +504,6 @@ export function renderReportHtml(report) {
|
|
|
497
504
|
${section("证据生产者", producers)}
|
|
498
505
|
${section("未知项", unknowns)}
|
|
499
506
|
${section("循环状态", stop)}
|
|
500
|
-
<footer>本报告不评估目标安全性;只陈述静态分析与验收记录。<br>生成器:@kangyishuai/dsh-casefile</footer>
|
|
507
|
+
<footer>本报告不评估目标安全性;只陈述静态分析与验收记录。<br>脱敏:${redacted ? "已脱敏(分享前仍建议自己复核一遍)" : "未脱敏(含原始路径与目标标识,分享前请自行处理)"}<br>生成器:@kangyishuai/dsh-casefile</footer>
|
|
501
508
|
</div></body></html>`;
|
|
502
509
|
}
|
package/lib/core/store.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// - JSONL append-only,修改用新记录 + supersedes(M0 先只追加);
|
|
12
12
|
// - 所有路径从 dataRoot 派生,不写死 ~/.dsh(可在临时目录里测)。
|
|
13
13
|
|
|
14
|
-
import { createHash } from "node:crypto";
|
|
14
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
15
15
|
import {
|
|
16
16
|
appendFileSync,
|
|
17
17
|
existsSync,
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
readdirSync,
|
|
20
20
|
readFileSync,
|
|
21
21
|
renameSync,
|
|
22
|
+
rmSync,
|
|
22
23
|
statSync,
|
|
23
24
|
writeFileSync,
|
|
24
25
|
} from "node:fs";
|
|
@@ -58,6 +59,47 @@ export const RECORD_FILES = /** @type {const} */ ({
|
|
|
58
59
|
attestations: "attestations.jsonl",
|
|
59
60
|
});
|
|
60
61
|
|
|
62
|
+
/** 回收站条目名:`<ISO 时间戳(: . 换成 -)>-<projectId>`。只认这个形状,别的条目保留不删。 */
|
|
63
|
+
const TRASH_ENTRY_RE =
|
|
64
|
+
/^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z-([a-z0-9][a-z0-9-]{0,63})$/u;
|
|
65
|
+
|
|
66
|
+
/** 归档单个产物的默认体积上限(64 MiB):避免把整段录屏/大 HAR 读进主进程内存。 */
|
|
67
|
+
export const DEFAULT_MAX_ARTIFACT_BYTES = 64 * 1024 * 1024;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 递归统计目录的文件数与字节数(读不了的文件跳过,不猜)。
|
|
71
|
+
* @param {string} dir
|
|
72
|
+
* @returns {{ bytes: number, files: number }}
|
|
73
|
+
*/
|
|
74
|
+
function dirStats(dir) {
|
|
75
|
+
let bytes = 0;
|
|
76
|
+
let files = 0;
|
|
77
|
+
/** @type {import("node:fs").Dirent[]} */
|
|
78
|
+
let children = [];
|
|
79
|
+
try {
|
|
80
|
+
children = readdirSync(dir, { withFileTypes: true });
|
|
81
|
+
} catch {
|
|
82
|
+
return { bytes, files };
|
|
83
|
+
}
|
|
84
|
+
for (const entry of children) {
|
|
85
|
+
const path = `${dir}/${entry.name}`;
|
|
86
|
+
try {
|
|
87
|
+
const stat = statSync(path);
|
|
88
|
+
if (stat.isDirectory()) {
|
|
89
|
+
const nested = dirStats(path);
|
|
90
|
+
bytes += nested.bytes;
|
|
91
|
+
files += nested.files;
|
|
92
|
+
} else if (stat.isFile()) {
|
|
93
|
+
bytes += stat.size;
|
|
94
|
+
files += 1;
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
// 读不了的条目跳过:口径是"已知文件的大小",不假装统计完整。
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { bytes, files };
|
|
101
|
+
}
|
|
102
|
+
|
|
61
103
|
/**
|
|
62
104
|
* @param {unknown} value
|
|
63
105
|
* @returns {value is Record<string, any>}
|
|
@@ -71,7 +113,11 @@ function isRecord(value) {
|
|
|
71
113
|
*/
|
|
72
114
|
export class CaseStore {
|
|
73
115
|
/**
|
|
74
|
-
* @param {{
|
|
116
|
+
* @param {{
|
|
117
|
+
* dataRoot: string,
|
|
118
|
+
* logger?: { warn: (...args: unknown[]) => void },
|
|
119
|
+
* maxArtifactBytes?: number,
|
|
120
|
+
* }} options
|
|
75
121
|
*/
|
|
76
122
|
constructor(options) {
|
|
77
123
|
if (!options || typeof options.dataRoot !== "string" || options.dataRoot === "") {
|
|
@@ -79,6 +125,14 @@ export class CaseStore {
|
|
|
79
125
|
}
|
|
80
126
|
this.dataRoot = options.dataRoot;
|
|
81
127
|
this.logger = options.logger ?? { warn: () => {} };
|
|
128
|
+
const configuredMaxArtifactBytes = options.maxArtifactBytes;
|
|
129
|
+
/** @type {number} */
|
|
130
|
+
this.maxArtifactBytes =
|
|
131
|
+
typeof configuredMaxArtifactBytes === "number" && configuredMaxArtifactBytes > 0
|
|
132
|
+
? configuredMaxArtifactBytes
|
|
133
|
+
: DEFAULT_MAX_ARTIFACT_BYTES;
|
|
134
|
+
/** 进程内串行化用的 promise 链(按文件路径分键,单进程即可覆盖绝大部分并发)。 @type {Map<string, Promise<void>>} */
|
|
135
|
+
this.locks = new Map();
|
|
82
136
|
this.ensureRoot();
|
|
83
137
|
}
|
|
84
138
|
|
|
@@ -148,15 +202,67 @@ export class CaseStore {
|
|
|
148
202
|
}
|
|
149
203
|
|
|
150
204
|
/**
|
|
151
|
-
* 原子写 JSON
|
|
205
|
+
* 原子写 JSON(先写唯一临时文件再 rename)。
|
|
206
|
+
* 临时名带 pid + 随机后缀:同一个文件被并发写时不会互相截断(AUD-CASEFILE-07)。
|
|
152
207
|
* @param {string} file
|
|
153
208
|
* @param {Record<string, any>} value
|
|
154
209
|
*/
|
|
155
210
|
writeJson(file, value) {
|
|
156
211
|
mkdirSync(dirname(file), { recursive: true });
|
|
157
|
-
const tmp = `${file}.tmp-${process.pid}`;
|
|
158
|
-
|
|
159
|
-
|
|
212
|
+
const tmp = `${file}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
213
|
+
try {
|
|
214
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
215
|
+
renameSync(tmp, file);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
try {
|
|
218
|
+
rmSync(tmp, { force: true });
|
|
219
|
+
} catch {
|
|
220
|
+
/* 清理失败不掩盖原始错误 */
|
|
221
|
+
}
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* 进程内按 key 串行化:`prior.then(fn)` 保证同一个文件的读-改-写不会交错。
|
|
228
|
+
* 只覆盖单进程;跨进程仍可能竞争,但至少临时文件唯一,不会写出半截 JSON。
|
|
229
|
+
* @template T
|
|
230
|
+
* @param {string} key
|
|
231
|
+
* @param {() => T | Promise<T>} fn
|
|
232
|
+
* @returns {Promise<T>}
|
|
233
|
+
*/
|
|
234
|
+
withLock(key, fn) {
|
|
235
|
+
const prior = this.locks.get(key) ?? Promise.resolve();
|
|
236
|
+
const run = prior.then(() => fn());
|
|
237
|
+
const settled = run.then(
|
|
238
|
+
() => {},
|
|
239
|
+
() => {},
|
|
240
|
+
);
|
|
241
|
+
this.locks.set(key, settled);
|
|
242
|
+
settled.then(() => {
|
|
243
|
+
if (this.locks.get(key) === settled) this.locks.delete(key);
|
|
244
|
+
});
|
|
245
|
+
return run;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 读-改-写一个 JSON 文件(在进程内锁里完成,避免丢失更新)。
|
|
250
|
+
* 文件不存在时返回 null 且不创建。
|
|
251
|
+
* `mutate` 可以是异步的:锁会一直持有到写盘完成,所以「读 → await → 写」不会交错。
|
|
252
|
+
* 注意:node 的同步 IO 本身不可交错,锁覆盖的是**回调里含 await** 的情形;
|
|
253
|
+
* 跨进程的竞争仍不覆盖(只靠唯一临时文件名保证不会写出半截 JSON)。
|
|
254
|
+
* @param {string} file
|
|
255
|
+
* @param {(current: Record<string, any>) => Record<string, any> | Promise<Record<string, any>>} mutate
|
|
256
|
+
* @returns {Promise<Record<string, any> | null>}
|
|
257
|
+
*/
|
|
258
|
+
updateJson(file, mutate) {
|
|
259
|
+
return this.withLock(file, async () => {
|
|
260
|
+
const current = this.readJson(file);
|
|
261
|
+
if (current == null) return null;
|
|
262
|
+
const next = (await mutate(current)) ?? current;
|
|
263
|
+
this.writeJson(file, next);
|
|
264
|
+
return next;
|
|
265
|
+
});
|
|
160
266
|
}
|
|
161
267
|
|
|
162
268
|
/**
|
|
@@ -234,6 +340,64 @@ export class CaseStore {
|
|
|
234
340
|
});
|
|
235
341
|
}
|
|
236
342
|
|
|
343
|
+
/**
|
|
344
|
+
* 写数据根级审计(append-only)。
|
|
345
|
+
* 用途:项目目录被移进回收站后就写不进项目内 audit.jsonl,必须在数据根留痕(ADR 0002 §4)。
|
|
346
|
+
* @param {Record<string, any>} entry
|
|
347
|
+
*/
|
|
348
|
+
auditRoot(entry) {
|
|
349
|
+
const file = join(this.dataRoot, "audit.jsonl");
|
|
350
|
+
writeFileSync(file, `${JSON.stringify({ at: nowIso(), ...entry })}\n`, {
|
|
351
|
+
encoding: "utf8",
|
|
352
|
+
flag: "a",
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* 读数据根级审计。
|
|
358
|
+
* @returns {Record<string, any>[]}
|
|
359
|
+
*/
|
|
360
|
+
readAuditRoot() {
|
|
361
|
+
const file = join(this.dataRoot, "audit.jsonl");
|
|
362
|
+
if (!existsSync(file)) return [];
|
|
363
|
+
return readFileSync(file, "utf8")
|
|
364
|
+
.split("\n")
|
|
365
|
+
.map((line) => line.trim())
|
|
366
|
+
.filter(Boolean)
|
|
367
|
+
.map((line) => {
|
|
368
|
+
try {
|
|
369
|
+
return JSON.parse(line);
|
|
370
|
+
} catch {
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
})
|
|
374
|
+
.filter((row) => row !== null);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* 记「最近打开的项目」(跨会话/UI 共用;只用于提示,不代替会话指针)。
|
|
379
|
+
* @param {string} projectId
|
|
380
|
+
*/
|
|
381
|
+
markLastOpened(projectId) {
|
|
382
|
+
const id = String(projectId ?? "");
|
|
383
|
+
if (!ID_RE.test(id)) return;
|
|
384
|
+
this.writeJson(join(this.dataRoot, "last-opened.json"), {
|
|
385
|
+
version: 1,
|
|
386
|
+
projectId: id,
|
|
387
|
+
at: nowIso(),
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* 读「最近打开的项目」id;文件不存在/读坏返回 null。
|
|
393
|
+
* @returns {string | null}
|
|
394
|
+
*/
|
|
395
|
+
lastOpenedProjectId() {
|
|
396
|
+
const value = this.readJson(join(this.dataRoot, "last-opened.json"));
|
|
397
|
+
const id = value?.projectId;
|
|
398
|
+
return typeof id === "string" && ID_RE.test(id) ? id : null;
|
|
399
|
+
}
|
|
400
|
+
|
|
237
401
|
/**
|
|
238
402
|
* 读审计。
|
|
239
403
|
* @param {string} projectId
|
|
@@ -326,23 +490,208 @@ export class CaseStore {
|
|
|
326
490
|
return next;
|
|
327
491
|
}
|
|
328
492
|
|
|
493
|
+
/** 回收站根目录。 @returns {string} */
|
|
494
|
+
get trashRoot() {
|
|
495
|
+
return join(this.dataRoot, "trash");
|
|
496
|
+
}
|
|
497
|
+
|
|
329
498
|
/**
|
|
330
|
-
*
|
|
331
|
-
*
|
|
499
|
+
* 项目目录当前占用的文件数与字节数(drop 的影响面口径)。
|
|
500
|
+
* @param {string} projectId
|
|
501
|
+
* @returns {{ bytes: number, files: number }}
|
|
502
|
+
*/
|
|
503
|
+
projectImpact(projectId) {
|
|
504
|
+
return dirStats(this.projectDir(projectId));
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* drop 的**预览**回收站路径(按当前时间生成的目录名)。
|
|
509
|
+
* 只用于 dry-run 展示:实际 drop 会重新取时间戳,所以预览路径不是最终落点(F5)。
|
|
510
|
+
* @param {string} projectId
|
|
511
|
+
* @returns {string}
|
|
512
|
+
*/
|
|
513
|
+
expectedTrashPath(projectId) {
|
|
514
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
515
|
+
return join(this.trashRoot, `${stamp}-${projectId}`);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* 丢弃:把整个项目目录移进 `<dataRoot>/trash/`,可恢复。
|
|
520
|
+
* 破坏性操作,必须显式 confirm(由 actions 层校验);本方法只做搬迁。
|
|
332
521
|
* @param {string} projectId
|
|
333
522
|
* @returns {{ trashedTo: string, project: Record<string, any> }}
|
|
334
523
|
*/
|
|
335
524
|
dropProject(projectId) {
|
|
336
525
|
const project = this.getProject(projectId);
|
|
337
526
|
if (!project) throw new CaseStoreError("project-not-found", `项目不存在:${projectId}`);
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
341
|
-
const target = join(trashRoot, `${stamp}-${projectId}`);
|
|
527
|
+
mkdirSync(this.trashRoot, { recursive: true });
|
|
528
|
+
const target = this.expectedTrashPath(projectId);
|
|
342
529
|
renameSync(this.projectDir(projectId), target);
|
|
343
530
|
return { trashedTo: target, project };
|
|
344
531
|
}
|
|
345
532
|
|
|
533
|
+
/**
|
|
534
|
+
* 列回收站里**认识**的条目;来历不明的条目单独计数(不删、不猜)。
|
|
535
|
+
* @returns {{ entries: Record<string, any>[], unknown: string[] }}
|
|
536
|
+
*/
|
|
537
|
+
scanTrash() {
|
|
538
|
+
/** @type {Record<string, any>[]} */
|
|
539
|
+
const entries = [];
|
|
540
|
+
/** @type {string[]} */
|
|
541
|
+
const unknown = [];
|
|
542
|
+
if (!existsSync(this.trashRoot)) return { entries, unknown };
|
|
543
|
+
let children;
|
|
544
|
+
try {
|
|
545
|
+
children = readdirSync(this.trashRoot, { withFileTypes: true });
|
|
546
|
+
} catch (error) {
|
|
547
|
+
this.logger.warn(`casefile: 回收站不可读:${String(error)}`);
|
|
548
|
+
return { entries, unknown };
|
|
549
|
+
}
|
|
550
|
+
for (const entry of children) {
|
|
551
|
+
if (!entry.isDirectory()) {
|
|
552
|
+
unknown.push(entry.name);
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
const match = TRASH_ENTRY_RE.exec(entry.name);
|
|
556
|
+
if (!match) {
|
|
557
|
+
unknown.push(entry.name);
|
|
558
|
+
this.logger.warn(`casefile: 回收站里有不认识的条目,已保留:${entry.name}`);
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
const path = join(this.trashRoot, entry.name);
|
|
562
|
+
const stats = dirStats(path);
|
|
563
|
+
// project.json 可能读不了(坏 JSON / 版本高于本插件):条目仍然要列出来
|
|
564
|
+
// (它还在 trash 里、还能手工处理),元数据按「未知」降级,而不是让整张表报错(N2)。
|
|
565
|
+
/** @type {Record<string, any> | null} */
|
|
566
|
+
let project = null;
|
|
567
|
+
let metadataUnreadable = false;
|
|
568
|
+
try {
|
|
569
|
+
project = this.readJson(join(path, "project.json"));
|
|
570
|
+
} catch (error) {
|
|
571
|
+
metadataUnreadable = true;
|
|
572
|
+
this.logger.warn(
|
|
573
|
+
`casefile: 回收站条目 ${entry.name} 的 project.json 读不了(${String(/** @type {any} */ (error)?.code ?? error)}),元数据按未知处理`,
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
entries.push({
|
|
577
|
+
name: entry.name,
|
|
578
|
+
projectId: match[8],
|
|
579
|
+
path,
|
|
580
|
+
trashedAt: `${match[1]}-${match[2]}-${match[3]}T${match[4]}:${match[5]}:${match[6]}.${match[7]}Z`,
|
|
581
|
+
bytes: stats.bytes,
|
|
582
|
+
files: stats.files,
|
|
583
|
+
title: typeof project?.title === "string" ? project.title : null,
|
|
584
|
+
state: typeof project?.state === "string" ? project.state : null,
|
|
585
|
+
metadataUnreadable,
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
entries.sort((a, b) => String(b.trashedAt).localeCompare(String(a.trashedAt)));
|
|
589
|
+
return { entries, unknown };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* 从回收站恢复一个条目。
|
|
594
|
+
* @param {string} name 回收站条目名(不接受路径,防穿越)
|
|
595
|
+
* @returns {{ project: Record<string, any>, restoredTo: string }}
|
|
596
|
+
*/
|
|
597
|
+
restoreTrash(name) {
|
|
598
|
+
const entry = String(name ?? "");
|
|
599
|
+
const match = TRASH_ENTRY_RE.exec(entry);
|
|
600
|
+
if (!match) {
|
|
601
|
+
throw new CaseStoreError("invalid-input", `不是认识的回收站条目名:${entry || "(空)"}`);
|
|
602
|
+
}
|
|
603
|
+
const path = join(this.trashRoot, entry);
|
|
604
|
+
if (!existsSync(path)) {
|
|
605
|
+
throw new CaseStoreError("not-found", `回收站里没有这个条目:${entry}`);
|
|
606
|
+
}
|
|
607
|
+
const projectId = match[8];
|
|
608
|
+
const projectDir = this.projectDir(projectId);
|
|
609
|
+
if (existsSync(join(projectDir, "project.json"))) {
|
|
610
|
+
throw new CaseStoreError(
|
|
611
|
+
"project-exists",
|
|
612
|
+
`项目 ${projectId} 现在已存在;先处理同名项目再恢复(不会覆盖现有数据)`,
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
// 搬家前先校验条目里的 project.json(F3):坏条目不能被「恢复」成 projects/ 下的孤儿。
|
|
616
|
+
// 失败时什么都不搬,条目继续留在回收站(数据可救)。
|
|
617
|
+
/** @type {Record<string, any> | null} */
|
|
618
|
+
let manifest = null;
|
|
619
|
+
try {
|
|
620
|
+
manifest = this.readJson(join(path, "project.json"));
|
|
621
|
+
} catch (error) {
|
|
622
|
+
throw new CaseStoreError(
|
|
623
|
+
"not-found",
|
|
624
|
+
`回收站条目不可恢复(${String(/** @type {any} */ (error)?.code ?? error)}),条目仍保留在回收站:${entry}`,
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
if (!manifest) {
|
|
628
|
+
throw new CaseStoreError(
|
|
629
|
+
"not-found",
|
|
630
|
+
`回收站条目缺少可读的 project.json,条目仍保留在回收站:${entry}`,
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
const manifestId = String(manifest.id ?? "");
|
|
634
|
+
if (manifestId !== projectId || !ID_RE.test(manifestId)) {
|
|
635
|
+
throw new CaseStoreError(
|
|
636
|
+
"invalid-input",
|
|
637
|
+
`回收站条目的 project.json 与条目名不一致(${manifestId || "空"} ≠ ${projectId}),未移动:${entry}`,
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
mkdirSync(join(this.dataRoot, "projects"), { recursive: true });
|
|
641
|
+
renameSync(path, projectDir);
|
|
642
|
+
/** @type {Record<string, any> | null} */
|
|
643
|
+
let project = null;
|
|
644
|
+
try {
|
|
645
|
+
project = this.getProject(projectId);
|
|
646
|
+
} catch {
|
|
647
|
+
project = null;
|
|
648
|
+
}
|
|
649
|
+
if (!project) {
|
|
650
|
+
// 搬家后仍读不到(例如并发把文件写坏):回滚,别让项目在 projects/ 里变成幽灵。
|
|
651
|
+
try {
|
|
652
|
+
renameSync(projectDir, path);
|
|
653
|
+
} catch {
|
|
654
|
+
this.logger.warn(`casefile: 恢复回滚失败,项目留在 projects/${projectId}`);
|
|
655
|
+
}
|
|
656
|
+
throw new CaseStoreError("project-not-found", `恢复后读不到项目,已回滚到回收站:${entry}`);
|
|
657
|
+
}
|
|
658
|
+
return { project, restoredTo: projectDir };
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* 清空回收站里认识的条目(显式硬删;来历不明的条目保留)。
|
|
663
|
+
* @param {string[] | undefined} names 只清这些条目;省略 = 全部认识的条目
|
|
664
|
+
* @returns {{ purged: number, bytes: number, names: string[], skipped: number }}
|
|
665
|
+
*/
|
|
666
|
+
purgeTrash(names) {
|
|
667
|
+
const { entries, unknown } = this.scanTrash();
|
|
668
|
+
/** @type {Record<string, any>[]} */
|
|
669
|
+
let selected = entries;
|
|
670
|
+
if (names != null) {
|
|
671
|
+
const wanted = new Set(names.map(String));
|
|
672
|
+
selected = entries.filter((entry) => wanted.has(entry.name));
|
|
673
|
+
const found = new Set(selected.map((entry) => entry.name));
|
|
674
|
+
const missing = [...wanted].filter((name) => !found.has(name));
|
|
675
|
+
if (missing.length > 0) {
|
|
676
|
+
throw new CaseStoreError("not-found", `回收站里没有这些条目:${missing.join("、")}`);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
let bytes = 0;
|
|
680
|
+
/** @type {string[]} */
|
|
681
|
+
const purgedNames = [];
|
|
682
|
+
for (const entry of selected) {
|
|
683
|
+
bytes += Number(entry.bytes) || 0;
|
|
684
|
+
rmSync(entry.path, { recursive: true, force: false });
|
|
685
|
+
purgedNames.push(entry.name);
|
|
686
|
+
}
|
|
687
|
+
return {
|
|
688
|
+
purged: purgedNames.length,
|
|
689
|
+
bytes,
|
|
690
|
+
names: purgedNames,
|
|
691
|
+
skipped: unknown.length,
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
346
695
|
/**
|
|
347
696
|
* 局部更新项目字段。
|
|
348
697
|
* @param {string} projectId
|
|
@@ -390,13 +739,13 @@ export class CaseStore {
|
|
|
390
739
|
|
|
391
740
|
/**
|
|
392
741
|
* 只更新 updatedAt,不写审计(记录追加时用)。
|
|
742
|
+
* 走 updateJson 的进程内锁:连续的 add 不会互相覆盖 project.json(AUD-CASEFILE-07)。
|
|
393
743
|
* @param {string} projectId
|
|
744
|
+
* @returns {Promise<Record<string, any> | null>}
|
|
394
745
|
*/
|
|
395
746
|
touch(projectId) {
|
|
396
747
|
const file = join(this.projectDir(projectId), "project.json");
|
|
397
|
-
|
|
398
|
-
if (!project) return;
|
|
399
|
-
this.writeJson(file, { ...project, updatedAt: nowIso() });
|
|
748
|
+
return this.updateJson(file, (project) => ({ ...project, updatedAt: nowIso() }));
|
|
400
749
|
}
|
|
401
750
|
|
|
402
751
|
/**
|
|
@@ -431,6 +780,13 @@ export class CaseStore {
|
|
|
431
780
|
if (!stat.isFile()) {
|
|
432
781
|
throw new CasefileInputError("invalid-input", `不是普通文件:${source}`);
|
|
433
782
|
}
|
|
783
|
+
// 先做 stat 预检再读正文:几百 MB 的 HAR/录屏直接 readFileSync 会让主进程内存尖峰(AUD-CASEFILE-06)。
|
|
784
|
+
if (stat.size > this.maxArtifactBytes) {
|
|
785
|
+
throw new CasefileInputError(
|
|
786
|
+
"artifact-too-large",
|
|
787
|
+
`产物 ${source} 有 ${stat.size} 字节,超过上限 ${this.maxArtifactBytes} 字节;请先裁剪或显式调大 maxArtifactBytes`,
|
|
788
|
+
);
|
|
789
|
+
}
|
|
434
790
|
const bytes = readFileSync(source);
|
|
435
791
|
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
436
792
|
const dir = join(this.projectDir(projectId), "artifacts");
|