mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: implement API response sanitizer and enhance middleware for cross-domain handling
This commit is contained in:
parent
f4b942984c
commit
9bbcb58c79
5 changed files with 284 additions and 4 deletions
60
apps/web/components/Avatar/SafeAvatar.tsx
Normal file
60
apps/web/components/Avatar/SafeAvatar.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import React from 'react'
|
||||
import Image from 'next/image'
|
||||
|
||||
interface SafeAvatarProps {
|
||||
src?: string
|
||||
alt: string
|
||||
size?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* SafeAvatar component that ensures correct domain for avatar images
|
||||
*/
|
||||
const SafeAvatar: React.FC<SafeAvatarProps> = ({
|
||||
src,
|
||||
alt,
|
||||
size = 40,
|
||||
className
|
||||
}) => {
|
||||
// Default empty avatar path that uses relative URL (domain-safe)
|
||||
const defaultAvatarSrc = '/images/empty_avatar.png'
|
||||
|
||||
// Handle potentially cross-domain avatar URLs
|
||||
const sanitizedSrc = React.useMemo(() => {
|
||||
if (!src) return defaultAvatarSrc
|
||||
|
||||
try {
|
||||
// Check if the URL has a domain
|
||||
const url = new URL(src, window.location.origin)
|
||||
|
||||
// If the URL is from a different domain, use the default avatar
|
||||
if (url.hostname !== window.location.hostname) {
|
||||
console.warn(`[SafeAvatar] Detected cross-domain avatar: ${src}`)
|
||||
return defaultAvatarSrc
|
||||
}
|
||||
|
||||
return src
|
||||
} catch (e) {
|
||||
// If parsing fails, just use the src as is (could be a relative path)
|
||||
return src
|
||||
}
|
||||
}, [src])
|
||||
|
||||
return (
|
||||
<Image
|
||||
src={sanitizedSrc}
|
||||
alt={alt}
|
||||
width={size}
|
||||
height={size}
|
||||
className={className}
|
||||
onError={(e) => {
|
||||
// If image fails to load, fallback to default
|
||||
const target = e.target as HTMLImageElement
|
||||
target.src = defaultAvatarSrc
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default SafeAvatar
|
||||
|
|
@ -4,6 +4,33 @@ import { NextResponse } from 'next/server';
|
|||
export function middleware(request) {
|
||||
// Get the current hostname from the request headers
|
||||
const currentHostname = request.headers.get('host');
|
||||
|
||||
// Always inspect for cross-domain requests regardless of referrer
|
||||
const url = request.nextUrl.clone();
|
||||
const path = url.pathname;
|
||||
|
||||
// Check for common patterns that might indicate cross-domain content
|
||||
// 1. Handle image files that might be requested from the wrong domain
|
||||
if (path.endsWith('.png') || path.endsWith('.jpg') || path.endsWith('.jpeg') ||
|
||||
path.endsWith('.gif') || path.endsWith('.webp') || path.endsWith('.svg')) {
|
||||
// Ensure image path is properly routed to current domain
|
||||
if (path.includes('empty_avatar.png')) {
|
||||
console.log(`Intercepting image request: ${path}`);
|
||||
// Rewrite all empty_avatar.png requests to use the local domain
|
||||
return NextResponse.rewrite(new URL(`/images/empty_avatar.png`, request.url));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Check if request is going to the wrong domain through API path
|
||||
if (path.includes('/api/') && request.headers.has('referer')) {
|
||||
const refererUrl = new URL(request.headers.get('referer'));
|
||||
// If referer domain doesn't match the requested API domain, redirect
|
||||
if (refererUrl.hostname !== currentHostname) {
|
||||
console.log(`Redirecting cross-domain API request: ${path}`);
|
||||
const newUrl = new URL(path, `https://${currentHostname}`);
|
||||
return NextResponse.redirect(newUrl);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the referrer URL if it exists
|
||||
const referer = request.headers.get('referer');
|
||||
|
|
@ -19,10 +46,6 @@ export function middleware(request) {
|
|||
console.log(`Cross-domain request detected: ${refererHostname} -> ${currentHostname}`);
|
||||
|
||||
// For path segments that might include another domain
|
||||
const url = request.nextUrl.clone();
|
||||
const path = url.pathname;
|
||||
|
||||
// Check if the path includes another domain name (simple check for static files)
|
||||
if (path.includes('/next/static/') || path.includes('/api/')) {
|
||||
// Ensure all paths use the current hostname
|
||||
// This prevents asset URL problems when different hostnames appear in the path
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ export default function Document() {
|
|||
<script src="/runtime-config.js" strategy="beforeInteractive" />
|
||||
{/* Load comprehensive API interceptor */}
|
||||
<script src="/api-interceptor.js" strategy="beforeInteractive" />
|
||||
{/* Load API response sanitizer */}
|
||||
<script src="/api-response-sanitizer.js" strategy="beforeInteractive" />
|
||||
</Head>
|
||||
<body>
|
||||
<Main />
|
||||
|
|
|
|||
94
apps/web/public/api-response-sanitizer.js
Normal file
94
apps/web/public/api-response-sanitizer.js
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* API Response Sanitizer
|
||||
*
|
||||
* This script specifically handles API responses to ensure they don't contain
|
||||
* URLs pointing to the wrong domain.
|
||||
*/
|
||||
(function() {
|
||||
console.log('[Domain Isolation] Installing API response sanitizer...');
|
||||
|
||||
// Save reference to the original fetch
|
||||
const originalFetch = window.fetch;
|
||||
|
||||
/**
|
||||
* Recursively sanitize objects to replace URLs from wrong domains
|
||||
*/
|
||||
function sanitizeObject(obj, currentDomain) {
|
||||
if (!obj || typeof obj !== 'object') return obj;
|
||||
|
||||
// Handle arrays
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(item => sanitizeObject(item, currentDomain));
|
||||
}
|
||||
|
||||
// Handle objects
|
||||
const result = {};
|
||||
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
// Check if this is a URL string value
|
||||
if (typeof value === 'string' &&
|
||||
(value.startsWith('http://') || value.startsWith('https://'))) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.hostname !== currentDomain &&
|
||||
!url.hostname.includes('api-gateway.umami.dev')) {
|
||||
console.log(`[Sanitizer] Found cross-domain URL: ${value}`);
|
||||
const newValue = value.replace(url.hostname, currentDomain);
|
||||
result[key] = newValue;
|
||||
continue;
|
||||
}
|
||||
} catch (e) {
|
||||
// Not a valid URL, keep original value
|
||||
}
|
||||
}
|
||||
|
||||
// Process nested objects/arrays
|
||||
if (value && typeof value === 'object') {
|
||||
result[key] = sanitizeObject(value, currentDomain);
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Override fetch to sanitize responses
|
||||
window.fetch = async function(...args) {
|
||||
const currentDomain = window.location.hostname;
|
||||
|
||||
// Call original fetch
|
||||
const response = await originalFetch.apply(this, args);
|
||||
|
||||
// Clone the response so we can read it multiple times
|
||||
const clonedResponse = response.clone();
|
||||
|
||||
// Only process JSON responses from API endpoints
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (contentType && contentType.includes('application/json') &&
|
||||
(args[0].includes('/api/') || args[0].includes('api/v1'))) {
|
||||
|
||||
try {
|
||||
// Read and parse the response
|
||||
const originalData = await clonedResponse.json();
|
||||
|
||||
// Sanitize the data
|
||||
const sanitizedData = sanitizeObject(originalData, currentDomain);
|
||||
|
||||
// Create a new response with sanitized data
|
||||
return new Response(JSON.stringify(sanitizedData), {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[Domain Isolation] Error sanitizing response:', e);
|
||||
return response; // Return original response on error
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
console.log('[Domain Isolation] API response sanitizer installed');
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue