fix: reject legacy copy paths and surface native Add failures

This commit is contained in:
阿白叔 committed 2026-11-03 12:51:35 +08:00
1 parent e915aaa865
commit 9ac2f91dde
5 files changed
+248 -1

No files matched your search

@@ -0,0 +1,110 @@
"""Observed native copy failure and conservative legacy Win32 path admission."""
import hashlib
import json
from pathlib import Path
import re
import time
_COPY_ERROR = b'Error! Cannot copy iCDB base of Reusable Block project.'
_LOG_LIMIT = 2*1024*1024
def snapshot_add_log(library):
path = Path(library).parent/'LogFiles/ReuseBlockLogLO.txt'
try:
data = b''
if path.exists():
with path.open('rb') as stream: data = stream.read(_LOG_LIMIT+1)
if len(data) > _LOG_LIMIT: raise ValueError('Native Add log exceeds the bounded observation limit.')
return {'path': str(path), 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
except (OSError, ValueError) as error:
return {'path': str(path), 'unavailable': str(error)}
def fresh_add_failure(baseline, name):
if 'unavailable' in baseline: return None
try:
with Path(baseline['path']).open('rb') as stream:
data = stream.read(_LOG_LIMIT+1)
offset = baseline['size']
if (len(data) > _LOG_LIMIT or len(data) < offset
or hashlib.sha256(data[:offset]).hexdigest() != baseline['sha256']):
return None
marker = re.compile(rb'REUSE BLOCK:\s*INFORMATION:\s*'+re.escape(name.encode('mbcs'))
+rb'\s+'+re.escape(_COPY_ERROR))
for line in data[offset:].splitlines():
if marker.search(line): return line.decode('mbcs')
except (OSError, UnicodeError):
pass
return None
def failure_ack_button(title, static_text, buttons):
if title != 'Library Manager' or static_text.strip() != '系统找不到指定的路径。' or len(buttons) != 1:
return None
button = buttons[0]
if (button.get('id') == 2 and button.get('class') == 'Button'
and button.get('text') == '确定' and button.get('enabled') is True):
return button['hwnd']
return None
def validate_native_copy_paths(source, library, name):
from .scoped_manifest import scan_tree
from .network_path import absolute_preserving_drive
source = absolute_preserving_drive(source)
target = absolute_preserving_drive(library).parent/'ReusableBlocksLP'/name/'Work'
paths = [source.parent, *scan_tree(source.parent)]
for path in paths:
relative = path.relative_to(source.parent)
for label, candidate in (('暂存来源', path), ('目标', target/relative)):
# Legacy CopyFile's 260-WCHAR buffer includes the terminating NUL.
length = len(str(candidate).encode('utf-16-le'))//2
if length >= 260:
raise ValueError(f'NATIVE_PATH_TOO_LONG: {label}路径为 {length} 个字符,已超过原生复制支持范围。'
f'请缩短操作数据/证据目录或目标库路径后重试;所有工程和日志文件均保留。路径:{candidate}')
def observe_add_failure(desktop, owned_pids, root, baseline, name, state):
"""Record owned modal evidence and acknowledge only the observed error box."""
import pythoncom, win32con, win32gui, win32process
from .management import _write_json
fresh_log = fresh_add_failure(baseline, name)
for handle in desktop.EnumDesktopWindows():
hwnd = int(handle)
if (win32process.GetWindowThreadProcessId(hwnd)[1] not in owned_pids
or not win32gui.IsWindowVisible(hwnd) or win32gui.GetClassName(hwnd) != '#32770'):
continue
title = win32gui.GetWindowText(hwnd)
if title in ('New Reusable Block', 'Reusable Blocks'): continue
children = []
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(int(child)), None)
controls = [{'hwnd': child, 'id': win32gui.GetDlgCtrlID(child), 'class': win32gui.GetClassName(child),
'text': win32gui.GetWindowText(child), 'enabled': bool(win32gui.IsWindowEnabled(child))}
for child in children]
static = '\n'.join(c['text'] for c in controls if c['class'] == 'Static')
buttons = [c for c in controls if c['class'] == 'Button']
record = {'hwnd': hwnd, 'title': title, 'controls': controls, 'fresh_log_failure': fresh_log}
key = json.dumps(record, ensure_ascii=False, sort_keys=True)
if key not in state.setdefault('observed', set()):
state['observed'].add(key)
with (Path(root)/'native-add-dialogs.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(record, ensure_ascii=False)+'\n')
button = failure_ack_button(title, static, buttons)
if button is not None and win32process.GetWindowThreadProcessId(button)[1] in owned_pids:
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
deadline = time.monotonic()+2
while win32gui.IsWindow(hwnd) and time.monotonic() < deadline:
pythoncom.PumpWaitingMessages(); time.sleep(.05)
record['acknowledged'] = not win32gui.IsWindow(hwnd)
_write_json(Path(root)/'native-add-output.json', {'success_message': None, 'failure': record})
raise RuntimeError('NATIVE_ADD_FAILED: '+static.strip()
+ (' '+fresh_log if fresh_log else '')
+ ('' if record['acknowledged'] else ';原生错误对话框尚未确认关闭。'))
if fresh_log:
first_seen = state.setdefault('failure_seen_at', time.monotonic())
# Allow the paired native error popup to appear for normal acknowledgement.
if time.monotonic()-first_seen >= 2:
_write_json(Path(root)/'native-add-output.json', {'success_message': None,
'failure': {'fresh_log_failure': fresh_log, 'acknowledged': False}})
raise RuntimeError('NATIVE_ADD_FAILED: '+fresh_log)
+12 -1
View File
@@ -218,12 +218,17 @@ class NativeManagementAdapter:
return self._add_transaction(request, Path(evidence))
def prepare_add_transaction(self, request, root, *, original_source):
from .native_engineering_identity import project_library, asset_identity, capture_identity
from .native_engineering_identity import project_library, asset_identity, capture_identity, IdentityOutcome
from .native_add_failures import validate_native_copy_paths
from .management_transaction import current_lease, prepare_transaction
from .management import source_project
from .backup_recovery import _align_library
if not self.capabilities()['add'].supported:
raise ValueError(self.capabilities()['add'].reason)
try:
validate_native_copy_paths(request.source, request.library, request.name)
except ValueError as error:
return request, IdentityOutcome(None, True, str(error), Path(root))
current_lease(request.library)
original_assets = asset_identity(original_source, project_library(original_source))
staged, pcb, _ = source_project(request.source, request.top_level_block)
@@ -617,6 +622,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
_dispatch_diagnostics(root, 'after-pywinauto-import', app, library)
from .backup_recovery import _align_library
from .management import source_project
from .native_add_failures import validate_native_copy_paths, snapshot_add_log, observe_add_failure
source, pcb, top = source_project(job['source'], job.get('top_level_block', ''))
source_folder = 'source-replacement' if job['operation'] == 'probe_readd' else 'source'
source_root = (Path(root).resolve()/'source'
@@ -624,6 +630,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
else Path(root).parent.resolve()/source_folder)
if not source.is_relative_to(source_root):
raise ValueError('隔离新增只允许使用本次复制的来源工程。')
validate_native_copy_paths(source, job['library'], job['name'])
_align_library(source, pcb, Path(job['library']))
_dispatch_diagnostics(root, 'after-source-alignment', app, library,
paths={'source': str(source), 'pcb': str(pcb), 'library_argument': job['library']})
@@ -673,10 +680,14 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
ok = win32gui.GetDlgItem(dialog, 1083)
if not ok:
raise RuntimeError('原生新增确认按钮缺失。')
log_baseline = snapshot_add_log(job['library'])
_write_json(root/'native-add-log-baseline.json', log_baseline)
observed_failures = {}
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
success = None
while time.monotonic() < deadline:
pythoncom.PumpWaitingMessages()
observe_add_failure(desktop, owned_pids, root, log_baseline, job['name'], observed_failures)
for hwnd in desktop.EnumDesktopWindows():
if win32process.GetWindowThreadProcessId(hwnd)[1] not in owned_pids or not win32gui.IsWindowVisible(hwnd):
continue