braidio 0.0.72__tar.gz → 0.0.73__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 (143) hide show
  1. {braidio-0.0.72 → braidio-0.0.73}/PKG-INFO +2 -1
  2. braidio-0.0.73/braidio/mcp/_docs.py +137 -0
  3. {braidio-0.0.72 → braidio-0.0.73}/pyproject.toml +2 -2
  4. {braidio-0.0.72 → braidio-0.0.73}/tests/test_mcp.py +67 -16
  5. braidio-0.0.72/braidio/mcp/_docs.py +0 -183
  6. {braidio-0.0.72 → braidio-0.0.73}/.editorconfig +0 -0
  7. {braidio-0.0.72 → braidio-0.0.73}/.gitattributes +0 -0
  8. {braidio-0.0.72 → braidio-0.0.73}/.gitignore +0 -0
  9. {braidio-0.0.72 → braidio-0.0.73}/LICENSE +0 -0
  10. {braidio-0.0.72 → braidio-0.0.73}/README.md +0 -0
  11. {braidio-0.0.72 → braidio-0.0.73}/braidio/__init__.py +0 -0
  12. {braidio-0.0.72 → braidio-0.0.73}/braidio/_paths.py +0 -0
  13. {braidio-0.0.72 → braidio-0.0.73}/braidio/bodies/__init__.py +0 -0
  14. {braidio-0.0.72 → braidio-0.0.73}/braidio/bodies/_domain.py +0 -0
  15. {braidio-0.0.72 → braidio-0.0.73}/braidio/bodies/_render_nodes.py +0 -0
  16. {braidio-0.0.72 → braidio-0.0.73}/braidio/bodies/_tiers.py +0 -0
  17. {braidio-0.0.72 → braidio-0.0.73}/braidio/bodies/_video.py +0 -0
  18. {braidio-0.0.72 → braidio-0.0.73}/braidio/captions.py +0 -0
  19. {braidio-0.0.72 → braidio-0.0.73}/braidio/compose.py +0 -0
  20. {braidio-0.0.72 → braidio-0.0.73}/braidio/conversation.py +0 -0
  21. {braidio-0.0.72 → braidio-0.0.73}/braidio/cost.py +0 -0
  22. {braidio-0.0.72 → braidio-0.0.73}/braidio/data/skills/braidio/SKILL.md +0 -0
  23. {braidio-0.0.72 → braidio-0.0.73}/braidio/data/skills/braidio-commentary-video/SKILL.md +0 -0
  24. {braidio-0.0.72 → braidio-0.0.73}/braidio/defaults.py +0 -0
  25. {braidio-0.0.72 → braidio-0.0.73}/braidio/delivery.py +0 -0
  26. {braidio-0.0.72 → braidio-0.0.73}/braidio/downloads.py +0 -0
  27. {braidio-0.0.72 → braidio-0.0.73}/braidio/formats.py +0 -0
  28. {braidio-0.0.72 → braidio-0.0.73}/braidio/genre.py +0 -0
  29. {braidio-0.0.72 → braidio-0.0.73}/braidio/importing/__init__.py +0 -0
  30. {braidio-0.0.72 → braidio-0.0.73}/braidio/importing/__main__.py +0 -0
  31. {braidio-0.0.72 → braidio-0.0.73}/braidio/importing/_catalog.py +0 -0
  32. {braidio-0.0.72 → braidio-0.0.73}/braidio/importing/_manifest.py +0 -0
  33. {braidio-0.0.72 → braidio-0.0.73}/braidio/importing/_writer.py +0 -0
  34. {braidio-0.0.72 → braidio-0.0.73}/braidio/kinds.py +0 -0
  35. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/__init__.py +0 -0
  36. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/_guide.py +0 -0
  37. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/_helpers.py +0 -0
  38. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/_media.py +0 -0
  39. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/credentials.py +0 -0
  40. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/metering.py +0 -0
  41. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/tools.py +0 -0
  42. {braidio-0.0.72 → braidio-0.0.73}/braidio/mcp/workspace.py +0 -0
  43. {braidio-0.0.72 → braidio-0.0.73}/braidio/multivoice.py +0 -0
  44. {braidio-0.0.72 → braidio-0.0.73}/braidio/music.py +0 -0
  45. {braidio-0.0.72 → braidio-0.0.73}/braidio/pacing.py +0 -0
  46. {braidio-0.0.72 → braidio-0.0.73}/braidio/project.py +0 -0
  47. {braidio-0.0.72 → braidio-0.0.73}/braidio/provenance.py +0 -0
  48. {braidio-0.0.72 → braidio-0.0.73}/braidio/relevance.py +0 -0
  49. {braidio-0.0.72 → braidio-0.0.73}/braidio/render.py +0 -0
  50. {braidio-0.0.72 → braidio-0.0.73}/braidio/rights.py +0 -0
  51. {braidio-0.0.72 → braidio-0.0.73}/braidio/script.py +0 -0
  52. {braidio-0.0.72 → braidio-0.0.73}/braidio/sources.py +0 -0
  53. {braidio-0.0.72 → braidio-0.0.73}/braidio/structure.py +0 -0
  54. {braidio-0.0.72 → braidio-0.0.73}/braidio/style.py +0 -0
  55. {braidio-0.0.72 → braidio-0.0.73}/braidio/textprep.py +0 -0
  56. {braidio-0.0.72 → braidio-0.0.73}/braidio/timeline.py +0 -0
  57. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/__init__.py +0 -0
  58. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_asset_refs.py +0 -0
  59. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_common.py +0 -0
  60. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_dialogue.py +0 -0
  61. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_episode.py +0 -0
  62. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_ingest.py +0 -0
  63. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_narration.py +0 -0
  64. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_segment.py +0 -0
  65. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_video_cut.py +0 -0
  66. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_video_panels.py +0 -0
  67. {braidio-0.0.72 → braidio-0.0.73}/braidio/transforms/_voice.py +0 -0
  68. {braidio-0.0.72 → braidio-0.0.73}/braidio/tts.py +0 -0
  69. {braidio-0.0.72 → braidio-0.0.73}/braidio/video.py +0 -0
  70. {braidio-0.0.72 → braidio-0.0.73}/braidio/voice_library.py +0 -0
  71. {braidio-0.0.72 → braidio-0.0.73}/braidio/weave.py +0 -0
  72. {braidio-0.0.72 → braidio-0.0.73}/braidio/weave_config.py +0 -0
  73. {braidio-0.0.72 → braidio-0.0.73}/conftest.py +0 -0
  74. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/Extraction and nw-App Design.md +0 -0
  75. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/research/commentary-formats-and-styles.md +0 -0
  76. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/research/conversational-vs-narration-tts.md +0 -0
  77. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/research/notebooklm-and-conversational-pacing.md +0 -0
  78. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/README.md +0 -0
  79. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/anti-platitude-checklist.md +0 -0
  80. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/commentary-voice-guide.md +0 -0
  81. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/_style-groups.md +0 -0
  82. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/amanda-dobbins.md +0 -0
  83. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/david-sims.md +0 -0
  84. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/griffin-newman.md +0 -0
  85. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/helen-molesworth.md +0 -0
  86. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/hrishikesh-hirway.md +0 -0
  87. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/jason-mantzoukas.md +0 -0
  88. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/john-mcwhorter.md +0 -0
  89. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/jon-caramanica.md +0 -0
  90. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/june-diane-raphael.md +0 -0
  91. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/karina-longworth.md +0 -0
  92. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/katy-hessel.md +0 -0
  93. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/louis-theroux.md +0 -0
  94. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/mallory-rubin.md +0 -0
  95. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/melvyn-bragg.md +0 -0
  96. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/michael-barbaro.md +0 -0
  97. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/nate-sloan-charlie-harding.md +0 -0
  98. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/paul-scheer.md +0 -0
  99. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/sean-fennessey.md +0 -0
  100. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/talk-art.md +0 -0
  101. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/style/voices/yasi-salek.md +0 -0
  102. {braidio-0.0.72 → braidio-0.0.73}/misc/docs/youtube_ingest_credentials.md +0 -0
  103. {braidio-0.0.72 → braidio-0.0.73}/tests/_audio.py +0 -0
  104. {braidio-0.0.72 → braidio-0.0.73}/tests/test_body_schema_stability.py +0 -0
  105. {braidio-0.0.72 → braidio-0.0.73}/tests/test_conversation.py +0 -0
  106. {braidio-0.0.72 → braidio-0.0.73}/tests/test_cost.py +0 -0
  107. {braidio-0.0.72 → braidio-0.0.73}/tests/test_credits_card.py +0 -0
  108. {braidio-0.0.72 → braidio-0.0.73}/tests/test_defaults.py +0 -0
  109. {braidio-0.0.72 → braidio-0.0.73}/tests/test_delivery.py +0 -0
  110. {braidio-0.0.72 → braidio-0.0.73}/tests/test_downloads.py +0 -0
  111. {braidio-0.0.72 → braidio-0.0.73}/tests/test_expressiveness.py +0 -0
  112. {braidio-0.0.72 → braidio-0.0.73}/tests/test_formats.py +0 -0
  113. {braidio-0.0.72 → braidio-0.0.73}/tests/test_genre_placement.py +0 -0
  114. {braidio-0.0.72 → braidio-0.0.73}/tests/test_importing.py +0 -0
  115. {braidio-0.0.72 → braidio-0.0.73}/tests/test_mcp_caller_key.py +0 -0
  116. {braidio-0.0.72 → braidio-0.0.73}/tests/test_media_auth.py +0 -0
  117. {braidio-0.0.72 → braidio-0.0.73}/tests/test_multivoice.py +0 -0
  118. {braidio-0.0.72 → braidio-0.0.73}/tests/test_music.py +0 -0
  119. {braidio-0.0.72 → braidio-0.0.73}/tests/test_namespaced_source.py +0 -0
  120. {braidio-0.0.72 → braidio-0.0.73}/tests/test_nw_app.py +0 -0
  121. {braidio-0.0.72 → braidio-0.0.73}/tests/test_pacing.py +0 -0
  122. {braidio-0.0.72 → braidio-0.0.73}/tests/test_packaging.py +0 -0
  123. {braidio-0.0.72 → braidio-0.0.73}/tests/test_render_settings.py +0 -0
  124. {braidio-0.0.72 → braidio-0.0.73}/tests/test_script.py +0 -0
  125. {braidio-0.0.72 → braidio-0.0.73}/tests/test_sources.py +0 -0
  126. {braidio-0.0.72 → braidio-0.0.73}/tests/test_structure.py +0 -0
  127. {braidio-0.0.72 → braidio-0.0.73}/tests/test_textprep_style.py +0 -0
  128. {braidio-0.0.72 → braidio-0.0.73}/tests/test_timeline.py +0 -0
  129. {braidio-0.0.72 → braidio-0.0.73}/tests/test_transforms.py +0 -0
  130. {braidio-0.0.72 → braidio-0.0.73}/tests/test_transforms_dialogue.py +0 -0
  131. {braidio-0.0.72 → braidio-0.0.73}/tests/test_transforms_episode_members.py +0 -0
  132. {braidio-0.0.72 → braidio-0.0.73}/tests/test_transforms_rights.py +0 -0
  133. {braidio-0.0.72 → braidio-0.0.73}/tests/test_transforms_secrets.py +0 -0
  134. {braidio-0.0.72 → braidio-0.0.73}/tests/test_transforms_structure.py +0 -0
  135. {braidio-0.0.72 → braidio-0.0.73}/tests/test_tts_api_key.py +0 -0
  136. {braidio-0.0.72 → braidio-0.0.73}/tests/test_video.py +0 -0
  137. {braidio-0.0.72 → braidio-0.0.73}/tests/test_video_bodies.py +0 -0
  138. {braidio-0.0.72 → braidio-0.0.73}/tests/test_video_footage.py +0 -0
  139. {braidio-0.0.72 → braidio-0.0.73}/tests/test_video_transforms.py +0 -0
  140. {braidio-0.0.72 → braidio-0.0.73}/tests/test_voice_library.py +0 -0
  141. {braidio-0.0.72 → braidio-0.0.73}/tests/test_weave.py +0 -0
  142. {braidio-0.0.72 → braidio-0.0.73}/tests/test_weave_config.py +0 -0
  143. {braidio-0.0.72 → braidio-0.0.73}/tests/test_wire_descriptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: braidio
