@kangyishuai/dsh-casefile 0.2.2 → 0.3.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/lib/actions.js CHANGED
@@ -10,6 +10,7 @@ import { buildAttestation } from "./core/attestation.js";
10
10
  import { buildSpecPack, redactPack, renderSpecMarkdown, writeSpecPack } from "./core/brief.js";
11
11
  import { createCheckers } from "./core/checks.js";
12
12
  import { hashTree, shortDigest } from "./core/digest.js";
13
+ import { awaitLogin } from "./core/login-wait.js";
13
14
  import { gradeCapabilities } from "./core/manifest.js";
14
15
  import {
15
16
  CasefileInputError,
@@ -206,8 +207,14 @@ export function createActions(options) {
206
207
  */
207
208
  async addEvidence(projectId, input, exec) {
208
209
  const project = requireProject(projectId);
210
+ // 产物接管:/tmp 里的东西会被清理,清了 sha256 就无法复算,项目只能停在 investigating。
211
+ const archived =
212
+ typeof input?.artifactPath === "string" && input.artifactPath.trim() !== ""
213
+ ? store.archiveArtifact(project.id, input.artifactPath)
214
+ : null;
209
215
  const record = normalizeEvidence({
210
216
  ...input,
217
+ artifact: archived,
211
218
  sessionId: input?.sessionId ?? sessionOf(exec) ?? null,
212
219
  });
213
220
  store.appendRecord(project.id, "evidence", record);
@@ -1122,6 +1129,42 @@ export function createActions(options) {
1122
1129
  return { ...overview, summary: summarizeOverview(overview) };
1123
1130
  },
1124
1131
 
1132
+ // ---------- 等登录(人机协作) ----------
1133
+
1134
+ /**
1135
+ * 轮询等用户完成登录。带超时,不假装成功。
1136
+ * @param {string} projectId
1137
+ * @param {{
1138
+ * endpoint: string, urlPrefix?: string, readyJs?: string,
1139
+ * pollMs?: number, timeoutMs?: number,
1140
+ * }} input
1141
+ * @returns {Promise<Record<string, any>>}
1142
+ */
1143
+ async awaitLogin(projectId, input) {
1144
+ const project = requireProject(projectId);
1145
+ const endpoint = String(input?.endpoint ?? "").trim();
1146
+ if (endpoint === "") {
1147
+ throw new CasefileInputError(
1148
+ "invalid-input",
1149
+ "endpoint 不能为空(形如 http://127.0.0.1:9223)",
1150
+ );
1151
+ }
1152
+ const result = await awaitLogin({
1153
+ endpoint,
1154
+ urlPrefix: input?.urlPrefix,
1155
+ readyJs: input?.readyJs,
1156
+ pollMs: input?.pollMs,
1157
+ timeoutMs: input?.timeoutMs,
1158
+ });
1159
+ store.audit(project.id, {
1160
+ actor: "agent",
1161
+ action: "access/await-login",
1162
+ target: endpoint,
1163
+ detail: { status: result.status, attempts: result.attempts, waitedMs: result.waitedMs },
1164
+ });
1165
+ return result;
1166
+ },
1167
+
1125
1168
  // ---------- 覆盖率 / 关闭 / 报告(M3 收尾) ----------
1126
1169
 
1127
1170
  /**
@@ -0,0 +1,205 @@
1
+ // @ts-check
2
+ // core/login-wait.js:等用户完成登录(轮询 CDP 页面就绪条件)。
3
+ //
4
+ // 为什么需要它:登录态页面要人参与(输账号/扫码/二次验证)。agent 不能干等,
5
+ // 也不能假装成功——所以做成"带超时的轮询 + 明确状态":
6
+ // - ready:就绪判据为真,可以继续采集
7
+ // - timeout:到点还没好,保留现场,调用方决定是否重来
8
+ // - error:端点/页面不可用(不存在、CDP 层失败)
9
+ // 判据用一段 JS 表达式(返回 boolean),由调用方给出——casefile 不猜"登录成功"长什么样。
10
+
11
+ /**
12
+ * @typedef {{
13
+ * status: "ready" | "timeout" | "error",
14
+ * attempts: number,
15
+ * waitedMs: number,
16
+ * pollMs: number,
17
+ * timeoutMs: number,
18
+ * lastValue: boolean | null,
19
+ * hint: string,
20
+ * detail?: string,
21
+ * }} LoginWaitResult
22
+ */
23
+
24
+ /** 默认轮询参数。 */
25
+ export const LOGIN_WAIT_DEFAULTS = {
26
+ pollMs: 2000,
27
+ timeoutMs: 180000,
28
+ readyJs: '!document.querySelector("input[type=password]")',
29
+ };
30
+
31
+ /**
32
+ * 在 CDP 端点上找一个 HTTP(S) 页面 target。
33
+ * @param {string} endpoint 形如 http://127.0.0.1:9223
34
+ * @param {string} [urlPrefix] 只选 URL 以它开头的页面
35
+ * @returns {Promise<{ id: string, url: string } | null>}
36
+ */
37
+ export async function findPageTarget(endpoint, urlPrefix) {
38
+ const base = String(endpoint).replace(/\/+$/, "");
39
+ const response = await fetch(`${base}/json/list`, { signal: AbortSignal.timeout(10000) });
40
+ if (!response.ok) throw new Error(`target discovery failed: HTTP ${response.status}`);
41
+ const targets = await response.json();
42
+ const pages = (Array.isArray(targets) ? targets : []).filter(
43
+ (/** @type {any} */ item) => item?.type === "page" && /^https?:/u.test(String(item.url ?? "")),
44
+ );
45
+ if (pages.length === 0) return null;
46
+ const picked =
47
+ (urlPrefix
48
+ ? pages.find((/** @type {any} */ item) => String(item.url).startsWith(urlPrefix))
49
+ : null) ?? pages[0];
50
+ return { id: String(picked.id), url: String(picked.url) };
51
+ }
52
+
53
+ /**
54
+ * 在页面里求值(一次性 WebSocket,用完即断)。
55
+ * @param {string} wsUrl
56
+ * @param {string} expression
57
+ * @returns {Promise<boolean>}
58
+ */
59
+ async function evaluateOnce(wsUrl, expression) {
60
+ return await new Promise((resolve, reject) => {
61
+ const socket = new WebSocket(wsUrl);
62
+ const timer = setTimeout(() => {
63
+ try {
64
+ socket.close();
65
+ } catch {
66
+ // 关闭失败不影响超时语义
67
+ }
68
+ reject(new Error("evaluate timeout"));
69
+ }, 10000);
70
+ socket.onopen = () => {
71
+ socket.send(
72
+ JSON.stringify({
73
+ id: 1,
74
+ method: "Runtime.evaluate",
75
+ params: { expression, returnByValue: true },
76
+ }),
77
+ );
78
+ };
79
+ socket.onerror = () => {
80
+ clearTimeout(timer);
81
+ reject(new Error("cdp socket error"));
82
+ };
83
+ socket.onmessage = (/** @type {any} */ event) => {
84
+ let message;
85
+ try {
86
+ message = JSON.parse(String(event.data));
87
+ } catch {
88
+ return;
89
+ }
90
+ if (message.id !== 1) return;
91
+ clearTimeout(timer);
92
+ try {
93
+ socket.close();
94
+ } catch {
95
+ // 忽略
96
+ }
97
+ if (message.error) {
98
+ reject(new Error(`cdp error: ${JSON.stringify(message.error)}`));
99
+ return;
100
+ }
101
+ resolve(message.result?.result?.value === true);
102
+ };
103
+ });
104
+ }
105
+
106
+ /**
107
+ * 轮询等登录就绪。
108
+ * @param {{
109
+ * endpoint: string,
110
+ * urlPrefix?: string,
111
+ * readyJs?: string,
112
+ * pollMs?: number,
113
+ * timeoutMs?: number,
114
+ * sleep?: (ms: number) => Promise<void>,
115
+ * probe?: (wsUrl: string, expression: string) => Promise<boolean>,
116
+ * }} input
117
+ * @returns {Promise<LoginWaitResult>}
118
+ */
119
+ export async function awaitLogin(input) {
120
+ const pollMs =
121
+ Number.isInteger(input.pollMs) && Number(input.pollMs) > 0
122
+ ? Number(input.pollMs)
123
+ : LOGIN_WAIT_DEFAULTS.pollMs;
124
+ const timeoutMs =
125
+ Number.isInteger(input.timeoutMs) && Number(input.timeoutMs) > 0
126
+ ? Number(input.timeoutMs)
127
+ : LOGIN_WAIT_DEFAULTS.timeoutMs;
128
+ const readyJs =
129
+ typeof input.readyJs === "string" && input.readyJs.trim() !== ""
130
+ ? input.readyJs
131
+ : LOGIN_WAIT_DEFAULTS.readyJs;
132
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
133
+ const probe = input.probe ?? evaluateOnce;
134
+ const started = Date.now();
135
+ let attempts = 0;
136
+ /** @type {boolean | null} */
137
+ let lastValue = null;
138
+
139
+ while (Date.now() - started < timeoutMs) {
140
+ attempts += 1;
141
+ try {
142
+ const endpoint = String(input.endpoint ?? "").replace(/\/+$/, "");
143
+ const response = await fetch(`${endpoint}/json/list`, { signal: AbortSignal.timeout(10000) });
144
+ if (!response.ok) throw new Error(`target discovery failed: HTTP ${response.status}`);
145
+ const targets = await response.json();
146
+ const pages = (Array.isArray(targets) ? targets : []).filter(
147
+ (/** @type {any} */ item) =>
148
+ item?.type === "page" && /^https?:/u.test(String(item.url ?? "")),
149
+ );
150
+ const wanted = input.urlPrefix;
151
+ const picked =
152
+ (wanted
153
+ ? pages.find((/** @type {any} */ item) => String(item.url).startsWith(wanted))
154
+ : null) ?? pages[0];
155
+ if (!picked) {
156
+ lastValue = null;
157
+ await sleep(pollMs);
158
+ continue;
159
+ }
160
+ lastValue = await probe(String(picked.webSocketDebuggerUrl), readyJs);
161
+ if (lastValue === true) {
162
+ return {
163
+ status: "ready",
164
+ attempts,
165
+ waitedMs: Date.now() - started,
166
+ pollMs,
167
+ timeoutMs,
168
+ lastValue,
169
+ hint: "已就绪:可以继续采集了。",
170
+ };
171
+ }
172
+ } catch (error) {
173
+ const message = error instanceof Error ? error.message : String(error);
174
+ // 端点还没起来 / 页面还没开也属于"等",只有明确不可恢复才报错
175
+ // 端点还没起来(浏览器没启动 / 端口没开)属于可以继续等,不该立刻判失败;
176
+ // 等满 timeoutMs 后由循环出口统一报 timeout。
177
+ if (/ECONNREFUSED|ECONNRESET|fetch failed|target discovery failed/u.test(message)) {
178
+ lastValue = null;
179
+ await sleep(pollMs);
180
+ continue;
181
+ }
182
+ return {
183
+ status: "error",
184
+ attempts,
185
+ waitedMs: Date.now() - started,
186
+ pollMs,
187
+ timeoutMs,
188
+ lastValue,
189
+ hint: "CDP 端点或页面不可用;确认带 --remote-debugging-port 的浏览器已启动并打开了目标页。",
190
+ detail: message.slice(0, 500),
191
+ };
192
+ }
193
+ await sleep(pollMs);
194
+ }
195
+
196
+ return {
197
+ status: "timeout",
198
+ attempts,
199
+ waitedMs: Date.now() - started,
200
+ pollMs,
201
+ timeoutMs,
202
+ lastValue,
203
+ hint: "等待超时:登录还没完成。现场保留,你可以登录后重新调用,或调大 timeoutMs。",
204
+ };
205
+ }
package/lib/core/model.js CHANGED
@@ -219,11 +219,6 @@ export function normalizeProjectInput(input) {
219
219
  };
220
220
  }
221
221
 
222
- /**
223
- * 规范化一条证据(只投影 REA 的结论)。
224
- * @param {Record<string, any>} input
225
- * @returns {Record<string, any>}
226
- */
227
222
  /**
228
223
  * 外部生产者(谁采的、用什么方式采的、用户是否明示确认过)。
229
224
  * casefile 自己不采集:它只记录产出者,责任与合法性归操作者。
@@ -258,6 +253,34 @@ export function normalizeProducer(raw) {
258
253
  return Object.keys(producer).length === 0 ? null : producer;
259
254
  }
260
255
 
256
+ /**
257
+ * 规范化一条证据(只投影 REA 的结论)。
258
+ * @param {Record<string, any>} input
259
+ * @returns {Record<string, any>}
260
+ */
261
+ /**
262
+ * 归档产物元信息(由 store.archiveArtifact 产出,这里只做形状校验)。
263
+ * @param {any} raw
264
+ * @returns {Record<string, any> | null}
265
+ */
266
+ export function normalizeArtifact(raw) {
267
+ if (raw == null) return null;
268
+ if (typeof raw !== "object" || Array.isArray(raw)) {
269
+ throw new CasefileInputError("invalid-input", "artifact 必须是对象");
270
+ }
271
+ const sha256 = text(raw.sha256, "artifact.sha256", { max: 128 });
272
+ const file = text(raw.file, "artifact.file", { max: 400 });
273
+ return {
274
+ sha256,
275
+ bytes: Number.isInteger(raw.bytes) && raw.bytes >= 0 ? raw.bytes : 0,
276
+ file,
277
+ originalName:
278
+ raw.originalName == null
279
+ ? null
280
+ : text(raw.originalName, "artifact.originalName", { max: 200 }),
281
+ };
282
+ }
283
+
261
284
  /**
262
285
  * 规范化一条证据(只投影 REA 的结论)。
263
286
  * @param {Record<string, any>} input
@@ -278,6 +301,7 @@ export function normalizeEvidence(input) {
278
301
  summary: text(input?.summary, "summary", { max: 4000 }),
279
302
  refs: textList(input?.refs, "refs"),
280
303
  producer: normalizeProducer(input?.producer),
304
+ artifact: normalizeArtifact(input?.artifact),
281
305
  claimIds: idList(input?.claimIds, "claimIds"),
282
306
  };
283
307
  }
package/lib/core/store.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // - JSONL append-only,修改用新记录 + supersedes(M0 先只追加);
12
12
  // - 所有路径从 dataRoot 派生,不写死 ~/.dsh(可在临时目录里测)。
13
13
 
14
+ import { createHash } from "node:crypto";
14
15
  import {
15
16
  appendFileSync,
16
17
  existsSync,
@@ -18,9 +19,10 @@ import {
18
19
  readdirSync,
19
20
  readFileSync,
20
21
  renameSync,
22
+ statSync,
21
23
  writeFileSync,
22
24
  } from "node:fs";
23
- import { dirname, join } from "node:path";
25
+ import { basename, dirname, extname, join } from "node:path";
24
26
  import {
25
27
  CasefileInputError,
26
28
  ID_RE,
@@ -364,6 +366,35 @@ export class CaseStore {
364
366
  return candidate;
365
367
  }
366
368
 
369
+ /**
370
+ * 把外部采集产物归档进项目目录,返回归档后的元信息。
371
+ * 目的:/tmp 里的产物会被清理,清了就无法复算 sha256,项目只能停在 investigating。
372
+ * @param {string} projectId
373
+ * @param {string} sourcePath 绝对路径的现成产物
374
+ * @returns {{ sha256: string, bytes: number, file: string, originalName: string }}
375
+ */
376
+ archiveArtifact(projectId, sourcePath) {
377
+ const source = String(sourcePath ?? "").trim();
378
+ if (source === "" || !existsSync(source)) {
379
+ throw new CasefileInputError("invalid-input", `产物不存在:${source || "(空)"}`);
380
+ }
381
+ const stat = statSync(source);
382
+ if (!stat.isFile()) {
383
+ throw new CasefileInputError("invalid-input", `不是普通文件:${source}`);
384
+ }
385
+ const bytes = readFileSync(source);
386
+ const digest = createHash("sha256").update(bytes).digest("hex");
387
+ const dir = join(this.projectDir(projectId), "artifacts");
388
+ mkdirSync(dir, { recursive: true });
389
+ const name = basename(source);
390
+ const ext = extname(name);
391
+ const file = join("artifacts", `${digest.slice(0, 16)}${ext}`);
392
+ const target = join(this.projectDir(projectId), file);
393
+ // 同样的内容只存一份:同一 sha256 已存在就直接复用
394
+ if (!existsSync(target)) writeFileSync(target, bytes);
395
+ return { sha256: digest, bytes: bytes.length, file, originalName: name };
396
+ }
397
+
367
398
  /**
368
399
  * 记录一个 builder 子会话 id(数据根级,不分项目)。
369
400
  * builder 只该收到规格包,不该写账本——写类工具遇到它会拒绝。
package/lib/service.js CHANGED
@@ -210,6 +210,7 @@ export class CasefileService extends TypertRemoteService {
210
210
  closeObligation: (projectId, id, input) => this.actions.closeObligation(projectId, id, input),
211
211
  reopenObligation: (projectId, id, note) => this.actions.reopenObligation(projectId, id, note),
212
212
  overview: () => this.actions.overview(),
213
+ awaitLogin: (projectId, input) => this.actions.awaitLogin(projectId, input),
213
214
  runCycle: (projectId, input) => this.actions.runCycle(projectId, input),
214
215
  isBuilderSession: (sessionId) =>
215
216
  this.store.listBuilderSessions().has(String(sessionId ?? "")),
@@ -459,6 +460,19 @@ export class CasefileService extends TypertRemoteService {
459
460
  }
460
461
  }
461
462
 
463
+ /**
464
+ * @param {string} projectId
465
+ * @param {Record<string, any>} input
466
+ * @returns {Promise<Record<string, any>>}
467
+ */
468
+ async awaitLogin(projectId, input) {
469
+ try {
470
+ return await this.actions.awaitLogin(projectId, /** @type {any} */ (input));
471
+ } catch (error) {
472
+ fail(error);
473
+ }
474
+ }
475
+
462
476
  /**
463
477
  * @param {string} projectId
464
478
  * @param {Record<string, any>} input
@@ -665,6 +679,7 @@ declareRemote(CasefileService, "listChecks");
665
679
  declareRemote(CasefileService, "closeObligation");
666
680
  declareRemote(CasefileService, "reopenObligation");
667
681
  declareRemote(CasefileService, "overview");
682
+ declareRemote(CasefileService, "awaitLogin");
668
683
  declareRemote(CasefileService, "runCycle");
669
684
  declareRemote(CasefileService, "closeProject");
670
685
  declareRemote(CasefileService, "exportReport");
package/lib/tools.js CHANGED
@@ -17,6 +17,7 @@ export const TOOL_NAMES = /** @type {const} */ ({
17
17
  feature: "case_feature",
18
18
  unknown: "case_unknown",
19
19
  obligation: "case_obligation",
20
+ access: "case_access",
20
21
  build: "case_build",
21
22
  check: "case_check",
22
23
  brief: "case_brief",
@@ -251,6 +252,11 @@ export function buildToolDefinitions(handlers, projectOf) {
251
252
  description:
252
253
  "产出该证据的工具标识(REA 工具名,或外部工具如 scrapling/StealthyFetcher)",
253
254
  },
255
+ artifactPath: {
256
+ type: "string",
257
+ description:
258
+ "可选:把外部采集产物(HTML/HAR/截图)归档进项目目录并记录 sha256;/tmp 产物会被清理,归档后才能长期复算",
259
+ },
254
260
  producer: {
255
261
  type: "object",
256
262
  additionalProperties: false,
@@ -537,6 +543,52 @@ export function buildToolDefinitions(handlers, projectOf) {
537
543
  },
538
544
  },
539
545
 
546
+ {
547
+ name: TOOL_NAMES.access,
548
+ description:
549
+ "访问协助:await-login 轮询等人完成登录(带超时,就绪/超时/错误三态,不假装成功)。用于登录态页面采集前。",
550
+ parameters: {
551
+ type: "object",
552
+ additionalProperties: false,
553
+ properties: {
554
+ action: { type: "string", enum: ["await-login"] },
555
+ projectId: PROJECT_ID,
556
+ endpoint: { type: "string", description: "CDP 端点,形如 http://127.0.0.1:9223" },
557
+ urlPrefix: { type: "string", description: "只选 URL 以它开头的页面" },
558
+ readyJs: {
559
+ type: "string",
560
+ description: "就绪判据(返回 boolean 的 JS 表达式),默认「页面里没有密码输入框」",
561
+ },
562
+ pollMs: { type: "integer", description: "轮询间隔,默认 2000" },
563
+ timeoutMs: { type: "integer", description: "最长等待,默认 180000(3 分钟)" },
564
+ },
565
+ required: ["action"],
566
+ },
567
+ output: { schema: TOOL_OUTPUT_SCHEMA, render: renderToolResult },
568
+ /** @param {any} args @param {any} exec */
569
+ async execute(args, exec) {
570
+ return run(async () => {
571
+ await assertWriter(exec);
572
+ assertAction(args.action, ["await-login"]);
573
+ const id = projectId(args, exec);
574
+ const result = await handlers.awaitLogin(id, {
575
+ endpoint: args.endpoint,
576
+ urlPrefix: args.urlPrefix,
577
+ readyJs: args.readyJs,
578
+ pollMs: args.pollMs,
579
+ timeoutMs: args.timeoutMs,
580
+ });
581
+ return {
582
+ ...result,
583
+ summary:
584
+ result.status === "ready"
585
+ ? `已就绪(等了 ${result.waitedMs}ms,${result.attempts} 次探测)`
586
+ : `${result.status}:${result.hint}`,
587
+ };
588
+ });
589
+ },
590
+ },
591
+
540
592
  {
541
593
  name: TOOL_NAMES.build,
542
594
  description:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-casefile",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Evidence-first reverse-engineering workbench on top of REA: observations become citable evidence, a handoff spec pack, and recomputable acceptance checks. No bridge, no engine.",
5
5
  "keywords": [
6
6
  "dsh",