Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix: centralize Flash hyperlink safety

myhloli0394f75f7a62
diff --git a/mineru/model/flash/_shared/hyperlink.py b/mineru/model/flash/_shared/hyperlink.py
new file mode 100644
index 00000000..15f02812
--- /dev/null
+++ b/mineru/model/flash/_shared/hyperlink.py
@@ -0,0 +1,82 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""Flash 各格式复用的超链接目标校验与内部协议转义。"""
+
+from __future__ import annotations
+
+import html
+from collections.abc import Collection
+from typing import Any, Final
+from urllib.parse import urlsplit
+
+
+DEFAULT_EXTERNAL_HYPERLINK_SCHEMES: Final = frozenset({"http", "https", "mailto", "tel"})
+OFFICE_EXTERNAL_HYPERLINK_SCHEMES: Final = DEFAULT_EXTERNAL_HYPERLINK_SCHEMES | {"ftp"}
+
+
+def escape_inline_protocol_text(value: Any) -> str:
+ """把不可信字面文本转义为不会重建 MinerU 行内协议的内容。"""
+ return html.escape(str(value), quote=False)
+
+
+def sanitize_hyperlink_target(
+ value: Any,
+ *,
+ allowed_schemes: Collection[str] = DEFAULT_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative: bool = False,
+ allow_fragment: bool = False,
+ allow_root_relative: bool = False,
+) -> str | None:
+ """按格式策略保留安全外链、相对链接或文档内 fragment。"""
+ if value is None:
+ return None
+ normalized = str(value).strip()
+ if (
+ not normalized
+ or normalized == "."
+ or any(ord(char) < 0x20 or ord(char) == 0x7F or 0xD800 <= ord(char) <= 0xDFFF for char in normalized)
+ or any(char in normalized for char in ("<", ">", "\\"))
+ or normalized.startswith("//")
+ ):
+ return None
+ try:
+ parsed = urlsplit(normalized)
+ except ValueError:
+ return None
+ scheme = parsed.scheme.casefold()
+ allowed = {item.casefold() for item in allowed_schemes}
+ if scheme:
+ if scheme not in allowed:
+ return None
+ if scheme in {"http", "https", "ftp"}:
+ try:
+ if not parsed.netloc or parsed.hostname is None:
+ return None
+ except ValueError:
+ return None
+ elif not parsed.path:
+ return None
+ return normalized
+ if parsed.netloc:
+ return None
+ if normalized.startswith("#"):
+ return normalized if allow_fragment and normalized[1:].strip() else None
+ if normalized.startswith("/") and not allow_root_relative:
+ return None
+ return normalized if allow_relative else None
+
+
+def render_inline_hyperlink(label_markup: str, target: str) -> str:
+ """把已安全构造的标签内容和目标写入统一 hyperlink 行内协议。"""
+ if not label_markup or not target:
+ return label_markup
+ escaped_target = escape_inline_protocol_text(target)
+ return f"<hyperlink>{label_markup}<url>{escaped_target}</url></hyperlink>"
+
+
+__all__ = [
+ "DEFAULT_EXTERNAL_HYPERLINK_SCHEMES",
+ "OFFICE_EXTERNAL_HYPERLINK_SCHEMES",
+ "escape_inline_protocol_text",
+ "render_inline_hyperlink",
+ "sanitize_hyperlink_target",
+]
diff --git a/mineru/model/flash/epub/styles.py b/mineru/model/flash/epub/styles.py
index d51e0030..1c18debb 100644
--- a/mineru/model/flash/epub/styles.py
+++ b/mineru/model/flash/epub/styles.py
@@ -119,6 +119,14 @@ def _local_name(element: etree._Element) -> str:
return etree.QName(element).localname.casefold()
+def _numeric_font_weight(value: str) -> int | None:
+ """在整数转换前解析 CSS Fonts 允许的一到一千字重。"""
+ if not value.isascii() or not value.isdigit() or len(value) > 4:
+ return None
+ weight = int(value)
+ return weight if 1 <= weight <= 1_000 else None
+
+
def _parse_declarations(value: str) -> tuple[TextStyleDelta, bool | None]:
"""从声明串提取字体语义和 display/visibility 隐藏状态。"""
bold = italic = underline = strikethrough = superscript = subscript = None
@@ -130,7 +138,12 @@ def _parse_declarations(value: str) -> tuple[TextStyleDelta, bool | None]:
name = name.strip().casefold()
normalized = raw_value.split("!important", 1)[0].strip().casefold()
if name == "font-weight":
- bold = normalized in {"bold", "bolder"} or normalized.isdigit() and int(normalized) >= 600
+ if normalized in {"bold", "bolder"}:
+ bold = True
+ elif normalized in {"normal", "lighter"}:
+ bold = False
+ elif (weight := _numeric_font_weight(normalized)) is not None:
+ bold = weight >= 600
elif name == "font-style":
italic = normalized in {"italic", "oblique"}
elif name in {"text-decoration", "text-decoration-line"}:
diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.py
index 9192c84a..ccc2e995 100644
--- a/mineru/model/flash/epub/xhtml.py
+++ b/mineru/model/flash/epub/xhtml.py
@@ -8,12 +8,12 @@ import hashlib
import html
import re
from dataclasses import dataclass
-from urllib.parse import urlsplit
from lxml import etree # type: ignore[reportMissingImports]
from ....types import BlockType
from ....utils.image_payload import parse_image_data_uri_strict
+from .._shared.hyperlink import render_inline_hyperlink, sanitize_hyperlink_target
from .._shared.mathml import mathml_to_latex
from .constants import IMAGE_MEDIA_BY_EXTENSION, SVG_MEDIA_TYPE
from .package import EpubPackage
@@ -73,7 +73,6 @@ _SKIPPED_TAGS = frozenset(
"video",
}
)
-_SAFE_EXTERNAL_SCHEMES = frozenset({"http", "https", "mailto", "tel"})
_INDIVIDUAL_NOTE_TYPE_ORDER = ("footnote", "endnote", "rearnote")
_INDIVIDUAL_NOTE_ROLE_ORDER = ("doc-footnote", "doc-endnote")
_INDIVIDUAL_NOTE_TYPES = frozenset(_INDIVIDUAL_NOTE_TYPE_ORDER)
@@ -339,14 +338,13 @@ class EpubAnchorRegistry:
def resolve_anchor(self, href: str, *, base_part: str) -> str | None:
"""解析指向正文标题或 note 的 EPUB 包内链接,并返回不带井号的 anchor。"""
- normalized = (href or "").strip()
- if not normalized or any(ord(char) < 32 for char in normalized) or any(char in normalized for char in ("<", ">")):
- return None
- try:
- split = urlsplit(normalized)
- except ValueError:
- return None
- if split.scheme or split.netloc or normalized.startswith(("//", "\\")):
+ normalized = sanitize_hyperlink_target(
+ href,
+ allowed_schemes=(),
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ if normalized is None:
return None
target = self._package.resolve_reference(normalized, base_part=base_part)
if target is None:
@@ -355,24 +353,10 @@ class EpubAnchorRegistry:
def resolve_link(self, href: str, *, base_part: str) -> str | None:
"""解析安全外部链接或指向已输出标题/note 的 EPUB 内部链接。"""
- normalized = (href or "").strip()
- if not normalized or any(ord(char) < 32 for char in normalized) or any(char in normalized for char in ("<", ">")):
- return None
- try:
- split = urlsplit(normalized)
- except ValueError:
- return None
- if split.scheme:
- if split.scheme.casefold() not in _SAFE_EXTERNAL_SCHEMES:
- return None
- if split.scheme.casefold() in {"http", "https"}:
- try:
- if not split.netloc or split.hostname is None:
- return None
- except ValueError:
- return None
- return normalized
- anchor = self.resolve_anchor(normalized, base_part=base_part)
+ external = sanitize_hyperlink_target(href)
+ if external is not None:
+ return external
+ anchor = self.resolve_anchor(href, base_part=base_part)
return f"#{anchor}" if anchor else None
@@ -549,10 +533,7 @@ class EpubChapterConverter:
href = element.get("href") or element.get(_XLINK_HREF) or ""
target = self.anchors.resolve_link(href, base_part=self.chapter_path)
if target and content.strip():
- return (
- f"<hyperlink>{content}<url>{html.escape(target, quote=False)}</url></hyperlink>",
- extras,
- )
+ return render_inline_hyperlink(content, target), extras
return content, extras
@staticmethod
diff --git a/mineru/model/flash/office/doc/doc_converter.py b/mineru/model/flash/office/doc/doc_converter.py
index 45942d17..213eba7e 100644
--- a/mineru/model/flash/office/doc/doc_converter.py
+++ b/mineru/model/flash/office/doc/doc_converter.py
@@ -145,9 +145,9 @@ class DocConverter:
continue
segments.append(
OfficeRichTextSegment(
- text=escape(run.text, quote=False).replace("\n", "<br/>"),
+ text=run.text,
style=cls._style_names(run.style),
- hyperlink=escape(run.hyperlink, quote=True) if run.hyperlink else None,
+ hyperlink=run.hyperlink,
)
)
flush_segments()
diff --git a/mineru/model/flash/office/doc/fields.py b/mineru/model/flash/office/doc/fields.py
index 480276f1..24292a3d 100644
--- a/mineru/model/flash/office/doc/fields.py
+++ b/mineru/model/flash/office/doc/fields.py
@@ -5,14 +5,13 @@
from __future__ import annotations
import re
-from urllib.parse import urlparse
from loguru import logger
+from ..._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
from .models import DocTextRun
_TOKEN_RE = re.compile(r'"(?:\\.|[^"\\])*"|\\\S|\S+')
-_DRIVE_PATH_RE = re.compile(r"^[A-Za-z]:[\\/]")
def field_keyword(instruction: str) -> str:
@@ -52,25 +51,6 @@ def _unquote(token: str) -> str:
return token.replace(r"\"", '"').replace(r"\\", "\\")
-def sanitize_hyperlink_target(target: str) -> str | None:
- """仅保留网络、内部 fragment 和非本地安全相对链接。"""
-
- candidate = target.strip()
- if not candidate:
- return None
- lowered = candidate.casefold()
- if lowered.startswith(("javascript:", "data:", "vbscript:", "file:")):
- return None
- if candidate.startswith(("\\\\", "//", "/")) or _DRIVE_PATH_RE.match(candidate):
- return None
- parsed = urlparse(candidate)
- if parsed.scheme and parsed.scheme.casefold() not in {"http", "https", "mailto", "ftp"}:
- return None
- if parsed.scheme.casefold() == "mailto" and not parsed.path:
- return None
- return candidate
-
-
def hyperlink_target(instruction: str) -> str | None:
"""从 HYPERLINK 字段读取 URL 与可选内部书签。"""
@@ -101,7 +81,12 @@ def hyperlink_target(instruction: str) -> str | None:
candidate = f"#{anchor}"
else:
return None
- safe = sanitize_hyperlink_target(candidate)
+ safe = sanitize_hyperlink_target(
+ candidate,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
if safe is None:
logger.warning(f"DOC hyperlink target was rejected: {candidate!r}")
return safe
diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.py
index 8ef6ef66..76c832a1 100644
--- a/mineru/model/flash/office/odf/text.py
+++ b/mineru/model/flash/office/odf/text.py
@@ -9,11 +9,14 @@ import re
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
-from urllib.parse import urlsplit
from lxml import etree # type: ignore[reportMissingImports]
from .....types import BlockType
+from ..._shared.hyperlink import (
+ escape_inline_protocol_text,
+ sanitize_hyperlink_target,
+)
from ..._shared.mathml import mathml_to_latex
from ..._shared.image import image_to_b64str
from ..image import create_text_placeholder, serialize_office_image
@@ -37,7 +40,6 @@ from .table import OdfTableExpansionBudget, parse_table_grid, table_grid_to_html
_WHITESPACE_RE = re.compile(r"[\t\r\n ]+")
-_SAFE_EXTERNAL_HYPERLINK_SCHEMES = frozenset({"http", "https", "mailto", "tel"})
@dataclass(slots=True)
@@ -71,40 +73,6 @@ def _clean_xml_text(value: str | None) -> str:
return _WHITESPACE_RE.sub(" ", value)
-def _escape_href(value: str) -> str:
- """转义进入 HTML href 属性的 ODF 链接值。"""
- return html.escape(value, quote=True)
-
-
-def _safe_hyperlink(value: str | None) -> str | None:
- """保留安全相对链接与允许协议,拒绝活动协议和协议相对地址。"""
- if value is None:
- return None
- normalized = value.strip()
- if not normalized or any(ord(char) < 32 for char in normalized) or any(char in normalized for char in ("<", ">")):
- return None
- if normalized.startswith(("//", "\\")):
- return None
- try:
- parsed = urlsplit(normalized)
- except ValueError:
- return None
- scheme = parsed.scheme.casefold()
- if not scheme:
- return normalized
- if scheme not in _SAFE_EXTERNAL_HYPERLINK_SCHEMES:
- return None
- if scheme in {"http", "https"}:
- try:
- if not parsed.netloc or parsed.hostname is None:
- return None
- except ValueError:
- return None
- elif not parsed.path:
- return None
- return normalized
-
-
def _paragraph_anchor(paragraph: etree._Element) -> str | None:
"""返回段落最终能够挂载到输出 block 的首个 bookmark 名称。"""
for tag in (qname("text", "bookmark"), qname("text", "bookmark-start")):
@@ -170,7 +138,7 @@ def render_atoms_to_html(atoms: Sequence[InlineAtom]) -> str:
if isinstance(atom, InlineText):
rendered = _style_html(html.escape(atom.text), atom.style)
if atom.hyperlink:
- rendered = f'<a href="{_escape_href(atom.hyperlink)}">{rendered}</a>'
+ rendered = f'<a href="{html.escape(atom.hyperlink, quote=True)}">{rendered}</a>'
parts.append(rendered)
elif isinstance(atom, InlineMath):
parts.append(f"<eq>{html.escape(atom.latex)}</eq>")
@@ -212,13 +180,13 @@ def render_atoms_to_model(atoms: Sequence[InlineAtom], *, trim_edges: bool = Fal
for atom in atoms:
if isinstance(atom, InlineText):
style_names = atom.style.names()
- hyperlink = html.escape(atom.hyperlink, quote=False) if atom.hyperlink else None
+ hyperlink = atom.hyperlink
if text_fragments and (style_names != fragment_style or hyperlink != fragment_hyperlink):
flush_text_fragments()
if not text_fragments:
fragment_style = style_names
fragment_hyperlink = hyperlink
- text_fragments.append(html.escape(atom.text, quote=False))
+ text_fragments.append(atom.text)
continue
flush_segments()
if isinstance(atom, InlineMath):
@@ -226,7 +194,7 @@ def render_atoms_to_model(atoms: Sequence[InlineAtom], *, trim_edges: bool = Fal
elif isinstance(atom, InlineBreak):
parts.append("\n")
elif isinstance(atom, InlineImage) and atom.alt:
- parts.append(atom.alt)
+ parts.append(escape_inline_protocol_text(atom.alt))
elif isinstance(atom, (InlineBlockGroup, InlineNote)):
continue
flush_segments()
@@ -306,7 +274,11 @@ class OdfBlockParser:
atoms=atoms,
)
elif child.tag == qname("text", "a"):
- target = _safe_hyperlink(child.get(qname("xlink", "href")))
+ target = sanitize_hyperlink_target(
+ child.get(qname("xlink", "href")),
+ allow_relative=True,
+ allow_fragment=True,
+ )
if target is not None and target.startswith("#") and target[1:] not in self._anchor_targets:
target = None
self._walk_inlines(
@@ -333,6 +305,11 @@ class OdfBlockParser:
pass
elif child.tag == qname("text", "note"):
self._parse_note(child, style=style, hyperlink=hyperlink, atoms=atoms)
+ elif child.tag == qname("office", "annotation"):
+ if annotation_text := self._annotation_text(child):
+ atoms.append(InlineNote(annotation_text))
+ elif child.tag == qname("office", "annotation-end"):
+ pass
elif child.tag == qname("draw", "frame"):
inline_atom, blocks = self._parse_frame(child)
if inline_atom is not None:
@@ -362,6 +339,10 @@ class OdfBlockParser:
)
self._append_text_atom(atoms, child.tail, style=style, hyperlink=hyperlink)
+ def _annotation_text(self, annotation: etree._Element) -> str:
+ """只提取 ODF annotation 的正文段落与列表,不混入作者日期元数据。"""
+ return flatten_block_text(self.parse_container(annotation)).strip()
+
def _parse_note(
self,
note: etree._Element,
@@ -826,6 +807,12 @@ class OdfBlockParser:
return blocks
if element.tag == qname("text", "list"):
return [item for item in self.parse_list_blocks(element) if isinstance(item, dict)]
+ if element.tag == qname("office", "annotation"):
+ if annotation_text := self._annotation_text(element):
+ self.notes.append(annotation_text)
+ return []
+ if element.tag == qname("office", "annotation-end"):
+ return []
if element.tag == qname("table", "table"):
table_block = self.parse_table(element)
return [table_block] if table_block is not None else []
diff --git a/mineru/model/flash/office/ppt/parser.py b/mineru/model/flash/office/ppt/parser.py
index e2cc5f19..1489be99 100644
--- a/mineru/model/flash/office/ppt/parser.py
+++ b/mineru/model/flash/office/ppt/parser.py
@@ -8,11 +8,11 @@ from dataclasses import dataclass, replace
import struct
from typing import Iterable
import unicodedata
-from urllib.parse import urlparse
import zlib
from loguru import logger
+from ..._shared.hyperlink import sanitize_hyperlink_target
from ..errors import (
LegacyOfficeEncryptedError,
LegacyOfficeMalformedError,
@@ -399,16 +399,6 @@ def _decode_text_atom(record: PptRecord) -> str | None:
return None
-def _safe_hyperlink_target(target: str) -> str | None:
- """仅允许公开输出中可安全表达的外部链接 scheme。"""
-
- normalized = target.strip()
- if not normalized:
- return None
- scheme = urlparse(normalized).scheme.lower()
- return normalized if scheme in _ALLOWED_LINK_SCHEMES else None
-
-
def _hyperlink_targets(document: PptRecord, budget: RecordBudget) -> dict[int, str]:
"""建立 ExHyperlinkId 到安全外链目标的映射。"""
@@ -425,7 +415,7 @@ def _hyperlink_targets(document: PptRecord, budget: RecordBudget) -> dict[int, s
strings.append(utf16_text(child.payload))
if link_id is None or not strings:
continue
- safe_target = _safe_hyperlink_target(strings[-1])
+ safe_target = sanitize_hyperlink_target(strings[-1], allowed_schemes=_ALLOWED_LINK_SCHEMES)
if safe_target is None:
logger.warning(f"PPT_UNSAFE_HYPERLINK: hyperlink id={link_id} was downgraded")
continue
diff --git a/mineru/model/flash/office/ppt/ppt_converter.py b/mineru/model/flash/office/ppt/ppt_converter.py
index 64fe4f1b..34e51573 100644
--- a/mineru/model/flash/office/ppt/ppt_converter.py
+++ b/mineru/model/flash/office/ppt/ppt_converter.py
@@ -4,7 +4,6 @@
from __future__ import annotations
-from html import escape
from typing import Any, BinaryIO
from ..legacy.ole import BoundedOleReader
@@ -76,9 +75,9 @@ class PptConverter:
segments = [
OfficeRichTextSegment(
- text=escape(run.text, quote=False).replace("\n", " "),
+ text=run.text.replace("\n", " "),
style=cls._run_styles(run),
- hyperlink=escape(run.hyperlink, quote=False) if run.hyperlink else None,
+ hyperlink=run.hyperlink,
)
for run in paragraph.runs
if run.text
diff --git a/mineru/model/flash/office/pptx/pptx_converter.py b/mineru/model/flash/office/pptx/pptx_converter.py
index 4ef021d8..8d38671d 100644
--- a/mineru/model/flash/office/pptx/pptx_converter.py
+++ b/mineru/model/flash/office/pptx/pptx_converter.py
@@ -26,7 +26,7 @@ from ..streams import read_stream_bytes_from_start, rewind_stream
from .package_normalizer import normalize_pptx_package
from ..._shared.xycut import sort_entries
from .....types import BlockType
-from ..rich_text import OfficeRichTextSegment, build_rich_text_from_segments
+from ..rich_text import OfficeRichTextSegment, build_rich_text_from_segments, format_text_with_hyperlink
from ..._shared.image import image_to_b64str
IGNORED_NOTES_PLACEHOLDER_TYPES: Final = {
@@ -1188,20 +1188,7 @@ class PptxConverter:
style_str: Optional[str] = None,
) -> str:
"""按Office约定格式输出带样式/超链接的文本片段。"""
- if not text:
- return ""
-
- if hyperlink is None or str(hyperlink).strip() in ("", "."):
- if style_str:
- return f'<text style="{style_str}">{text}</text>'
- return text
-
- if style_str:
- text_tag = f'<text style="{style_str}">{text}</text>'
- else:
- text_tag = f"<text>{text}</text>"
-
- return f"<hyperlink>{text_tag}<url>{hyperlink}</url></hyperlink>"
+ return format_text_with_hyperlink(text, hyperlink, style_str)
def _resolve_hyperlink_from_run(self, run, shape) -> Optional[str]:
"""解析 run 对应的超链接,优先公开 API,回退到 XML + rels。"""
diff --git a/mineru/model/flash/office/rich_text.py b/mineru/model/flash/office/rich_text.py
index 05b43579..e5b27fa9 100644
--- a/mineru/model/flash/office/rich_text.py
+++ b/mineru/model/flash/office/rich_text.py
@@ -2,6 +2,13 @@
from dataclasses import dataclass
from typing import Any, Optional
+from .._shared.hyperlink import (
+ OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ escape_inline_protocol_text,
+ render_inline_hyperlink,
+ sanitize_hyperlink_target,
+)
+
VISIBLE_SPACE_STYLES = {"underline", "emphasis", "strikethrough"}
@@ -158,19 +165,25 @@ def format_text_tag(
"""生成 Office 内部富文本 text 标签;无样式普通文本默认不包标签。"""
if not text:
return text
+ escaped_text = escape_inline_protocol_text(text).replace("\r\n", "\n").replace("\r", "\n")
if style_str:
- return f'<text style="{style_str}">{text}</text>'
+ return f'<text style="{style_str}">{escaped_text}</text>'
if force_tag:
- return f"<text>{text}</text>"
- return text
+ return f"<text>{escaped_text}</text>"
+ return escaped_text
def is_valid_hyperlink_target(hyperlink: Any) -> bool:
"""判断超链接目标是否可作为真实链接输出。"""
- if hyperlink is None:
- return False
- hyperlink_str = str(hyperlink)
- return bool(hyperlink_str and hyperlink_str.strip() and hyperlink_str != ".")
+ return (
+ sanitize_hyperlink_target(
+ hyperlink,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ is not None
+ )
def format_text_with_hyperlink(
@@ -181,23 +194,34 @@ def format_text_with_hyperlink(
"""按 Office 内部约定输出带样式/超链接的文本片段。"""
if not text:
return text
- if not is_valid_hyperlink_target(hyperlink):
+ safe_target = sanitize_hyperlink_target(
+ hyperlink,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ if safe_target is None:
return format_text_tag(text, style_str)
text_tag = format_text_tag(text, style_str, force_tag=True)
- return f"<hyperlink>{text_tag}<url>{hyperlink}</url></hyperlink>"
+ return render_inline_hyperlink(text_tag, safe_target)
def _format_hyperlink_segments(group: list[OfficeRichTextSegment]) -> str:
"""将连续同 URL 的多个片段渲染成单个 hyperlink 标签。"""
if not group:
return ""
- hyperlink = group[0].hyperlink
- if not is_valid_hyperlink_target(hyperlink):
+ safe_target = sanitize_hyperlink_target(
+ group[0].hyperlink,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ if safe_target is None:
return "".join(format_text_tag(segment.text, _style_str(segment.style)) for segment in group if segment.text)
text_tags = [format_text_tag(segment.text, _style_str(segment.style), force_tag=True) for segment in group if segment.text]
- return f"<hyperlink>{''.join(text_tags)}<url>{hyperlink}</url></hyperlink>"
+ return render_inline_hyperlink("".join(text_tags), safe_target)
def format_hyperlink_group(
@@ -295,7 +319,12 @@ def build_rich_text_from_segments(
OfficeRichTextSegment(
segment.text,
_style_str(segment.style),
- str(segment.hyperlink) if segment.hyperlink is not None else None,
+ sanitize_hyperlink_target(
+ segment.hyperlink,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ ),
)
for segment in segments
if segment.text is not None and segment.text != ""
diff --git a/mineru/model/flash/office/rtf/converter.py b/mineru/model/flash/office/rtf/converter.py
index c4897752..b08ee304 100644
--- a/mineru/model/flash/office/rtf/converter.py
+++ b/mineru/model/flash/office/rtf/converter.py
@@ -195,9 +195,9 @@ class RtfConverter:
hyperlink = self._resolved_hyperlink(inline.hyperlink)
segments.append(
OfficeRichTextSegment(
- text=escape(inline.text, quote=False),
+ text=inline.text,
style=_style_names(inline),
- hyperlink=escape(hyperlink, quote=False) if hyperlink is not None else None,
+ hyperlink=hyperlink,
)
)
elif isinstance(inline, RtfInlineEquation):
diff --git a/mineru/model/flash/office/rtf/parser.py b/mineru/model/flash/office/rtf/parser.py
index 69bf1221..5f1ba064 100644
--- a/mineru/model/flash/office/rtf/parser.py
+++ b/mineru/model/flash/office/rtf/parser.py
@@ -7,10 +7,10 @@ import codecs
from dataclasses import dataclass, field, replace
import re
from typing import BinaryIO, Literal
-from urllib.parse import urlsplit
from loguru import logger
+from ..._shared.hyperlink import sanitize_hyperlink_target
from .....filetypes import rtf_header_offset
from ..errors import LegacyOfficeMalformedError, LegacyOfficeResourceLimitError
from ..limits import MAX_ASSET_TOTAL_BYTES, MAX_ENTRY_BYTES, MAX_GRID_SLOTS
@@ -796,28 +796,6 @@ def _capture_picture_group(data: bytes) -> _PictCapture | None:
return capture
-def _safe_hyperlink_target(target: str, *, local: bool) -> str | None:
- """保留安全文档链接;活动协议和协议相对地址一律降级。"""
- normalized = target.strip()
- if not normalized or any(ord(char) < 0x20 for char in normalized):
- return None
- if local:
- return f"#{normalized.lstrip('#')}" if normalized.lstrip("#") else None
- if normalized.startswith(("//", "\\")):
- return None
- try:
- parsed = urlsplit(normalized)
- except ValueError:
- return None
- if not parsed.scheme:
- return normalized
- if parsed.scheme.casefold() not in {"http", "https", "mailto", "tel"}:
- return None
- if parsed.scheme.casefold() in {"http", "https"} and (not parsed.netloc or parsed.hostname is None):
- return None
- return normalized
-
-
class RtfParser:
"""把一个 RTF 字节串解析为无布局、单逻辑页的 typed document。"""
@@ -1027,7 +1005,8 @@ class RtfParser:
if match is None:
return
raw_target = match.group("quoted") or match.group("bare") or ""
- target = _safe_hyperlink_target(raw_target, local=bool(match.group("local")))
+ candidate = f"#{raw_target.lstrip('#')}" if match.group("local") else raw_target
+ target = sanitize_hyperlink_target(candidate, allow_relative=True, allow_fragment=True)
if target is None:
return
start = min(frame.inline_start, len(self.context.inlines))
diff --git a/mineru/model/flash/office/spreadsheet/projector.py b/mineru/model/flash/office/spreadsheet/projector.py
index b11c4bc5..3b0324c6 100644
--- a/mineru/model/flash/office/spreadsheet/projector.py
+++ b/mineru/model/flash/office/spreadsheet/projector.py
@@ -7,7 +7,6 @@ import collections
import html
from collections.abc import Iterator
from typing import Any
-from urllib.parse import urlparse
from loguru import logger
from openpyxl.cell.rich_text import CellRichText
@@ -15,6 +14,7 @@ from openpyxl.workbook.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet
from .....types import BlockType
+from ..._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
from .html import EQUATION_BOOKENDS, render_spreadsheet_table
from .models import AnchoredBlock, DataRegion, ExcelCell, ExcelTable, FormulaMap, SheetImage
@@ -835,24 +835,6 @@ class SpreadsheetProjector:
return ""
- @staticmethod
- def _sanitize_hyperlink_target(target: str) -> str:
- """仅保留允许 scheme 的超链接并转义属性字符。"""
- href = target.strip()
- if not href:
- return ""
-
- if href.lower().startswith(("javascript:", "data:", "vbscript:")):
- return ""
-
- parsed = urlparse(href)
- allowed_schemes = {"http", "https", "mailto", "ftp"}
- scheme = parsed.scheme.lower() if parsed.scheme else ""
- if scheme and scheme not in allowed_schemes:
- return ""
-
- return html.escape(href, quote=True)
-
@staticmethod
def _apply_inline_font_tags(text_html: str, inline_font: Any) -> str:
"""按 openpyxl 行内字体顺序包装可见 HTML 标签。"""
@@ -884,7 +866,13 @@ class SpreadsheetProjector:
if cell.value is None:
return "", False
- link_target = self._sanitize_hyperlink_target(self._get_cell_hyperlink_target(cell))
+ safe_target = sanitize_hyperlink_target(
+ self._get_cell_hyperlink_target(cell),
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ link_target = html.escape(safe_target, quote=True) if safe_target else ""
if isinstance(cell.value, CellRichText):
html_parts = []
diff --git a/mineru/model/flash/office/xls/parser.py b/mineru/model/flash/office/xls/parser.py
index 3bbdf2e8..0d210266 100644
--- a/mineru/model/flash/office/xls/parser.py
+++ b/mineru/model/flash/office/xls/parser.py
@@ -6,11 +6,11 @@ from __future__ import annotations
from dataclasses import dataclass, field
import struct
-from urllib.parse import urlparse
import uuid
from loguru import logger
+from ..._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
from ..errors import (
LegacyOfficeEncryptedError,
LegacyOfficeMalformedError,
@@ -527,23 +527,6 @@ def _read_obj(payload: bytes) -> _SheetObject | None:
)
-def _sanitize_hyperlink_target(target: str) -> str | None:
- """保留 XlsxModel 允许的网络、邮件、内部与相对链接。"""
-
- candidate = target.strip().replace("\x00", "")
- if not candidate:
- return None
- lowered = candidate.casefold()
- if lowered.startswith(("javascript:", "data:", "vbscript:", "file:")):
- return None
- parsed = urlparse(candidate)
- if parsed.scheme and parsed.scheme.casefold() not in {"http", "https", "mailto", "ftp"}:
- return None
- if parsed.scheme.casefold() == "mailto" and not parsed.path:
- return None
- return candidate
-
-
def _read_hyperlink_unicode(payload: bytes, cursor: int) -> tuple[str | None, int]:
"""读取 Hyperlink Object 中含末尾 NUL 的 UTF-16 字符串。"""
@@ -624,7 +607,12 @@ def _read_hyperlink_target(payload: bytes) -> str | None:
if blocked_local_file:
logger.warning("XLS_HYPERLINK_BLOCKED: local File Moniker")
return None
- sanitized = _sanitize_hyperlink_target(target or "")
+ sanitized = sanitize_hyperlink_target(
+ target,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
if target and sanitized is None:
logger.warning("XLS_HYPERLINK_BLOCKED: target={!r}", target)
return sanitized
diff --git a/mineru/model/flash/pdf/document.py b/mineru/model/flash/pdf/document.py
index 30322109..d7c54b8e 100644
--- a/mineru/model/flash/pdf/document.py
+++ b/mineru/model/flash/pdf/document.py
@@ -11,7 +11,6 @@ from contextlib import contextmanager
from dataclasses import dataclass
from io import BytesIO
from typing import Any, Iterator, Literal, TypeAlias, cast
-from urllib.parse import urlsplit
import numpy as np
import pypdfium2 as pdfium
@@ -23,6 +22,7 @@ from PIL import Image, ImageOps
from ....types import BBox, PageInfo
from ....utils.image import crop_pil_image
+from .._shared.hyperlink import sanitize_hyperlink_target
from .._shared.image import image_to_bytes
from .classify import classify
from .pdfium import _pdfium_lock
@@ -1301,26 +1301,7 @@ def _form_bbox_from_object(
def _validate_pdf_external_link_target(value: str) -> str | None:
"""校验 PDF URI Action,只保留显式且可安全输出的外部链接。"""
-
- target = value.strip()
- if not target or any(ord(char) < 0x20 or ord(char) == 0x7F or 0xD800 <= ord(char) <= 0xDFFF for char in target):
- return None
- try:
- parsed = urlsplit(target)
- except ValueError:
- return None
- scheme = parsed.scheme.lower()
- if scheme not in _PDF_EXTERNAL_LINK_SCHEMES:
- return None
- if scheme in {"http", "https"}:
- try:
- if not parsed.netloc or parsed.hostname is None:
- return None
- except ValueError:
- return None
- elif not parsed.path:
- return None
- return target
+ return sanitize_hyperlink_target(value, allowed_schemes=_PDF_EXTERNAL_LINK_SCHEMES)
def _get_pdfium_uri_path(raw_doc: Any, raw_action: Any) -> str | None:
diff --git a/mineru/model/flash/pdf/text_styles.py b/mineru/model/flash/pdf/text_styles.py
index c15d9067..6a4912ef 100644
--- a/mineru/model/flash/pdf/text_styles.py
+++ b/mineru/model/flash/pdf/text_styles.py
@@ -13,6 +13,7 @@ from typing import Any, Iterable, Literal, Sequence, TypeVar, cast
from loguru import logger
from ....types import BBox, BlockType, RAW_CAPTION, RAW_FOOTNOTE
+from .._shared.hyperlink import render_inline_hyperlink
from .document import PDFLinkAnnotation
from ....utils.text import is_hyphen_at_line_end
@@ -1904,11 +1905,9 @@ def _wrap_link_intervals(
key=lambda item: (item.start, item.end, item.target),
reverse=True,
):
- escaped_target = html.escape(interval.target, quote=False)
output = (
- f"{output[: interval.start]}<hyperlink>"
- f"{output[interval.start : interval.end]}"
- f"<url>{escaped_target}</url></hyperlink>"
+ f"{output[: interval.start]}"
+ f"{render_inline_hyperlink(output[interval.start : interval.end], interval.target)}"
f"{output[interval.end :]}"
)
return output
diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.py
index 3f073c82..d0802f55 100644
--- a/tests/unittest/test_flash_epub.py
+++ b/tests/unittest/test_flash_epub.py
@@ -605,6 +605,19 @@ def test_epub_stylesheet_indexes_repeated_selectors_and_preserves_cascade_order(
assert len(stylesheet._class_cascades) == 3
+def test_epub_stylesheet_rejects_overlong_numeric_font_weight_before_int() -> None:
+ """验证超长或越界数字字重作为无效声明忽略且不会覆盖继承样式。"""
+ stylesheet = EpubStylesheet()
+ stylesheet.add(f".x {{ font-weight: {'9' * 100_000}; }} .y {{ font-weight: 1001; }}")
+
+ inherited = TextStyle(bold=True)
+ overlong = stylesheet.resolve(etree.fromstring(b'<span class="x"/>'), inherited)
+ out_of_range = stylesheet.resolve(etree.fromstring(b'<span class="y"/>'), inherited)
+
+ assert overlong.text.bold is True
+ assert out_of_range.text.bold is True
+
+
def test_doclib_extracts_epub_metadata(tmp_path: Path) -> None:
"""验证 doclib 从 OPF 读取元数据和 spine 逻辑页数。"""
source = tmp_path / "book.epub"
diff --git a/tests/unittest/test_flash_legacy_doc.py b/tests/unittest/test_flash_legacy_doc.py
index efa114ff..08dbc7aa 100644
--- a/tests/unittest/test_flash_legacy_doc.py
+++ b/tests/unittest/test_flash_legacy_doc.py
@@ -11,7 +11,7 @@ import pytest
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
from mineru.backend.postprocess.lists import fix_office_list_blocks
from mineru.model.flash import DocModel
-from mineru.model.flash.office.doc.fields import sanitize_hyperlink_target
+from mineru.model.flash._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
from mineru.model.flash.office.doc.models import DocCharStyle, DocTableCell
from mineru.model.flash.office.doc.parser import _RawTableRow, _materialize_table_rows
from mineru.model.flash.office.doc.records import DocBudget
@@ -126,7 +126,15 @@ def test_doc_hyperlink_field_keeps_safe_target_and_drops_dangerous_target() -> N
def test_doc_hyperlink_security_policy(target: str, expected: str | None) -> None:
"""验证 DOC 链接白名单拒绝本地和可执行目标。"""
- assert sanitize_hyperlink_target(target) == expected
+ assert (
+ sanitize_hyperlink_target(
+ target,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ == expected
+ )
def test_doc_character_sprms_preserve_visible_styles_and_hide_revisions() -> None:
diff --git a/tests/unittest/test_flash_legacy_ppt.py b/tests/unittest/test_flash_legacy_ppt.py
index aa70e8d0..d47bf05a 100644
--- a/tests/unittest/test_flash_legacy_ppt.py
+++ b/tests/unittest/test_flash_legacy_ppt.py
@@ -10,6 +10,7 @@ import pytest
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
from mineru.model.flash import PptModel
+from mineru.model.flash._shared.hyperlink import sanitize_hyperlink_target
from mineru.model.flash.office.errors import LegacyOfficeEncryptedError, LegacyOfficeResourceLimitError
from mineru.model.flash.office.ppt import parser as ppt_parser
from mineru.model.flash.office.ppt.models import PptPresentation, PptSlide
@@ -127,10 +128,14 @@ def test_ppt_is_supported_by_public_parser(tmp_path: Path) -> None:
def test_safe_ppt_hyperlink_schemes_are_explicit() -> None:
"""验证外链白名单保留 Web/邮件链接并拒绝本地或脚本目标。"""
- assert ppt_parser._safe_hyperlink_target("https://example.com/a") == "https://example.com/a"
- assert ppt_parser._safe_hyperlink_target("mailto:[email protected]") == "mailto:[email protected]"
- assert ppt_parser._safe_hyperlink_target("file:///tmp/a") is None
- assert ppt_parser._safe_hyperlink_target("javascript:alert(1)") is None
+ assert sanitize_hyperlink_target("https://example.com/a", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) == (
+ "https://example.com/a"
+ )
+ assert sanitize_hyperlink_target("mailto:[email protected]", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) == (
+ )
+ assert sanitize_hyperlink_target("file:///tmp/a", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) is None
+ assert sanitize_hyperlink_target("javascript:alert(1)", allowed_schemes=ppt_parser._ALLOWED_LINK_SCHEMES) is None
def test_ppt_hyperlink_range_splits_utf16_and_style_boundaries() -> None:
diff --git a/tests/unittest/test_flash_legacy_xls.py b/tests/unittest/test_flash_legacy_xls.py
index 9efee996..1872b9b5 100644
--- a/tests/unittest/test_flash_legacy_xls.py
+++ b/tests/unittest/test_flash_legacy_xls.py
@@ -10,6 +10,7 @@ import pytest
from mineru.backend.analyze import aio_doc_analyze, doc_analyze
from mineru.model.flash import XlsModel
+from mineru.model.flash._shared.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
from mineru.model.flash.office.errors import (
LegacyOfficeEncryptedError,
LegacyOfficeMissingPartError,
@@ -17,7 +18,6 @@ from mineru.model.flash.office.errors import (
)
from mineru.model.flash.office.limits import MAX_RECORDS
from mineru.model.flash.office.xls import xls_converter as xls_converter_module
-from mineru.model.flash.office.xls import parser as xls_parser
from mineru.model.flash.office.xls.number_format import format_number, format_text
from mineru.model.flash.office.xls.records import RecordBudget
from mineru.parser import parse
@@ -184,11 +184,16 @@ def test_xls_text_format_and_unsafe_hyperlink_fallback() -> None:
)
pages = XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", records)])))
assert pages == [[{"type": BlockType.TEXT, "content": "unsafe"}]]
- assert xls_parser._sanitize_hyperlink_target("mailto:[email protected]") == ("mailto:[email protected]")
- assert xls_parser._sanitize_hyperlink_target("#Sheet2!A1") == "#Sheet2!A1"
- assert xls_parser._sanitize_hyperlink_target("../relative/path") == "../relative/path"
- assert xls_parser._sanitize_hyperlink_target("file:///tmp/local.xls") is None
- assert xls_parser._sanitize_hyperlink_target("custom:payload") is None
+ policy = {
+ "allowed_schemes": OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ "allow_relative": True,
+ "allow_fragment": True,
+ }
+ assert sanitize_hyperlink_target("mailto:[email protected]", **policy) == "mailto:[email protected]"
+ assert sanitize_hyperlink_target("#Sheet2!A1", **policy) == "#Sheet2!A1"
+ assert sanitize_hyperlink_target("../relative/path", **policy) == "../relative/path"
+ assert sanitize_hyperlink_target("file:///tmp/local.xls", **policy) is None
+ assert sanitize_hyperlink_target("custom:payload", **policy) is None
def test_xls_filepass_and_broken_boundsheet_behaviors() -> None:
diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.py
index d7e1cc10..c36ac7b3 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -916,6 +916,53 @@ def test_odf_flattened_titles_and_notes_keep_literal_protocol_escaped() -> None:
assert "javascript:alert(1)" not in relationships
+def test_odf_inline_image_alt_escapes_literal_hyperlink_protocol() -> None:
+ """验证行内图片 title/desc 不会重建活动 hyperlink。"""
+ literal = "&lt;hyperlink&gt;&lt;text&gt;click&lt;/text&gt;&lt;url&gt;javascript:alert(1)&lt;/url&gt;&lt;/hyperlink&gt;"
+ content = f"""<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
+ xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
+ xmlns:xlink="http://www.w3.org/1999/xlink">
+ <office:body><office:text><text:p>Before <draw:frame>
+ <draw:image xlink:href="Pictures/pixel.png"/><svg:title>{literal}</svg:title>
+ </draw:frame> After</text:p></office:text></office:body></office:document-content>"""
+ payload = build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})
+ middle, model = doc_analyze(payload, file_suffix="odt")
+
+ raw_content = model.pages[0][0]["content"]
+ markdown = render_markdown(middle)
+ docx = render_docx(middle)
+ with ZipFile(BytesIO(docx)) as package:
+ relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")
+
+ assert "&lt;hyperlink&gt;" in raw_content
+ assert "<hyperlink>" not in raw_content
+ assert "](javascript:" not in markdown
+ assert "javascript:alert(1)" not in relationships
+
+
+def test_odf_annotation_emits_page_footnote_without_metadata_in_body() -> None:
+ """验证标准 annotation 正文作为页脚注保留,作者日期不拼入周围正文。"""
+ content = """<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
+ xmlns:dc="http://purl.org/dc/elements/1.1/">
+ <office:body><office:text><text:p>Before <office:annotation office:name="comment-1">
+ <dc:creator>Alice</dc:creator><dc:date>2026-01-01</dc:date><text:p>Review note</text:p>
+ </office:annotation>After<office:annotation-end office:name="comment-1"/></text:p>
+ </office:text></office:body></office:document-content>"""
+
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))
+
+ body = next(block for block in pages[0] if block["type"] == BlockType.TEXT)
+ annotation = next(block for block in pages[0] if block["type"] == BlockType.PAGE_FOOTNOTE)
+ assert body["content"] == "Before After"
+ assert annotation["content"] == "Review note"
+ assert "Alice" not in str(pages) and "2026-01-01" not in str(pages)
+
+
def test_ods_sheet_titles_escape_literal_inline_protocol() -> None:
"""验证多 sheet 标题不会把名称中的内部协议重建为活动链接。"""
literal = "&lt;hyperlink&gt;&lt;text&gt;x&lt;/text&gt;&lt;url&gt;javascript:alert(1)&lt;/url&gt;&lt;/hyperlink&gt;"
diff --git a/tests/unittest/test_flash_shared_helpers.py b/tests/unittest/test_flash_shared_helpers.py
index 877c4c4b..0f501c2c 100644
--- a/tests/unittest/test_flash_shared_helpers.py
+++ b/tests/unittest/test_flash_shared_helpers.py
@@ -9,12 +9,18 @@ from PIL import Image
import pytest
from lxml import etree
+from mineru.model.flash._shared.hyperlink import (
+ OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ render_inline_hyperlink,
+ sanitize_hyperlink_target,
+)
from mineru.model.flash._shared.image import image_to_b64str, image_to_bytes
from mineru.model.flash._shared.mathml import mathml_to_latex
from mineru.model.flash.office.doc import records as doc_records
from mineru.model.flash.office.legacy.binary import bounded_slice, get_f64, get_i16, get_u16, get_u32
from mineru.model.flash.office.opc import relationship_source_base_dir, write_zip_package
from mineru.model.flash.office.ppt import records as ppt_records
+from mineru.model.flash.office.rich_text import OfficeRichTextSegment, build_rich_text_from_segments
from mineru.model.flash.office.xls import records as xls_records
@@ -70,6 +76,52 @@ def test_mathml_annotation_scan_skips_non_element_nodes(extra_node: str) -> None
assert mathml_to_latex(math) == "x^2"
+ ("target", "expected"),
+ [
+ ("https://example.com/path", "https://example.com/path"),
+ ("mailto:[email protected]", "mailto:[email protected]"),
+ ("#anchor", "#anchor"),
+ ("../relative/path", "../relative/path"),
+ ("javascript:alert(1)", None),
+ ("file:///tmp/local", None),
+ ("//example.com/path", None),
+ (r"C:\local\file", None),
+ ("https:///missing-host", None),
+ ("https://example.com/a\x01b", None),
+ ],
+)
+def test_shared_hyperlink_policy_rejects_active_and_local_targets(target: str, expected: str | None) -> None:
+ """验证共享策略统一处理外链、fragment、相对路径和危险目标。"""
+ assert (
+ sanitize_hyperlink_target(
+ target,
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ == expected
+ )
+
+
+def test_shared_hyperlink_protocol_escapes_url_and_rich_text_labels() -> None:
+ """验证共享协议构造不会由 URL 或 Office 标签文本重建内部标记。"""
+ assert render_inline_hyperlink("safe", "https://example.com/?a=1&b=2") == (
+ "<hyperlink>safe<url>https://example.com/?a=1&amp;b=2</url></hyperlink>"
+ )
+ unsafe = build_rich_text_from_segments(
+ [OfficeRichTextSegment("<hyperlink>click</hyperlink>", hyperlink="javascript:alert(1)")]
+ )
+ safe = build_rich_text_from_segments(
+ [OfficeRichTextSegment("<b>click</b>", style="bold", hyperlink="https://example.com/?a=1&b=2")]
+ )
+
+ assert unsafe == "&lt;hyperlink&gt;click&lt;/hyperlink&gt;"
+ assert safe == (
+ '<hyperlink><text style="bold">&lt;b&gt;click&lt;/b&gt;</text><url>https://example.com/?a=1&amp;b=2</url></hyperlink>'
+ )
+
+
def test_legacy_binary_readers_preserve_bounds_and_values() -> None:
"""验证旧版 Office 共用读取器只在完整边界内返回小端数值。"""
data = struct.pack("<HhId", 0xABCD, -123, 0x1234_5678, 1.25)