3
- Version: 0.0.72
3
+ Version: 0.0.73
4
4
  Summary: Weave narration with extracted media segments into audiovisual productions
5
5
  Project-URL: Homepage, https://github.com/thorwhalen/braidio
6
6
  Project-URL: Repository, https://github.com/thorwhalen/braidio
@@ -46,6 +46,7 @@ Provides-Extra: mcp
46
46
  Requires-Dist: dol>=0.3.57; extra == 'mcp'
47
47
  Requires-Dist: falaw[fal]; extra == 'mcp'
48
48
  Requires-Dist: fastmcp; extra == 'mcp'
49
+ Requires-Dist: graze>=0.1.45; extra == 'mcp'
49
50
  Requires-Dist: lacing; extra == 'mcp'
50
51
  Requires-Dist: nw>=0.0.65; extra == 'mcp'
51
52
  Requires-Dist: py2mcp>=0.1.9; extra == 'mcp'
@@ -0,0 +1,137 @@
1
+ """Document ingestion for the braidio MCP server: fetch a URI or accept text, then
2
+ extract plaintext so an agent can analyze source material into a Script.
3
+
4
+ Fetching is **SSRF-hardened** because the connector fetches user-supplied URLs
5
+ server-side on a shared production box. The guard is ``graze.guarded_fetch``'s (one
6
+ implementation for the fleet): http/https only on ports {80, 443}; every hop's
7
+ address is resolved once, checked as globally routable, and *pinned* — the socket
8
+ goes to exactly that address, so DNS rebinding cannot swap in an internal one; each
9
+ redirect hop is re-validated; the whole fetch is bounded by one wall-clock budget
10
+ and a byte cap. This module keeps only the braidio-facing contract: ``ValueError``
11
+ for every refusal (what the tools turn into a ``ToolError``) and a content type.
12
+
13
+ Extraction is content-type aware: HTML is stripped to text, PDF uses ``pypdf``
14
+ (page-capped), everything else is decoded as UTF-8.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import io
20
+ import ipaddress
21
+ import urllib.parse
22
+ from html.parser import HTMLParser
23
+
24
+ import graze
25
+
26
+ #: Fetch bounds (whole fetch, all hops).
27
+ MAX_BYTES = 10 * 1024 * 1024
28
+ MAX_REDIRECTS = 5
29
+ TOTAL_TIMEOUT_S = 25.0 # wall-clock budget for the whole fetch
30
+ ALLOWED_SCHEMES = ("http", "https")
31
+ ALLOWED_PORTS = frozenset({80, 443})
32
+ PDF_MAX_PAGES = 300
33
+
34
+ #: Identifies braidio to the origin server. Kept honest (no browser spoofing) so
35
+ #: operators can see, and rate-limit, what is fetching their documents.
36
+ USER_AGENT = "braidio-mcp/1.0"
37
+
38
+
39
+ class _TextHTMLParser(HTMLParser):
40
+ """Collect visible text from HTML, skipping <script>/<style>."""
41
+
42
+ def __init__(self):
43
+ super().__init__()
44
+ self._chunks: list[str] = []
45
+ self._skip = 0
46
+
47
+ def handle_starttag(self, tag, attrs):
48
+ if tag in ("script", "style"):
49
+ self._skip += 1
50
+
51
+ def handle_endtag(self, tag):
52
+ if tag in ("script", "style") and self._skip:
53
+ self._skip -= 1
54
+
55
+ def handle_data(self, data):
56
+ if not self._skip and data.strip():
57
+ self._chunks.append(data)
58
+
59
+ def text(self) -> str:
60
+ return " ".join(" ".join(self._chunks).split())
61
+
62
+
63
+ def _host_is_public(host: str, port: int) -> bool:
64
+ """True only if every address ``host`` resolves to passes graze's public-only policy."""
65
+ try:
66
+ addresses = graze.system_resolver(host, port)
67
+ except OSError:
68
+ return False
69
+ return bool(addresses) and all(
70
+ graze.default_public_only(ipaddress.ip_address(a)) for a in addresses
71
+ )
72
+
73
+
74
+ def _validate_target(uri: str) -> None:
75
+ """Reject a URI whose scheme/host/port isn't a public http(s) endpoint.
76
+
77
+ A pre-flight for callers that hand the URL to something else to fetch
78
+ (``download_audio`` -> yt-dlp); it cannot pin the address, ``fetch_uri`` can.
79
+ """
80
+ parts = urllib.parse.urlparse(uri)
81
+ if parts.scheme not in ALLOWED_SCHEMES:
82
+ raise ValueError(f"only http/https URIs are supported, got {parts.scheme!r}")
83
+ port = parts.port or (443 if parts.scheme == "https" else 80)
84
+ if port not in ALLOWED_PORTS:
85
+ raise ValueError(f"port {port} is not allowed (only 80/443)")
86
+ if not parts.hostname or not _host_is_public(parts.hostname, port):
87
+ raise ValueError(f"refusing to fetch a non-public host: {parts.hostname!r}")
88
+
89
+
90
+ def fetch_uri(uri: str, **fetch_options) -> tuple[bytes, str]:
91
+ """Fetch a public http(s) URI (SSRF-hardened). Returns ``(bytes, content_type)``.
92
+
93
+ ``fetch_options`` go to ``graze.guarded_open`` (``resolver``, ``connector``,
94
+ ``is_allowed_address``, ...), overriding braidio's bounds; they are the test seam.
95
+ """
96
+ options = dict(
97
+ allow_schemes=ALLOWED_SCHEMES,
98
+ allow_ports=ALLOWED_PORTS,
99
+ max_redirects=MAX_REDIRECTS,
100
+ timeout=TOTAL_TIMEOUT_S,
101
+ max_bytes=MAX_BYTES,
102
+ headers={"User-Agent": USER_AGENT},
103
+ )
104
+ try:
105
+ with graze.guarded_open(uri, **{**options, **fetch_options}) as resp:
106
+ ctype = (resp.headers.get("Content-Type") or "").split(";")[0].strip()
107
+ data = resp.read()
108
+ except graze.UnsafeTarget as err:
109
+ raise ValueError(str(err)) from err
110
+ except graze.HTTPStatusError as err:
111
+ raise ValueError(f"fetch failed: HTTP {err.status}") from err
112
+ except graze.GuardedFetchError as err:
113
+ raise ValueError(f"fetch failed: {err}") from err
114
+ return data, ctype.lower() or "application/octet-stream"
115
+
116
+
117
+ def _pdf_text(data: bytes) -> str:
118
+ try:
119
+ from pypdf import PdfReader
120
+ except ImportError as exc: # pragma: no cover - optional dep
121
+ raise ValueError("PDF ingestion needs pypdf (pip install pypdf)") from exc
122
+ reader = PdfReader(io.BytesIO(data))
123
+ pages = list(reader.pages)[:PDF_MAX_PAGES] # cap work on an adversarial PDF
124
+ return "\n\n".join((page.extract_text() or "") for page in pages).strip()
125
+
126
+
127
+ def extract_text(data: bytes, content_type: str) -> str:
128
+ """Extract plaintext from ``data`` given its ``content_type``."""
129
+ ct = (content_type or "").lower()
130
+ if "pdf" in ct:
131
+ return _pdf_text(data)
132
+ text = data.decode("utf-8", "replace")
133
+ if "html" in ct or "xml" in ct:
134
+ parser = _TextHTMLParser()
135
+ parser.feed(text)
136
+ return parser.text()
137
+ return text
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "braidio"
9
- version = "0.0.72"
9
+ version = "0.0.73"
10
10
  description = "Weave narration with extracted media segments into audiovisual productions"
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.10"
@@ -136,7 +136,7 @@ nw-app = ["lacing", "nw>=0.0.65", "falaw[fal]"]
136
136
  # older dol without it.
