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

View File

@@ -22,12 +22,16 @@ export default function LoginPage() {
const [showPassword, setShowPassword] = useState(false);
const oauthError = searchParams.get('error');
const oauthErrorMessage =
oauthError === 'oauth_failed'
? 'Đăng nhập bằng mạng xã hội thất bại. Vui lòng thử lại.'
: oauthError
? decodeURIComponent(oauthError)
: null;
const OAUTH_ERROR_MESSAGES: Record<string, string> = {
oauth_failed: 'Đă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.',
invalid_request: 'Yêu cầu đăng nhập không hợp lệ. Vui lòng thử lại.',
server_error: 'Lỗi máy chủ. Vui lòng thử lại sau.',
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 {
register,

View File

@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -282,12 +283,14 @@ export default function DashboardPage() {
href={`/listings/${listing.id}`}
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 ? (
<img
src={listing.property.media[0]?.url}
alt=""
className="h-full w-full object-cover"
<Image
src={listing.property.media[0]?.url ?? ''}
alt={listing.property.title}
fill
sizes="64px"
className="object-cover"
/>
) : (
<div className="flex h-full items-center justify-center text-xs text-muted-foreground">

View File

@@ -1,6 +1,7 @@
'use client';
import * as React from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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">
<div className="relative aspect-[4/3] bg-muted">
{listing.property.media.length > 0 ? (
<img
src={listing.property.media[0]?.url}
<Image
src={listing.property.media[0]?.url ?? ''}
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">
Chua co anh
Chưa có nh
</div>
)}
<div className="absolute left-2 top-2">
@@ -279,12 +282,14 @@ export default function ListingsPage() {
href={`/listings/${listing.id}`}
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 ? (
<img
src={listing.property.media[0]?.url}
alt=""
className="h-full w-full object-cover"
<Image
src={listing.property.media[0]?.url ?? ''}
alt={listing.property.title}
fill
sizes="56px"
className="object-cover"
/>
) : (
<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 [featuredListings, setFeaturedListings] = React.useState<ListingDetail[]>([]);
const [loadingFeatured, setLoadingFeatured] = React.useState(true);
const [featuredError, setFeaturedError] = React.useState(false);
React.useEffect(() => {
const fetchFeatured = React.useCallback(() => {
setLoadingFeatured(true);
setFeaturedError(false);
listingsApi
.search({ status: 'ACTIVE', limit: 6 })
.then((res) => setFeaturedListings(res.data))
.catch(() => {})
.catch(() => setFeaturedError(true))
.finally(() => setLoadingFeatured(false));
}, []);
React.useEffect(() => {
fetchFeatured();
}, [fetchFeatured]);
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
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="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
</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 ? (
<div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{featuredListings.map((listing) => (

View File

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

View File

@@ -10,7 +10,13 @@ export default function GlobalError({
reset: () => void;
}) {
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]);
return (

View File

@@ -1,6 +1,7 @@
'use client';
import * as React from 'react';
import Image from 'next/image';
import { cn } from '@/lib/utils';
import type { PropertyMedia } from '@/lib/listings-api';
@@ -30,10 +31,13 @@ export function ImageGallery({ media, className }: ImageGalleryProps) {
<div className={cn('space-y-3', className)}>
{/* Main image */}
<div className="relative aspect-video overflow-hidden rounded-lg bg-muted">
<img
src={images[selectedIndex]?.url}
<Image
src={images[selectedIndex]?.url ?? ''}
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 && (
<>
@@ -66,14 +70,16 @@ export function ImageGallery({ media, className }: ImageGalleryProps) {
key={img.id}
onClick={() => setSelectedIndex(index)}
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',
)}
>
<img
<Image
src={img.url}
alt={img.caption || `Thumbnail ${index + 1}`}
className="h-full w-full object-cover"
fill
sizes="64px"
className="object-cover"
/>
</button>
))}

View File

@@ -1,5 +1,6 @@
'use client';
import Image from 'next/image';
import Link from 'next/link';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -27,75 +28,91 @@ interface 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 (
<Link href={`/listings/${listing.id}`}>
<Card className="group h-full overflow-hidden transition-shadow hover:shadow-md">
<div className={`relative bg-muted ${compact ? 'aspect-[16/10]' : 'aspect-[4/3]'}`}>
{listing.property.media.length > 0 ? (
<img
src={listing.property.media[0]?.url}
alt={listing.property.title}
className="h-full w-full object-cover transition-transform group-hover:scale-105"
loading="lazy"
/>
) : (
<div className="flex h-full items-center justify-center text-muted-foreground">
Chưa nh
</div>
)}
<div className="absolute left-2 top-2 flex gap-1">
<Badge variant="default" className="text-xs">
{listing.transactionType === 'SALE' ? 'Bán' : 'Cho thuê'}
</Badge>
<Badge variant="secondary" className="text-xs">
{PROPERTY_TYPE_LABELS[listing.property.propertyType] || listing.property.propertyType}
</Badge>
</div>
{listing.property.media.length > 1 && (
<div className="absolute bottom-2 right-2">
<Badge variant="outline" className="bg-black/50 text-xs text-white border-none">
{listing.property.media.length} nh
<article
aria-label={`${listing.property.title}${transactionLabel} ${propertyTypeLabel}, ${formatPrice(listing.priceVND)} VNĐ`}
>
<Link href={`/listings/${listing.id}`}>
<Card className="group h-full overflow-hidden transition-shadow hover:shadow-md">
<div className={`relative bg-muted ${compact ? 'aspect-[16/10]' : 'aspect-[4/3]'}`}>
{listing.property.media.length > 0 ? (
<Image
src={listing.property.media[0]?.url ?? ''}
alt={`Ảnh bất động sản: ${listing.property.title}`}
fill
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
className="object-cover transition-transform group-hover:scale-105"
/>
) : (
<div className="flex h-full items-center justify-center text-muted-foreground" aria-hidden="true">
Chưa nh
</div>
)}
<div className="absolute left-2 top-2 flex gap-1">
<Badge variant="default" className="text-xs">
{transactionLabel}
</Badge>
<Badge variant="secondary" className="text-xs">
{propertyTypeLabel}
</Badge>
</div>
)}
</div>
<CardContent className="p-4">
<p className="text-lg font-bold text-primary">
{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>
<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>
{listing.property.media.length > 1 && (
<div className="absolute bottom-2 right-2">
<Badge variant="outline" className="bg-black/50 text-xs text-white border-none" aria-label={`${listing.property.media.length} ảnh`}>
{listing.property.media.length} nh
</Badge>
</div>
)}
</div>
</CardContent>
</Card>
</Link>
<CardContent className="p-4">
<p className="text-lg font-bold text-primary">
{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 {
result: PaginatedResult<ListingDetail> | null;
loading: boolean;
error?: boolean;
onRetry?: () => void;
page: number;
sort: string;
onPageChange: (page: number) => void;
@@ -18,6 +20,8 @@ interface SearchResultsProps {
export function SearchResults({
result,
loading,
error,
onRetry,
page,
sort,
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) {
return (
<div className="flex min-h-[400px] flex-col items-center justify-center text-muted-foreground">

View File

@@ -2,6 +2,28 @@
const nextConfig = {
reactStrictMode: true,
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;