Skip to content

feat: add page context awareness to chat assistant - #19

Merged
neuromechanist merged 4 commits into
developfrom
claude/page-context-awareness-oSA5R
Jan 9, 2026
Merged

neuromechanist merged 4 commits into
developfrom
claude/page-context-awareness-oSA5R

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Jan 9, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adds page context awareness to the HED chat assistant, allowing it to understand and reference the page where the user is asking questions from. This enables more contextually relevant answers when users are browsing HED documentation.

Changes:

  • Frontend: Capture and send page URL/title with API requests

    • New includePageContext config option (default: true)
    • Privacy notice displayed when page context is enabled
    • Configurable showPageContextNotice and pageContextNoticeText options
  • API: Add PageContext model with URL validation

    • Max length constraints on URL (2048) and title (500)
    • URL scheme validation (only http/https allowed, raises explicit error)
  • Agent: Add fetch_current_page tool and system prompt context

    • Tool is bound to the specific page URL (prevents SSRF)
    • SSRF protection blocks private IPs, localhost, link-local addresses
    • Redirect validation to prevent redirect-based SSRF
    • Content-type validation (HTML only)
    • System prompt includes page context when available
  • Dependencies: Add markdownify for HTML-to-markdown conversion

Security Measures

  • SSRF protection with IP/domain validation
  • Returns resolved IP from validation to mitigate TOCTOU attacks
  • Bound tool that only fetches the specific page URL
  • URL scheme and length validation at API layer (explicit error on invalid)
  • Manual redirect handling with validation
  • Comprehensive logging for all security events
  • Specific exception handling (no broad exception catches)

Security Review Fixes

Addressed all findings from PR review:

Critical Issues (Fixed):

  • Silent DNS failure handling: Now returns error instead of silently passing
  • Broad exception handlers: Now catches specific exceptions (gaierror, herror, TimeoutError, ValueError)
  • TOCTOU race condition: Returns resolved IP from is_safe_url for use in fetch

Important Issues (Fixed):

  • Silent URL scheme conversion: Now raises ValueError for invalid schemes
  • Missing logging: Added comprehensive logging for all security events
  • Missing redirect SSRF tests: Added tests for redirect-based attacks

Test plan

  • Run existing tests (uv run pytest tests/ - all 362 tests pass)
  • New tests for SSRF protection (54 tests total for page context)
  • Test API PageContext model validation
  • Test HEDAssistant with page context
  • Test redirect SSRF protection
  • Test content-type validation
  • Test timeout and error handling
  • Test fetch_current_page tool invocation
  • Achieve 87% coverage for page context code in hed.py
  • Manual testing with widget embedded on HED documentation page

claude added 2 commits January 9, 2026 04:08
This feature allows the chat assistant to be aware of the page where
the widget is embedded, enabling more contextually relevant answers.

Changes:
- Frontend: Capture page URL and title, send with API requests via
  page_context field. New includePageContext config option (default: true)
- API: Add PageContext model and page_context field to AskRequest,
  pass through to HEDAssistant
- Agent: Add PageContext dataclass, include in system prompt when
  provided, add fetch_page_content tool to retrieve page content
  when the user's question relates to the embedded page
- Dependencies: Add markdownify for HTML-to-markdown conversion
Security improvements:
- Add SSRF protection with IP/domain validation (blocks private IPs,
  localhost, link-local, and reserved ranges)
- Validate redirect targets to prevent redirect-based SSRF
- Disable automatic redirects and handle them manually with validation
- Add URL scheme validation at API layer (max length, valid scheme)
- Add title max length validation to prevent DoS
- Validate content-type to ensure HTML responses only

Tool design improvements:
- Create bound fetch_current_page tool that only fetches the specific
  page URL from page_context (prevents LLM from requesting arbitrary URLs)
- Move imports to module level for better performance

Privacy improvements:
- Add privacy notice in frontend widget when page context is enabled
- Add configurable showPageContextNotice and pageContextNoticeText options

