dsh-uitest 2.3.1 → 2.4.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 +72 -11
- package/bin/uitest.mjs +189 -11
- package/client.js +81 -11
- package/host/agent-bridge.mjs +9 -2
- package/host/agent-test.mjs +1 -1
- package/host/context-budget.mjs +1 -1
- package/index.js +14 -2
- package/lib/agent-session.mjs +81 -3
- package/lib/agent-tasks.mjs +212 -0
- package/lib/batch.mjs +204 -13
- package/lib/browser-ab.mjs +21 -6
- package/lib/browser.mjs +5 -5
- package/lib/config.mjs +1 -0
- package/lib/convert.mjs +178 -40
- package/lib/doc-structure.mjs +316 -0
- package/lib/flow.mjs +49 -14
- package/lib/knowledge-central-episodes.mjs +120 -0
- package/lib/knowledge-central-import.mjs +16 -1
- package/lib/knowledge-central.mjs +149 -22
- package/lib/knowledge-clean.mjs +749 -0
- package/lib/knowledge-consolidate.mjs +1271 -0
- package/lib/knowledge-coverage.mjs +150 -0
- package/lib/knowledge-docs.mjs +3 -3
- package/lib/knowledge-effect.mjs +148 -0
- package/lib/knowledge-facts.mjs +1008 -0
- package/lib/knowledge-maintain.mjs +185 -0
- package/lib/knowledge-permission.mjs +447 -0
- package/lib/knowledge-query.mjs +304 -26
- package/lib/knowledge-store.mjs +169 -14
- package/lib/knowledge-summarize.mjs +332 -0
- package/lib/knowledge.mjs +944 -47
- package/lib/learn-run.mjs +157 -51
- package/lib/run-learn.mjs +34 -0
- package/lib/run-observe.mjs +95 -27
- package/lib/run-stats.mjs +71 -0
- package/package.json +12 -2
- package/scripts/knowledge-central-purge.mjs +248 -0
- package/scripts/knowledge-central-sync.mjs +102 -20
- package/scripts/knowledge-consolidate.mjs +158 -0
- package/scripts/knowledge-coverage.mjs +94 -0
- package/scripts/knowledge-effect.mjs +82 -0
- package/scripts/knowledge-permission-probe.mjs +196 -0
- package/scripts/knowledge-permission-report.mjs +140 -0
- package/scripts/knowledge-report.mjs +492 -0
- package/scripts/knowledge-summarize.mjs +200 -0
- package/skills/uitest/SKILL.md +4 -2
- package/skills/uitest/references/convert-knowledge.md +66 -13
- package/studio/host.mjs +120 -3
- package/studio/knowledge.mjs +195 -45
- package/studio/snapshot.mjs +6 -1
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// 批次后知识维护:整理正典(备份后落盘)→ 重新摘要 → 增量同步中心库。
|
|
2
|
+
// 通过现有 CLI 串行执行,复用脚本已验证的参数、备份与幂等逻辑;失败不阻断批次收尾。
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
|
|
7
|
+
import { centralConfig } from './knowledge-central.mjs';
|
|
8
|
+
|
|
9
|
+
const execFileAsync = promisify(execFile);
|
|
10
|
+
|
|
11
|
+
const SCRIPTS = {
|
|
12
|
+
consolidate: fileURLToPath(new URL('../scripts/knowledge-consolidate.mjs', import.meta.url)),
|
|
13
|
+
summarize: fileURLToPath(new URL('../scripts/knowledge-summarize.mjs', import.meta.url)),
|
|
14
|
+
sync: fileURLToPath(new URL('../scripts/knowledge-central-sync.mjs', import.meta.url)),
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
/** 批次后维护开关;默认关闭,需在 knowledge.maintenance.afterBatch 显式开启。 */
|
|
20
|
+
export function maintenanceOptions(config) {
|
|
21
|
+
const raw = config?.knowledge?.maintenance || {};
|
|
22
|
+
return {
|
|
23
|
+
afterBatch: raw.afterBatch === true,
|
|
24
|
+
consolidate: raw.consolidate !== false,
|
|
25
|
+
summarize: raw.summarize !== false,
|
|
26
|
+
sync: raw.sync !== false,
|
|
27
|
+
timeoutMs: Math.max(60_000, Number(raw.timeoutMs) || DEFAULT_TIMEOUT_MS),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function targetArgs(config) {
|
|
32
|
+
const dir = config?.knowledge?.dir;
|
|
33
|
+
if (dir) return ['--dir', String(dir)];
|
|
34
|
+
const library = config?.knowledge?.library;
|
|
35
|
+
if (library) return ['--library', String(library)];
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseJson(text) {
|
|
40
|
+
const value = String(text || '').trim();
|
|
41
|
+
if (!value) return null;
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(value);
|
|
44
|
+
} catch {
|
|
45
|
+
const start = value.indexOf('{');
|
|
46
|
+
const end = value.lastIndexOf('}');
|
|
47
|
+
if (start < 0 || end <= start) return null;
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(value.slice(start, end + 1));
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseSyncCounts(stdout) {
|
|
57
|
+
const text = String(stdout || '');
|
|
58
|
+
const knowledge = text.match(/知识组待同步\s*(\d+),已同步\s*(\d+)/);
|
|
59
|
+
const evidence = text.match(/证据组待同步\s*(\d+),已同步\s*(\d+)/);
|
|
60
|
+
return {
|
|
61
|
+
knowledgePending: knowledge ? Number(knowledge[1]) : null,
|
|
62
|
+
knowledgeSynced: knowledge ? Number(knowledge[2]) : null,
|
|
63
|
+
evidencePending: evidence ? Number(evidence[1]) : null,
|
|
64
|
+
evidenceSynced: evidence ? Number(evidence[2]) : null,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function runScript(name, args, { timeoutMs, run }) {
|
|
69
|
+
const [script, ...rest] = args;
|
|
70
|
+
if (run) return run(name, script, rest);
|
|
71
|
+
try {
|
|
72
|
+
const { stdout, stderr } = await execFileAsync(process.execPath, [script, ...rest], {
|
|
73
|
+
timeout: timeoutMs,
|
|
74
|
+
maxBuffer: 20 * 1024 * 1024,
|
|
75
|
+
windowsHide: true,
|
|
76
|
+
});
|
|
77
|
+
return { ok: true, code: 0, stdout, stderr, error: '' };
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
ok: false,
|
|
81
|
+
code: Number(error.code) || 1,
|
|
82
|
+
stdout: String(error.stdout || ''),
|
|
83
|
+
stderr: String(error.stderr || ''),
|
|
84
|
+
error: String(error.message || error),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 串行执行维护。任何阶段失败都只记录到 stages,不抛错(整理失败会中止后续阶段)。
|
|
91
|
+
* @returns {{ok:boolean, stages:object, error:string}}
|
|
92
|
+
*/
|
|
93
|
+
export async function maintainKnowledge(config, { options = maintenanceOptions(config), logger = null, run = null, onStage = null } = {}) {
|
|
94
|
+
const project = config?.projectDir;
|
|
95
|
+
if (!project) {
|
|
96
|
+
return { ok: false, stages: {}, error: '知识维护缺少 projectDir' };
|
|
97
|
+
}
|
|
98
|
+
const central = centralConfig(config);
|
|
99
|
+
const stages = {};
|
|
100
|
+
const total = 3;
|
|
101
|
+
const progress = async (stage, done) => {
|
|
102
|
+
if (typeof onStage === 'function') await onStage({ stage, done, total });
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
if (options.consolidate !== false) {
|
|
106
|
+
await progress('consolidate', 0);
|
|
107
|
+
const result = await runScript('consolidate', [
|
|
108
|
+
SCRIPTS.consolidate, '--project', project, ...targetArgs(config), '--apply', '--json',
|
|
109
|
+
], { timeoutMs: options.timeoutMs, run });
|
|
110
|
+
const report = parseJson(result.stdout);
|
|
111
|
+
stages.consolidate = {
|
|
112
|
+
ok: result.ok,
|
|
113
|
+
code: result.code,
|
|
114
|
+
stats: report?.stats || null,
|
|
115
|
+
actions: Array.isArray(report?.actions) ? report.actions.slice(0, 20) : [],
|
|
116
|
+
error: result.ok ? '' : (result.stderr || result.error || '整理失败'),
|
|
117
|
+
};
|
|
118
|
+
if (!result.ok) {
|
|
119
|
+
if (logger?.warn) logger.warn('知识维护:整理失败 ' + stages.consolidate.error);
|
|
120
|
+
return { ok: false, stages, error: '知识整理失败:' + stages.consolidate.error };
|
|
121
|
+
}
|
|
122
|
+
} else {
|
|
123
|
+
stages.consolidate = { ok: true, skipped: true };
|
|
124
|
+
}
|
|
125
|
+
await progress('consolidate', 1);
|
|
126
|
+
|
|
127
|
+
const centralEnabled = central.enabled;
|
|
128
|
+
if (options.summarize !== false && centralEnabled) {
|
|
129
|
+
await progress('summarize', 1);
|
|
130
|
+
const result = await runScript('summarize', [
|
|
131
|
+
SCRIPTS.summarize, '--project', project, ...targetArgs(config), '--url', central.url, '--apply', '--json',
|
|
132
|
+
], { timeoutMs: options.timeoutMs, run });
|
|
133
|
+
const report = parseJson(result.stdout);
|
|
134
|
+
stages.summarize = {
|
|
135
|
+
ok: result.code === 0,
|
|
136
|
+
partial: result.code === 2,
|
|
137
|
+
code: result.code,
|
|
138
|
+
planned: report?.planned ?? null,
|
|
139
|
+
applied: report?.applied ?? null,
|
|
140
|
+
rejected: report?.rejected ?? null,
|
|
141
|
+
failed: report?.failed ?? null,
|
|
142
|
+
error: result.code === 0 ? '' : (result.stderr || result.error || '摘要失败'),
|
|
143
|
+
};
|
|
144
|
+
if (!stages.summarize.ok && logger?.warn) logger.warn('知识维护:摘要未全部完成 ' + stages.summarize.error);
|
|
145
|
+
} else {
|
|
146
|
+
stages.summarize = {
|
|
147
|
+
ok: true,
|
|
148
|
+
skipped: true,
|
|
149
|
+
reason: centralEnabled ? '已关闭摘要' : '中心知识库未启用',
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
await progress('summarize', 2);
|
|
153
|
+
|
|
154
|
+
if (options.sync !== false && centralEnabled) {
|
|
155
|
+
await progress('sync', 2);
|
|
156
|
+
const result = await runScript('sync', [
|
|
157
|
+
SCRIPTS.sync, '--project', project,
|
|
158
|
+
'--url', central.url,
|
|
159
|
+
'--group-id', central.groupId,
|
|
160
|
+
'--evidence-group-id', central.evidenceGroupId,
|
|
161
|
+
'--fast',
|
|
162
|
+
], { timeoutMs: options.timeoutMs, run });
|
|
163
|
+
stages.sync = {
|
|
164
|
+
ok: result.ok,
|
|
165
|
+
code: result.code,
|
|
166
|
+
...parseSyncCounts(result.stdout),
|
|
167
|
+
error: result.ok ? '' : (result.stderr || result.error || '同步失败'),
|
|
168
|
+
};
|
|
169
|
+
if (!result.ok && logger?.warn) logger.warn('知识维护:中心同步失败 ' + stages.sync.error);
|
|
170
|
+
} else {
|
|
171
|
+
stages.sync = {
|
|
172
|
+
ok: true,
|
|
173
|
+
skipped: true,
|
|
174
|
+
reason: centralEnabled ? '已关闭同步' : '中心知识库未启用',
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
await progress('sync', 3);
|
|
178
|
+
|
|
179
|
+
const summarizeOk = stages.summarize.ok || stages.summarize.skipped === true;
|
|
180
|
+
const syncOk = stages.sync.ok || stages.sync.skipped === true;
|
|
181
|
+
const ok = stages.consolidate.ok && summarizeOk && syncOk;
|
|
182
|
+
return { ok, stages, error: ok ? '' : '知识维护未全部完成' };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export { SCRIPTS, parseSyncCounts };
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
// 角色权限探测:按账号角色打开只读页面,采集可见按钮,与知识里的期望按钮比对,
|
|
2
|
+
// 产出 role.permission 探测事实。探测只导航、不点击,默认预览,--apply 才并入事实库。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { accountsForExecution, accountConfigFor, selectAccountForRole } from '../studio/accounts.mjs';
|
|
7
|
+
import { login as browserLogin, launchSession } from './browser-ab.mjs';
|
|
8
|
+
import { resolveUrl } from './config.mjs';
|
|
9
|
+
import { isDialogPageRecord, isLoginPageRecord } from './knowledge-clean.mjs';
|
|
10
|
+
import { applyFactConsolidation, canonicalButtonName, loadFacts, pageButtonNames, planFactConsolidation, probePermissionCandidates } from './knowledge-facts.mjs';
|
|
11
|
+
import { knowledgeDir } from './knowledge.mjs';
|
|
12
|
+
import { createLogger, ensureDir, nowIso, slug, writeJsonFile } from './util.mjs';
|
|
13
|
+
|
|
14
|
+
const MAX_PAGES_DEFAULT = 20;
|
|
15
|
+
|
|
16
|
+
// 在正文最大的同源文档里收集可见按钮与表头;只读,不触发任何点击。
|
|
17
|
+
const PROBE_OBSERVE_SCRIPT = `(() => {
|
|
18
|
+
const visible = (el) => {
|
|
19
|
+
try { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; } catch { return false; }
|
|
20
|
+
};
|
|
21
|
+
const docs = [];
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
const add = (doc) => { if (doc && !seen.has(doc)) { seen.add(doc); docs.push(doc); } };
|
|
24
|
+
add(document);
|
|
25
|
+
for (let i = 0; i < docs.length; i += 1) {
|
|
26
|
+
let frames = [];
|
|
27
|
+
try { frames = [...docs[i].querySelectorAll('iframe')]; } catch { frames = []; }
|
|
28
|
+
for (const frame of frames) {
|
|
29
|
+
try { add(frame.contentDocument); } catch { /* 跨域不可观察 */ }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const weight = (doc) => {
|
|
33
|
+
try { return (doc.body?.innerText || '').trim().length + doc.querySelectorAll('th, [role="columnheader"]').length * 200; } catch { return 0; }
|
|
34
|
+
};
|
|
35
|
+
let root = docs[0];
|
|
36
|
+
let best = weight(root);
|
|
37
|
+
for (const doc of docs.slice(1)) {
|
|
38
|
+
const next = weight(doc);
|
|
39
|
+
if (next > best) { root = doc; best = next; }
|
|
40
|
+
}
|
|
41
|
+
const text = (root.body?.innerText || '').trim();
|
|
42
|
+
// 壳层(系统切换、账号菜单)与表格单元格里的普通链接不是页面按钮:
|
|
43
|
+
// 普通 <a> 只有在按钮/操作区里才算权限入口,避免把单号、人名当成按钮。
|
|
44
|
+
const isChrome = (el) => {
|
|
45
|
+
try {
|
|
46
|
+
if (el.closest('header, nav, [role="navigation"], .e10header, [class*="header-menu"], [class*="navbar"], [class*="sidebar"], [class*="breadcrumb"], [class*="topbar"]')) return true;
|
|
47
|
+
if (el.tagName === 'A') {
|
|
48
|
+
const actionish = el.matches('[class*="btn"], [class*="button"]')
|
|
49
|
+
|| Boolean(el.closest('[class*="operate"], [class*="btn-group"], [class*="button-group"]'));
|
|
50
|
+
if (!actionish) return true;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
} catch { return true; }
|
|
54
|
+
};
|
|
55
|
+
const pick = (selector) => [...root.querySelectorAll(selector)]
|
|
56
|
+
.filter((el) => visible(el) && !isChrome(el))
|
|
57
|
+
.map((el) => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim())
|
|
58
|
+
.filter(Boolean);
|
|
59
|
+
return {
|
|
60
|
+
url: root.location?.href || location.href,
|
|
61
|
+
title: root.title || document.title || '',
|
|
62
|
+
textLength: text.length,
|
|
63
|
+
buttons: [...new Set(pick('button, a, [role="button"]'))],
|
|
64
|
+
headers: [...new Set(pick('th, [role="columnheader"]'))],
|
|
65
|
+
};
|
|
66
|
+
})()`;
|
|
67
|
+
|
|
68
|
+
function asArray(value) {
|
|
69
|
+
return Array.isArray(value) ? value : value === undefined || value === null ? [] : [value];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function buttonTargets(page) {
|
|
73
|
+
return pageButtonNames(page);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 选择可探测页面:正典、有 URL、不是需要点击才出现的弹窗。 */
|
|
77
|
+
export function buildPermissionProbePlan(knowledge = {}, { roles = [], pages = [], limit = MAX_PAGES_DEFAULT } = {}) {
|
|
78
|
+
const wanted = new Set(asArray(pages).map((item) => String(item || '').trim()).filter(Boolean));
|
|
79
|
+
const targets = asArray(knowledge?.pages?.pages)
|
|
80
|
+
.filter((page) => page && page.status === 'canonical')
|
|
81
|
+
.filter((page) => !isDialogPageRecord(page))
|
|
82
|
+
.filter((page) => !isLoginPageRecord(page))
|
|
83
|
+
.filter((page) => typeof page.url === 'string' && page.url.trim())
|
|
84
|
+
.filter((page) => !wanted.size || wanted.has(String(page.id)) || wanted.has(String(page.title)))
|
|
85
|
+
.map((page) => ({
|
|
86
|
+
id: String(page.id),
|
|
87
|
+
title: String(page.title || page.id),
|
|
88
|
+
url: String(page.url).trim(),
|
|
89
|
+
expected: buttonTargets(page),
|
|
90
|
+
headers: asArray(page.table?.headers).map((item) => String(item)).filter(Boolean).slice(0, 40),
|
|
91
|
+
// 页面学习记录的首屏/稳定耗时是这台系统最可信的等待依据(PAGE/自定义应用常见 20–60s)。
|
|
92
|
+
waits: {
|
|
93
|
+
loadMs: Math.max(0, Number(page.waits?.loadMs) || 0),
|
|
94
|
+
settleMs: Math.max(0, Number(page.waits?.settleMs) || 0),
|
|
95
|
+
},
|
|
96
|
+
}))
|
|
97
|
+
.sort((a, b) => b.expected.length - a.expected.length || a.id.localeCompare(b.id))
|
|
98
|
+
.slice(0, Math.max(1, Number(limit) || MAX_PAGES_DEFAULT));
|
|
99
|
+
return {
|
|
100
|
+
roles: [...new Set(asArray(roles).map((item) => String(item || '').trim()).filter(Boolean))],
|
|
101
|
+
pages: targets,
|
|
102
|
+
targets: targets.reduce((sum, page) => sum + page.expected.length, 0),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 默认只探测已有会话文件的角色;显式 --roles 可探测有账号(可登录)的角色。 */
|
|
107
|
+
export function probeRolesForAccounts(config, wanted = []) {
|
|
108
|
+
const accounts = accountsForExecution(config);
|
|
109
|
+
const roles = new Map();
|
|
110
|
+
for (const account of accounts) {
|
|
111
|
+
for (const role of account.roles || []) {
|
|
112
|
+
if (!roles.has(role)) roles.set(role, []);
|
|
113
|
+
roles.get(role).push(account);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const requested = asArray(wanted).map((item) => String(item || '').trim()).filter(Boolean);
|
|
117
|
+
const list = requested.length ? requested : [...roles.keys()].filter((role) => (roles.get(role) || []).some((account) => account.sessionReady));
|
|
118
|
+
return list
|
|
119
|
+
.map((role) => {
|
|
120
|
+
const matched = roles.get(role) || [];
|
|
121
|
+
// 角色权限必须尽量由只承担该角色的账号探测;同一账号兼任多角色时,
|
|
122
|
+
// 看到的是角色并集,不能代表单个角色。
|
|
123
|
+
const single = matched.filter((item) => (item.roles || []).length === 1);
|
|
124
|
+
const account = single.find((item) => item.sessionReady)
|
|
125
|
+
|| single[0]
|
|
126
|
+
|| matched.find((item) => item.sessionReady)
|
|
127
|
+
|| matched[0]
|
|
128
|
+
|| null;
|
|
129
|
+
return {
|
|
130
|
+
role,
|
|
131
|
+
account: account ? { id: account.id, username: account.username, roles: account.roles, sessionReady: Boolean(account.sessionReady) } : null,
|
|
132
|
+
accountCount: matched.length,
|
|
133
|
+
singleRole: account ? (account.roles || []).length === 1 : false,
|
|
134
|
+
};
|
|
135
|
+
})
|
|
136
|
+
.filter((entry) => entry.account);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function stateFileFor(config, account) {
|
|
140
|
+
const active = accountConfigFor(config, account);
|
|
141
|
+
return active.paths?.stateFile || '';
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function copyStateForProbe(config, account, runId) {
|
|
145
|
+
const source = stateFileFor(config, account);
|
|
146
|
+
if (!source || !fs.existsSync(source)) return '';
|
|
147
|
+
const stateDir = ensureDir(path.join(config.paths.uitestDir, 'studio', 'state'));
|
|
148
|
+
const target = path.join(stateDir, 'permission-probe-' + runId + '-' + slug(account.id) + '.json');
|
|
149
|
+
fs.copyFileSync(source, target);
|
|
150
|
+
return target;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function waitForLoginForm(session, timeoutMs = 15000) {
|
|
154
|
+
const started = Date.now();
|
|
155
|
+
while (Date.now() - started < timeoutMs) {
|
|
156
|
+
const ready = await session.page.evaluate(() => {
|
|
157
|
+
const button = [...document.querySelectorAll('button, input[type="button"], input[type="submit"]')]
|
|
158
|
+
.some((el) => /^\s*登录\s*$/.test((el.innerText || el.value || '').trim()) && el.getBoundingClientRect().width > 0);
|
|
159
|
+
const password = [...document.querySelectorAll('input[type="password"]')]
|
|
160
|
+
.some((el) => el.getBoundingClientRect().width > 0);
|
|
161
|
+
return button && password;
|
|
162
|
+
}).catch(() => false);
|
|
163
|
+
if (ready) return true;
|
|
164
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
165
|
+
}
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function readObservation(session) {
|
|
170
|
+
return session.page.evaluate(PROBE_OBSERVE_SCRIPT);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function normalizeHeaderName(value) {
|
|
174
|
+
return String(value ?? '')
|
|
175
|
+
.replace(/[↑↓]/g, '')
|
|
176
|
+
.replace(/(?:升序|降序)$/g, '')
|
|
177
|
+
.replace(/\s+/g, ' ')
|
|
178
|
+
.trim();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function headerHit(observed, target = {}) {
|
|
182
|
+
const headers = asArray(observed?.headers).map(normalizeHeaderName).filter(Boolean);
|
|
183
|
+
const known = asArray(target?.headers).map(normalizeHeaderName).filter(Boolean);
|
|
184
|
+
if (!known.length) return headers.length > 0;
|
|
185
|
+
return known.some((header) => headers.some((item) => item === header || item.includes(header) || header.includes(item)));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 就绪判据:已知表头的页面必须等到表头,不能凭壳层按钮或正文提前放行;
|
|
190
|
+
* 没有表头知识的页面等正文 ≥500 字,避免把门户空壳当成业务页面。
|
|
191
|
+
*/
|
|
192
|
+
function pageReady(observed, target = {}) {
|
|
193
|
+
if (asArray(target?.headers).length) return headerHit(observed, target);
|
|
194
|
+
return asArray(observed?.headers).length > 0 || (Number(observed?.textLength) || 0) >= 500;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function pageUsable(observed, target = {}) {
|
|
198
|
+
if (asArray(target?.headers).length) return headerHit(observed, target);
|
|
199
|
+
return asArray(observed?.headers).length > 0 || (Number(observed?.textLength) || 0) >= 500;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** PAGE 型路由首屏先渲染门户壳,自定义应用经外框加载;没有 waits 知识时也要给足首屏预算。 */
|
|
203
|
+
function routeWaitFloor(url) {
|
|
204
|
+
const text = String(url || '');
|
|
205
|
+
if (/\/PAGE\//i.test(text)) return 20000;
|
|
206
|
+
if (/\/(?:link|sp\/custom)\//i.test(text)) return 25000;
|
|
207
|
+
return 0;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** 页面预算:取页面知识与默认值中更稳妥的一档;稳定期最多 10s,避免整轮探测被个别页面拖死。 */
|
|
211
|
+
function pageBudget(target = {}, { contentMs = 0, settleMs = 0 } = {}) {
|
|
212
|
+
const waits = target?.waits || {};
|
|
213
|
+
return {
|
|
214
|
+
contentMs: Math.max(Number(contentMs) || 0, Number(waits.loadMs) || 0, routeWaitFloor(target?.url)),
|
|
215
|
+
settleMs: Math.min(Math.max(Number(settleMs) || 0, Number(waits.settleMs) || 0), 10000),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 最终落点校验:登录页、门户首页或其他页面都不是目标页,不能按目标页写权限结论。 */
|
|
220
|
+
function landingProblem(targetUrl, observedUrl) {
|
|
221
|
+
let target = null;
|
|
222
|
+
let observed = null;
|
|
223
|
+
try {
|
|
224
|
+
target = new URL(targetUrl);
|
|
225
|
+
observed = new URL(observedUrl);
|
|
226
|
+
} catch {
|
|
227
|
+
return '';
|
|
228
|
+
}
|
|
229
|
+
if (target.host && observed.host && target.host !== observed.host) return '跳转到其他站点 ' + observed.host;
|
|
230
|
+
const path = observed.pathname || '/';
|
|
231
|
+
if (/\/login(?:[?#/]|$)/i.test(path)) return '跳转到登录页';
|
|
232
|
+
if (path === '/' && target.pathname !== '/') return '跳转到门户首页';
|
|
233
|
+
if (target.pathname && path !== target.pathname) {
|
|
234
|
+
const segments = target.pathname.split('/').filter(Boolean);
|
|
235
|
+
const stable = segments.filter((segment) => /\d{8,}/.test(segment)).pop() || segments[segments.length - 1] || '';
|
|
236
|
+
if (!stable || !path.includes(stable)) return '跳转到其他页面 ' + path;
|
|
237
|
+
}
|
|
238
|
+
return '';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function observePage(session, url, {
|
|
242
|
+
navigationMs,
|
|
243
|
+
settleMs = 2500,
|
|
244
|
+
contentMs = 12000,
|
|
245
|
+
login = browserLogin,
|
|
246
|
+
target = {},
|
|
247
|
+
} = {}) {
|
|
248
|
+
await session.page.goto(url, { waitUntil: 'domcontentloaded', timeout: navigationMs });
|
|
249
|
+
const firstUrl = session.page.url();
|
|
250
|
+
if (/\/login(?:[?#/]|$)/i.test(firstUrl)) await waitForLoginForm(session);
|
|
251
|
+
await login(session, { logger: null });
|
|
252
|
+
if (/\/login(?:[?#/]|$)/i.test(firstUrl) || /\/login(?:[?#/]|$)/i.test(session.page.url())) {
|
|
253
|
+
await session.page.goto(url, { waitUntil: 'domcontentloaded', timeout: navigationMs });
|
|
254
|
+
}
|
|
255
|
+
// 低代码页面先出壳再懒加载正文;正文/表头都没出现就继续等,避免把空壳记成权限结论。
|
|
256
|
+
let observed = await readObservation(session);
|
|
257
|
+
const started = Date.now();
|
|
258
|
+
while (contentMs > 0 && Date.now() - started < contentMs && !pageReady(observed, target)) {
|
|
259
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
260
|
+
observed = await readObservation(session);
|
|
261
|
+
}
|
|
262
|
+
if (settleMs > 0) await new Promise((resolve) => setTimeout(resolve, settleMs));
|
|
263
|
+
observed = await readObservation(session);
|
|
264
|
+
const observedUrl = String(observed?.url || session.page.url() || url);
|
|
265
|
+
return {
|
|
266
|
+
url: observedUrl,
|
|
267
|
+
title: String(observed?.title || ''),
|
|
268
|
+
textLength: Number(observed?.textLength) || 0,
|
|
269
|
+
buttons: asArray(observed?.buttons).map((item) => String(item)).slice(0, 300),
|
|
270
|
+
headers: asArray(observed?.headers).map((item) => String(item)).slice(0, 200),
|
|
271
|
+
accessible: (Number(observed?.textLength) || 0) > 40,
|
|
272
|
+
landingProblem: landingProblem(url, observedUrl),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 逐角色打开页面并采集可见按钮。`deps.launch` / `deps.login` 可注入,便于单测;
|
|
278
|
+
* 返回的账号信息只含用户名与角色,不含密码。
|
|
279
|
+
*/
|
|
280
|
+
export async function probeRolePermissions(config, plan, {
|
|
281
|
+
accounts = null,
|
|
282
|
+
roleAccountIds = {},
|
|
283
|
+
headless = true,
|
|
284
|
+
logger = null,
|
|
285
|
+
navigationMs = 45000,
|
|
286
|
+
settleMs = 2500,
|
|
287
|
+
contentMs = 12000,
|
|
288
|
+
launch = launchSession,
|
|
289
|
+
login = browserLogin,
|
|
290
|
+
at = nowIso(),
|
|
291
|
+
runId = '',
|
|
292
|
+
} = {}) {
|
|
293
|
+
const log = logger || createLogger({ quiet: true });
|
|
294
|
+
const accountList = accounts || accountsForExecution(config);
|
|
295
|
+
const id = runId || at.replace(/[:.]/g, '-');
|
|
296
|
+
const results = [];
|
|
297
|
+
const facts = [];
|
|
298
|
+
const warnings = [];
|
|
299
|
+
for (const target of plan.pages || []) {
|
|
300
|
+
if (!target?.url) warnings.push('页面缺少 URL:' + (target?.id || ''));
|
|
301
|
+
}
|
|
302
|
+
for (const role of plan.roles || []) {
|
|
303
|
+
const preferredId = String(roleAccountIds?.[role] || '');
|
|
304
|
+
const account = (preferredId && accountList.find((item) => String(item.id) === preferredId || String(item.username) === preferredId))
|
|
305
|
+
|| selectAccountForRole(config, role, { accounts: accountList });
|
|
306
|
+
if (!account) {
|
|
307
|
+
results.push({ role, account: null, pages: [], error: '没有匹配角色的测试账号' });
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
const stateCopy = copyStateForProbe(config, account, id);
|
|
311
|
+
const active = accountConfigFor(config, account);
|
|
312
|
+
const profileDir = ensureDir(path.join(config.paths.uitestDir, 'profiles', 'permission-probe', slug(id), slug(account.id)));
|
|
313
|
+
const sessionConfig = {
|
|
314
|
+
...active,
|
|
315
|
+
browser: { ...(active.browser || {}), profile: profileDir },
|
|
316
|
+
paths: { ...(active.paths || {}), ...(stateCopy ? { stateFile: stateCopy } : {}) },
|
|
317
|
+
};
|
|
318
|
+
let session = null;
|
|
319
|
+
const roleResult = {
|
|
320
|
+
role,
|
|
321
|
+
account: { id: account.id, username: account.username, sessionReady: Boolean(account.sessionReady) },
|
|
322
|
+
pages: [],
|
|
323
|
+
error: '',
|
|
324
|
+
};
|
|
325
|
+
try {
|
|
326
|
+
session = await launch(sessionConfig, {
|
|
327
|
+
headless,
|
|
328
|
+
logger: log,
|
|
329
|
+
sessionName: 'uitest-permission-' + slug(id) + '-' + slug(account.id),
|
|
330
|
+
});
|
|
331
|
+
const observations = [];
|
|
332
|
+
for (const target of plan.pages || []) {
|
|
333
|
+
try {
|
|
334
|
+
const targetUrl = resolveUrl(config, target.url);
|
|
335
|
+
const budget = pageBudget(target, { contentMs, settleMs });
|
|
336
|
+
const observed = await observePage(session, targetUrl, { navigationMs, ...budget, login, target });
|
|
337
|
+
if (observed.landingProblem) {
|
|
338
|
+
observations.push({ target, observed, error: observed.landingProblem });
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
// 行链接/计数标签会被当作可见按钮;正典只留可复用的按钮名。
|
|
342
|
+
const visible = [...new Set(observed.buttons.map(canonicalButtonName).filter(Boolean))];
|
|
343
|
+
observations.push({ target, observed, visible });
|
|
344
|
+
} catch (error) {
|
|
345
|
+
const message = String(error?.message || error);
|
|
346
|
+
observations.push({ target, error: message });
|
|
347
|
+
// 登录失败时继续下一页只会反复撞锁,直接结束该角色。
|
|
348
|
+
if (/登录(?:失败|页找不到)/.test(message)) {
|
|
349
|
+
roleResult.error = message;
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// 每个页面都出现的按钮属于壳层(系统切换、账号菜单),不是页面权限。
|
|
355
|
+
const frequency = new Map();
|
|
356
|
+
for (const item of observations) {
|
|
357
|
+
for (const button of item.visible || []) frequency.set(button, (frequency.get(button) || 0) + 1);
|
|
358
|
+
}
|
|
359
|
+
const chromeThreshold = Math.max(3, Math.ceil(observations.length * 0.8));
|
|
360
|
+
for (const item of observations) {
|
|
361
|
+
if (item.error) {
|
|
362
|
+
roleResult.pages.push({ id: item.target.id, title: item.target.title, error: item.error });
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
const reliable = pageUsable(item.observed, item.target);
|
|
366
|
+
if (!reliable) {
|
|
367
|
+
// 空壳页面既不能证明“可见”,也不能证明“不可见”,留作未探测缺口。
|
|
368
|
+
roleResult.pages.push({
|
|
369
|
+
id: item.target.id,
|
|
370
|
+
title: item.target.title,
|
|
371
|
+
error: '页面未加载(未出现已知表头,正文/按钮不足)',
|
|
372
|
+
accessible: false,
|
|
373
|
+
textLength: item.observed.textLength,
|
|
374
|
+
headers: item.observed.headers,
|
|
375
|
+
});
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const expected = new Set(item.target.expected);
|
|
379
|
+
const visible = item.visible.filter((button) => expected.has(button) || (frequency.get(button) || 0) < chromeThreshold);
|
|
380
|
+
const pageFacts = probePermissionCandidates({
|
|
381
|
+
role,
|
|
382
|
+
page: item.target.id,
|
|
383
|
+
url: item.observed.url,
|
|
384
|
+
buttons: visible,
|
|
385
|
+
expected: item.target.expected,
|
|
386
|
+
at,
|
|
387
|
+
});
|
|
388
|
+
facts.push(...pageFacts);
|
|
389
|
+
roleResult.pages.push({
|
|
390
|
+
id: item.target.id,
|
|
391
|
+
title: item.target.title,
|
|
392
|
+
expected: item.target.expected,
|
|
393
|
+
visible,
|
|
394
|
+
missing: item.target.expected.filter((button) => !visible.includes(button)),
|
|
395
|
+
headers: item.observed.headers,
|
|
396
|
+
accessible: item.observed.accessible,
|
|
397
|
+
textLength: item.observed.textLength,
|
|
398
|
+
factCount: pageFacts.length,
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
} catch (error) {
|
|
402
|
+
roleResult.error = String(error?.message || error);
|
|
403
|
+
} finally {
|
|
404
|
+
if (session) await session.close().catch(() => {});
|
|
405
|
+
if (stateCopy) {
|
|
406
|
+
try { fs.rmSync(stateCopy, { force: true }); } catch { /* ignore */ }
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
results.push(roleResult);
|
|
410
|
+
}
|
|
411
|
+
return { at, roles: results, facts, warnings };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** 探测事实并入本地事实库:与已有事实一起按稳定键归并,冲突保留待人工裁决。 */
|
|
415
|
+
export function applyProbeFacts(config, probe, { at = '' } = {}) {
|
|
416
|
+
const existing = loadFacts(config);
|
|
417
|
+
// 探测覆盖范围用于收口旧结论:成功观察但没再出现的按钮按未观察到累计,
|
|
418
|
+
// 没能落到目标页(登录页/门户/空壳)的旧结论直接标为不可验证。
|
|
419
|
+
const scopeRoles = {};
|
|
420
|
+
for (const entry of asArray(probe?.roles)) {
|
|
421
|
+
if (!entry?.role) continue;
|
|
422
|
+
const pages = asArray(entry.pages).map((page) => String(page?.id || '')).filter(Boolean);
|
|
423
|
+
const invalid = asArray(entry.pages).filter((page) => page?.error).map((page) => String(page.id || '')).filter(Boolean);
|
|
424
|
+
scopeRoles[entry.role] = { pages: [...new Set(pages)], invalid: [...new Set(invalid)] };
|
|
425
|
+
}
|
|
426
|
+
// 探测只覆盖少量事实键:未出现的事实保持原状,不累计 stale misses;
|
|
427
|
+
// 既有候选继续留在 candidates.jsonl 里,供下一轮完整整理使用。
|
|
428
|
+
const plan = planFactConsolidation({
|
|
429
|
+
candidates: probe.facts,
|
|
430
|
+
existingFacts: existing.facts,
|
|
431
|
+
now: at || probe.at || nowIso(),
|
|
432
|
+
partial: true,
|
|
433
|
+
// 本次探测覆盖到的键以最新观察为准:旧探测的相反结论不再作为永久冲突保留。
|
|
434
|
+
supersedeProbe: true,
|
|
435
|
+
probeScope: { roles: scopeRoles },
|
|
436
|
+
});
|
|
437
|
+
const result = applyFactConsolidation(config, plan, { preserveCandidates: true });
|
|
438
|
+
return { ...result, factStats: plan.stats, factErrors: plan.errors };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** 把一次探测结果留档,便于复核;探测结果本身不进正典。 */
|
|
442
|
+
export function saveProbeRun(config, probe) {
|
|
443
|
+
const dir = ensureDir(path.join(knowledgeDir(config), '.archive', 'probe-' + String(probe.at || nowIso()).replace(/[:.]/g, '-')));
|
|
444
|
+
const file = path.join(dir, 'permission-probe.json');
|
|
445
|
+
writeJsonFile(file, probe);
|
|
446
|
+
return file;
|
|
447
|
+
}
|