137
137
  # nw>=0.0.58: see the nw-app note above (the `secrets=` seam, braidio#58; the
138
138
  # asset-ref declarations `braidio.transforms` makes on import, nw#55).
139
- mcp = ["fastmcp", "py2mcp>=0.1.9", "pypdf", "dol>=0.3.57", "lacing", "nw>=0.0.65", "falaw[fal]", "yb[download]>=0.1.7"]
139
+ mcp = ["fastmcp", "py2mcp>=0.1.9", "pypdf", "dol>=0.3.57", "lacing", "nw>=0.0.65", "falaw[fal]", "yb[download]>=0.1.7", "graze>=0.1.45"]
140
140
  # The importer (`braidio.importing`): a finished commentary production ->
141
141
  # a real project graph. Needs the nw-app layer (it writes annotations) plus
142
142
  # `illustration` for licence normalization.
@@ -931,33 +931,84 @@ def test_oneshot_render_resolves_asset_id(monkeypatch):
931
931
  def test_docs_rejects_disallowed_port(monkeypatch):
932
932
  from braidio.mcp import _docs
933
933
 
934
- monkeypatch.setattr(_docs, "_host_is_public", lambda h: True)
934
+ monkeypatch.setattr(_docs, "_host_is_public", lambda h, port: True)
935
935
  with pytest.raises(ValueError, match="port"):
