fix(web): frontend quality — XSS, error states, a11y, image optimization, security headers

- Whitelist OAuth error codes; never render raw URL params (XSS fix)
- Add error state UI with retry button for API failures on homepage and search
- Use <article> for property cards with ARIA labels and semantic list markup
- Replace raw <img> with Next.js <Image> across all listing/gallery/KYC pages
- Add security headers (X-Content-Type-Options, X-Frame-Options, etc.) in next.config.js
- Gate console.error behind NODE_ENV check in global error boundary
- Mapbox confirmed npm-bundled (SRI N/A)

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 06:32:08 +07:00
parent e9889539ea
commit afa70320f5
11 changed files with 215 additions and 104 deletions

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback } from 'react';
import Image from 'next/image';
import { import {
CheckCircle, CheckCircle,
XCircle, XCircle,
@@ -97,11 +98,13 @@ function KycDetailView({ item, onApprove, onReject }: {
{kycData.frontImageUrl && ( {kycData.frontImageUrl && (
<div className="space-y-1"> <div className="space-y-1">
<div className="text-xs text-muted-foreground">Mặt trước</div> <div className="text-xs text-muted-foreground">Mặt trước</div>
<div className="aspect-video overflow-hidden rounded-md border bg-muted"> <div className="relative aspect-video overflow-hidden rounded-md border bg-muted">
<img <Image
src={kycData.frontImageUrl} src={kycData.frontImageUrl}
alt="Mặt trước giấy tờ" alt="Mặt trước giấy tờ"
className="h-full w-full object-contain" fill
sizes="(max-width: 768px) 100vw, 400px"
className="object-contain"
/> />
</div> </div>
</div> </div>
@@ -109,11 +112,13 @@ function KycDetailView({ item, onApprove, onReject }: {
{kycData.backImageUrl && ( {kycData.backImageUrl && (
<div className="space-y-1"> <div className="space-y-1">
<div className="text-xs text-muted-foreground">Mặt sau</div> <div className="text-xs text-muted-foreground">Mặt sau</div>
<div className="aspect-video overflow-hidden rounded-md border bg-muted"> <div className="relative aspect-video overflow-hidden rounded-md border bg-muted">
<img <Image
src={kycData.backImageUrl} src={kycData.backImageUrl}
alt="Mặt sau giấy tờ" alt="Mặt sau giấy tờ"
className="h-full w-full object-contain" fill
sizes="(max-width: 768px) 100vw, 400px"
className="object-contain"
/> />
</div> </div>
</div> </div>
@@ -121,11 +126,13 @@ function KycDetailView({ item, onApprove, onReject }: {
{kycData.selfieUrl && ( {kycData.selfieUrl && (
<div className="space-y-1"> <div className="space-y-1">
<div className="text-xs text-muted-foreground">nh selfie</div> <div className="text-xs text-muted-foreground">nh selfie</div>
<div className="aspect-video overflow-hidden rounded-md border bg-muted"> <div className="relative aspect-video overflow-hidden rounded-md border bg-muted">
<img <Image
src={kycData.selfieUrl} src={kycData.selfieUrl}
alt="Selfie" alt="Selfie"
className="h-full w-full object-contain" fill
sizes="(max-width: 768px) 100vw, 400px"
className="object-contain"
/> />
</div> </div>
</div> </div>

View File

@@ -22,12 +22,16 @@ export default function LoginPage() {
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const oauthError = searchParams.get('error'); const oauthError = searchParams.get('error');
const oauthErrorMessage = const OAUTH_ERROR_MESSAGES: Record<string, string> = {
oauthError === 'oauth_failed' oauth_failed: 'Đăng nhập bằng mạng xã hội thất bại. Vui lòng thử lại.',
? 'Đăng nhập bằng mạng xã hội thất bại. Vui lòng thử lại.' access_denied: 'Bạn đã từ chối quyền truy cập. Vui lòng thử lại.',
: oauthError invalid_request: 'Yêu cầu đăng nhập không hợp lệ. Vui lòng thử lại.',
? decodeURIComponent(oauthError) server_error: 'Lỗi máy chủ. Vui lòng thử lại sau.',
: null; temporarily_unavailable: 'Dịch vụ tạm thời không khả dụng. Vui lòng thử lại sau.',
};
const oauthErrorMessage = oauthError
? OAUTH_ERROR_MESSAGES[oauthError] ?? 'Đã xảy ra lỗi khi đăng nhập. Vui lòng thử lại.'
: null;
const { const {
register, register,

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -282,12 +283,14 @@ export default function DashboardPage() {
href={`/listings/${listing.id}`} href={`/listings/${listing.id}`}
className="flex items-center gap-4 rounded-lg border p-3 transition-colors hover:bg-accent" className="flex items-center gap-4 rounded-lg border p-3 transition-colors hover:bg-accent"
> >
<div className="h-12 w-16 flex-shrink-0 overflow-hidden rounded bg-muted"> <div className="relative h-12 w-16 flex-shrink-0 overflow-hidden rounded bg-muted">
{listing.property.media.length > 0 ? ( {listing.property.media.length > 0 ? (
<img <Image
src={listing.property.media[0]?.url} src={listing.property.media[0]?.url ?? ''}
alt="" alt={listing.property.title}
className="h-full w-full object-cover" fill
sizes="64px"
className="object-cover"
/> />
) : ( ) : (
<div className="flex h-full items-center justify-center text-xs text-muted-foreground"> <div className="flex h-full items-center justify-center text-xs text-muted-foreground">

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import * as React from 'react'; import * as React from 'react';
import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -203,14 +204,16 @@ export default function ListingsPage() {
<Card className="h-full overflow-hidden transition-shadow hover:shadow-md"> <Card className="h-full overflow-hidden transition-shadow hover:shadow-md">
<div className="relative aspect-[4/3] bg-muted"> <div className="relative aspect-[4/3] bg-muted">
{listing.property.media.length > 0 ? ( {listing.property.media.length > 0 ? (
<img <Image
src={listing.property.media[0]?.url} src={listing.property.media[0]?.url ?? ''}
alt={listing.property.title} alt={listing.property.title}
className="h-full w-full object-cover" fill
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
className="object-cover"
/> />
) : ( ) : (
<div className="flex h-full items-center justify-center text-muted-foreground"> <div className="flex h-full items-center justify-center text-muted-foreground">
Chua co anh Chưa có nh
</div> </div>
)} )}
<div className="absolute left-2 top-2"> <div className="absolute left-2 top-2">
@@ -279,12 +282,14 @@ export default function ListingsPage() {
href={`/listings/${listing.id}`} href={`/listings/${listing.id}`}
className="group flex items-center gap-3" className="group flex items-center gap-3"
> >
<div className="h-10 w-14 flex-shrink-0 overflow-hidden rounded bg-muted"> <div className="relative h-10 w-14 flex-shrink-0 overflow-hidden rounded bg-muted">
{listing.property.media.length > 0 ? ( {listing.property.media.length > 0 ? (
<img <Image
src={listing.property.media[0]?.url} src={listing.property.media[0]?.url ?? ''}
alt="" alt={listing.property.title}
className="h-full w-full object-cover" fill
sizes="56px"
className="object-cover"
/> />
) : ( ) : (
<div className="flex h-full items-center justify-center text-xs text-muted-foreground"> <div className="flex h-full items-center justify-center text-xs text-muted-foreground">

View File

@@ -37,15 +37,22 @@ export default function LandingPage() {
const [propertyType, setPropertyType] = React.useState(''); const [propertyType, setPropertyType] = React.useState('');
const [featuredListings, setFeaturedListings] = React.useState<ListingDetail[]>([]); const [featuredListings, setFeaturedListings] = React.useState<ListingDetail[]>([]);
const [loadingFeatured, setLoadingFeatured] = React.useState(true); const [loadingFeatured, setLoadingFeatured] = React.useState(true);
const [featuredError, setFeaturedError] = React.useState(false);
React.useEffect(() => { const fetchFeatured = React.useCallback(() => {
setLoadingFeatured(true);
setFeaturedError(false);
listingsApi listingsApi
.search({ status: 'ACTIVE', limit: 6 }) .search({ status: 'ACTIVE', limit: 6 })
.then((res) => setFeaturedListings(res.data)) .then((res) => setFeaturedListings(res.data))
.catch(() => {}) .catch(() => setFeaturedError(true))
.finally(() => setLoadingFeatured(false)); .finally(() => setLoadingFeatured(false));
}, []); }, []);
React.useEffect(() => {
fetchFeatured();
}, [fetchFeatured]);
const handleSearch = (e: React.FormEvent) => { const handleSearch = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
const params = new URLSearchParams(); const params = new URLSearchParams();
@@ -147,6 +154,13 @@ export default function LandingPage() {
<div className="mt-8 flex min-h-[300px] items-center justify-center"> <div className="mt-8 flex min-h-[300px] items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /> <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
</div> </div>
) : featuredError ? (
<div className="mt-8 flex min-h-[200px] flex-col items-center justify-center gap-3 text-muted-foreground">
<p>Không thể tải tin đăng. Vui lòng thử lại.</p>
<Button variant="outline" size="sm" onClick={fetchFeatured}>
Thử lại
</Button>
</div>
) : featuredListings.length > 0 ? ( ) : featuredListings.length > 0 ? (
<div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3"> <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{featuredListings.map((listing) => ( {featuredListings.map((listing) => (

View File

@@ -42,6 +42,7 @@ function SearchContent() {
const [page, setPage] = React.useState(Number(searchParams.get('page')) || 1); const [page, setPage] = React.useState(Number(searchParams.get('page')) || 1);
const [result, setResult] = React.useState<PaginatedResult<ListingDetail> | null>(null); const [result, setResult] = React.useState<PaginatedResult<ListingDetail> | null>(null);
const [loading, setLoading] = React.useState(true); const [loading, setLoading] = React.useState(true);
const [searchError, setSearchError] = React.useState(false);
const [viewMode, setViewMode] = React.useState<ViewMode>('list'); const [viewMode, setViewMode] = React.useState<ViewMode>('list');
const [showMobileFilters, setShowMobileFilters] = React.useState(false); const [showMobileFilters, setShowMobileFilters] = React.useState(false);
const [selectedListingId, setSelectedListingId] = React.useState<string | undefined>(); const [selectedListingId, setSelectedListingId] = React.useState<string | undefined>();
@@ -67,10 +68,14 @@ function SearchContent() {
if (filters.maxArea) params['maxArea'] = Number(filters.maxArea); if (filters.maxArea) params['maxArea'] = Number(filters.maxArea);
if (filters.bedrooms) params['bedrooms'] = Number(filters.bedrooms); if (filters.bedrooms) params['bedrooms'] = Number(filters.bedrooms);
setSearchError(false);
listingsApi listingsApi
.search(params) .search(params)
.then(setResult) .then(setResult)
.catch(() => setResult(null)) .catch(() => {
setResult(null);
setSearchError(true);
})
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, [filters, page]); }, [filters, page]);
@@ -214,6 +219,8 @@ function SearchContent() {
<SearchResults <SearchResults
result={result} result={result}
loading={loading} loading={loading}
error={searchError}
onRetry={fetchListings}
page={page} page={page}
sort={filters.sort} sort={filters.sort}
onPageChange={setPage} onPageChange={setPage}
@@ -236,6 +243,8 @@ function SearchContent() {
<SearchResults <SearchResults
result={result} result={result}
loading={loading} loading={loading}
error={searchError}
onRetry={fetchListings}
page={page} page={page}
sort={filters.sort} sort={filters.sort}
onPageChange={setPage} onPageChange={setPage}

View File

@@ -10,7 +10,13 @@ export default function GlobalError({
reset: () => void; reset: () => void;
}) { }) {
useEffect(() => { useEffect(() => {
console.error('Unhandled error:', error); // Report to error tracking service in production; log digest only
if (process.env.NODE_ENV === 'production') {
// TODO: integrate with Sentry/Datadog when available
// errorReporter.captureException(error);
} else {
console.error('Unhandled error:', error);
}
}, [error]); }, [error]);
return ( return (

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import * as React from 'react'; import * as React from 'react';
import Image from 'next/image';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import type { PropertyMedia } from '@/lib/listings-api'; import type { PropertyMedia } from '@/lib/listings-api';
@@ -30,10 +31,13 @@ export function ImageGallery({ media, className }: ImageGalleryProps) {
<div className={cn('space-y-3', className)}> <div className={cn('space-y-3', className)}>
{/* Main image */} {/* Main image */}
<div className="relative aspect-video overflow-hidden rounded-lg bg-muted"> <div className="relative aspect-video overflow-hidden rounded-lg bg-muted">
<img <Image
src={images[selectedIndex]?.url} src={images[selectedIndex]?.url ?? ''}
alt={images[selectedIndex]?.caption || `Ảnh ${selectedIndex + 1}`} alt={images[selectedIndex]?.caption || `Ảnh ${selectedIndex + 1}`}
className="h-full w-full object-cover" fill
sizes="(max-width: 768px) 100vw, 60vw"
className="object-cover"
priority={selectedIndex === 0}
/> />
{images.length > 1 && ( {images.length > 1 && (
<> <>
@@ -66,14 +70,16 @@ export function ImageGallery({ media, className }: ImageGalleryProps) {
key={img.id} key={img.id}
onClick={() => setSelectedIndex(index)} onClick={() => setSelectedIndex(index)}
className={cn( className={cn(
'h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border-2 transition-colors', 'relative h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border-2 transition-colors',
index === selectedIndex ? 'border-primary' : 'border-transparent opacity-70 hover:opacity-100', index === selectedIndex ? 'border-primary' : 'border-transparent opacity-70 hover:opacity-100',
)} )}
> >
<img <Image
src={img.url} src={img.url}
alt={img.caption || `Thumbnail ${index + 1}`} alt={img.caption || `Thumbnail ${index + 1}`}
className="h-full w-full object-cover" fill
sizes="64px"
className="object-cover"
/> />
</button> </button>
))} ))}

View File

@@ -1,5 +1,6 @@
'use client'; 'use client';
import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { Card, CardContent } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -27,75 +28,91 @@ interface PropertyCardProps {
} }
export function PropertyCard({ listing, compact }: PropertyCardProps) { export function PropertyCard({ listing, compact }: PropertyCardProps) {
const transactionLabel = listing.transactionType === 'SALE' ? 'Bán' : 'Cho thuê';
const propertyTypeLabel = PROPERTY_TYPE_LABELS[listing.property.propertyType] || listing.property.propertyType;
return ( return (
<Link href={`/listings/${listing.id}`}> <article
<Card className="group h-full overflow-hidden transition-shadow hover:shadow-md"> aria-label={`${listing.property.title}${transactionLabel} ${propertyTypeLabel}, ${formatPrice(listing.priceVND)} VNĐ`}
<div className={`relative bg-muted ${compact ? 'aspect-[16/10]' : 'aspect-[4/3]'}`}> >
{listing.property.media.length > 0 ? ( <Link href={`/listings/${listing.id}`}>
<img <Card className="group h-full overflow-hidden transition-shadow hover:shadow-md">
src={listing.property.media[0]?.url} <div className={`relative bg-muted ${compact ? 'aspect-[16/10]' : 'aspect-[4/3]'}`}>
alt={listing.property.title} {listing.property.media.length > 0 ? (
className="h-full w-full object-cover transition-transform group-hover:scale-105" <Image
loading="lazy" src={listing.property.media[0]?.url ?? ''}
/> alt={`Ảnh bất động sản: ${listing.property.title}`}
) : ( fill
<div className="flex h-full items-center justify-center text-muted-foreground"> sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
Chưa nh className="object-cover transition-transform group-hover:scale-105"
</div> />
)} ) : (
<div className="absolute left-2 top-2 flex gap-1"> <div className="flex h-full items-center justify-center text-muted-foreground" aria-hidden="true">
<Badge variant="default" className="text-xs"> Chưa nh
{listing.transactionType === 'SALE' ? 'Bán' : 'Cho thuê'} </div>
</Badge> )}
<Badge variant="secondary" className="text-xs"> <div className="absolute left-2 top-2 flex gap-1">
{PROPERTY_TYPE_LABELS[listing.property.propertyType] || listing.property.propertyType} <Badge variant="default" className="text-xs">
</Badge> {transactionLabel}
</div> </Badge>
{listing.property.media.length > 1 && ( <Badge variant="secondary" className="text-xs">
<div className="absolute bottom-2 right-2"> {propertyTypeLabel}
<Badge variant="outline" className="bg-black/50 text-xs text-white border-none">
{listing.property.media.length} nh
</Badge> </Badge>
</div> </div>
)} {listing.property.media.length > 1 && (
</div> <div className="absolute bottom-2 right-2">
<CardContent className="p-4"> <Badge variant="outline" className="bg-black/50 text-xs text-white border-none" aria-label={`${listing.property.media.length} ảnh`}>
<p className="text-lg font-bold text-primary"> {listing.property.media.length} nh
{formatPrice(listing.priceVND)} VNĐ </Badge>
{listing.transactionType === 'RENT' && listing.rentPriceMonthly && ( </div>
<span className="text-sm font-normal text-muted-foreground">/tháng</span>
)}
</p>
<h3 className="mt-1 line-clamp-1 font-medium">{listing.property.title}</h3>
<p className="mt-1 line-clamp-1 text-sm text-muted-foreground">
{listing.property.address}, {listing.property.district}, {listing.property.city}
</p>
<div className="mt-3 flex flex-wrap gap-1.5">
<Badge variant="secondary" className="text-xs">
{listing.property.areaM2} m²
</Badge>
{listing.property.bedrooms != null && (
<Badge variant="secondary" className="text-xs">
{listing.property.bedrooms} PN
</Badge>
)}
{listing.property.bathrooms != null && listing.property.bathrooms > 0 && (
<Badge variant="secondary" className="text-xs">
{listing.property.bathrooms} PT
</Badge>
)}
{listing.property.direction && (
<Badge variant="outline" className="text-xs">
Hướng {listing.property.direction === 'NORTH' ? 'Bắc' :
listing.property.direction === 'SOUTH' ? 'Nam' :
listing.property.direction === 'EAST' ? 'Đông' :
listing.property.direction === 'WEST' ? 'Tây' :
listing.property.direction}
</Badge>
)} )}
</div> </div>
</CardContent> <CardContent className="p-4">
</Card> <p className="text-lg font-bold text-primary">
</Link> {formatPrice(listing.priceVND)} VNĐ
{listing.transactionType === 'RENT' && listing.rentPriceMonthly && (
<span className="text-sm font-normal text-muted-foreground">/tháng</span>
)}
</p>
<h3 className="mt-1 line-clamp-1 font-medium">{listing.property.title}</h3>
<p className="mt-1 line-clamp-1 text-sm text-muted-foreground">
{listing.property.address}, {listing.property.district}, {listing.property.city}
</p>
<ul className="mt-3 flex flex-wrap gap-1.5" aria-label="Thông tin bất động sản">
<li>
<Badge variant="secondary" className="text-xs">
{listing.property.areaM2} m²
</Badge>
</li>
{listing.property.bedrooms != null && (
<li>
<Badge variant="secondary" className="text-xs">
{listing.property.bedrooms} PN
</Badge>
</li>
)}
{listing.property.bathrooms != null && listing.property.bathrooms > 0 && (
<li>
<Badge variant="secondary" className="text-xs">
{listing.property.bathrooms} PT
</Badge>
</li>
)}
{listing.property.direction && (
<li>
<Badge variant="outline" className="text-xs">
Hướng {listing.property.direction === 'NORTH' ? 'Bắc' :
listing.property.direction === 'SOUTH' ? 'Nam' :
listing.property.direction === 'EAST' ? 'Đông' :
listing.property.direction === 'WEST' ? 'Tây' :
listing.property.direction}
</Badge>
</li>
)}
</ul>
</CardContent>
</Card>
</Link>
</article>
); );
} }

View File

@@ -9,6 +9,8 @@ import type { ListingDetail, PaginatedResult } from '@/lib/listings-api';
interface SearchResultsProps { interface SearchResultsProps {
result: PaginatedResult<ListingDetail> | null; result: PaginatedResult<ListingDetail> | null;
loading: boolean; loading: boolean;
error?: boolean;
onRetry?: () => void;
page: number; page: number;
sort: string; sort: string;
onPageChange: (page: number) => void; onPageChange: (page: number) => void;
@@ -18,6 +20,8 @@ interface SearchResultsProps {
export function SearchResults({ export function SearchResults({
result, result,
loading, loading,
error,
onRetry,
page, page,
sort, sort,
onPageChange, onPageChange,
@@ -31,6 +35,20 @@ export function SearchResults({
); );
} }
if (error) {
return (
<div className="flex min-h-[400px] flex-col items-center justify-center gap-3 text-muted-foreground">
<p className="text-lg font-medium">Không thể tải kết quả tìm kiếm</p>
<p className="text-sm">Đã xảy ra lỗi. Vui lòng thử lại.</p>
{onRetry && (
<Button variant="outline" size="sm" onClick={onRetry}>
Thử lại
</Button>
)}
</div>
);
}
if (!result || result.data.length === 0) { if (!result || result.data.length === 0) {
return ( return (
<div className="flex min-h-[400px] flex-col items-center justify-center text-muted-foreground"> <div className="flex min-h-[400px] flex-col items-center justify-center text-muted-foreground">

View File

@@ -2,6 +2,28 @@
const nextConfig = { const nextConfig = {
reactStrictMode: true, reactStrictMode: true,
output: 'standalone', output: 'standalone',
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**',
},
],
},
async headers() {
return [
{
source: '/(.*)',
headers: [
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-XSS-Protection', value: '1; mode=block' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(self)' },
],
},
];
},
}; };
module.exports = nextConfig; module.exports = nextConfig;