odforge 0.3.3__tar.gz → 0.3.4__tar.gz

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.
Files changed (174) hide show
  1. {odforge-0.3.3 → odforge-0.3.4}/PKG-INFO +1 -1
  2. odforge-0.3.4/src/odforge/__init__.py +1 -0
  3. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/layoutcheck.py +3 -2
  4. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/preview.py +4 -0
  5. odforge-0.3.4/src/odforge/untrusted.py +423 -0
  6. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/validate.py +21 -1
  7. {odforge-0.3.3 → odforge-0.3.4}/tests/test_layoutcheck.py +1 -1
  8. odforge-0.3.4/tests/test_untrusted.py +326 -0
  9. {odforge-0.3.3 → odforge-0.3.4}/tests/test_validate.py +10 -4
  10. odforge-0.3.3/src/odforge/__init__.py +0 -1
  11. {odforge-0.3.3 → odforge-0.3.4}/.gitignore +0 -0
  12. {odforge-0.3.3 → odforge-0.3.4}/LICENSE +0 -0
  13. {odforge-0.3.3 → odforge-0.3.4}/README.md +0 -0
  14. {odforge-0.3.3 → odforge-0.3.4}/constraints.txt +0 -0
  15. {odforge-0.3.3 → odforge-0.3.4}/hatch_build.py +0 -0
  16. {odforge-0.3.3 → odforge-0.3.4}/pyproject.toml +0 -0
  17. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/SKILL.md +0 -0
  18. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/academic.md +0 -0
  19. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/clay.md +0 -0
  20. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/color-system.md +0 -0
  21. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/crimson.md +0 -0
  22. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/dark.md +0 -0
  23. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/forest.md +0 -0
  24. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/gold.md +0 -0
  25. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/minimal.md +0 -0
  26. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/navy.md +0 -0
  27. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/plum.md +0 -0
  28. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/sky.md +0 -0
  29. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/slate.md +0 -0
  30. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/teal.md +0 -0
  31. {odforge-0.3.3 → odforge-0.3.4}/skills/odforge-design/themes/violet.md +0 -0
  32. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/benchmark.py +0 -0
  33. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/check.py +0 -0
  34. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/cli.py +0 -0
  35. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/components.py +0 -0
  36. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/critic.py +0 -0
  37. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/docfonts.py +0 -0
  38. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/editor_api.py +0 -0
  39. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/editor_launch.py +0 -0
  40. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/editor_routes.py +0 -0
  41. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/extract.py +0 -0
  42. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/feedback.py +0 -0
  43. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/fontembed.py +0 -0
  44. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/ir.py +0 -0
  45. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/llm.py +0 -0
  46. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/localguard.py +0 -0
  47. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/mcp_server.py +0 -0
  48. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/media.py +0 -0
  49. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/odpedit.py +0 -0
  50. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/package.py +0 -0
  51. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/pagefacts.py +0 -0
  52. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/references.py +0 -0
  53. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/render/__init__.py +0 -0
  54. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/render/odp.py +0 -0
  55. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/render/ods.py +0 -0
  56. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/render/odt.py +0 -0
  57. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/scene.py +0 -0
  58. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/setup_agents.py +0 -0
  59. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/templates.py +0 -0
  60. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/textmetrics.py +0 -0
  61. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/textutil.py +0 -0
  62. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/themes.py +0 -0
  63. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/watch.py +0 -0
  64. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/webapi.py +0 -0
  65. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/xmlsafe.py +0 -0
  66. {odforge-0.3.3 → odforge-0.3.4}/src/odforge/zipguard.py +0 -0
  67. {odforge-0.3.3 → odforge-0.3.4}/tests/conftest.py +0 -0
  68. {odforge-0.3.3 → odforge-0.3.4}/tests/test_benchmark.py +0 -0
  69. {odforge-0.3.3 → odforge-0.3.4}/tests/test_check.py +0 -0
  70. {odforge-0.3.3 → odforge-0.3.4}/tests/test_cli.py +0 -0
  71. {odforge-0.3.3 → odforge-0.3.4}/tests/test_critic.py +0 -0
  72. {odforge-0.3.3 → odforge-0.3.4}/tests/test_deck_quality.py +0 -0
  73. {odforge-0.3.3 → odforge-0.3.4}/tests/test_editor.py +0 -0
  74. {odforge-0.3.3 → odforge-0.3.4}/tests/test_editor_launch.py +0 -0
  75. {odforge-0.3.3 → odforge-0.3.4}/tests/test_extract.py +0 -0
  76. {odforge-0.3.3 → odforge-0.3.4}/tests/test_integration_pipeline.py +0 -0
  77. {odforge-0.3.3 → odforge-0.3.4}/tests/test_ir.py +0 -0
  78. {odforge-0.3.3 → odforge-0.3.4}/tests/test_llm.py +0 -0
  79. {odforge-0.3.3 → odforge-0.3.4}/tests/test_localguard.py +0 -0
  80. {odforge-0.3.3 → odforge-0.3.4}/tests/test_mcp.py +0 -0
  81. {odforge-0.3.3 → odforge-0.3.4}/tests/test_media.py +0 -0
  82. {odforge-0.3.3 → odforge-0.3.4}/tests/test_package.py +0 -0
  83. {odforge-0.3.3 → odforge-0.3.4}/tests/test_pagefacts.py +0 -0
  84. {odforge-0.3.3 → odforge-0.3.4}/tests/test_preview.py +0 -0
  85. {odforge-0.3.3 → odforge-0.3.4}/tests/test_render_odp.py +0 -0
  86. {odforge-0.3.3 → odforge-0.3.4}/tests/test_render_ods.py +0 -0
  87. {odforge-0.3.3 → odforge-0.3.4}/tests/test_render_odt.py +0 -0
  88. {odforge-0.3.3 → odforge-0.3.4}/tests/test_setup_agents.py +0 -0
  89. {odforge-0.3.3 → odforge-0.3.4}/tests/test_sources.py +0 -0
  90. {odforge-0.3.3 → odforge-0.3.4}/tests/test_templates.py +0 -0
  91. {odforge-0.3.3 → odforge-0.3.4}/tests/test_textmetrics.py +0 -0
  92. {odforge-0.3.3 → odforge-0.3.4}/tests/test_watch.py +0 -0
  93. {odforge-0.3.3 → odforge-0.3.4}/tests/test_webapi.py +0 -0
  94. {odforge-0.3.3 → odforge-0.3.4}/tests/test_zipguard.py +0 -0
  95. {odforge-0.3.3 → odforge-0.3.4}/web/editor.html +0 -0
  96. {odforge-0.3.3 → odforge-0.3.4}/web/index.html +0 -0
  97. {odforge-0.3.3 → odforge-0.3.4}/web/package-lock.json +0 -0
  98. {odforge-0.3.3 → odforge-0.3.4}/web/package.json +0 -0
  99. {odforge-0.3.3 → odforge-0.3.4}/web/src/App.test.tsx +0 -0
  100. {odforge-0.3.3 → odforge-0.3.4}/web/src/App.tsx +0 -0
  101. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/ConfirmBar.test.tsx +0 -0
  102. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/ConfirmBar.tsx +0 -0
  103. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/DiscoveryPanel.test.tsx +0 -0
  104. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/DiscoveryPanel.tsx +0 -0
  105. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/DownloadDock.test.tsx +0 -0
  106. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/DownloadDock.tsx +0 -0
  107. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/ErrorPanel.test.tsx +0 -0
  108. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/ErrorPanel.tsx +0 -0
  109. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/GateRail.test.tsx +0 -0
  110. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/GateRail.tsx +0 -0
  111. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/HomeDashboard.test.tsx +0 -0
  112. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/HomeDashboard.tsx +0 -0
  113. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/OutlineRail.test.tsx +0 -0
  114. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/OutlineRail.tsx +0 -0
  115. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/PreviewStage.tsx +0 -0
  116. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/PromptBar.test.tsx +0 -0
  117. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/PromptBar.tsx +0 -0
  118. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/SideNav.tsx +0 -0
  119. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/StatusNarrator.tsx +0 -0
  120. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/TemplateGallery.test.tsx +0 -0
  121. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/TemplateGallery.tsx +0 -0
  122. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/TemplatesPage.tsx +0 -0
  123. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/UnitCell.tsx +0 -0
  124. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/UnitDetail.test.tsx +0 -0
  125. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/UnitDetail.tsx +0 -0
  126. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/WaitingCard.tsx +0 -0
  127. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/display.test.tsx +0 -0
  128. {odforge-0.3.3 → odforge-0.3.4}/web/src/components/preview.test.tsx +0 -0
  129. {odforge-0.3.3 → odforge-0.3.4}/web/src/main.tsx +0 -0
  130. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/Bars.tsx +0 -0
  131. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/Canvas.tsx +0 -0
  132. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/Comments.tsx +0 -0
  133. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/EditorApp.tsx +0 -0
  134. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/Elements.tsx +0 -0
  135. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/PageList.tsx +0 -0
  136. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/SlideView.test.tsx +0 -0
  137. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/SlideView.tsx +0 -0
  138. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/api.ts +0 -0
  139. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/editor.css +0 -0
  140. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/geometry.test.ts +0 -0
  141. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/geometry.ts +0 -0
  142. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/main.tsx +0 -0
  143. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/richtext.test.ts +0 -0
  144. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/richtext.ts +0 -0
  145. {odforge-0.3.3 → odforge-0.3.4}/web/src/next/types.ts +0 -0
  146. {odforge-0.3.3 → odforge-0.3.4}/web/src/smoke.test.ts +0 -0
  147. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/api.test.ts +0 -0
  148. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/api.ts +0 -0
  149. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/cockpit.test.ts +0 -0
  150. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/cockpit.ts +0 -0
  151. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/discovery.test.ts +0 -0
  152. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/discovery.ts +0 -0
  153. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/errors.test.ts +0 -0
  154. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/errors.ts +0 -0
  155. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/mockStream.test.ts +0 -0
  156. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/mockStream.ts +0 -0
  157. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/sse.test.ts +0 -0
  158. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/sse.ts +0 -0
  159. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/subscribe.test.ts +0 -0
  160. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/taskName.test.ts +0 -0
  161. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/taskName.ts +0 -0
  162. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/throttle.test.ts +0 -0
  163. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/throttle.ts +0 -0
  164. {odforge-0.3.3 → odforge-0.3.4}/web/src/state/types.ts +0 -0
  165. {odforge-0.3.3 → odforge-0.3.4}/web/src/styles/app.css +0 -0
  166. {odforge-0.3.3 → odforge-0.3.4}/web/src/styles/layout.test.ts +0 -0
  167. {odforge-0.3.3 → odforge-0.3.4}/web/src/test/setup.ts +0 -0
  168. {odforge-0.3.3 → odforge-0.3.4}/web/src/theme/contrast.test.ts +0 -0
  169. {odforge-0.3.3 → odforge-0.3.4}/web/src/theme/tokens.css +0 -0
  170. {odforge-0.3.3 → odforge-0.3.4}/web/src/theme/useTheme.test.ts +0 -0
  171. {odforge-0.3.3 → odforge-0.3.4}/web/src/theme/useTheme.ts +0 -0
  172. {odforge-0.3.3 → odforge-0.3.4}/web/tsconfig.json +0 -0
  173. {odforge-0.3.3 → odforge-0.3.4}/web/tsconfig.test.json +0 -0
  174. {odforge-0.3.3 → odforge-0.3.4}/web/vite.config.ts +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: odforge
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Forge natural language into native ODF documents (.odt/.odp/.ods)
5
5
  Project-URL: Homepage, https://github.com/FantasySakura0515/ODForge