Tests:
- Add comprehensive tests for SSRF protection (37 new tests)
- Test localhost, private IPs, link-local, reserved IPs are blocked
- Test valid public URLs are allowed
- Test PageContext model validation
- Test HEDAssistant with and without page context
@neuromechanist
neuromechanist changed the base branch from main to develop January 9, 2026 18:37
@neuromechanist

Copy link
Copy Markdown
Member Author

PR Review Summary

Critical Issues (3 found)

1. Silent DNS Failure Handling

File: src/agents/hed.py:48-49
Issue: DNS resolution failure silently passes with pass, allowing potentially dangerous URLs to bypass validation.

except socket.gaierror:
    pass  # Allow, will fail at fetch time

Fix: Return an error instead of silently passing - DNS failures should be treated as security-relevant events.

2. Broad Exception Handlers

File: src/agents/hed.py:50-51
Issue: Bare except Exception catches all errors including programming bugs, making debugging difficult.

except Exception as e:
    return False, f"URL validation failed: {e}"

Fix: Catch specific exceptions (ValueError, socket.error, etc.) to avoid masking bugs.

3. TOCTOU Race Condition

File: src/agents/hed.py:34-49 and 66-73
Issue: DNS resolution happens twice - once in validation, once in fetch. A malicious DNS server could return different IPs (DNS rebinding attack).
Fix: Resolve DNS once, cache the IP, and use it directly for the connection. Consider using httpx with explicit IP binding.

Important Issues (3 found)

1. Silent URL Scheme Conversion

File: src/api/routers/hed.py:31-33
Issue: Invalid URL schemes return None silently instead of raising validation error.
Fix: Consider raising a ValueError to make the validation explicit.

2. Missing Logging

Issue: Security-relevant events (blocked URLs, SSRF attempts) are not logged.
Fix: Add structured logging for security events to aid in monitoring and incident response.

3. Missing Redirect SSRF Tests

File: tests/test_agents/test_page_context.py
Issue: No tests for redirect-based SSRF attacks (e.g., external URL redirecting to internal IP).
Fix: Add tests for redirect validation behavior.

Suggestions

  • Add content-type validation tests
  • Add DNS resolution edge case tests
  • Add fetch_current_page tool invocation tests
  • Add content truncation tests (verify large pages are handled properly)

Strengths

  • Well-designed security architecture with bound tool pattern
  • Comprehensive SSRF protection covering private IPs, loopback, and link-local
  • Good API validation with Pydantic models
  • Clear system prompt context integration
  • Privacy notice for user transparency

Recommended Action

  1. Fix critical issues (DNS handling, exception handling, TOCTOU)
  2. Address important issues (logging, explicit validation)
  3. Add missing tests to achieve >90% coverage
  4. Re-run review after fixes

- Fix silent DNS failure handling: return error instead of passing
- Add specific exception handling for socket errors (gaierror, herror, timeout)
- Add comprehensive logging for all security events
- Make URL validation explicit: raise ValueError for invalid schemes
- Return resolved IP from is_safe_url to mitigate TOCTOU attacks
- Add comprehensive tests for redirect SSRF, content-type validation,
  timeout handling, and tool invocation
- Achieve 87% coverage for page context code in hed.py
@neuromechanist

Copy link
Copy Markdown
Member Author

Manual Testing Completed

Performed end-to-end testing of the page context awareness feature using the chat widget:

Test Setup

  • Started local dev server on port 38528
  • Served frontend demo from localhost:8888
  • Opened the OSA Chat Widget Demo page

Test Results

Page Context Detection: PASSED

SSRF Protection: PASSED

  • When the assistant attempted to fetch the localhost URL, the SSRF protection correctly blocked it
  • Server log showed: SSRF blocked: private IP 127.0.0.1 for host localhost

Verification

  • Page context (URL + title) is correctly sent from widget to server
  • Assistant can identify and reference the current page
  • SSRF protection blocks attempts to fetch private/localhost URLs
  • Widget shows "Online" status indicator
  • Page context notice displays correctly at bottom of chat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Want flexibility in the docs that are used.

2 participants