refactor: 重构解析器架构并添加编码检测和配置管理
简化 parse_input() 为纯调度器,通过遍历 readers 的 supports() 方法识别输入类型,移除 URL 特殊处理和文件检查逻辑。各 reader 的 parse() 方法负责完整验证(文件存在、格式有效性)。 新增功能: - 添加 chardet 编码自动检测,支持多种中文编码回退机制 - 创建统一配置类管理编码、下载超时、日志等级等配置项 - HTML reader 支持本地文件编码检测和 URL 统一处理 安全性改进: - 修复 safe_open_zip() 路径遍历漏洞,使用 pathlib 规范化路径 - 添加边界检查,search_markdown() 检查负数参数 其他改进: - 修复类型注解(argparse.Namespace) - 日志系统仅输出 ERROR 级别,避免干扰 Markdown 输出 - 更新 BaseReader 接口文档,明确 supports() 和 parse() 职责划分 - 同步 delta specs 到主 specs(document-reading、html-reader、configuration、encoding-detection)
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
IMAGE_PATTERN = re.compile(r"!\[[^\]]*\]\([^)]+\)")
|
||||
@@ -75,13 +76,18 @@ def safe_open_zip(zip_file: zipfile.ZipFile, name: str) -> Optional[zipfile.ZipE
|
||||
"""安全地从 ZipFile 中打开文件,防止路径遍历攻击"""
|
||||
if not name:
|
||||
return None
|
||||
if name.startswith("/") or name.startswith(".."):
|
||||
|
||||
try:
|
||||
normalized = Path(name).as_posix()
|
||||
# 检查是否包含父目录引用
|
||||
if ".." in Path(normalized).parts:
|
||||
return None
|
||||
# 检查是否为绝对路径
|
||||
if Path(normalized).is_absolute():
|
||||
return None
|
||||
return zip_file.open(name)
|
||||
except (ValueError, OSError):
|
||||
return None
|
||||
if "/../" in name or name.endswith("/.."):
|
||||
return None
|
||||
if "\\" in name:
|
||||
return None
|
||||
return zip_file.open(name)
|
||||
|
||||
|
||||
def normalize_markdown_whitespace(content: str) -> str:
|
||||
@@ -171,6 +177,13 @@ def search_markdown(
|
||||
content: str, pattern: str, context_lines: int = 0
|
||||
) -> Optional[str]:
|
||||
"""使用正则表达式搜索 markdown 文档,返回匹配结果及其上下文"""
|
||||
# 边界检查
|
||||
if not content:
|
||||
return None
|
||||
|
||||
if context_lines < 0:
|
||||
raise ValueError("context_lines 必须为非负整数")
|
||||
|
||||
try:
|
||||
regex = re.compile(pattern)
|
||||
except re.error:
|
||||
|
||||
Reference in New Issue
Block a user