6
6
  Project-URL: Source, https://github.com/FantasySakura0515/ODForge
@@ -0,0 +1 @@
1
+ __version__ = "0.3.4"
@@ -43,6 +43,7 @@ from lxml import etree
43
43
 
44
44
  from .validate import run_soffice_convert
45
45
  from .xmlsafe import safe_fromstring
46
+ from .zipguard import read_xml_member
46
47
 
47
48
  _NS = {
48
49
  "draw": "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
@@ -190,9 +191,9 @@ def _cm(value: Optional[str]) -> float:
190
191
 
191
192
  def _read_parts(path: Path) -> tuple[etree._Element, etree._Element]:
192
193
  with zipfile.ZipFile(path) as package:
193
- content = safe_fromstring(package.read("content.xml"))
194
+ content = safe_fromstring(read_xml_member(package, "content.xml"))
194
195
  try:
195
- styles = safe_fromstring(package.read("styles.xml"))
196
+ styles = safe_fromstring(read_xml_member(package, "styles.xml"))
196
197
  except KeyError:
197
198
  styles = content
198
199
  return content, styles
@@ -14,6 +14,7 @@ from __future__ import annotations
14
14
  import shutil
15
15
  import subprocess
16
16
  import tempfile
17
+ import zipfile
17
18
  from pathlib import Path
18
19
 
19
20
  # `pymupdf`, never the legacy `fitz` alias: importing `fitz` makes PyMuPDF print
@@ -54,6 +55,9 @@ def convert_to_pdf(odf_path: Path, outdir: Path) -> Path:
54
55
  f"soffice timed out after {_SOFFICE_TIMEOUT}s converting "
55
56
  f"{odf_path.name} to pdf"
56
57
  ) from exc
58
+ except (ValueError, zipfile.BadZipFile) as exc:
59
+ # Not a package that can be sealed against outside links; never rendered.
60
+ raise RuntimeError(f"cannot render {odf_path.name}: {exc}") from exc
57
61
 
58
62
  if proc.returncode != 0:
59
63
  detail = (proc.stderr or proc.stdout or "").strip()
@@ -0,0 +1,423 @@
1
+ """Make a copy of a document that cannot reach outside itself when rendered.
2
+
3
+ A document may point at things that are not in its package: a picture at
4
+ ``file:///…`` or ``http://…``, a linked section, a DDE source, a downloadable
5
+ font. LibreOffice follows those while converting — so rendering a file from
6
+ someone else could pull a local file into the output, or call out to a server.
7
+ Its own "block untrusted links" setting does not stop this for a file opened
8
+ from disk (tried; the linked picture still rendered).
9
+
10
+ So the copy keeps only what points back into the package. Any attribute that
11
+ names something to load (``xlink:href``, ``*-url``, ``form:image-data``…) is
12
+ kept only when its target is a member of the package; DDE connections are
13
+ removed; formulas that call the web or read another file lose the formula and
14
+ keep their stored value; link refresh on load is switched off; embedded SVG
15
+ gets the same treatment, including ``url(…)`` in its styles, and inline
16
+ ``data:`` content is kept only when it is a plain raster image. Hyperlinks a
17
+ reader would have to click (``text:a``, ``draw:a``) are left alone: nothing
18
+ fetches them. For a layout check this changes nothing that matters — text
19
+ frames and their text are untouched.
20
+
21
+ Word-family files keep their outside targets in relationship parts instead;
22
+ there, every relationship that leaves the package is dropped, hyperlinks
23
+ included (the declared type cannot be trusted).
24
+ They are only accepted when the caller asks (``allow_ooxml``).
25
+
26
+ Everything here fails closed. A part that should be XML and does not parse, a
27
+ package that looks like two formats at once, a file whose name disagrees with
28
+ what it contains: each is refused, because the alternative is handing
29
+ LibreOffice bytes this code did not understand.
30
+
31
+ This closes the ways a document asks LibreOffice to fetch something that we know
32
+ of. It is not a sandbox: to render files from strangers on a machine that holds
33
+ secrets, also run the process without network or access to those files.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import base64
39
+ import binascii
40
+ import posixpath
41
+ import re
42
+ import zipfile
43
+ from pathlib import Path
44
+ from typing import Set
45
+ from urllib.parse import unquote
46
+
47
+ from lxml import etree
48
+
49
+ from .xmlsafe import safe_fromstring
50
+
51
+ _TEXT = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"
52
+ _TABLE = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
53
+ _OFFICE = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"
54
+ _CONFIG = "urn:oasis:names:tc:opendocument:xmlns:config:1.0"
55
+ # Links that are only followed when a person clicks them.
56
+ _CLICK_ONLY = {
57
+ f"{{{_TEXT}}}a",
58
+ "{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}a",
59
+ }
60
+ # Elements whose whole purpose is to pull data from another program or file.
61
+ _DDE = {
62
+ f"{{{_TEXT}}}dde-connection-decls",
63
+ f"{{{_TEXT}}}dde-connection-decl",
64
+ f"{{{_TEXT}}}dde-connection",
65
+ f"{{{_OFFICE}}}dde-source",
66
+ f"{{{_TABLE}}}dde-links",
67
+ f"{{{_TABLE}}}dde-link",
68
+ }
69
+ # Attributes that hold something LibreOffice evaluates.
70
+ _FORMULA_NAMES = ("formula", "expression", "condition")
71
+ _XML_BASE = "{http://www.w3.org/XML/1998/namespace}base"
72
+ _BINARY_DATA = f"{{{_OFFICE}}}binary-data"
73
+ # Word field codes that load another file or talk to another program.
74
+ # No word boundaries: it is matched against instructions joined without spaces.
75
+ _OUTSIDE_FIELD = re.compile(r"INCLUDEPICTURE|INCLUDETEXT|IMPORT|LINK|DDE", re.IGNORECASE)
76
+ # A formula that reaches out: web and DDE functions, or a reference into another
77
+ # file ('file:///…'#Sheet.A1). The cell keeps its stored value without it.
78
+ _OUTSIDE_FORMULA = re.compile(
79
+ r"WEBSERVICE|FILTERXML|\bDDE\s*\(|\bINDIRECT\s*\(|'[^']*'\s*#|://", re.IGNORECASE
80
+ )
81
+ _SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")
82
+ # In SVG styles: url(#gradient) stays, url(anything else) goes. @import too.
83
+ _CSS_URL = re.compile(r"url\(\s*(['\"]?)(?!#)[^)]*\1\s*\)", re.IGNORECASE)
84
+ _CSS_IMPORT = re.compile(r"@import[^;]*;?", re.IGNORECASE)
85
+
86
+ _INLINE_RASTER = re.compile(
87
+ r"data:image/(png|jpeg|gif|webp);base64,([A-Za-z0-9+/]*={0,2})$", re.IGNORECASE
88
+ )
89
+ _PNG, _JPEG, _GIF = b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", (b"GIF87a", b"GIF89a")
90
+ _FONT_MAGIC = (b"OTTO", b"\x00\x01\x00\x00", b"true", b"ttcf", b"wOFF", b"wOF2")
91
+ _BINARY_MAGIC = (_PNG, _JPEG, *_GIF, *_FONT_MAGIC)
92
+
93
+
94
+ def _is_raster_base64(text: str) -> bool:
95
+ """Whether base64 ``text`` (as in ``office:binary-data``) decodes to plain pixels."""
96
+ try:
97
+ head = base64.b64decode(re.sub(r"\s+", "", text)[:64], validate=True)
98
+ except (binascii.Error, ValueError):
99
+ return False
100
+ return head.startswith((_PNG, _JPEG, *_GIF)) or (head[:4] == b"RIFF" and head[8:12] == b"WEBP")
101
+
102
+
103
+ def _is_inline_raster(value: str) -> bool:
104
+ """A declared raster type, strict base64, and bytes that are that type."""
105
+ match = _INLINE_RASTER.match(value.strip())
106
+ if match is None:
107
+ return False
108
+ try:
109
+ data = base64.b64decode(match.group(2), validate=True)
110
+ except (binascii.Error, ValueError):
111
+ return False
112
+ kind = match.group(1).lower()
113
+ if kind == "png":
114
+ return data.startswith(_PNG)
115
+ if kind == "jpeg":
116
+ return data.startswith(_JPEG)
117
+ if kind == "gif":
118
+ return data.startswith(_GIF)
119
+ return data[:4] == b"RIFF" and data[8:12] == b"WEBP"
120
+
121
+
122
+ _RELATIONSHIP = "{http://schemas.openxmlformats.org/package/2006/relationships}Relationship"
123
+
124
+ _ODF_MIMETYPE_PREFIX = "application/vnd.oasis.opendocument."
125
+ # What a package says it is must match what its name says it is: LibreOffice
126
+ # looks at both, and a disagreement is a way to be read as something else.
127
+ _ODF_SUFFIXES = {
128
+ "text": {".odt", ".ott", ".oth", ".odm", ".otm"},
129
+ "presentation": {".odp", ".otp"},
130
+ "spreadsheet": {".ods", ".ots"},
131
+ "graphics": {".odg", ".otg"},
132
+ }
133
+ _OOXML_SUFFIXES = {".docx", ".pptx", ".xlsx"}
134
+ _OOXML_MARKERS = ("[Content_Types].xml", "_rels/.rels")
135
+
136
+ _MAX_PART_BYTES = 64 * 1024 * 1024
137
+ _MAX_TOTAL_BYTES = 512 * 1024 * 1024
138
+
139
+
140
+ def _is_target_attribute(name: str) -> bool:
141
+ """Attributes that name something to load: any ``href``, ``*-url``, ``image-data``…"""
142
+ local = name.rsplit("}", 1)[-1].lower()
143
+ return local in ("href", "url", "src", "image-data") or local.endswith(("-url", "-uri"))
144
+
145
+
146
+ def _stays_inside(value: str, base: str, members: Set[str]) -> bool:
147
+ """Whether ``value`` names something that is actually in the package.
148
+
149
+ An allowlist, not a search for bad patterns: the target is decoded,
150
+ resolved against the part it appears in, and kept only when the package has
151
+ a member there. Anything LibreOffice might read differently from this code
152
+ (odd escapes, schemes, absolute or parent paths) simply names no member.
153
+ """
154
+ value = value.strip()
155
+ if not value or value.startswith("#"):
156
+ return True # empty, or a place inside this same part
157
+ if value[:5].lower() == "data:":
158
+ # Inline bytes fetch nothing — as long as they are plain pixels. An
159
+ # inline SVG or HTML is another document, with links of its own that
160
+ # nothing here has looked at.
161
+ return _is_inline_raster(value)
162
+ for _ in range(3): # %252e%252e → %2e%2e → ..
163
+ decoded = unquote(value)
164
+ if decoded == value:
165
+ break
166
+ value = decoded
167
+ value = value.replace("\\", "/").split("#", 1)[0]
168
+ if _SCHEME.match(value) or value.startswith("/"):
169
+ return False
170
+ resolved = posixpath.normpath(posixpath.join(base, value))
171
+ if resolved in (".", "") or resolved.startswith(".."):
172
+ return False
173
+ return resolved in members or any(m.startswith(resolved + "/") for m in members)
174
+
175
+
176
+ def _css_unescape(css: str) -> str:
177
+ """Read CSS escapes the way a stylesheet parser does (``u\\72l`` is ``url``)."""
178
+
179
+ def char(match: re.Match[str]) -> str:
180
+ try:
181
+ return chr(int(match.group(1), 16))
182
+ except (ValueError, OverflowError):
183
+ return ""
184
+
185
+ css = re.sub(r"\\([0-9A-Fa-f]{1,6})[ \t\r\n\f]?", char, css)
186
+ return re.sub(r"\\(.)", r"\1", css, flags=re.DOTALL)
187
+
188
+
189
+ def _seal_css(css: str) -> str:
190
+ # Escapes are resolved before looking; no legitimate url() needs one.
191
+ return _CSS_URL.sub("none", _CSS_IMPORT.sub("", _css_unescape(css)))
192
+
193
+
194
+ def _local(tag: str) -> str:
195
+ return tag.rsplit("}", 1)[-1].lower()
196
+
197
+
198
+ def _seal_xml(data: bytes, base: str, members: Set[str]) -> bytes:
199
+ root = safe_fromstring(data)
200
+ changed = False
201
+ is_svg = _local(root.tag) == "svg" # by local name: the namespace is the file's own claim
202
+ for element in list(root.iter()):
203
+ if not isinstance(element.tag, str):
204
+ continue
205
+ if element.tag in _DDE:
206
+ parent = element.getparent()
207
+ if parent is not None:
208
+ parent.remove(element)
209
+ changed = True
210
+ continue
211
+ for name, value in list(element.attrib.items()):
212
+ local = _local(name)
213
+ if local == "formula" and not value.lstrip().lower().startswith(("of:", "=")):
214
+ # Older formula grammars spell an outside reference differently;
215
+ # only the one this code can read is let through.
216
+ del element.attrib[name]
217
+ changed = True
218
+ elif (
219
+ local in _FORMULA_NAMES or local.endswith(("-address", "-range", "-ranges"))
220
+ ) and _OUTSIDE_FORMULA.search(value):
221
+ del element.attrib[name]
222
+ changed = True
223
+ if element.get(_XML_BASE) is not None:
224
+ # Would re-point every relative target below it somewhere else.
225
+ del element.attrib[_XML_BASE]
226
+ changed = True
227
+ if element.tag == _BINARY_DATA and not _is_raster_base64(element.text or ""):
228
+ # Inline content that is not plain pixels (an SVG, an OLE object)
229
+ # is a document of its own that nothing here has read.
230
+ parent = element.getparent()
231
+ if parent is not None:
232
+ parent.remove(element)
233
+ changed = True
234
+ continue
235
+ if element.tag not in _CLICK_ONLY:
236
+ for name, value in list(element.attrib.items()):
237
+ if _is_target_attribute(name) and not _stays_inside(value, base, members):
238
+ del element.attrib[name]
239
+ changed = True
240
+ # url(…) can sit in any attribute (style, fill, filter, mask…).
241
+ for name, value in list(element.attrib.items()):
242
+ if "url(" in _css_unescape(value).lower():
243
+ sealed = _seal_css(value)
244
+ if sealed != value:
245
+ element.set(name, sealed)
246
+ changed = True
247
+ if is_svg and _local(element.tag) == "style":
248
+ # All of it, including text hidden after comments inside the element.
249
+ css = "".join(element.itertext())
250
+ for child in list(element):
251
+ element.remove(child)
252
+ element.text = _seal_css(css)
253
+ changed = True
254
+ # settings.xml: never refresh links on load.
255
+ if (
256
+ element.tag == f"{{{_CONFIG}}}config-item"
257
+ and element.get(f"{{{_CONFIG}}}name") == "LinkUpdateMode"
258
+ and (element.text or "").strip() != "0"
259
+ ):
260
+ element.text = "0"
261
+ changed = True
262
+ return _serialise(root, data, changed)
263
+
264
+
265
+ def _serialise(root: etree._Element, original: bytes, changed: bool) -> bytes:
266
+ """The original bytes when nothing changed — unless they carry a DTD.
267
+
268
+ A DOCTYPE can declare entities this parser refused to expand and another
269
+ parser might not, so it never travels: the tree is written out without it.
270
+ Entity references left in the tree then name nothing, which is a load error
271
+ rather than a file read.
272
+ """
273
+ info = root.getroottree().docinfo
274
+ if not changed and not info.doctype and not info.internalDTD and not info.externalDTD:
275
+ return original
276
+ body = etree.tostring(root, encoding="UTF-8", with_tail=False, doctype="")
277
+ return b"<?xml version='1.0' encoding='UTF-8'?>\n" + body.lstrip()
278
+
279
+
280
+ def _seal_ooxml_part(data: bytes) -> bytes:
281
+ """Blank Word field codes that would load a file or call another program.
282
+
283
+ A field's instruction can be split across any number of runs ("INCLUDE" +
284
+ "PICTURE"), so the instructions of the whole part are read as one string
285
+ with the whitespace taken out. If a loading keyword shows up anywhere in
286
+ it, every instruction in the part is blanked: fields then show the result
287
+ the file already stores, which is all a render needs.
288
+ """
289
+ root = safe_fromstring(data)
290
+ instructions = [
291
+ el for el in root.iter() if isinstance(el.tag, str) and _local(el.tag) == "instrtext"
292
+ ]
293
+ simple = [
294
+ (el, name)
295
+ for el in root.iter()
296
+ if isinstance(el.tag, str)
297
+ for name in el.attrib
298
+ if _local(name) == "instr"
299
+ ]
300
+ combined = "".join(el.text or "" for el in instructions) + "".join(
301
+ el.get(name, "") for el, name in simple
302
+ )
303
+ changed = False
304
+ if _OUTSIDE_FIELD.search(re.sub(r"\s+", "", combined)):
305
+ for el in instructions:
306
+ el.text = ""
307
+ for el, name in simple:
308
+ el.set(name, "")
309
+ changed = True
310
+ return _serialise(root, data, changed)
311
+
312
+
313
+ def _seal_rels(data: bytes) -> bytes:
314
+ """Drop every OOXML relationship that points outside the package.
315
+
316
+ Hyperlinks go too. The type a relationship declares is the document's own
317
+ claim: one labelled "hyperlink" can still be referenced from a picture, and
318
+ would then be fetched. Losing clickable links costs a render nothing.
319
+ """
320
+ root = safe_fromstring(data)
321
+ changed = False
322
+ for rel in list(root.iter(_RELATIONSHIP)):
323
+ target = rel.get("Target", "")
324
+ leaves = (
325
+ rel.get("TargetMode", "").lower() == "external"
326
+ or _SCHEME.match(target) is not None
327
+ or target.startswith(("\\\\", "//"))
328
+ )
329
+ if leaves:
330
+ parent = rel.getparent()
331
+ if parent is not None:
332
+ parent.remove(rel)
333
+ changed = True
334
+ return _serialise(root, data, changed)
335
+
336
+
337
+ def _looks_like_xml(name: str, data: bytes) -> bool:
338
+ """By name *or* by content: a part LibreOffice would parse must be sealed."""
339
+ if name.lower().endswith((".xml", ".svg", ".rels", ".rdf", ".xhtml")):
340
+ return True
341
+ if data[:2] in (b"\xff\xfe", b"\xfe\xff") or data[:4] == b"\x00\x00\xfe\xff":
342
+ return True # UTF-16 / UTF-32 text
343
+ # Anything that opens with markup, however much padding comes first — and
344
+ # anything that mentions a document root early on, whatever precedes it.
345
+ if data.lstrip(b"\xef\xbb\xbf \t\r\n\f\x00").startswith(b"<"):
346
+ return True
347
+ head = data[:8192].lower()
348
+ if b"<svg" in head or b"<!doctype" in head or b"<html" in head:
349
+ return True # whatever the first bytes claim; unparseable → refused
350
+ # A real picture or font may carry an XML metadata packet (photos often
351
+ # embed XMP), and refusing those would refuse ordinary documents. Only a
352
+ # full signature earns that, and only for the bare "<?xml" marker.
353
+ if data.startswith(_BINARY_MAGIC) or (data[:4] == b"RIFF" and data[8:12] == b"WEBP"):
354
+ return False
355
+ return b"<?xml" in head
356
+
357
+
358
+ def _kind(path: Path, source: zipfile.ZipFile, members: Set[str], allow_ooxml: bool) -> str:
359
+ """``"odf"`` or ``"ooxml"``; raises ``ValueError`` for anything ambiguous."""
360
+ mimetype = ""
361
+ if "mimetype" in members:
362
+ with source.open("mimetype") as member:
363
+ mimetype = member.read(256).decode("ascii", errors="replace").strip()
364
+ looks_ooxml = any(marker in members for marker in _OOXML_MARKERS)
365
+ suffix = path.suffix.lower()
366
+
367
+ if mimetype.startswith(_ODF_MIMETYPE_PREFIX):
368
+ if looks_ooxml:
369
+ raise ValueError(f"{path.name} 同時像 ODF 又像 Word 家族的檔案,不處理")
370
+ # "text-web", "text-master", "presentation-template" → their base kind.
371
+ family = mimetype[len(_ODF_MIMETYPE_PREFIX) :].split("-", 1)[0]
372
+ if suffix not in _ODF_SUFFIXES.get(family, set()):
373
+ raise ValueError(f"{path.name} 的副檔名和內容({mimetype})對不上,不處理")
374
+ return "odf"
375
+ if allow_ooxml and looks_ooxml and not mimetype and suffix in _OOXML_SUFFIXES:
376
+ return "ooxml"
377
+ raise ValueError(f"{path.name} 不是可以處理的文件格式")
378
+
379
+
380
+ def sealed_copy(path: Path, outdir: Path, *, allow_ooxml: bool = False) -> Path:
381
+ """Write ``path`` into ``outdir`` under the same name, without outside links.
382
+
383
+ Raises ``ValueError`` for a file that is not what its name says, that holds
384
+ a part which should be XML and is not, or that is too large to be a real
385
+ document; ``zipfile.BadZipFile`` for one that is not a zip at all.
386
+ """
387
+ path = Path(path)
388
+ target = Path(outdir) / path.name
389
+ if target.resolve() == path.resolve():
390
+ raise ValueError("封住連結的副本不能寫回原檔")
391
+ total = 0
392
+ with zipfile.ZipFile(path) as source, zipfile.ZipFile(target, "w") as out:
393
+ members = {info.filename for info in source.infolist()}
394
+ kind = _kind(path, source, members, allow_ooxml)
395
+ for info in source.infolist():
396
+ with source.open(info) as member:
397
+ data = member.read(_MAX_PART_BYTES + 1)
398
+ total += len(data)
399
+ if len(data) > _MAX_PART_BYTES or total > _MAX_TOTAL_BYTES:
400
+ raise ValueError(f"{path.name} 解開後太大,不處理")
401
+ if data[:2] == b"\x1f\x8b" or info.filename.lower().endswith(".svgz"):
402
+ # Compressed markup (.svgz) would reach LibreOffice unread.
403
+ raise ValueError(f"{path.name} 內含壓縮過的 {info.filename},不處理")
404
+ if data and _looks_like_xml(info.filename, data):
405
+ try:
406
+ if kind == "ooxml" and not info.filename.lower().endswith(".svg"):
407
+ if info.filename.lower().endswith(".rels"):
408
+ data = _seal_rels(data)
409
+ else:
410
+ data = _seal_ooxml_part(data)
411
+ else:
412
+ data = _seal_xml(data, posixpath.dirname(info.filename), members)
413
+ except etree.XMLSyntaxError as exc:
414
+ # Never pass on bytes that could not be read: a part this
415
+ # parser rejects but LibreOffice accepts would go unsealed.
416
+ raise ValueError(f"{path.name} 的 {info.filename} 讀不懂,不處理") from exc
417
+ stored = info.filename == "mimetype"
418
+ out.writestr(
419
+ zipfile.ZipInfo(info.filename, date_time=info.date_time),
420
+ data,
421
+ compress_type=zipfile.ZIP_STORED if stored else zipfile.ZIP_DEFLATED,
422
+ )
423
+ return target
@@ -194,7 +194,9 @@ def _build_soffice_cmd(
194
194
  fmt,
195
195
  "--outdir",
196
196
  str(outdir),
197
- str(src),
197
+ # Absolute, so a file named like an option ("-env:…", "--accept=…") is
198
+ # always read as a path.
199
+ str(Path(src).resolve()),
198
200
  ]
199
201
 
200
202
 
@@ -204,6 +206,8 @@ def run_soffice_convert(
204
206
  fmt: str,
205
207
  outdir: Path,
206
208
  timeout: int = _SOFFICE_TIMEOUT,
209
+ *,
210
+ trusted: bool = False,
207
211
  ) -> subprocess.CompletedProcess:
208
212
  """Convert ``src`` to ``fmt`` in ``outdir`` via an isolated soffice profile.
