bpmax-cli 0.2.1-beta.6 → 0.2.1-beta.61
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 +20 -7
- package/dist/bin.js +38862 -12421
- package/dist/bin.js.map +1 -1
- package/package.json +10 -5
- package/scripts/install-skills.mjs +27 -60
- package/scripts/run-source-cli.mjs +145 -0
- package/skills/bpmax-ai-taskbook/SKILL.md +12 -0
- package/skills/bpmax-ai-taskbook/references/blueprint-taskbook-gates.md +120 -0
- package/skills/bpmax-ai-taskbook/references/taskbook-template.md +41 -1
- package/skills/bpmax-api-platform-editor/SKILL.md +24 -31
- package/skills/bpmax-api-platform-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-api-platform-editor/references/platform-api-map.md +2 -2
- package/skills/bpmax-api-platform-editor/references/runtime-workflow.md +3 -3
- package/skills/bpmax-approval-matrix/SKILL.md +54 -2
- package/skills/bpmax-blueprint-doc-workflow/SKILL.md +15 -2
- package/skills/bpmax-blueprint-doc-workflow/references/blueprint-structure.md +8 -0
- package/skills/bpmax-blueprint-doc-workflow/references/per-flow-required-structure.md +13 -0
- package/skills/bpmax-blueprint-doc-workflow/references/sample-missing-modeling-review.xml +23 -0
- package/skills/bpmax-blueprint-doc-workflow/references/sample-paragraph-flow-details.xml +27 -0
- package/skills/bpmax-blueprint-doc-workflow/references/sample-pass.xml +45 -28
- package/skills/bpmax-blueprint-doc-workflow/references/source-traceability-and-flow-modeling.md +115 -0
- package/skills/bpmax-blueprint-doc-workflow/scripts/lint_blueprint_doc.py +386 -5
- package/skills/bpmax-bug-reporting/SKILL.md +72 -0
- package/skills/bpmax-builder-shared/SKILL.md +1 -0
- package/skills/bpmax-builder-shared/configuration-impact-review.md +76 -0
- package/skills/bpmax-builder-shared/template_script_hard_rules.py +3 -1
- package/skills/bpmax-builder-shared/tests/test_template_script_hard_rules.py +16 -0
- package/skills/bpmax-business-skill/SKILL.md +3 -1
- package/skills/bpmax-cli/SKILL.md +44 -0
- package/skills/bpmax-config-latest/SKILL.md +4 -0
- package/skills/bpmax-console-template-editor/SKILL.md +113 -523
- package/skills/bpmax-console-template-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-console-template-editor/references/full-detail-guide.md +45 -0
- package/skills/bpmax-console-template-editor/references/local-temp-workflow.md +13 -12
- package/skills/bpmax-console-template-editor/scripts/console_template_editor_common.py +299 -78
- package/skills/bpmax-console-template-editor/tests/test_console_template_editor.py +344 -30
- package/skills/bpmax-dataset-field-template-editor/SKILL.md +131 -594
- package/skills/bpmax-dataset-field-template-editor/references/full-detail-guide.md +570 -0
- package/skills/bpmax-dataset-field-template-editor/references/nested-field-patterns.md +8 -8
- package/skills/bpmax-dataset-field-template-editor/references/runtime-verified-field-page-shape.md +1 -1
- package/skills/bpmax-dataset-field-template-editor/scripts/dataset_field_editor_common.py +11 -77
- package/skills/bpmax-dataset-field-template-editor/scripts/export_dataset_field.py +4 -57
- package/skills/bpmax-dataset-field-template-editor/scripts/init_create_dataset_field.py +2 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/inspect_dataset_field_runtime.py +4 -78
- package/skills/bpmax-dataset-field-template-editor/scripts/submit_dataset_field.py +3 -89
- package/skills/bpmax-dataset-field-template-editor/tests/test_dataset_field_editor.py +14 -0
- package/skills/bpmax-dataset-field-template-editor/tests/test_init_create_dataset_field.py +2 -0
- package/skills/bpmax-dataset-template-editor/SKILL.md +123 -778
- package/skills/bpmax-dataset-template-editor/references/dataset-script-runtime-matrix.md +11 -0
- package/skills/bpmax-dataset-template-editor/references/full-detail-guide.md +753 -0
- package/skills/bpmax-dataset-template-editor/references/runtime-gotchas.md +12 -0
- package/skills/bpmax-dataset-template-editor/references/ui-to-backend-field-map.md +1 -0
- package/skills/bpmax-dataset-template-editor/references/work-file-to-submit-mapping.md +2 -2
- package/skills/bpmax-dataset-template-editor/scripts/basic_table_audit.py +8 -1
- package/skills/bpmax-dataset-template-editor/scripts/dataset_editor_common.py +9 -90
- package/skills/bpmax-dataset-template-editor/scripts/export_dataset.py +8 -1
- package/skills/bpmax-dataset-template-editor/scripts/resolve_dataset.py +8 -1
- package/skills/bpmax-dataset-template-editor/scripts/submit_dataset.py +1 -2
- package/skills/bpmax-dataset-template-editor/scripts/verify_dataset_list.py +8 -1
- package/skills/bpmax-dataset-template-editor/scripts/verify_publish_health.py +8 -1
- package/skills/bpmax-dataset-template-editor/tests/test_dataset_editor.py +6 -40
- package/skills/bpmax-e2e-flow-config-orchestrator/SKILL.md +18 -4
- package/skills/bpmax-e2e-flow-config-orchestrator/agents/openai.yaml +2 -2
- package/skills/bpmax-e2e-flow-config-orchestrator/references/orchestration-matrix.md +13 -9
- package/skills/bpmax-e2e-flow-test-operator/SKILL.md +173 -546
- package/skills/bpmax-e2e-flow-test-operator/agents/openai.yaml +2 -3
- package/skills/bpmax-e2e-flow-test-operator/references/ai-test-suite.md +181 -15
- package/skills/bpmax-e2e-flow-test-operator/references/browser-action-dsl.md +166 -0
- package/skills/bpmax-e2e-flow-test-operator/references/browser-only-checkpoints.md +15 -7
- package/skills/bpmax-e2e-flow-test-operator/references/full-detail-guide.md +589 -0
- package/skills/bpmax-e2e-flow-test-operator/references/minimal-test-loop.md +12 -8
- package/skills/bpmax-e2e-flow-test-operator/references/negative-sale-api-matrix.md +4 -4
- package/skills/bpmax-e2e-flow-test-operator/references/profile-schema.md +1 -1
- package/skills/bpmax-e2e-flow-test-operator/references/state-schema.md +3 -1
- package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_doc.py +7 -5
- package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_state.py +2 -2
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_runner.py +5 -1
- package/skills/bpmax-e2e-flow-test-operator/tests/test_negative_sale_api_tools.py +71 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/SKILL.md +64 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/agents/openai.yaml +7 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/automation-generation-pipeline.md +33 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/autonomous-execution.md +40 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/batch-generation-and-execution.md +17 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/browser-action-runner.md +19 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/browser-recording-and-replay.md +95 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/form-script-generation.md +41 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/identity-and-failure-routing.md +90 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/multi-request-mutation.md +9 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/scenario-coverage-generation.md +17 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/scoped-execution.md +13 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/step-restartability-and-state.md +23 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/test-assets-and-evidence.md +9 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/test-data-and-selector-contract.md +51 -0
- package/skills/bpmax-e2e-flow-test-operator-v2/references/test-preflight-and-confirmation.md +32 -0
- package/skills/bpmax-filter-template-editor/SKILL.md +114 -551
- package/skills/bpmax-filter-template-editor/references/experience-coverage-matrix.md +18 -18
- package/skills/bpmax-filter-template-editor/references/filter-content-schema.md +21 -0
- package/skills/bpmax-filter-template-editor/references/filter-request-shape.md +29 -26
- package/skills/bpmax-filter-template-editor/references/filter-runtime-patterns.md +19 -2
- package/skills/bpmax-filter-template-editor/references/full-detail-guide.md +56 -0
- package/skills/bpmax-filter-template-editor/references/runtime-verified-filter-page-shape.md +10 -9
- package/skills/bpmax-filter-template-editor/scripts/filter_template_editor_common.py +7 -57
- package/skills/bpmax-filter-template-editor/tests/test_filter_template_editor.py +4 -48
- package/skills/bpmax-flow/SKILL.md +2 -0
- package/skills/bpmax-flow-detail-template-editor/SKILL.md +53 -0
- package/skills/bpmax-flow-template-editor/SKILL.md +122 -1084
- package/skills/bpmax-flow-template-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-flow-template-editor/references/diff-strategy.md +3 -3
- package/skills/bpmax-flow-template-editor/references/editor-runtime-vs-draft.md +9 -9
- package/skills/bpmax-flow-template-editor/references/flow-template-api-workflow.md +2 -1
- package/skills/bpmax-flow-template-editor/references/full-detail-guide.md +1157 -0
- package/skills/bpmax-flow-template-editor/references/local-temp-workflow.md +1 -1
- package/skills/bpmax-flow-template-editor/references/project-create-runtime-gotchas.md +17 -0
- package/skills/bpmax-flow-template-editor/references/requirement-to-node-mapping.md +8 -3
- package/skills/bpmax-flow-template-editor/references/runtime-verified-flow-detail-shape.md +7 -7
- package/skills/bpmax-flow-template-editor/references/runtime-verified-meta-fields.md +2 -2
- package/skills/bpmax-flow-template-editor/references/runtime-verified-node-fields.md +12 -2
- package/skills/bpmax-flow-template-editor/references/save-draft-request-shape.md +7 -23
- package/skills/bpmax-flow-template-editor/references/work-file-to-submit-mapping.md +1 -1
- package/skills/bpmax-flow-template-editor/tests/test_flow_template_editor.py +19 -75
- package/skills/bpmax-form-template-editor/SKILL.md +137 -1133
- package/skills/bpmax-form-template-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-form-template-editor/references/dynamic-field-state.md +167 -0
- package/skills/bpmax-form-template-editor/references/form-template-api-workflow.md +51 -51
- package/skills/bpmax-form-template-editor/references/full-detail-guide.md +1115 -0
- package/skills/bpmax-form-template-editor/references/local-temp-workflow.md +4 -4
- package/skills/bpmax-form-template-editor/references/payload-checklist.md +3 -1
- package/skills/bpmax-form-template-editor/references/sub-form-patterns.md +6 -0
- package/skills/bpmax-form-template-editor/scripts/form_template_editor_common.py +8 -0
- package/skills/bpmax-form-template-editor/tests/test_form_template_editor.py +42 -19
- package/skills/bpmax-functional-test-design/LICENSE.upstream +24 -0
- package/skills/bpmax-functional-test-design/SKILL.md +80 -0
- package/skills/bpmax-functional-test-design/agents/openai.yaml +4 -0
- package/skills/bpmax-functional-test-design/references/bpmax-test-suite-output.md +95 -0
- package/skills/bpmax-functional-test-design/references/decision-table-testing.md +50 -0
- package/skills/bpmax-functional-test-design/references/domain-testing.md +43 -0
- package/skills/bpmax-functional-test-design/references/state-transition-testing.md +47 -0
- package/skills/bpmax-functional-test-design/references/technique-selection.md +38 -0
- package/skills/bpmax-functional-test-design/references/use-case-testing.md +55 -0
- package/skills/bpmax-group-model-editor/SKILL.md +24 -0
- package/skills/bpmax-icon-catalog/SKILL.md +18 -0
- package/skills/bpmax-icon-catalog/agents/openai.yaml +4 -0
- package/skills/bpmax-icon-catalog/assets/ri-icons.json +3140 -0
- package/skills/bpmax-icon-catalog/references/source-contract.md +3 -0
- package/skills/bpmax-list-template-editor/SKILL.md +120 -466
- package/skills/bpmax-list-template-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-list-template-editor/references/content-config-shape.md +16 -4
- package/skills/bpmax-list-template-editor/references/full-detail-guide.md +458 -0
- package/skills/bpmax-list-template-editor/references/list-template-api-workflow.md +6 -9
- package/skills/bpmax-list-template-editor/references/local-temp-workflow.md +1 -1
- package/skills/bpmax-list-template-editor/references/special-formats.md +5 -2
- package/skills/bpmax-list-template-editor/scripts/list_template_editor_common.py +9 -78
- package/skills/bpmax-memory-protocol/SKILL.md +7 -6
- package/skills/bpmax-nav-config-editor/SKILL.md +14 -17
- package/skills/bpmax-nav-config-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-nav-config-editor/references/api-workflow.md +2 -2
- package/skills/bpmax-nav-config-editor/references/runtime-probing.md +11 -12
- package/skills/bpmax-plugin-config/SKILL.md +55 -5
- package/skills/bpmax-project/SKILL.md +37 -1
- package/skills/bpmax-project-detail-template-editor/SKILL.md +13 -39
- package/skills/bpmax-project-detail-template-editor/agents/openai.yaml +2 -2
- package/skills/bpmax-role-editor/SKILL.md +7 -30
- package/skills/bpmax-shared/SKILL.md +19 -9
- package/skills/bpmax-team-editor/SKILL.md +27 -0
- package/skills/bpmax-ui-ux-audit/LICENSE.upstream +23 -0
- package/skills/bpmax-ui-ux-audit/SKILL.md +42 -0
- package/skills/bpmax-ui-ux-audit/agents/openai.yaml +4 -0
- package/skills/bpmax-ui-ux-audit/references/audit-framework.md +39 -0
- package/skills/bpmax-ui-ux-audit/references/bpmax-ux-findings.md +56 -0
- package/skills/bpmax-user/SKILL.md +33 -1
- package/skills/bpmax-user-mock-operator/SKILL.md +58 -56
- package/skills/bpmax-user-mock-operator/agents/openai.yaml +2 -2
- package/skills/bpmax-user-mock-operator/scripts/chrome_identity_bridge.mjs +1248 -0
- package/skills/bpmax-user-model-editor/SKILL.md +24 -0
- package/skills/bpmax-workspace-editor/SKILL.md +1 -0
- package/skills/form-control-library/references/form-template-submit-schema.md +1 -1
- package/skills/bpmax-user-mock-operator/scripts/switch_user_identity.py +0 -37
- package/skills/bpmax-user-mock-operator/scripts/user_mock_operator_common.py +0 -136
- package/skills/bpmax-user-mock-operator/tests/test_user_mock_operator.py +0 -138
|
@@ -0,0 +1,1248 @@
|
|
|
1
|
+
import { chmod, lstat, readFile, realpath, rename, unlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
const REQUEST_KIND = 'bpmax_identity_browser_request';
|
|
5
|
+
const RESULT_KIND = 'bpmax_identity_browser_result';
|
|
6
|
+
const REVEAL_MOCK_ACTION = 'bpmaxzuibang';
|
|
7
|
+
const TARGET_SEARCH_ATTEMPTS = 3;
|
|
8
|
+
const TARGET_SEARCH_TIMEOUT_MS = 10_000;
|
|
9
|
+
const ROUTE_READY_TIMEOUT_MS = 120_000;
|
|
10
|
+
const IDENTITY_READBACK_ATTEMPTS = 2;
|
|
11
|
+
const LEASE_LOCK_STALE_MS = 5 * 60 * 1000;
|
|
12
|
+
const LEASE_LOCK_ATTEMPTS = 100;
|
|
13
|
+
|
|
14
|
+
function isRecord(value) {
|
|
15
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function pathInside(parent, child) {
|
|
19
|
+
const relative = path.relative(parent, child);
|
|
20
|
+
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function lstatOptional(file) {
|
|
24
|
+
try {
|
|
25
|
+
return await lstat(file);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error?.code === 'ENOENT') return null;
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function assertRegularFileOrMissing(file, label, { mustBeMissing = false } = {}) {
|
|
33
|
+
const info = await lstatOptional(file);
|
|
34
|
+
if (!info) return;
|
|
35
|
+
if (info.isSymbolicLink() || !info.isFile()) throw new Error(`identity_${label}_unsafe`);
|
|
36
|
+
if (mustBeMissing) throw new Error(`identity_${label}_already_exists`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function validateOutputPaths(request, requestFile) {
|
|
40
|
+
const requestPath = path.resolve(requestFile);
|
|
41
|
+
const runDir = await realpath(path.resolve(request.run_dir));
|
|
42
|
+
const evidenceDir = await realpath(path.resolve(request.evidence_dir));
|
|
43
|
+
const requestInfo = await lstat(requestPath);
|
|
44
|
+
if (requestInfo.isSymbolicLink() || !requestInfo.isFile()) throw new Error('identity_request_unsafe');
|
|
45
|
+
const realRequest = await realpath(requestPath);
|
|
46
|
+
const resultPath = path.resolve(request.result_path);
|
|
47
|
+
const screenshotPath = path.resolve(request.screenshot_path);
|
|
48
|
+
const leasePath = path.resolve(request.lease.lease_file);
|
|
49
|
+
const [resultParent, screenshotParent, leaseParent] = await Promise.all([
|
|
50
|
+
realpath(path.dirname(resultPath)),
|
|
51
|
+
realpath(path.dirname(screenshotPath)),
|
|
52
|
+
realpath(path.dirname(leasePath)),
|
|
53
|
+
]);
|
|
54
|
+
if (!pathInside(runDir, evidenceDir)
|
|
55
|
+
|| !pathInside(evidenceDir, realRequest)
|
|
56
|
+
|| !pathInside(evidenceDir, resultParent)
|
|
57
|
+
|| !pathInside(runDir, screenshotParent)
|
|
58
|
+
|| !pathInside(runDir, leaseParent)) {
|
|
59
|
+
throw new Error('identity_output_scope_invalid');
|
|
60
|
+
}
|
|
61
|
+
await Promise.all([
|
|
62
|
+
assertRegularFileOrMissing(resultPath, 'result', { mustBeMissing: true }),
|
|
63
|
+
assertRegularFileOrMissing(screenshotPath, 'screenshot', { mustBeMissing: true }),
|
|
64
|
+
assertRegularFileOrMissing(leasePath, 'lease'),
|
|
65
|
+
]);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function writeJsonExclusive(file, value) {
|
|
69
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
|
|
70
|
+
await chmod(file, 0o600);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function writeJsonAtomic(file, value) {
|
|
74
|
+
await assertRegularFileOrMissing(file, 'lease');
|
|
75
|
+
const temp = `${file}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
76
|
+
try {
|
|
77
|
+
await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
|
|
78
|
+
await chmod(temp, 0o600);
|
|
79
|
+
await rename(temp, file);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
await unlink(temp).catch(() => undefined);
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function withLeaseLock(leaseFile, action) {
|
|
87
|
+
const lockFile = `${leaseFile}.lock`;
|
|
88
|
+
const owner = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
89
|
+
for (let attempt = 0; attempt < LEASE_LOCK_ATTEMPTS; attempt += 1) {
|
|
90
|
+
try {
|
|
91
|
+
await writeFile(lockFile, `${JSON.stringify({ owner, created_at: new Date().toISOString() })}\n`, {
|
|
92
|
+
encoding: 'utf8',
|
|
93
|
+
flag: 'wx',
|
|
94
|
+
mode: 0o600,
|
|
95
|
+
});
|
|
96
|
+
try {
|
|
97
|
+
return await action();
|
|
98
|
+
} finally {
|
|
99
|
+
try {
|
|
100
|
+
const current = JSON.parse(await readFile(lockFile, 'utf8'));
|
|
101
|
+
if (isRecord(current) && current.owner === owner) await unlink(lockFile);
|
|
102
|
+
} catch {
|
|
103
|
+
// Never remove a lock whose ownership cannot be proved.
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
108
|
+
const info = await lstatOptional(lockFile);
|
|
109
|
+
if (!info?.isFile() || info.isSymbolicLink()) throw new Error('identity_lease_lock_unsafe');
|
|
110
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
throw new Error('identity_lease_lock_timeout');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function assertLeaseTransitionCurrent(existing, request, { allowMissing = false } = {}) {
|
|
117
|
+
if (!isRecord(existing) || Object.keys(existing).length === 0) {
|
|
118
|
+
if (allowMissing) return;
|
|
119
|
+
throw new Error('identity_lease_changed');
|
|
120
|
+
}
|
|
121
|
+
if (allowMissing && existing.state === 'released') return;
|
|
122
|
+
if (existing.lease_id !== request.lease.lease_id
|
|
123
|
+
|| !['active', 'uncertain'].includes(existing.state)) {
|
|
124
|
+
throw new Error('identity_lease_changed');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function assertReleaseClaimAvailable(existing, request) {
|
|
129
|
+
const claimRequestId = String(existing.release_operation_request_id || '');
|
|
130
|
+
if (!claimRequestId || claimRequestId === request.request_id) return;
|
|
131
|
+
const claimTime = Date.parse(String(existing.mutation_intent_at || ''));
|
|
132
|
+
if (Number.isFinite(claimTime) && Date.now() - claimTime > LEASE_LOCK_STALE_MS) return;
|
|
133
|
+
throw new Error('identity_lease_recovery_in_progress');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function identityUiLabelCandidates() {
|
|
137
|
+
return {
|
|
138
|
+
simulation: ['模拟', 'Simulation', 'シミュレーション'],
|
|
139
|
+
exitSimulation: ['退出模拟', 'Exit Simulation', 'シミュレーションを終了'],
|
|
140
|
+
logout: ['退出登录', 'Log out', 'ログアウト'],
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function labelsFor(language) {
|
|
145
|
+
const preferred = String(language).toLowerCase().startsWith('en')
|
|
146
|
+
? 1
|
|
147
|
+
: /^(?:jap|ja)/i.test(String(language))
|
|
148
|
+
? 2
|
|
149
|
+
: 0;
|
|
150
|
+
const order = (values) => [values[preferred], ...values.filter((_, index) => index !== preferred)];
|
|
151
|
+
const candidates = identityUiLabelCandidates();
|
|
152
|
+
return {
|
|
153
|
+
simulation: order(candidates.simulation),
|
|
154
|
+
exitSimulation: order(candidates.exitSimulation),
|
|
155
|
+
logout: order(candidates.logout),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function mockStateFromGuideAction(count, label, labels) {
|
|
160
|
+
if (count > 1) throw new Error(`identity_exit_simulation_count_${count}`);
|
|
161
|
+
if (count === 0) return false;
|
|
162
|
+
if (labels.exitSimulation.includes(label)) return true;
|
|
163
|
+
if (labels.logout.includes(label)) return false;
|
|
164
|
+
throw new Error('identity_action_label_not_found');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function profileRouteUserId(value, returnUrl) {
|
|
168
|
+
const url = new URL(value);
|
|
169
|
+
const trusted = new URL(returnUrl);
|
|
170
|
+
if (url.origin !== trusted.origin) return null;
|
|
171
|
+
const workspaceMatch = trusted.pathname.match(/^\/w:([^/]+)(?:\/|$)/);
|
|
172
|
+
const allowedPaths = new Set(['/userProfileEditor', '/userProfileEditor/']);
|
|
173
|
+
if (workspaceMatch) {
|
|
174
|
+
allowedPaths.add(`/w:${workspaceMatch[1]}/userProfileEditor`);
|
|
175
|
+
allowedPaths.add(`/w:${workspaceMatch[1]}/userProfileEditor/`);
|
|
176
|
+
}
|
|
177
|
+
if (!allowedPaths.has(url.pathname)) return null;
|
|
178
|
+
const id = Number(url.searchParams.get('id'));
|
|
179
|
+
return Number.isSafeInteger(id) && id > 0 ? id : null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function validateRequest(value) {
|
|
183
|
+
if (!isRecord(value)
|
|
184
|
+
|| value.schema_version !== 1
|
|
185
|
+
|| value.kind !== REQUEST_KIND
|
|
186
|
+
|| value.transport !== 'chrome_control_ui'
|
|
187
|
+
|| !['status', 'mock', 'unmock'].includes(value.operation)
|
|
188
|
+
|| !value.request_id
|
|
189
|
+
|| !value.nonce
|
|
190
|
+
|| !value.origin
|
|
191
|
+
|| !value.return_url
|
|
192
|
+
|| !value.run_dir
|
|
193
|
+
|| !value.evidence_dir
|
|
194
|
+
|| !value.result_path
|
|
195
|
+
|| !value.screenshot_path
|
|
196
|
+
|| !isRecord(value.lease)
|
|
197
|
+
|| !value.lease.lease_file
|
|
198
|
+
|| value.screenshot_mime !== 'image/jpeg'
|
|
199
|
+
|| !String(value.screenshot_path).toLowerCase().endsWith('.jpg')
|
|
200
|
+
|| (value.operation === 'mock' && (!Number.isSafeInteger(Number(value.target_user_id)) || !String(value.target_user_name || '').trim()))
|
|
201
|
+
|| (value.operation === 'unmock' && !trustedOriginalIdentity(value.lease.expected_original_user, 'lease'))) {
|
|
202
|
+
throw new Error('identity_browser_request_invalid');
|
|
203
|
+
}
|
|
204
|
+
if (Date.parse(value.expires_at) <= Date.now()) throw new Error('identity_browser_request_expired');
|
|
205
|
+
const origin = new URL(value.origin).origin;
|
|
206
|
+
const workspace = String(value.workspace || '').trim();
|
|
207
|
+
const expectedReturnUrl = new URL(value.href_path, origin).toString();
|
|
208
|
+
const expectedManagementUrl = `${origin}/w:${encodeURIComponent(workspace)}/userManagement`;
|
|
209
|
+
const expectedActions = value.operation === 'status'
|
|
210
|
+
? ['read_current_identity']
|
|
211
|
+
: value.operation === 'mock'
|
|
212
|
+
? ['read_current_identity', 'filter_target_name', 'verify_exact_user_id', 'click_simulation', 'click_exit_simulation']
|
|
213
|
+
: ['read_current_identity', 'click_exit_simulation'];
|
|
214
|
+
if (value.origin !== origin
|
|
215
|
+
|| value.return_url !== expectedReturnUrl
|
|
216
|
+
|| value.user_management_url !== expectedManagementUrl) {
|
|
217
|
+
throw new Error('identity_browser_origin_mismatch');
|
|
218
|
+
}
|
|
219
|
+
if (!Array.isArray(value.allowed_ui_actions)
|
|
220
|
+
|| value.allowed_ui_actions.length !== expectedActions.length
|
|
221
|
+
|| value.allowed_ui_actions.some((item, index) => item !== expectedActions[index])) {
|
|
222
|
+
throw new Error('identity_browser_actions_mismatch');
|
|
223
|
+
}
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function normalizeIdentity(value, source = 'unknown') {
|
|
228
|
+
if (!isRecord(value)) return null;
|
|
229
|
+
const id = Number(value.id);
|
|
230
|
+
const organizationId = Number(value.organization_id);
|
|
231
|
+
const mockByUser = Number(isRecord(value.mock_by_user) ? value.mock_by_user.id : value.mock_by_user);
|
|
232
|
+
const hasPoints = Array.isArray(value.points);
|
|
233
|
+
const points = hasPoints ? value.points.map(String) : [];
|
|
234
|
+
const hasPermissionShape = value.can_mock === true || value.can_mock === false || typeof value.role_key === 'string' || hasPoints;
|
|
235
|
+
const canMock = value.can_mock === true || value.can_mock === false
|
|
236
|
+
? value.can_mock
|
|
237
|
+
: hasPermissionShape
|
|
238
|
+
? value.role_key === 'super' || points.includes('organization.admin') || points.includes('user.mock')
|
|
239
|
+
: null;
|
|
240
|
+
return {
|
|
241
|
+
id: Number.isSafeInteger(id) && id > 0 ? id : null,
|
|
242
|
+
name: typeof value.name === 'string' && value.name.trim() ? value.name.trim() : null,
|
|
243
|
+
organization_id: Number.isSafeInteger(organizationId) && organizationId > 0 ? organizationId : null,
|
|
244
|
+
mock: value.mock === true || Number(value.mock) === 1,
|
|
245
|
+
mock_by_user: Number.isSafeInteger(mockByUser) && mockByUser > 0 ? mockByUser : null,
|
|
246
|
+
can_mock: canMock,
|
|
247
|
+
source,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function trustedOriginalIdentity(value, source = 'unknown') {
|
|
252
|
+
if (!isRecord(value) || value.mock !== false) return null;
|
|
253
|
+
const identity = normalizeIdentity(value, source);
|
|
254
|
+
return identity?.id ? identity : null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function recoverOriginalIdentity({ originalUser = null, targetUser = null, before = null } = {}) {
|
|
258
|
+
const trusted = trustedOriginalIdentity(originalUser, 'lease')
|
|
259
|
+
|| trustedOriginalIdentity(before, before?.source || 'unknown');
|
|
260
|
+
if (trusted) return trusted;
|
|
261
|
+
for (const value of [targetUser, originalUser, before]) {
|
|
262
|
+
const identity = normalizeIdentity(value, value?.source || 'unknown');
|
|
263
|
+
if (!identity?.mock_by_user) continue;
|
|
264
|
+
return {
|
|
265
|
+
id: identity.mock_by_user,
|
|
266
|
+
name: null,
|
|
267
|
+
organization_id: identity.organization_id,
|
|
268
|
+
mock: false,
|
|
269
|
+
mock_by_user: null,
|
|
270
|
+
can_mock: null,
|
|
271
|
+
source: identity.source,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function unique(locator, label) {
|
|
278
|
+
const count = await locator.count();
|
|
279
|
+
if (count !== 1) throw new Error(`${label}_count_${count}`);
|
|
280
|
+
return locator;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function waitForUniqueVisible(locator, label, timeoutMs = 15_000) {
|
|
284
|
+
const deadline = Date.now() + timeoutMs;
|
|
285
|
+
let lastCount = 0;
|
|
286
|
+
while (Date.now() <= deadline) {
|
|
287
|
+
lastCount = await locator.count();
|
|
288
|
+
if (lastCount > 1) throw new Error(`${label}_count_${lastCount}`);
|
|
289
|
+
if (lastCount === 1) {
|
|
290
|
+
if (typeof locator.isVisible !== 'function' || await locator.isVisible()) return locator;
|
|
291
|
+
}
|
|
292
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
293
|
+
}
|
|
294
|
+
throw new Error(lastCount === 1 ? `${label}_not_visible` : `${label}_count_${lastCount}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function waitForUrl(tab, expectedUrl, label, timeoutMs = ROUTE_READY_TIMEOUT_MS) {
|
|
298
|
+
const deadline = Date.now() + timeoutMs;
|
|
299
|
+
const expected = new URL(expectedUrl).toString();
|
|
300
|
+
let current = await tab.url();
|
|
301
|
+
while (current !== expected && Date.now() <= deadline) {
|
|
302
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
303
|
+
current = await tab.url();
|
|
304
|
+
}
|
|
305
|
+
if (current !== expected) throw new Error(`${label}_url_mismatch`);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function navigateAndWait(tab, url, readySelector, label) {
|
|
309
|
+
const expected = new URL(url).toString();
|
|
310
|
+
if (await tab.url() !== expected) {
|
|
311
|
+
try {
|
|
312
|
+
await tab.goto(expected);
|
|
313
|
+
} catch {
|
|
314
|
+
// A slow Nuxt route can finish after Chrome Control's navigation wait expires.
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
await waitForUrl(tab, expected, label);
|
|
318
|
+
if (readySelector) {
|
|
319
|
+
await waitForUniqueVisible(tab.playwright.locator(readySelector), `${label}_ready`, ROUTE_READY_TIMEOUT_MS);
|
|
320
|
+
} else {
|
|
321
|
+
await tab.playwright.waitForLoadState({ state: 'domcontentloaded' });
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function ensureOrigin(tab, request) {
|
|
326
|
+
const current = await tab.url();
|
|
327
|
+
if (!current || new URL(current).origin !== request.origin) {
|
|
328
|
+
await navigateAndWait(
|
|
329
|
+
tab,
|
|
330
|
+
request.return_url,
|
|
331
|
+
'.page-header .keep-right > .user-info',
|
|
332
|
+
'identity_return_page',
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function openGuide(tab) {
|
|
338
|
+
const deadline = Date.now() + 15_000;
|
|
339
|
+
while (Date.now() <= deadline) {
|
|
340
|
+
const guide = tab.playwright.locator('.guid-menu-container');
|
|
341
|
+
const guideCount = await guide.count();
|
|
342
|
+
if (guideCount > 1) throw new Error(`identity_guide_count_${guideCount}`);
|
|
343
|
+
if (guideCount === 1 && await guide.isVisible()) return guide;
|
|
344
|
+
|
|
345
|
+
const trigger = await waitForUniqueVisible(
|
|
346
|
+
tab.playwright.locator('.page-header .keep-right > .user-info'),
|
|
347
|
+
'identity_header_trigger',
|
|
348
|
+
Math.max(250, deadline - Date.now()),
|
|
349
|
+
);
|
|
350
|
+
await trigger.click({});
|
|
351
|
+
if (typeof tab.playwright.waitForTimeout === 'function') {
|
|
352
|
+
await tab.playwright.waitForTimeout(400);
|
|
353
|
+
} else {
|
|
354
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const count = await tab.playwright.locator('.guid-menu-container').count();
|
|
358
|
+
throw new Error(`identity_guide_count_${count}`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function dismissGuideBeforeMutation(tab, actions) {
|
|
362
|
+
const guide = tab.playwright.locator('.guid-menu-container');
|
|
363
|
+
const guideCount = await guide.count();
|
|
364
|
+
if (guideCount > 1) throw new Error(`identity_guide_count_${guideCount}`);
|
|
365
|
+
if (guideCount === 0 || (typeof guide.isVisible === 'function' && !await guide.isVisible())) return;
|
|
366
|
+
|
|
367
|
+
const close = tab.playwright.locator('.guid-menu-container .guide-header .el-icon-close');
|
|
368
|
+
const closeCount = await close.count();
|
|
369
|
+
if (closeCount !== 1) throw new Error(`identity_guide_close_count_${closeCount}`);
|
|
370
|
+
if (typeof close.isVisible === 'function' && !await close.isVisible()) {
|
|
371
|
+
throw new Error('identity_guide_close_not_visible');
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
await close.click({ trial: true });
|
|
375
|
+
await close.click({});
|
|
376
|
+
} catch (error) {
|
|
377
|
+
if (!isTransientLocatorError(error)) throw error;
|
|
378
|
+
const trigger = await waitForUniqueVisible(
|
|
379
|
+
tab.playwright.locator('.page-header .keep-right > .user-info'),
|
|
380
|
+
'identity_header_trigger_close',
|
|
381
|
+
5_000,
|
|
382
|
+
);
|
|
383
|
+
await trigger.click({ trial: true });
|
|
384
|
+
await trigger.click({});
|
|
385
|
+
actions.push('dismiss identity guide through stable header trigger');
|
|
386
|
+
}
|
|
387
|
+
await tab.playwright.waitForTimeout(400);
|
|
388
|
+
actions.push('dismiss identity guide before target mutation');
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function readVuexIdentity(tab) {
|
|
392
|
+
try {
|
|
393
|
+
const value = await tab.playwright.evaluate(() => {
|
|
394
|
+
const root = globalThis.$nuxt || globalThis.__NUXT__ || null;
|
|
395
|
+
const info = root?.$store?.state?.userInfo || root?.state?.userInfo || null;
|
|
396
|
+
if (!info) return null;
|
|
397
|
+
const points = Array.isArray(info.points) ? info.points.map(String) : [];
|
|
398
|
+
return {
|
|
399
|
+
id: info.id,
|
|
400
|
+
name: info.name,
|
|
401
|
+
organization_id: info.organization_id,
|
|
402
|
+
mock: info.mock,
|
|
403
|
+
mock_by_user: info.mock_by_user,
|
|
404
|
+
role_key: info.role_key,
|
|
405
|
+
can_mock: info.role_key === 'super' || points.includes('organization.admin') || points.includes('user.mock'),
|
|
406
|
+
};
|
|
407
|
+
});
|
|
408
|
+
return normalizeIdentity(value, 'vuex');
|
|
409
|
+
} catch {
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function readProfileRouteIdentity(tab, returnUrl) {
|
|
415
|
+
const guide = await openGuide(tab);
|
|
416
|
+
const nameLocator = await unique(guide.locator('.guide-footer .user-name', {}), 'identity_footer_name');
|
|
417
|
+
const name = (await nameLocator.innerText({})).trim() || null;
|
|
418
|
+
const userContainer = await unique(guide.locator('.guide-footer .user-container', {}), 'identity_profile_link');
|
|
419
|
+
await userContainer.click({});
|
|
420
|
+
const profileDeadline = Date.now() + 10_000;
|
|
421
|
+
let profileUrl = await tab.url();
|
|
422
|
+
let id = profileRouteUserId(profileUrl, returnUrl);
|
|
423
|
+
while (id === null && Date.now() <= profileDeadline) {
|
|
424
|
+
await tab.playwright.waitForTimeout(250);
|
|
425
|
+
profileUrl = await tab.url();
|
|
426
|
+
id = profileRouteUserId(profileUrl, returnUrl);
|
|
427
|
+
}
|
|
428
|
+
if (id === null) throw new Error('identity_profile_route_untrusted');
|
|
429
|
+
if (typeof tab.back === 'function') {
|
|
430
|
+
await tab.back();
|
|
431
|
+
}
|
|
432
|
+
await navigateAndWait(
|
|
433
|
+
tab,
|
|
434
|
+
returnUrl,
|
|
435
|
+
'.page-header .keep-right > .user-info',
|
|
436
|
+
'identity_profile_return',
|
|
437
|
+
);
|
|
438
|
+
return normalizeIdentity({ id, name }, 'profile_route');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async function readCurrentIdentity(tab, request, labels) {
|
|
442
|
+
await ensureOrigin(tab, request);
|
|
443
|
+
let identity = await readVuexIdentity(tab);
|
|
444
|
+
const guide = await openGuide(tab);
|
|
445
|
+
const nameLocator = await unique(guide.locator('.guide-footer .user-name', {}), 'identity_footer_name');
|
|
446
|
+
const visibleName = (await nameLocator.innerText({})).trim() || null;
|
|
447
|
+
let mocked = identity?.source === 'vuex' ? identity.mock : false;
|
|
448
|
+
if (!identity?.id) {
|
|
449
|
+
const exitAction = guide.locator('.guide-footer .action-item.log-out', {});
|
|
450
|
+
const exitCount = await exitAction.count();
|
|
451
|
+
const exitLabel = exitCount === 1 ? (await exitAction.innerText({})).trim() : null;
|
|
452
|
+
mocked = mockStateFromGuideAction(exitCount, exitLabel, labels);
|
|
453
|
+
identity = await readProfileRouteIdentity(tab, request.return_url);
|
|
454
|
+
}
|
|
455
|
+
await openGuide(tab);
|
|
456
|
+
return {
|
|
457
|
+
...(identity || normalizeIdentity({}, 'dom')),
|
|
458
|
+
name: visibleName || identity?.name || null,
|
|
459
|
+
mock: mocked,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function expectedOriginalUserId(request, before = null) {
|
|
464
|
+
const bound = trustedOriginalIdentity(request.lease.expected_original_user, 'lease');
|
|
465
|
+
if (bound?.id) return bound.id;
|
|
466
|
+
const mockByUser = Number(before?.mock_by_user);
|
|
467
|
+
return Number.isSafeInteger(mockByUser) && mockByUser > 0 ? mockByUser : null;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function isExpectedRestoredIdentity(request, before, identity, expectedIdOverride = null) {
|
|
471
|
+
if (!identity || identity.mock !== false) return false;
|
|
472
|
+
const override = Number(expectedIdOverride);
|
|
473
|
+
const expectedId = Number.isSafeInteger(override) && override > 0
|
|
474
|
+
? override
|
|
475
|
+
: expectedOriginalUserId(request, before);
|
|
476
|
+
return expectedId !== null && identity.id === expectedId;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async function refreshReturnPage(tab, request, label) {
|
|
480
|
+
try {
|
|
481
|
+
if (typeof tab.reload === 'function') {
|
|
482
|
+
await tab.reload();
|
|
483
|
+
} else {
|
|
484
|
+
await tab.goto(request.return_url);
|
|
485
|
+
}
|
|
486
|
+
} catch {
|
|
487
|
+
// The route checks below still verify whether the refresh completed.
|
|
488
|
+
}
|
|
489
|
+
await navigateAndWait(
|
|
490
|
+
tab,
|
|
491
|
+
request.return_url,
|
|
492
|
+
'.page-header .keep-right > .user-info',
|
|
493
|
+
label,
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function readRestoredIdentity(tab, request, labels, before, actions, expectedIdOverride = null) {
|
|
498
|
+
let identity = null;
|
|
499
|
+
for (let attempt = 1; attempt <= IDENTITY_READBACK_ATTEMPTS; attempt += 1) {
|
|
500
|
+
if (attempt > 1) actions.push(`retry restored identity readback attempt ${attempt}`);
|
|
501
|
+
await refreshReturnPage(tab, request, `identity_unmock_refresh_${attempt}`);
|
|
502
|
+
identity = await readCurrentIdentity(tab, request, labels);
|
|
503
|
+
if (isExpectedRestoredIdentity(request, before, identity, expectedIdOverride)) return identity;
|
|
504
|
+
}
|
|
505
|
+
return identity;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async function writeScreenshot(tab, file) {
|
|
509
|
+
const jpeg = Buffer.from(await tab.screenshot({ fullPage: false }));
|
|
510
|
+
if (jpeg.length < 3 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8 || jpeg[2] !== 0xff) {
|
|
511
|
+
throw new Error('identity_screenshot_jpeg_required');
|
|
512
|
+
}
|
|
513
|
+
await writeFile(file, jpeg, { flag: 'wx', mode: 0o600 });
|
|
514
|
+
await chmod(file, 0o600);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function isTransientLocatorError(error) {
|
|
518
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
519
|
+
return /timed out|selector deadline exceeded/i.test(message);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function isMockActionRevealRequired(error) {
|
|
523
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
524
|
+
return /identity_action_(?:label_not_found|not_visible)/.test(message);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function cssAttributeValue(value) {
|
|
528
|
+
return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function inspectExactTargetAction(tab, request, labels, timeoutMs) {
|
|
532
|
+
const targetUserId = String(request.target_user_id);
|
|
533
|
+
const targetUserName = String(request.target_user_name).trim();
|
|
534
|
+
return tab.playwright.evaluate(async ({ id, name, buttonLabels, waitMs, stableMs, managementUrl }) => {
|
|
535
|
+
const trusted = new URL(managementUrl);
|
|
536
|
+
const workspaceMatch = trusted.pathname.match(/^\/w:([^/]+)(?:\/|$)/);
|
|
537
|
+
const allowedProfilePaths = new Set(['/userProfileEditor', '/userProfileEditor/']);
|
|
538
|
+
if (workspaceMatch) {
|
|
539
|
+
allowedProfilePaths.add(`/w:${workspaceMatch[1]}/userProfileEditor`);
|
|
540
|
+
allowedProfilePaths.add(`/w:${workspaceMatch[1]}/userProfileEditor/`);
|
|
541
|
+
}
|
|
542
|
+
const trustedProfileId = (href) => {
|
|
543
|
+
try {
|
|
544
|
+
const url = new URL(href, trusted.origin);
|
|
545
|
+
if (url.origin !== trusted.origin || !allowedProfilePaths.has(url.pathname)) return null;
|
|
546
|
+
const value = Number(url.searchParams.get('id'));
|
|
547
|
+
return Number.isSafeInteger(value) && value > 0 ? String(value) : null;
|
|
548
|
+
} catch {
|
|
549
|
+
return null;
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
const inspect = () => {
|
|
553
|
+
const input = document.querySelector('.button-line > .el-input input');
|
|
554
|
+
const allRows = Array.from(document.querySelectorAll('tbody tr'));
|
|
555
|
+
const rows = allRows.filter((row) => Array.from(row.querySelectorAll('a[href]')).some(
|
|
556
|
+
(anchor) => trustedProfileId(anchor.getAttribute('href')) === id,
|
|
557
|
+
));
|
|
558
|
+
if (rows.length !== 1) {
|
|
559
|
+
return { status: rows.length > 1 ? 'ambiguous' : 'missing', row_count: rows.length };
|
|
560
|
+
}
|
|
561
|
+
const row = rows[0];
|
|
562
|
+
const profileLinks = Array.from(row.querySelectorAll('a[href]')).filter(
|
|
563
|
+
(anchor) => trustedProfileId(anchor.getAttribute('href')) === id,
|
|
564
|
+
);
|
|
565
|
+
const idCount = profileLinks.length;
|
|
566
|
+
const nameNodes = Array.from(row.querySelectorAll('.user-name-text'));
|
|
567
|
+
const actualName = nameNodes.length === 1 ? String(nameNodes[0].textContent || '').trim() : null;
|
|
568
|
+
const buttons = Array.from(row.querySelectorAll('button')).filter(
|
|
569
|
+
(button) => buttonLabels.includes(String(button.textContent || '').trim()),
|
|
570
|
+
);
|
|
571
|
+
const button = buttons.length === 1 ? buttons[0] : null;
|
|
572
|
+
const actionLabel = button ? String(button.textContent || '').trim() : null;
|
|
573
|
+
const buttonVisible = Boolean(button && button.getClientRects().length > 0);
|
|
574
|
+
const buttonEnabled = Boolean(button && !button.disabled && button.getAttribute('aria-disabled') !== 'true');
|
|
575
|
+
const ready = String(input?.value || '') === name
|
|
576
|
+
&& idCount === 1
|
|
577
|
+
&& nameNodes.length === 1
|
|
578
|
+
&& actualName === name
|
|
579
|
+
&& buttons.length === 1
|
|
580
|
+
&& buttonVisible
|
|
581
|
+
&& buttonEnabled;
|
|
582
|
+
return {
|
|
583
|
+
status: ready
|
|
584
|
+
? 'ready'
|
|
585
|
+
: actualName && actualName !== name
|
|
586
|
+
? 'name_mismatch'
|
|
587
|
+
: buttons.length === 0
|
|
588
|
+
? 'action_label_missing'
|
|
589
|
+
: buttons.length > 1
|
|
590
|
+
? 'action_label_ambiguous'
|
|
591
|
+
: !buttonVisible
|
|
592
|
+
? 'action_not_visible'
|
|
593
|
+
: !buttonEnabled
|
|
594
|
+
? 'action_disabled'
|
|
595
|
+
: 'candidate',
|
|
596
|
+
row_count: rows.length,
|
|
597
|
+
id_count: idCount,
|
|
598
|
+
name_count: nameNodes.length,
|
|
599
|
+
actual_name: actualName,
|
|
600
|
+
action_label: actionLabel,
|
|
601
|
+
button_count: buttons.length,
|
|
602
|
+
input_value: String(input?.value || ''),
|
|
603
|
+
row_index: allRows.indexOf(row),
|
|
604
|
+
profile_href: profileLinks.length === 1 ? profileLinks[0].getAttribute('href') : null,
|
|
605
|
+
};
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
const deadline = Date.now() + waitMs;
|
|
609
|
+
let sawCandidate = false;
|
|
610
|
+
let readySince = null;
|
|
611
|
+
while (Date.now() <= deadline) {
|
|
612
|
+
const state = inspect();
|
|
613
|
+
if (state.status === 'ready') {
|
|
614
|
+
readySince ??= Date.now();
|
|
615
|
+
if (Date.now() - readySince >= stableMs) return state;
|
|
616
|
+
} else {
|
|
617
|
+
readySince = null;
|
|
618
|
+
}
|
|
619
|
+
if (state.status === 'ambiguous' || state.status === 'name_mismatch') return state;
|
|
620
|
+
if (state.row_count > 0) sawCandidate = true;
|
|
621
|
+
else if (sawCandidate) return { ...state, status: 'overwritten' };
|
|
622
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
623
|
+
}
|
|
624
|
+
const finalState = inspect();
|
|
625
|
+
return ['action_label_missing', 'action_label_ambiguous', 'action_not_visible', 'action_disabled'].includes(finalState.status)
|
|
626
|
+
? finalState
|
|
627
|
+
: { ...finalState, status: 'timeout' };
|
|
628
|
+
}, {
|
|
629
|
+
id: targetUserId,
|
|
630
|
+
name: targetUserName,
|
|
631
|
+
buttonLabels: labels.simulation,
|
|
632
|
+
managementUrl: request.user_management_url,
|
|
633
|
+
waitMs: timeoutMs,
|
|
634
|
+
stableMs: 750,
|
|
635
|
+
}, { timeoutMs: timeoutMs + 5_000 });
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async function resolveExactTargetAction(tab, request, labels, timeoutMs) {
|
|
639
|
+
const state = await inspectExactTargetAction(tab, request, labels, timeoutMs);
|
|
640
|
+
if (state.status === 'ambiguous') throw new Error(`identity_exact_user_row_count_${state.row_count}`);
|
|
641
|
+
if (state.status === 'name_mismatch') throw new Error('identity_target_name_changed');
|
|
642
|
+
if (state.status === 'action_label_missing') throw new Error('identity_action_label_not_found');
|
|
643
|
+
if (state.status === 'action_label_ambiguous') throw new Error(`identity_action_label_ambiguous_${state.button_count}`);
|
|
644
|
+
if (state.status === 'action_not_visible') throw new Error('identity_action_not_visible');
|
|
645
|
+
if (state.status === 'action_disabled') throw new Error('identity_action_disabled');
|
|
646
|
+
if (state.status !== 'ready') return { state, resolved: null };
|
|
647
|
+
|
|
648
|
+
const targetUserName = String(request.target_user_name).trim();
|
|
649
|
+
const profileHref = String(state.profile_href || '');
|
|
650
|
+
const profileId = profileHref ? profileRouteUserId(new URL(profileHref, request.origin).toString(), request.user_management_url) : null;
|
|
651
|
+
const row = profileHref
|
|
652
|
+
? tab.playwright.locator(`tbody tr:has(a[href="${cssAttributeValue(profileHref)}"])`)
|
|
653
|
+
: null;
|
|
654
|
+
if (!row
|
|
655
|
+
|| profileId !== request.target_user_id
|
|
656
|
+
|| await row.count() !== 1
|
|
657
|
+
|| await row.locator('.user-name-text', {}).count() !== 1) {
|
|
658
|
+
return { state: { ...state, status: 'overwritten' }, resolved: null };
|
|
659
|
+
}
|
|
660
|
+
const simulation = row.getByRole('button', { name: state.action_label, exact: true });
|
|
661
|
+
const simulationCount = await simulation.count();
|
|
662
|
+
if (simulationCount !== 1) throw new Error(`identity_exact_simulation_button_count_${simulationCount}`);
|
|
663
|
+
|
|
664
|
+
return {
|
|
665
|
+
state,
|
|
666
|
+
resolved: {
|
|
667
|
+
simulation,
|
|
668
|
+
targetName: String(state.actual_name || '').trim(),
|
|
669
|
+
actionLabel: state.action_label,
|
|
670
|
+
},
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
async function waitForExactTargetAction(tab, search, request, labels, actions) {
|
|
675
|
+
const targetUserName = String(request.target_user_name).trim();
|
|
676
|
+
try {
|
|
677
|
+
const existing = await resolveExactTargetAction(tab, request, labels, 1_000);
|
|
678
|
+
if (existing.resolved) {
|
|
679
|
+
actions.push('reuse stable exact target search result');
|
|
680
|
+
return existing.resolved;
|
|
681
|
+
}
|
|
682
|
+
} catch (error) {
|
|
683
|
+
if (!isTransientLocatorError(error) && !isMockActionRevealRequired(error)) throw error;
|
|
684
|
+
if (isMockActionRevealRequired(error)) actions.push('reveal hidden simulation action');
|
|
685
|
+
}
|
|
686
|
+
for (let attempt = 1; attempt <= TARGET_SEARCH_ATTEMPTS; attempt += 1) {
|
|
687
|
+
if (attempt === 1) {
|
|
688
|
+
await search.fill(REVEAL_MOCK_ACTION, {});
|
|
689
|
+
// userManagement reveals the mock column from a 500 ms debounced watcher.
|
|
690
|
+
await tab.playwright.waitForTimeout(750);
|
|
691
|
+
} else {
|
|
692
|
+
await search.fill('', {});
|
|
693
|
+
await tab.playwright.waitForTimeout(100);
|
|
694
|
+
}
|
|
695
|
+
await search.fill(targetUserName, {});
|
|
696
|
+
actions.push(`search target user name attempt ${attempt}`);
|
|
697
|
+
await tab.playwright.waitForTimeout(2_000);
|
|
698
|
+
for (let observationAttempt = 1; observationAttempt <= 3; observationAttempt += 1) {
|
|
699
|
+
try {
|
|
700
|
+
const inspected = await resolveExactTargetAction(tab, request, labels, TARGET_SEARCH_TIMEOUT_MS);
|
|
701
|
+
if (inspected.resolved) return inspected.resolved;
|
|
702
|
+
if (inspected.state.status === 'overwritten') {
|
|
703
|
+
actions.push(`target result overwritten; retry search attempt ${attempt + 1}`);
|
|
704
|
+
break;
|
|
705
|
+
}
|
|
706
|
+
} catch (error) {
|
|
707
|
+
if (!isTransientLocatorError(error)) throw error;
|
|
708
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
709
|
+
actions.push(`transient target UI timeout on attempt ${attempt}.${observationAttempt}: ${message.slice(0, 120)}`);
|
|
710
|
+
}
|
|
711
|
+
await tab.playwright.waitForTimeout(2_000);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
throw new Error('identity_exact_user_row_count_0');
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
async function clickUniqueVisibleAction(tab, actionLabels, fallbackLocator) {
|
|
718
|
+
if (!tab.dom_cua?.get_visible_dom || !tab.dom_cua?.click) {
|
|
719
|
+
await fallbackLocator.click({});
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
const visibleDom = String(await tab.dom_cua.get_visible_dom());
|
|
723
|
+
const labelPattern = actionLabels
|
|
724
|
+
.map((label) => label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
|
|
725
|
+
.join('|');
|
|
726
|
+
const matches = Array.from(visibleDom.matchAll(
|
|
727
|
+
new RegExp(`<button\\s+[^>]*node_id=["']?([^\\s"'>]+)["']?[^>]*>(?:(?!</button>)[\\s\\S])*(?:${labelPattern})(?:(?!</button>)[\\s\\S])*</button>`, 'g'),
|
|
728
|
+
));
|
|
729
|
+
if (matches.length !== 1) throw new Error(`identity_visible_action_count_${matches.length}`);
|
|
730
|
+
await tab.dom_cua.click({ node_id: matches[0][1] });
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
async function clickMock(tab, request, labels, actions, onMutationAttempt = async () => undefined) {
|
|
734
|
+
await navigateAndWait(
|
|
735
|
+
tab,
|
|
736
|
+
request.user_management_url,
|
|
737
|
+
'.button-line > .el-input input',
|
|
738
|
+
'identity_user_management',
|
|
739
|
+
);
|
|
740
|
+
actions.push('navigate user management');
|
|
741
|
+
const search = await waitForUniqueVisible(
|
|
742
|
+
tab.playwright.locator('.button-line > .el-input input'),
|
|
743
|
+
'identity_user_search',
|
|
744
|
+
);
|
|
745
|
+
actions.push(`search target user name and verify exact id ${request.target_user_id}`);
|
|
746
|
+
let { simulation, targetName } = await waitForExactTargetAction(tab, search, request, labels, actions);
|
|
747
|
+
const simulationCount = await simulation.count();
|
|
748
|
+
if (simulationCount !== 1) throw new Error(`identity_exact_simulation_button_count_${simulationCount}`);
|
|
749
|
+
if (typeof simulation.isVisible === 'function' && !await simulation.isVisible()) {
|
|
750
|
+
throw new Error('identity_exact_simulation_button_not_visible');
|
|
751
|
+
}
|
|
752
|
+
if (typeof simulation.isEnabled === 'function' && !await simulation.isEnabled()) {
|
|
753
|
+
throw new Error('identity_exact_simulation_button_disabled');
|
|
754
|
+
}
|
|
755
|
+
await dismissGuideBeforeMutation(tab, actions);
|
|
756
|
+
const beforeTrial = await resolveExactTargetAction(tab, request, labels, 1_000);
|
|
757
|
+
if (!beforeTrial.resolved) throw new Error('identity_exact_user_row_changed_before_click');
|
|
758
|
+
simulation = beforeTrial.resolved.simulation;
|
|
759
|
+
targetName = beforeTrial.resolved.targetName;
|
|
760
|
+
await simulation.click({ trial: true });
|
|
761
|
+
actions.push(`verify simulation action is clickable for exact user id ${request.target_user_id}`);
|
|
762
|
+
const beforeMutation = await resolveExactTargetAction(tab, request, labels, 1_000);
|
|
763
|
+
if (!beforeMutation.resolved) throw new Error('identity_exact_user_row_changed_before_click');
|
|
764
|
+
simulation = beforeMutation.resolved.simulation;
|
|
765
|
+
targetName = beforeMutation.resolved.targetName;
|
|
766
|
+
await onMutationAttempt();
|
|
767
|
+
await clickUniqueVisibleAction(tab, labels.simulation, simulation);
|
|
768
|
+
actions.push(`click simulation for exact user id ${request.target_user_id}`);
|
|
769
|
+
await navigateAndWait(
|
|
770
|
+
tab,
|
|
771
|
+
request.return_url,
|
|
772
|
+
'.page-header .keep-right > .user-info',
|
|
773
|
+
'identity_mock_return',
|
|
774
|
+
);
|
|
775
|
+
return targetName;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function clickUnmock(tab, request, labels, actions, onMutationAttempt = async () => undefined) {
|
|
779
|
+
await ensureOrigin(tab, request);
|
|
780
|
+
const currentUrl = await tab.url();
|
|
781
|
+
const guide = await openGuide(tab);
|
|
782
|
+
const exit = await waitForUniqueVisible(
|
|
783
|
+
guide.locator('.guide-footer .action-item.log-out', {}),
|
|
784
|
+
'identity_exit_simulation',
|
|
785
|
+
);
|
|
786
|
+
if (!labels.exitSimulation.includes((await exit.innerText({})).trim())) {
|
|
787
|
+
throw new Error('identity_action_label_not_found');
|
|
788
|
+
}
|
|
789
|
+
await onMutationAttempt();
|
|
790
|
+
await tab.playwright.expectNavigation(
|
|
791
|
+
() => exit.click({}),
|
|
792
|
+
{ url: currentUrl, waitUntil: 'domcontentloaded', timeoutMs: ROUTE_READY_TIMEOUT_MS },
|
|
793
|
+
);
|
|
794
|
+
actions.push('click exit simulation');
|
|
795
|
+
await navigateAndWait(
|
|
796
|
+
tab,
|
|
797
|
+
request.return_url,
|
|
798
|
+
'.page-header .keep-right > .user-info',
|
|
799
|
+
'identity_unmock_return',
|
|
800
|
+
);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
async function bestEffortUnmock(tab, request, labels, expectedOriginalId = null) {
|
|
804
|
+
try {
|
|
805
|
+
const before = await readCurrentIdentity(tab, request, labels);
|
|
806
|
+
const isExpectedOriginal = (identity) => identity?.mock === false
|
|
807
|
+
&& (expectedOriginalId === null || identity.id === expectedOriginalId);
|
|
808
|
+
if (!before.mock) {
|
|
809
|
+
return { attempted: false, readback_confirmed: isExpectedOriginal(before), after: before };
|
|
810
|
+
}
|
|
811
|
+
const actions = [];
|
|
812
|
+
await clickUnmock(tab, request, labels, actions);
|
|
813
|
+
const after = await readRestoredIdentity(tab, request, labels, before, actions, expectedOriginalId);
|
|
814
|
+
return { attempted: true, readback_confirmed: isExpectedOriginal(after), after, actions };
|
|
815
|
+
} catch (error) {
|
|
816
|
+
return { attempted: true, readback_confirmed: false, error: error instanceof Error ? error.message : String(error) };
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
async function persistMutationIntentLease(request, before) {
|
|
821
|
+
await withLeaseLock(request.lease.lease_file, async () => {
|
|
822
|
+
let existing = {};
|
|
823
|
+
try {
|
|
824
|
+
const parsed = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
|
|
825
|
+
if (isRecord(parsed)) existing = parsed;
|
|
826
|
+
} catch {
|
|
827
|
+
// A mock starts without a lease; diagnostic recovery may also start without one.
|
|
828
|
+
}
|
|
829
|
+
assertLeaseTransitionCurrent(existing, request, { allowMissing: request.operation === 'mock' });
|
|
830
|
+
if (request.operation === 'unmock') assertReleaseClaimAvailable(existing, request);
|
|
831
|
+
const targetUser = request.operation === 'mock'
|
|
832
|
+
? normalizeIdentity({
|
|
833
|
+
id: request.target_user_id,
|
|
834
|
+
name: request.target_user_name,
|
|
835
|
+
organization_id: request.target_organization_id,
|
|
836
|
+
mock: true,
|
|
837
|
+
mock_by_user: before?.id,
|
|
838
|
+
}, 'unknown')
|
|
839
|
+
: existing.target_user || before || null;
|
|
840
|
+
const originalUser = recoverOriginalIdentity({
|
|
841
|
+
originalUser: existing.original_user,
|
|
842
|
+
targetUser,
|
|
843
|
+
before,
|
|
844
|
+
});
|
|
845
|
+
const nextLease = {
|
|
846
|
+
...existing,
|
|
847
|
+
schema_version: 1,
|
|
848
|
+
kind: 'bpmax_identity_lease',
|
|
849
|
+
lease_id: request.lease.lease_id,
|
|
850
|
+
state: 'uncertain',
|
|
851
|
+
operation_request_id: request.request_id,
|
|
852
|
+
created_at: existing.created_at || request.created_at,
|
|
853
|
+
...(request.lease.expires_at ? { expires_at: request.lease.expires_at } : {}),
|
|
854
|
+
target_user: targetUser,
|
|
855
|
+
original_user: originalUser,
|
|
856
|
+
browser_tool: 'chrome:control-chrome',
|
|
857
|
+
recovery_required: true,
|
|
858
|
+
binding: request.operation === 'mock' ? request.binding : existing.binding || request.binding,
|
|
859
|
+
mutation_intent_at: new Date().toISOString(),
|
|
860
|
+
...(request.operation === 'unmock' ? {
|
|
861
|
+
release_operation_request_id: request.request_id,
|
|
862
|
+
release_binding: request.binding,
|
|
863
|
+
} : {}),
|
|
864
|
+
};
|
|
865
|
+
if (request.operation === 'mock') {
|
|
866
|
+
delete nextLease.released_at;
|
|
867
|
+
delete nextLease.release_operation_request_id;
|
|
868
|
+
delete nextLease.release_binding;
|
|
869
|
+
delete nextLease.local_result_write_failed_at;
|
|
870
|
+
}
|
|
871
|
+
await writeJsonAtomic(request.lease.lease_file, nextLease);
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function sameIdentityBinding(left, right) {
|
|
876
|
+
if (!isRecord(left) || !isRecord(right)) return false;
|
|
877
|
+
return Boolean(left.diagnostic) === Boolean(right.diagnostic)
|
|
878
|
+
&& String(left.recording_session || '') === String(right.recording_session || '')
|
|
879
|
+
&& String(left.profile || '') === String(right.profile || '')
|
|
880
|
+
&& String(left.execution_manifest || '') === String(right.execution_manifest || '')
|
|
881
|
+
&& String(left.case_id || '') === String(right.case_id || '')
|
|
882
|
+
&& String(left.case_step_id || '') === String(right.case_step_id || '');
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
async function recoverMockMutationIntent(request, currentIdentity) {
|
|
886
|
+
try {
|
|
887
|
+
const lease = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
|
|
888
|
+
if (!isRecord(lease)
|
|
889
|
+
|| lease.kind !== 'bpmax_identity_lease'
|
|
890
|
+
|| lease.lease_id !== request.lease.lease_id
|
|
891
|
+
|| lease.operation_request_id !== request.request_id
|
|
892
|
+
|| !['active', 'uncertain'].includes(lease.state)
|
|
893
|
+
|| !sameIdentityBinding(lease.binding, request.binding)
|
|
894
|
+
|| !isRecord(lease.target_user)
|
|
895
|
+
|| Number(lease.target_user.id) !== Number(request.target_user_id)
|
|
896
|
+
|| Number(lease.target_user.organization_id || 0) !== Number(request.target_organization_id || 0)
|
|
897
|
+
|| !isRecord(lease.original_user)
|
|
898
|
+
|| Number(currentIdentity?.id) !== Number(request.target_user_id)
|
|
899
|
+
|| currentIdentity?.mock !== true) {
|
|
900
|
+
return null;
|
|
901
|
+
}
|
|
902
|
+
const original = normalizeIdentity(lease.original_user, 'lease');
|
|
903
|
+
if (!original || original.mock || !Number.isSafeInteger(Number(original.id))) return null;
|
|
904
|
+
return { original };
|
|
905
|
+
} catch {
|
|
906
|
+
return null;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
async function persistBrowserLease(request, result, options = {}) {
|
|
911
|
+
const now = new Date().toISOString();
|
|
912
|
+
const cleanup = options.cleanup || result.cleanup;
|
|
913
|
+
const localResultWriteFailed = options.localResultWriteFailed === true;
|
|
914
|
+
if (request.operation === 'mock') {
|
|
915
|
+
const originalId = Number(result.before?.id);
|
|
916
|
+
const restored = cleanup?.readback_confirmed === true
|
|
917
|
+
&& cleanup.after?.mock === false
|
|
918
|
+
&& Number.isSafeInteger(originalId)
|
|
919
|
+
&& originalId > 0
|
|
920
|
+
&& cleanup.after?.id === originalId;
|
|
921
|
+
const active = result.ok === true && result.readback_confirmed === true && result.after?.mock === true;
|
|
922
|
+
if (!restored && !active && result.mutation_attempted !== true && result.remote_submitted !== true) return;
|
|
923
|
+
await withLeaseLock(request.lease.lease_file, async () => {
|
|
924
|
+
let existing = {};
|
|
925
|
+
try {
|
|
926
|
+
const parsed = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
|
|
927
|
+
if (isRecord(parsed)) existing = parsed;
|
|
928
|
+
} catch {
|
|
929
|
+
// A mutating mock must already have persisted its intent lease.
|
|
930
|
+
}
|
|
931
|
+
assertLeaseTransitionCurrent(existing, request);
|
|
932
|
+
if (existing.operation_request_id !== request.request_id) throw new Error('identity_lease_changed');
|
|
933
|
+
const lease = {
|
|
934
|
+
...existing,
|
|
935
|
+
schema_version: 1,
|
|
936
|
+
kind: 'bpmax_identity_lease',
|
|
937
|
+
lease_id: request.lease.lease_id,
|
|
938
|
+
state: restored ? 'released' : active ? 'active' : 'uncertain',
|
|
939
|
+
operation_request_id: request.request_id,
|
|
940
|
+
created_at: request.created_at,
|
|
941
|
+
expires_at: request.lease.expires_at,
|
|
942
|
+
target_user: active
|
|
943
|
+
? result.after || result.current_user || existing.target_user || null
|
|
944
|
+
: existing.target_user || result.after || result.current_user || null,
|
|
945
|
+
original_user: recoverOriginalIdentity({
|
|
946
|
+
originalUser: existing.original_user,
|
|
947
|
+
targetUser: existing.target_user || result.after || result.current_user,
|
|
948
|
+
before: result.before,
|
|
949
|
+
}),
|
|
950
|
+
browser_tool: 'chrome:control-chrome',
|
|
951
|
+
recovery_required: !restored,
|
|
952
|
+
binding: existing.binding || request.binding,
|
|
953
|
+
...(restored ? { released_at: now } : {}),
|
|
954
|
+
...(localResultWriteFailed ? { local_result_write_failed_at: now } : {}),
|
|
955
|
+
};
|
|
956
|
+
await writeJsonAtomic(request.lease.lease_file, lease);
|
|
957
|
+
});
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
if (request.operation !== 'unmock') return;
|
|
961
|
+
if (result.ok !== true && result.mutation_attempted !== true) return;
|
|
962
|
+
await withLeaseLock(request.lease.lease_file, async () => {
|
|
963
|
+
let existing = {};
|
|
964
|
+
try {
|
|
965
|
+
const parsed = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
|
|
966
|
+
if (isRecord(parsed)) existing = parsed;
|
|
967
|
+
} catch {
|
|
968
|
+
// A missing or invalid prior lease remains fail-closed below.
|
|
969
|
+
}
|
|
970
|
+
assertLeaseTransitionCurrent(existing, request);
|
|
971
|
+
if (existing.release_operation_request_id !== request.request_id) {
|
|
972
|
+
throw new Error('identity_lease_changed');
|
|
973
|
+
}
|
|
974
|
+
const restored = result.ok === true
|
|
975
|
+
&& result.readback_confirmed === true
|
|
976
|
+
&& isExpectedRestoredIdentity(request, result.before, result.after);
|
|
977
|
+
const lease = {
|
|
978
|
+
...existing,
|
|
979
|
+
schema_version: 1,
|
|
980
|
+
kind: 'bpmax_identity_lease',
|
|
981
|
+
lease_id: request.lease.lease_id,
|
|
982
|
+
state: restored ? 'released' : 'uncertain',
|
|
983
|
+
operation_request_id: request.request_id,
|
|
984
|
+
created_at: existing.created_at || request.created_at,
|
|
985
|
+
original_user: trustedOriginalIdentity(request.lease.expected_original_user, 'lease'),
|
|
986
|
+
...(restored ? { released_at: result.finished_at || now } : {}),
|
|
987
|
+
browser_tool: 'chrome:control-chrome',
|
|
988
|
+
recovery_required: !restored,
|
|
989
|
+
binding: existing.binding || request.binding,
|
|
990
|
+
release_operation_request_id: request.request_id,
|
|
991
|
+
release_binding: request.binding,
|
|
992
|
+
...(localResultWriteFailed ? { local_result_write_failed_at: now } : {}),
|
|
993
|
+
};
|
|
994
|
+
await writeJsonAtomic(request.lease.lease_file, lease);
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
async function runOperation(tab, request) {
|
|
999
|
+
const startedAt = new Date().toISOString();
|
|
1000
|
+
const labels = labelsFor(request.language);
|
|
1001
|
+
const actions = [];
|
|
1002
|
+
await ensureOrigin(tab, request);
|
|
1003
|
+
let before = await readCurrentIdentity(tab, request, labels);
|
|
1004
|
+
let after = before;
|
|
1005
|
+
let permissionPreflight;
|
|
1006
|
+
let remoteSubmitted = false;
|
|
1007
|
+
let operationExecuted = false;
|
|
1008
|
+
let cleanup;
|
|
1009
|
+
let targetName;
|
|
1010
|
+
let mutationAttempted = false;
|
|
1011
|
+
let alreadyRestored = false;
|
|
1012
|
+
const markMutationAttempt = async () => {
|
|
1013
|
+
await persistMutationIntentLease(request, before);
|
|
1014
|
+
mutationAttempted = true;
|
|
1015
|
+
};
|
|
1016
|
+
try {
|
|
1017
|
+
if (request.operation === 'mock') {
|
|
1018
|
+
if (before.mock) {
|
|
1019
|
+
const recovered = await recoverMockMutationIntent(request, before);
|
|
1020
|
+
if (!recovered) throw new Error('identity_already_mocked');
|
|
1021
|
+
after = before;
|
|
1022
|
+
before = recovered.original;
|
|
1023
|
+
mutationAttempted = true;
|
|
1024
|
+
remoteSubmitted = true;
|
|
1025
|
+
operationExecuted = true;
|
|
1026
|
+
permissionPreflight = { granted: true, source: 'request_mutation_intent' };
|
|
1027
|
+
actions.push(`recover completed simulation for exact user id ${request.target_user_id}`);
|
|
1028
|
+
}
|
|
1029
|
+
if (before.can_mock === false) throw new Error('identity_user_mock_permission_missing');
|
|
1030
|
+
if (before.organization_id && request.target_organization_id && before.organization_id !== request.target_organization_id) {
|
|
1031
|
+
throw new Error('identity_target_organization_mismatch');
|
|
1032
|
+
}
|
|
1033
|
+
if (!after.mock) {
|
|
1034
|
+
permissionPreflight = {
|
|
1035
|
+
granted: before.can_mock !== false,
|
|
1036
|
+
source: before.can_mock === true ? 'current_user_points' : 'user_management_action',
|
|
1037
|
+
};
|
|
1038
|
+
targetName = await clickMock(tab, request, labels, actions, markMutationAttempt);
|
|
1039
|
+
remoteSubmitted = true;
|
|
1040
|
+
operationExecuted = true;
|
|
1041
|
+
after = await readCurrentIdentity(tab, request, labels);
|
|
1042
|
+
if (!after.mock || after.id !== request.target_user_id || (targetName && after.name !== targetName)) {
|
|
1043
|
+
throw new Error('identity_mock_readback_mismatch');
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
} else if (request.operation === 'unmock') {
|
|
1047
|
+
await persistMutationIntentLease(request, before);
|
|
1048
|
+
const expectedOriginalId = Number(request.lease.expected_original_user?.id);
|
|
1049
|
+
alreadyRestored = !before.mock
|
|
1050
|
+
&& Number.isSafeInteger(expectedOriginalId)
|
|
1051
|
+
&& expectedOriginalId > 0
|
|
1052
|
+
&& before.id === expectedOriginalId;
|
|
1053
|
+
if (!before.mock && !alreadyRestored) throw new Error('identity_not_mocked');
|
|
1054
|
+
if (alreadyRestored) {
|
|
1055
|
+
actions.push('confirm identity already restored to the lease origin');
|
|
1056
|
+
} else {
|
|
1057
|
+
await clickUnmock(tab, request, labels, actions, markMutationAttempt);
|
|
1058
|
+
remoteSubmitted = true;
|
|
1059
|
+
operationExecuted = true;
|
|
1060
|
+
after = await readRestoredIdentity(tab, request, labels, before, actions);
|
|
1061
|
+
if (!isExpectedRestoredIdentity(request, before, after)) {
|
|
1062
|
+
throw new Error('identity_unmock_readback_mismatch');
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
await openGuide(tab);
|
|
1067
|
+
await writeScreenshot(tab, request.screenshot_path);
|
|
1068
|
+
return {
|
|
1069
|
+
schema_version: 1,
|
|
1070
|
+
kind: RESULT_KIND,
|
|
1071
|
+
transport: 'chrome_control_ui',
|
|
1072
|
+
browser_tool: 'chrome:control-chrome',
|
|
1073
|
+
request_id: request.request_id,
|
|
1074
|
+
nonce: request.nonce,
|
|
1075
|
+
operation: request.operation,
|
|
1076
|
+
ok: true,
|
|
1077
|
+
mutation_attempted: mutationAttempted,
|
|
1078
|
+
operation_executed: operationExecuted,
|
|
1079
|
+
remote_submitted: remoteSubmitted,
|
|
1080
|
+
readback_confirmed: true,
|
|
1081
|
+
...(alreadyRestored ? { already_restored: true } : {}),
|
|
1082
|
+
before,
|
|
1083
|
+
after,
|
|
1084
|
+
current_user: after,
|
|
1085
|
+
...(permissionPreflight ? { permission_preflight: permissionPreflight } : {}),
|
|
1086
|
+
...(request.operation === 'mock' ? {
|
|
1087
|
+
lease: {
|
|
1088
|
+
lease_id: request.lease.lease_id,
|
|
1089
|
+
expires_at: request.lease.expires_at,
|
|
1090
|
+
recovery_required: true,
|
|
1091
|
+
},
|
|
1092
|
+
} : {}),
|
|
1093
|
+
actions,
|
|
1094
|
+
runtime_url: await tab.url(),
|
|
1095
|
+
screenshot_path: request.screenshot_path,
|
|
1096
|
+
screenshot_mime: request.screenshot_mime,
|
|
1097
|
+
started_at: startedAt,
|
|
1098
|
+
finished_at: new Date().toISOString(),
|
|
1099
|
+
};
|
|
1100
|
+
} catch (error) {
|
|
1101
|
+
if (mutationAttempted) {
|
|
1102
|
+
try {
|
|
1103
|
+
after = request.operation === 'unmock'
|
|
1104
|
+
? await readRestoredIdentity(tab, request, labels, before, actions)
|
|
1105
|
+
: await readCurrentIdentity(tab, request, labels);
|
|
1106
|
+
if (request.operation === 'mock' && after.mock && after.id === request.target_user_id) {
|
|
1107
|
+
remoteSubmitted = true;
|
|
1108
|
+
operationExecuted = true;
|
|
1109
|
+
permissionPreflight ??= { granted: true, source: 'user_management_action' };
|
|
1110
|
+
await openGuide(tab);
|
|
1111
|
+
await writeScreenshot(tab, request.screenshot_path);
|
|
1112
|
+
return {
|
|
1113
|
+
schema_version: 1,
|
|
1114
|
+
kind: RESULT_KIND,
|
|
1115
|
+
transport: 'chrome_control_ui',
|
|
1116
|
+
browser_tool: 'chrome:control-chrome',
|
|
1117
|
+
request_id: request.request_id,
|
|
1118
|
+
nonce: request.nonce,
|
|
1119
|
+
operation: request.operation,
|
|
1120
|
+
ok: true,
|
|
1121
|
+
mutation_attempted: true,
|
|
1122
|
+
operation_executed: true,
|
|
1123
|
+
remote_submitted: true,
|
|
1124
|
+
readback_confirmed: true,
|
|
1125
|
+
before,
|
|
1126
|
+
after,
|
|
1127
|
+
current_user: after,
|
|
1128
|
+
permission_preflight: permissionPreflight,
|
|
1129
|
+
lease: {
|
|
1130
|
+
lease_id: request.lease.lease_id,
|
|
1131
|
+
expires_at: request.lease.expires_at,
|
|
1132
|
+
recovery_required: true,
|
|
1133
|
+
},
|
|
1134
|
+
actions,
|
|
1135
|
+
recovered_after_action_error: true,
|
|
1136
|
+
runtime_url: await tab.url(),
|
|
1137
|
+
screenshot_path: request.screenshot_path,
|
|
1138
|
+
screenshot_mime: request.screenshot_mime,
|
|
1139
|
+
started_at: startedAt,
|
|
1140
|
+
finished_at: new Date().toISOString(),
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
if (request.operation === 'unmock' && isExpectedRestoredIdentity(request, before, after)) {
|
|
1144
|
+
remoteSubmitted = true;
|
|
1145
|
+
operationExecuted = true;
|
|
1146
|
+
await openGuide(tab);
|
|
1147
|
+
await writeScreenshot(tab, request.screenshot_path);
|
|
1148
|
+
return {
|
|
1149
|
+
schema_version: 1,
|
|
1150
|
+
kind: RESULT_KIND,
|
|
1151
|
+
transport: 'chrome_control_ui',
|
|
1152
|
+
browser_tool: 'chrome:control-chrome',
|
|
1153
|
+
request_id: request.request_id,
|
|
1154
|
+
nonce: request.nonce,
|
|
1155
|
+
operation: request.operation,
|
|
1156
|
+
ok: true,
|
|
1157
|
+
mutation_attempted: true,
|
|
1158
|
+
operation_executed: true,
|
|
1159
|
+
remote_submitted: true,
|
|
1160
|
+
readback_confirmed: true,
|
|
1161
|
+
before,
|
|
1162
|
+
after,
|
|
1163
|
+
current_user: after,
|
|
1164
|
+
actions,
|
|
1165
|
+
recovered_after_action_error: true,
|
|
1166
|
+
runtime_url: await tab.url(),
|
|
1167
|
+
screenshot_path: request.screenshot_path,
|
|
1168
|
+
screenshot_mime: request.screenshot_mime,
|
|
1169
|
+
started_at: startedAt,
|
|
1170
|
+
finished_at: new Date().toISOString(),
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
} catch {
|
|
1174
|
+
// The normal failure path below will retain a fail-closed lease state.
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
if (request.operation === 'mock' && (remoteSubmitted || after?.mock)) {
|
|
1178
|
+
remoteSubmitted = remoteSubmitted || after?.mock === true;
|
|
1179
|
+
cleanup = await bestEffortUnmock(tab, request, labels, before?.id ?? null);
|
|
1180
|
+
}
|
|
1181
|
+
try {
|
|
1182
|
+
await openGuide(tab);
|
|
1183
|
+
await writeScreenshot(tab, request.screenshot_path);
|
|
1184
|
+
} catch {
|
|
1185
|
+
// Completion will reject a missing screenshot and keep the lease fail-closed.
|
|
1186
|
+
}
|
|
1187
|
+
return {
|
|
1188
|
+
schema_version: 1,
|
|
1189
|
+
kind: RESULT_KIND,
|
|
1190
|
+
transport: 'chrome_control_ui',
|
|
1191
|
+
browser_tool: 'chrome:control-chrome',
|
|
1192
|
+
request_id: request.request_id,
|
|
1193
|
+
nonce: request.nonce,
|
|
1194
|
+
operation: request.operation,
|
|
1195
|
+
ok: false,
|
|
1196
|
+
mutation_attempted: mutationAttempted,
|
|
1197
|
+
operation_executed: operationExecuted,
|
|
1198
|
+
remote_submitted: remoteSubmitted,
|
|
1199
|
+
readback_confirmed: false,
|
|
1200
|
+
before,
|
|
1201
|
+
after,
|
|
1202
|
+
...(permissionPreflight ? { permission_preflight: permissionPreflight } : {}),
|
|
1203
|
+
...(cleanup ? { cleanup } : {}),
|
|
1204
|
+
actions,
|
|
1205
|
+
error: {
|
|
1206
|
+
kind: error instanceof Error ? error.message : 'identity_browser_failed',
|
|
1207
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1208
|
+
},
|
|
1209
|
+
runtime_url: await tab.url(),
|
|
1210
|
+
screenshot_path: request.screenshot_path,
|
|
1211
|
+
screenshot_mime: request.screenshot_mime,
|
|
1212
|
+
started_at: startedAt,
|
|
1213
|
+
finished_at: new Date().toISOString(),
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
export async function executeChromeIdentityBridge({ tab, requestFile }) {
|
|
1219
|
+
if (!tab?.playwright
|
|
1220
|
+
|| typeof tab.goto !== 'function'
|
|
1221
|
+
|| typeof tab.screenshot !== 'function') {
|
|
1222
|
+
throw new Error('chrome_control_tab_required');
|
|
1223
|
+
}
|
|
1224
|
+
const request = validateRequest(JSON.parse(await readFile(requestFile, 'utf8')));
|
|
1225
|
+
await validateOutputPaths(request, requestFile);
|
|
1226
|
+
const result = await runOperation(tab, request);
|
|
1227
|
+
try {
|
|
1228
|
+
await persistBrowserLease(request, result);
|
|
1229
|
+
await writeJsonExclusive(request.result_path, result);
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
let cleanup;
|
|
1232
|
+
if (request.operation === 'mock' && result.ok) {
|
|
1233
|
+
cleanup = await bestEffortUnmock(tab, request, labelsFor(request.language), result.before?.id ?? null);
|
|
1234
|
+
}
|
|
1235
|
+
await persistBrowserLease(request, result, { cleanup, localResultWriteFailed: true }).catch(() => undefined);
|
|
1236
|
+
throw error;
|
|
1237
|
+
}
|
|
1238
|
+
return {
|
|
1239
|
+
ok: result.ok,
|
|
1240
|
+
operation: request.operation,
|
|
1241
|
+
requestId: request.request_id,
|
|
1242
|
+
resultPath: request.result_path,
|
|
1243
|
+
screenshotPath: request.screenshot_path,
|
|
1244
|
+
currentUser: result.current_user || result.after || null,
|
|
1245
|
+
lease: result.lease || null,
|
|
1246
|
+
error: result.error || null,
|
|
1247
|
+
};
|
|
1248
|
+
}
|