Files
wehub-resource-sync 7a0da7932b
OSV-Scanner (Scheduled) / scan-scheduled (push) Failing after 0s
Create Release / test-gate (push) Has been cancelled
Create Release / release-gate (push) Has been cancelled
Create Release / ci-gate (push) Has been cancelled
Create Release / version-check (push) Has been cancelled
Create Release / e2e-test-gate (push) Has been cancelled
Create Release / responsive-test-gate (push) Has been cancelled
Create Release / compat-test-gate (push) Has been cancelled
Create Release / compose-integration-gate (push) Has been cancelled
Create Release / vulture-gate (push) Has been cancelled
Create Release / build (push) Has been cancelled
Create Release / provenance (push) Has been cancelled
Create Release / prerelease-docker (push) Has been cancelled
Create Release / publish-docker (push) Has been cancelled
Create Release / create-release (push) Has been cancelled
Create Release / cleanup-changelog (push) Has been cancelled
Create Release / trigger-pypi (push) Has been cancelled
Create Release / monitor-pypi (push) Has been cancelled
Create Release / Clean up orphan prerelease tags and signatures (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [research-form] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [research-metrics] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [research-workflow] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [settings-core] (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [history-news] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [library] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [link-analytics] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [chat-core] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [chat-lifecycle] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [error-benchmark] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [settings-pages] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) (push) Has been cancelled
Docker Tests (Consolidated) / Accessibility Tests (push) Has been cancelled
Docker Tests (Consolidated) / LLM Unit Tests (push) Has been cancelled
Docker Tests (Consolidated) / LLM Example Tests (push) Has been cancelled
Docker Tests (Consolidated) / Production Image Smoke Test (push) Has been cancelled
Docker Tests (Consolidated) / Infrastructure Tests (push) Has been cancelled
OSSF Scorecard / OSSF Security Scorecard Analysis (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [mobile] (push) Has been cancelled
Backwards Compatibility / Verify Encryption Constants (push) Has been cancelled
Backwards Compatibility / PyPI Version Compatibility (push) Has been cancelled
Backwards Compatibility / Database Migration Tests (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Docker Tests (Consolidated) / detect-changes (push) Has been cancelled
Docker Tests (Consolidated) / Build Test Image (push) Has been cancelled
Docker Tests (Consolidated) / All Pytest Tests + Coverage (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [accessibility] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [api-crud] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [auth-login] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [auth-pages] (push) Has been cancelled
Docker Tests (Consolidated) / UI Tests (Puppeteer) [auth-register] (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 13:08:55 +08:00

181 lines
5.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Pre-commit hook to check for unsafe URL scheme validation in JavaScript files.
This hook ensures that JavaScript code properly validates URLs to prevent
XSS attacks through javascript:, data:, and vbscript: schemes.
"""
import sys
import re
from pathlib import Path
def check_url_validation(file_path):
"""
Check if JavaScript file has proper URL validation.
Returns list of issues found.
"""
issues = []
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
lines = content.split("\n")
# Note: More advanced pattern checking could be added here
# Currently focusing on basic URL validation presence
# Check if the file imports or includes URL validation
has_url_validator = (
"URLValidator" in content
or "isUnsafeScheme" in content
or "isSafeUrl" in content
or "url-validator.js" in content # Check for script include
)
# Now focusing on external URLs only instead of all URL handling
# For now, only warn about files that handle external URLs
# Skip files that only handle internal navigation
handles_external_urls = (
"fetch(" in content
or "XMLHttpRequest" in content
or re.search(r"window\.open\s*\([^)]*http", content)
or re.search(r"href\s*=\s*['\"]https?://", content)
)
# If the file handles external URLs but doesn't have validation, that's concerning.
# (Previously there was a "has_basic_protection" short-circuit that checked for
# "javascript:" plus any of startsWith/includes/indexOf anywhere in the file —
# trivially satisfied by unrelated code or comments, so it masked real gaps.)
if handles_external_urls and not has_url_validator:
issues.append(
f"{file_path}: File handles external URLs but lacks URL validation checks"
)
# Check for specific problematic patterns
for line_num, line in enumerate(lines, 1):
# Skip comments
if line.strip().startswith("//") or line.strip().startswith("*"):
continue
# Check for .href or .src assignments without proper validation
if re.search(r"\.(href|src)\s*=\s*[a-zA-Z_$]", line):
# Only skip truly safe patterns
safe_patterns = [
# Internal navigation using known safe constants
r"window\.location\.href\s*=\s*URLS\.",
r"\.href\s*=\s*URLBuilder\.",
# Explicit relative/fragment URLs (safe by definition)
r"\.href\s*=\s*['\"][/#]",
# Safe browser APIs for generating URLs
r"\.href\s*=\s*URL\.createObjectURL",
r"\.href\s*=\s*canvas\.toDataURL",
# Already using the URLValidator
r"URLValidator\.(safeAssign|isSafeUrl)",
]
if any(re.search(pattern, line) for pattern in safe_patterns):
continue
# Check if it's preceded by validation
context_start = max(0, line_num - 5)
context = "\n".join(lines[context_start:line_num])
if not any(
check in context
for check in [
"URLValidator",
"isUnsafeScheme",
"isSafeUrl",
"javascript:",
"data:",
"vbscript:",
]
):
issues.append(
f"{file_path}:{line_num}: URL assignment without validation: {line.strip()}"
)
return issues
def main():
"""Main function to check all provided files."""
if len(sys.argv) < 2:
print("No files to check")
return 0
all_issues = []
# Path segments that mark a file as non-production (tests, vendored code, build output).
# Segment-matching avoids the bug where a bare substring like "test" silently skipped
# real production files such as attestation_service.js or latest_products.js.
SKIP_SEGMENTS = {
"tests",
"test",
"spec",
"specs",
"__tests__",
"vendor",
"node_modules",
"dist",
"build",
}
for file_path in sys.argv[1:]:
# Only check JavaScript files
if not file_path.endswith(".js"):
continue
p = Path(file_path)
if (
SKIP_SEGMENTS.intersection(p.parts)
or p.name.startswith("test_")
or p.name.endswith((".test.js", ".spec.js", ".min.js"))
):
continue
try:
issues = check_url_validation(file_path)
all_issues.extend(issues)
except Exception as e:
print(f"Error checking {file_path}: {e}")
continue
if all_issues:
print("❌ URL Security Issues Found:")
print("-" * 60)
for issue in all_issues:
print(f" • {issue}")
print("-" * 60)
print("\n📋 HOW TO FIX:")
print(
"\n1️⃣ Add this script tag to your HTML template (or include in your JS bundle):"
)
print(' <script src="/static/js/security/url-validator.js"></script>')
print(
"\n2️⃣ For dynamic URL assignments, use URLValidator.safeAssign():"
)
print(" // Instead of: element.href = url;")
print(" // Use: URLValidator.safeAssign(element, 'href', url);")
print("\n3️⃣ For URL validation before use:")
print(" if (URLValidator.isSafeUrl(url)) {")
print(" // URL is safe to use")
print(" }")
print("\n📁 URL Validator location:")
print(
" src/local_deep_research/web/static/js/security/url-validator.js"
)
print(
"\n🔒 This prevents XSS attacks through javascript:, data:, and vbscript: URLs"
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())