936
936
  _docs._validate_target("http://example.com:8080/x")
937
937
  _docs._validate_target("https://example.com/x") # 443 default is fine
938
938
 
939
939
 
940
- def test_docs_redirect_to_private_is_rejected(monkeypatch):
941
- # The CRITICAL fix: a public URL that 302s to an internal host must be refused,
942
- # and the internal target must never be fetched.
943
- import urllib.error
944
- import urllib.request as ureq
940
+ def _scripted_connector(responses, hops):
941
+ """A graze ``connector`` seam: records the pinned address, serves canned HTTP."""
942
+ import socket
943
+ import threading
945
944
 
945
+ def connect(address, timeout):
946
+ hops.append(address[0])
947
+ response = responses[len(hops) - 1]
948
+ client, server = socket.socketpair()
949
+
950
+ def serve():
951
+ server.recv(65536)
952
+ server.sendall(response)
953
+ server.close()
954
+
955
+ threading.Thread(target=serve, daemon=True).start()
956
+ return client
957
+
958
+ return connect
959
+
960
+
961
+ def test_docs_redirect_to_private_is_rejected():
962
+ # A public URL that 302s to an internal host must be refused, and the internal
963
+ # target must never be connected to.
946
964
  from braidio.mcp import _docs
947
965
 
948
- monkeypatch.setattr(_docs, "_host_is_public", lambda h: h != "127.0.0.1")
949
966
  hops = []