209
213
 
@@ -211,9 +215,23 @@ def run_soffice_convert(
211
215
  codebase. Creates a throwaway profile directory, passes it as
212
216
  ``-env:UserInstallation``, captures stdout/stderr and cleans the profile up.
213
217
  Raises :class:`subprocess.TimeoutExpired` on timeout (callers handle it).
218
+
219
+ The file handed to LibreOffice is a copy with its outside links removed
220
+ (:func:`odforge.untrusted.sealed_copy`): a document someone points the tool
221
+ at must not be able to pull local files into the output or call out while
222
+ it is rendered. Only ODF and OOXML packages can be sealed; anything else
223
+ raises ``ValueError`` / ``zipfile.BadZipFile``, whatever its name says.
224
+ ``trusted=True`` converts a file as it is — for input this code wrote.
214
225
  """
226
+ from .untrusted import sealed_copy
227
+
215
228
  profile_dir = Path(tempfile.mkdtemp(prefix="odforge-soffice-profile-"))
229
+ sealed_dir: Path | None = None
216
230
  try:
231
+ if not trusted:
232
+ # Same file name, so the output is named as the caller expects.
233
+ sealed_dir = Path(tempfile.mkdtemp(prefix="odforge-sealed-"))
234
+ src = sealed_copy(Path(src), sealed_dir, allow_ooxml=True)
217
235
  return subprocess.run(
218
236
  _build_soffice_cmd(soffice, src, fmt, outdir, profile_dir),
219
237
  # stdin must NOT be inherited: under an MCP/stdio host the parent's
@@ -228,6 +246,8 @@ def run_soffice_convert(
228
246
  )
229
247
  finally:
230
248
  shutil.rmtree(profile_dir, ignore_errors=True)
249
+ if sealed_dir is not None:
250
+ shutil.rmtree(sealed_dir, ignore_errors=True)
231
251
 
232
252
 
233
253
  # The error values LibreOffice writes into a cell whose formula it could not
@@ -203,7 +203,7 @@ def test_a_too_wide_table_in_a_text_document(tmp_path, sample_text_doc):
203
203
  "</tr></table><p>正常段落。</p></body></html>",
204
204
  encoding="utf-8",
205
205
  )
206
- run_soffice_convert(find_soffice(), html, "odt:writer8", tmp_path)
206
+ run_soffice_convert(find_soffice(), html, "odt:writer8", tmp_path, trusted=True)
207
207
  report = check_layout(tmp_path / "wide.odt", find_soffice())
208
208
  assert report.status == "overflow"
209
209
  assert "AAAA" in report.findings[0].excerpt