Files
starrrLight 8ad4b29e4c feat(附件): 增加请求级文本读取与上传代理
支持任意 POST 路径的 multipart 暂存、原始字节转发和 TXT、DOCX、DOC 文本提取;通过 host.files.read_text 提供请求内受限读取,禁止插件改写附件和上传正文。

增加附件数量、文本、解压、超时和读取次数限制,覆盖断开、异常及清理场景;补充依赖、LibreOffice 镜像安装和插件接口文档,不修改业务 Lua 插件。

验证:全量测试 128 通过、2 个既有失败、1 个跳过;既有失败为 test_example_redacts_cross_event_phone 和 test_network_example_uses_configuration_and_http_result,均缺少插件必填配置。Ruff 静态检查、改动文件格式检查、pip check 和差异检查通过;全仓格式检查保留两处既有问题。当前环境缺少 LibreOffice 和 Docker,真实 DOC 转换及镜像构建未验证。
2026-10-15 18:03:23 +08:00

154 lines
5.6 KiB
Python

"""Bounded text extraction in a disposable process; no document bytes enter Lua."""
import codecs
import json
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
from docx import Document
from docx.table import Table
from docx.text.paragraph import Paragraph
class TextBuffer:
def __init__(self, maximum):
self.maximum = maximum
self.parts = []
self.size = 0
self.partial = False
def add(self, text):
raw = text.encode("utf-8")
available = self.maximum - self.size
if len(raw) > available:
raw = raw[:available].decode("utf-8", errors="ignore").encode("utf-8")
self.partial = True
self.parts.append(raw.decode("utf-8"))
self.size += len(raw)
def result(self):
return "".join(self.parts), "partial" if self.partial else "complete"
def docx_text(path, limits):
# Inspect every archive member before python-docx expands any XML.
with zipfile.ZipFile(path) as archive:
entries = archive.infolist()
if (
len(entries) > limits["max_attachment_zip_entries"]
or sum(entry.file_size for entry in entries) > limits["max_attachment_unpacked_bytes"]
):
raise ValueError("archive limit")
if any(entry.flag_bits & 1 for entry in entries):
raise ValueError("encrypted archive")
if "word/document.xml" not in archive.namelist():
raise ValueError("not a Word document")
document = Document(path)
buffer = TextBuffer(limits["max_attachment_text_bytes"])
def blocks(container):
for block in container.iter_inner_content():
if isinstance(block, Paragraph):
buffer.add(block.text + "\n")
elif isinstance(block, Table):
for row in block.rows:
seen = set()
for cell in row.cells:
# A merged cell appears repeatedly in row.cells.
if cell._tc in seen:
continue
seen.add(cell._tc)
blocks(cell)
if buffer.partial:
return
if buffer.partial:
return
blocks(document)
return buffer.result()
def extract(path, declared_type, limits):
detected = declared_type
try:
with path.open("rb") as source:
signature = source.read(8)
if declared_type == "txt":
raw = path.read_bytes()
if raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
raise ValueError("unsupported encoding")
encoding = (
"utf-16"
if raw.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))
else "utf-8-sig"
)
text = raw.decode(encoding, errors="strict")
if "\x00" in text:
raise ValueError("binary content")
buffer = TextBuffer(limits["max_attachment_text_bytes"])
buffer.add(text)
text, status = buffer.result()
elif declared_type == "docx":
if not signature.startswith(b"PK"):
raise ValueError("invalid docx")
text, status = docx_text(path, limits)
elif declared_type == "doc":
if signature != bytes.fromhex("d0cf11e0a1b11ae1"):
raise ValueError("invalid doc")
executable = shutil.which("soffice") or shutil.which("libreoffice")
if not executable:
raise ValueError("converter unavailable")
profile = path.parent / "lo-profile"
profile.mkdir()
(profile / "user").mkdir()
(profile / "user" / "registrymodifications.xcu").write_text(
'<oor:items xmlns:oor="http://openoffice.org/2001/registry">'
'<item oor:path="/org.openoffice.Office.Common/Security/Scripting">'
'<prop oor:name="MacroSecurityLevel" oor:op="fuse"><value>3</value></prop>'
"</item></oor:items>",
encoding="utf-8",
)
subprocess.run(
[
executable,
f"-env:UserInstallation={profile.as_uri()}",
"--headless",
"--nologo",
"--nodefault",
"--norestore",
"--convert-to",
"docx",
"--outdir",
str(path.parent),
str(path),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
# The supervisor owns the deadline and kills the entire process tree.
)
converted = path.with_suffix(".docx")
if converted.stat().st_size > limits["max_attachment_unpacked_bytes"]:
raise ValueError("conversion limit")
text, status = docx_text(converted, limits)
else:
return {"text": "", "extraction_status": "unsupported", "detected_type": "unknown"}
return {"text": text, "extraction_status": status, "detected_type": detected}
except Exception:
# Never expose parser errors, local paths or document fragments.
return {"text": "", "extraction_status": "failed", "detected_type": detected}
def main():
path = Path(sys.argv[1])
limits = json.loads(sys.argv[3])
result = extract(path, sys.argv[2], limits)
Path(sys.argv[4]).write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
if __name__ == "__main__":
main()