950
-
951
- def fake_open(self, req, data=None, timeout=None):
952
- hops.append(req.full_url)
953
- raise urllib.error.HTTPError(
954
- req.full_url, 302, "redir", {"Location": "http://127.0.0.1/secret"}, None
967
+ redirect = b"HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1/secret\r\n\r\n"
968
+ with pytest.raises(ValueError, match="not allowed|non-public|refus"):
969
+ _docs.fetch_uri(
970
+ "http://public.example/start",
971
+ resolver=lambda host, port: (
972
+ ["93.184.216.34"] if host == "public.example" else [host]
973
+ ),
974
+ connector=_scripted_connector([redirect], hops),
955
975
  )
976
+ assert hops == ["93.184.216.34"] # never connected to the private target
956
977
 
957
- monkeypatch.setattr(ureq.OpenerDirector, "open", fake_open)
958
- with pytest.raises(ValueError):
959
- _docs.fetch_uri("http://public.example/start")
960
- assert hops == ["http://public.example/start"] # never fetched the private target
978
+
979
+ def test_docs_fetch_pins_the_address_it_validated():
980
+ # DNS rebinding: the resolver answers public the first time, internal after.
981
+ # The connection must go to the address that was checked, with one lookup.
982
+ from braidio.mcp import _docs
983
+
984
+ lookups, hops = [], []
985
+
986
+ def rebinding_resolver(host, port):
987
+ lookups.append(host)
988
+ return ["93.184.216.34"] if len(lookups) == 1 else ["127.0.0.1"]
989
+
990
+ body = b"HTTP/1.1 200 OK\r\nContent-Type: Text/Plain; charset=utf-8\r\nContent-Length: 2\r\n\r\nhi"
991
+ data, ctype = _docs.fetch_uri(
992
+ "http://rebind.example/x",
993
+ resolver=rebinding_resolver,
994
+ connector=_scripted_connector([body], hops),
995
+ )
996
+ assert (data, ctype) == (b"hi", "text/plain")
997
+ assert hops == ["93.184.216.34"] and len(lookups) == 1
998
+
999
+
1000
+ def test_docs_fetch_enforces_the_byte_cap(monkeypatch):
1001
+ from braidio.mcp import _docs
1002
+
1003
+ monkeypatch.setattr(_docs, "MAX_BYTES", 10) # braidio's own cap must reach graze
1004
+
1005
+ body = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n" + b"x" * 100
1006
+ with pytest.raises(ValueError, match="limit"):
1007
+ _docs.fetch_uri(
1008
+ "http://big.example/x",
1009
+ resolver=lambda host, port: ["93.184.216.34"],
1010
+ connector=_scripted_connector([body], []),
1011
+ )
961
1012
 
962
1013
 
963
1014
  @_NW
@@ -1,183 +0,0 @@
1
- """Document ingestion for the braidio MCP server: fetch a URI or accept text, then
2
- extract plaintext so an agent can analyze source material into a Script.
3
-
4
- Fetching is **SSRF-hardened** because the connector fetches user-supplied URLs
5
- server-side on a shared production box:
6
-
7
- - http/https only, on ports {80, 443};
8
- - the host must resolve to a *public* address (``ipaddress.is_global``), with
9
- IPv4-mapped IPv6 canonicalized — loopback / private / link-local / cloud-metadata
10
- (``169.254.169.254``) targets are refused;
11
- - **redirects are NOT auto-followed** — every hop's ``Location`` is re-validated, so
12
- a public URL can't ``302`` to an internal host;
13
- - the whole fetch is bounded by a wall-clock deadline, a redirect cap, and a
14
- total-bytes cap (chunked read), so a slow-loris or redirect loop can't pin a worker.
15
-
16
- Residual: a determined attacker who controls a domain's DNS could race the
17
- validate-vs-connect resolution (the two lookups aren't pinned to one IP). Accepted
18
- here because the connector is restricted to trusted, allowlisted users.
19
-
20
- Extraction is content-type aware: HTML is stripped to text, PDF uses ``pypdf``
21
- (page-capped), everything else is decoded as UTF-8.
22
- """
23
-
24
- from __future__ import annotations
25
-
26
- import io
27
- import ipaddress
28
- import socket
29
- import time
30
- import urllib.error
31
- import urllib.parse
32
- import urllib.request
33
- from html.parser import HTMLParser
34
-
35
- #: Fetch bounds (all hops).
36
- MAX_BYTES = 10 * 1024 * 1024
37
- MAX_REDIRECTS = 5
38
- TOTAL_TIMEOUT_S = 25.0 # wall-clock budget for the whole fetch
39
- OP_TIMEOUT_S = 10.0 # per-socket-op timeout
40
- ALLOWED_SCHEMES = ("http", "https")
41
- ALLOWED_PORTS = frozenset({80, 443})
42
- PDF_MAX_PAGES = 300
43
-
44
- #: Socket read granularity. Bounds how far past ``MAX_BYTES`` a hostile response can
45
- #: push us before the cap is enforced, and how often the deadline is re-checked.
46
- READ_CHUNK_BYTES = 64 * 1024
47
-
48
- #: HTTP statuses treated as a redirect worth following. Each hop is re-validated
49
- #: against the SSRF rules above, so a public URL can never redirect us inward.
50
- REDIRECT_STATUS_CODES = frozenset({301, 302, 303, 307, 308})
51
-
52
- #: Identifies braidio to the origin server. Kept honest (no browser spoofing) so
53
- #: operators can see, and rate-limit, what is fetching their documents.
54
- USER_AGENT = "braidio-mcp/1.0"
55
-
56
-
57
- class _TextHTMLParser(HTMLParser):
58
- """Collect visible text from HTML, skipping <script>/<style>."""
59
-
60
- def __init__(self):
61
- super().__init__()
62
- self._chunks: list[str] = []
63
- self._skip = 0
64
-
65
- def handle_starttag(self, tag, attrs):
66
- if tag in ("script", "style"):
67
- self._skip += 1
68
-
69
- def handle_endtag(self, tag):
70
- if tag in ("script", "style") and self._skip:
71
- self._skip -= 1
72
-
73
- def handle_data(self, data):
74
- if not self._skip and data.strip():
75
- self._chunks.append(data)
76
-
77
- def text(self) -> str:
78
- return " ".join(" ".join(self._chunks).split())
79
-
80
-
81
- class _NoRedirect(urllib.request.HTTPRedirectHandler):
82
- """Disable urllib's auto-follow — a 3xx raises so we validate the hop ourselves."""
83
-
84
- def redirect_request(self, *args, **kwargs): # noqa: D401, ARG002
85
- return None
86
-
87
-
88
- def _host_is_public(host: str) -> bool:
89
- """True only if every resolved address for ``host`` is globally routable."""
90
- try:
91
- infos = socket.getaddrinfo(host, None)
92
- except socket.gaierror:
93
- return False
94
- for info in infos:
95
- ip = ipaddress.ip_address(info[4][0])
96
- if ip.version == 6 and ip.ipv4_mapped is not None:
97
- ip = ip.ipv4_mapped # canonicalize ::ffff:127.0.0.1 etc.
98
- if not ip.is_global: # rejects private/loopback/link-local/reserved/…
99
- return False
100
- return True
101
-
102
-
103
- def _validate_target(uri: str) -> None:
104
- """Reject a URI whose scheme/host/port isn't a public http(s) endpoint."""
105
- parts = urllib.parse.urlparse(uri)
106
- if parts.scheme not in ALLOWED_SCHEMES:
107
- raise ValueError(f"only http/https URIs are supported, got {parts.scheme!r}")
108
- if not parts.hostname or not _host_is_public(parts.hostname):
109
- raise ValueError(f"refusing to fetch a non-public host: {parts.hostname!r}")
110
- port = parts.port or (443 if parts.scheme == "https" else 80)
111
- if port not in ALLOWED_PORTS:
112
- raise ValueError(f"port {port} is not allowed (only 80/443)")
113
-
114
-
115
- def _read_bounded(resp, deadline: float) -> bytes:
116
- """Read the body in chunks, enforcing the byte cap and the wall-clock deadline."""
117
- chunks: list[bytes] = []
118
- total = 0
119
- while total <= MAX_BYTES:
120
- if time.monotonic() > deadline:
121
- raise ValueError("document fetch exceeded its time budget")
122
- chunk = resp.read(READ_CHUNK_BYTES)
123
- if not chunk:
124
- break
125
- total += len(chunk)
126
- chunks.append(chunk)
127
- data = b"".join(chunks)
128
- if len(data) > MAX_BYTES:
129
- raise ValueError(f"document exceeds the {MAX_BYTES}-byte limit")
130
- return data
131
-
132
-
133
- def fetch_uri(uri: str) -> tuple[bytes, str]:
134
- """Fetch a public http(s) URI (SSRF-hardened). Returns ``(bytes, content_type)``."""
135
- deadline = time.monotonic() + TOTAL_TIMEOUT_S
136
- opener = urllib.request.build_opener(_NoRedirect)
137
- current = uri
138
- for _ in range(MAX_REDIRECTS + 1):
139
- _validate_target(current) # re-validate scheme/host/port at EVERY hop
140
- remaining = deadline - time.monotonic()
141
- if remaining <= 0:
142
- raise ValueError("document fetch exceeded its time budget")
143
- req = urllib.request.Request(current, headers={"User-Agent": USER_AGENT})
144
- try:
145
- resp = opener.open(req, timeout=min(OP_TIMEOUT_S, remaining)) # noqa: S310
146
- except urllib.error.HTTPError as err:
147
- loc = err.headers.get("Location") if err.headers else None
148
- if err.code in REDIRECT_STATUS_CODES and loc:
149
- current = urllib.parse.urljoin(current, loc)
150
- continue # the loop re-validates the redirect target
151
- raise ValueError(f"fetch failed: HTTP {err.code}") from err
152
- except urllib.error.URLError as err:
153
- raise ValueError(f"fetch failed: {err.reason}") from err
154
- with resp:
155
- ctype = (
156
- (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
157
- )
158
- data = _read_bounded(resp, deadline)
159
- return data, ctype or "application/octet-stream"
160
- raise ValueError(f"too many redirects (>{MAX_REDIRECTS})")
161
-
162
-
163
- def _pdf_text(data: bytes) -> str:
164
- try:
165
- from pypdf import PdfReader
166
- except ImportError as exc: # pragma: no cover - optional dep
167
- raise ValueError("PDF ingestion needs pypdf (pip install pypdf)") from exc
168
- reader = PdfReader(io.BytesIO(data))
169
- pages = list(reader.pages)[:PDF_MAX_PAGES] # cap work on an adversarial PDF
170
- return "\n\n".join((page.extract_text() or "") for page in pages).strip()
171
-
172
-
173
- def extract_text(data: bytes, content_type: str) -> str:
174
- """Extract plaintext from ``data`` given its ``content_type``."""
175
- ct = (content_type or "").lower()
176
- if "pdf" in ct:
177
- return _pdf_text(data)
178
- text = data.decode("utf-8", "replace")
179
- if "html" in ct or "xml" in ct:
180
- parser = _TextHTMLParser()
181
- parser.feed(text)
182
- return parser.text()
183
- return text
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes