-
Notifications
You must be signed in to change notification settings - Fork 5
refactor(platform): consolidate crawler tools into unified web tool #369
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
d651901
refactor(platform): consolidate crawler tools into unified web tool
larryro 96bf8d0
fix(platform): show thinking animation during tool processing and pre…
larryro 2647c96
fix(platform): prioritize current message attachments over previous c…
larryro 40dce8f
fix(crawler): add SSRF protection for URL fetch endpoint
larryro ba38ca2
fix(web): add specific handling for timeout/abort errors in browser_o…
larryro 86b3ff9
fix(web): include truncated status in WebFetchUrlResult
larryro 973dfec
fix(agents): reduce PII in multi-match CRM responses
larryro File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| """ | ||
| Web Router - URL content extraction endpoint. | ||
|
|
||
| Combines URL-to-PDF conversion with Vision-based text extraction. | ||
| """ | ||
|
|
||
| import socket | ||
| from ipaddress import ip_address | ||
| from urllib.parse import urlparse | ||
|
|
||
| from fastapi import APIRouter, HTTPException, status | ||
| from loguru import logger | ||
|
|
||
| from app.models import WebFetchExtractRequest, WebFetchExtractResponse | ||
| from app.services.file_parser_service import get_file_parser_service | ||
| from app.services.pdf_service import get_pdf_service | ||
|
|
||
| router = APIRouter(prefix="/api/v1/web", tags=["Web"]) | ||
|
|
||
|
|
||
| def validate_url_not_private(url_str: str) -> str: | ||
| """ | ||
| Validate that a URL does not resolve to a private/internal IP address. | ||
|
|
||
| Prevents SSRF attacks by blocking requests to loopback, link-local, | ||
| and private RFC1918/IPv6 addresses. | ||
|
|
||
| Args: | ||
| url_str: The URL to validate | ||
|
|
||
| Returns: | ||
| The hostname if validation passes | ||
|
|
||
| Raises: | ||
| HTTPException: If the URL host cannot be resolved or resolves to a private IP | ||
| """ | ||
| parsed_url = urlparse(url_str) | ||
| hostname = parsed_url.hostname or "" | ||
|
|
||
| if not hostname: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_400_BAD_REQUEST, | ||
| detail="Invalid URL: no hostname found", | ||
| ) | ||
|
|
||
| try: | ||
| resolved_ips = { | ||
| ip_address(info[4][0]) | ||
| for info in socket.getaddrinfo(hostname, None) | ||
| } | ||
| except socket.gaierror: | ||
| logger.warning(f"SSRF protection: unable to resolve hostname '{hostname}'") | ||
| raise HTTPException( | ||
| status_code=status.HTTP_400_BAD_REQUEST, | ||
| detail="Unable to resolve URL host", | ||
| ) | ||
|
|
||
| blocked_ips = [ | ||
| ip for ip in resolved_ips | ||
| if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved | ||
| ] | ||
|
|
||
| if blocked_ips: | ||
| logger.warning( | ||
| f"SSRF protection: blocked request to '{hostname}' " | ||
| f"(resolved to private/internal IPs: {blocked_ips})" | ||
| ) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_400_BAD_REQUEST, | ||
| detail="URL host is not allowed (resolves to private/internal address)", | ||
| ) | ||
|
|
||
| return hostname | ||
|
|
||
|
|
||
| @router.post("/fetch-and-extract", response_model=WebFetchExtractResponse) | ||
| async def fetch_and_extract(request: WebFetchExtractRequest): | ||
| """ | ||
| Fetch a URL, convert to PDF, and extract text content. | ||
|
|
||
| Pipeline: | ||
| 1. Navigate to URL with Playwright and render as PDF | ||
| 2. Extract text using PyMuPDF + Vision API (handles images, OCR for scanned content) | ||
|
|
||
| Args: | ||
| request: URL and optional extraction instruction | ||
|
|
||
| Returns: | ||
| Extracted content with metadata | ||
| """ | ||
| url_str = str(request.url) | ||
| hostname = validate_url_not_private(url_str) | ||
|
|
||
| try: | ||
| pdf_service = get_pdf_service() | ||
| if not pdf_service.initialized: | ||
| await pdf_service.initialize() | ||
|
|
||
| logger.info(f"Fetching URL as PDF: {url_str}") | ||
| pdf_bytes = await pdf_service.url_to_pdf( | ||
| url=url_str, | ||
| timeout=request.timeout, | ||
| ) | ||
|
|
||
| logger.info(f"Extracting content from PDF ({len(pdf_bytes)} bytes)") | ||
| parser = get_file_parser_service() | ||
| result = await parser.parse_pdf_with_vision( | ||
| pdf_bytes, | ||
| filename=f"{hostname}.pdf", | ||
| user_input=request.instruction, | ||
| process_images=True, | ||
| ocr_scanned_pages=True, | ||
| ) | ||
|
|
||
| if not result.get("success"): | ||
| return WebFetchExtractResponse( | ||
| success=False, | ||
| url=url_str, | ||
| content="", | ||
| word_count=0, | ||
| page_count=0, | ||
| error=result.get("error", "Failed to extract content from PDF"), | ||
| ) | ||
|
|
||
| full_text = result.get("full_text", "") | ||
| word_count = len(full_text.split()) if full_text else 0 | ||
|
|
||
| logger.info( | ||
| f"Content extracted: {word_count} words, {result.get('page_count', 0)} pages, " | ||
| f"vision_used={result.get('vision_used', False)}" | ||
| ) | ||
|
|
||
| return WebFetchExtractResponse( | ||
| success=True, | ||
| url=url_str, | ||
| content=full_text, | ||
| word_count=word_count, | ||
| page_count=result.get("page_count", 0), | ||
| vision_used=result.get("vision_used", False), | ||
| ) | ||
|
|
||
| except Exception: | ||
| logger.exception(f"Error fetching and extracting URL: {url_str}") | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail=f"Failed to fetch and extract content from URL: {url_str}", | ||
| ) from None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.