diff --git a/.gitignore b/.gitignore index f85520e..81fbba6 100644 --- a/.gitignore +++ b/.gitignore @@ -24,9 +24,9 @@ .DS_Store *.pem -# admin-uploaded images (keep folder via .gitkeep) -/public/uploads/* -!/public/uploads/.gitkeep +# admin-uploaded images (served by GET /uploads/[...path], not public/) +/uploads/ +/public/uploads/ # debug npm-debug.log* diff --git a/Dockerfile b/Dockerfile index 2d6e951..788d330 100644 --- a/Dockerfile +++ b/Dockerfile @@ -36,8 +36,11 @@ COPY --from=builder /app/public ./public COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static -# Writable dir for admin image uploads (mount a volume in compose for persistence) -RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads +# Writable dir for admin image uploads (mount a volume in compose for persistence). +# Keep this outside public/: Next standalone does not serve runtime public files. +RUN rm -rf ./public/uploads \ + && mkdir -p ./uploads \ + && chown -R nextjs:nodejs ./uploads USER nextjs diff --git a/Dockerfile.prebuilt b/Dockerfile.prebuilt index d89a1a2..9ef0565 100644 --- a/Dockerfile.prebuilt +++ b/Dockerfile.prebuilt @@ -18,8 +18,11 @@ COPY --chown=nextjs:nodejs . ./ # Next warns/breaks if a legacy root-level ./static exists alongside ./public RUN rm -rf ./static -# Writable dir for admin image uploads (mount a volume in compose for persistence) -RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads +# Writable dir for admin image uploads (mount a volume in compose for persistence). +# Keep this outside public/: Next standalone does not serve runtime public files. +RUN rm -rf ./public/uploads \ + && mkdir -p ./uploads \ + && chown -R nextjs:nodejs ./uploads USER nextjs EXPOSE 3000 diff --git a/docker-compose.yml b/docker-compose.yml index d7c5a25..a2de30b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,11 +13,11 @@ services: - HOSTNAME=0.0.0.0 - NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-https://edu.mstaut.ir} - DATABASE_URL=${DATABASE_URL:?Set DATABASE_URL in a protected environment file} - - UPLOAD_DIR=/app/public/uploads + - UPLOAD_DIR=/app/uploads # Nginx Proxy Manager: edu.mstaut.ir → http://aut-management-faculty:3000 # DB: same Docker network as container `insaight-postgres` (not the public IP). volumes: - - uploads_data:/app/public/uploads + - uploads_data:/app/uploads expose: - "3000" networks: diff --git a/public/uploads/.gitkeep b/public/uploads/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/scripts/deploy-production.sh b/scripts/deploy-production.sh index 186e86a..2e685f8 100644 --- a/scripts/deploy-production.sh +++ b/scripts/deploy-production.sh @@ -44,8 +44,8 @@ docker run --rm --network "$NETWORK" --env-file "$ENV_FILE" \ # Check the database and a minimal page set before switching the public upstream. CANDIDATE="edu-candidate-${REVISION:0:12}" docker run -d --name "$CANDIDATE" --network "$NETWORK" --env-file "$ENV_FILE" \ - -e UPLOAD_DIR=/app/public/uploads \ - -v "$UPLOAD_VOLUME:/app/public/uploads" \ + -e UPLOAD_DIR=/app/uploads \ + -v "$UPLOAD_VOLUME:/app/uploads" \ "$IMAGE" cleanup_candidate() { docker rm -f "$CANDIDATE" >/dev/null 2>&1 || true; } trap cleanup_candidate EXIT @@ -101,8 +101,8 @@ rollback() { trap rollback ERR docker run -d --name "$CONTAINER" --restart unless-stopped \ --network "$NETWORK" --env-file "$ENV_FILE" \ - -e UPLOAD_DIR=/app/public/uploads \ - -v "$UPLOAD_VOLUME:/app/public/uploads" \ + -e UPLOAD_DIR=/app/uploads \ + -v "$UPLOAD_VOLUME:/app/uploads" \ -p 127.0.0.1:3000:3000 "$IMAGE" READY=false for attempt in $(seq 1 20); do diff --git a/scripts/dump-database.mjs b/scripts/dump-database.mjs index 44d0a05..b6977c2 100644 --- a/scripts/dump-database.mjs +++ b/scripts/dump-database.mjs @@ -149,17 +149,15 @@ async function main() { } const sequences = await client.query(` - SELECT sequencename, last_value, is_called + SELECT sequencename, last_value FROM pg_sequences WHERE schemaname = 'public' ORDER BY sequencename `); for (const seq of sequences.rows) { - const called = seq.is_called === true; + if (seq.last_value == null) continue; const seqName = String(seq.sequencename).replaceAll("'", "''"); - lines.push( - `SELECT setval('${seqName}', ${Number(seq.last_value)}, ${called});`, - ); + lines.push(`SELECT setval('${seqName}', ${Number(seq.last_value)}, true);`); } lines.push("", "COMMIT;", ""); diff --git a/src/app/(main)/alumni/page.tsx b/src/app/(main)/alumni/page.tsx index fc8bad5..84713ad 100644 --- a/src/app/(main)/alumni/page.tsx +++ b/src/app/(main)/alumni/page.tsx @@ -1,6 +1,6 @@ import type { Metadata } from "next"; -import Image from "next/image"; import { getTranslations } from "next-intl/server"; +import { CmsImage } from "@/components/atoms/CmsImage"; import { Container } from "@/components/atoms/Container"; import { Heading } from "@/components/atoms/Heading"; import { Section } from "@/components/atoms/Section"; @@ -41,7 +41,7 @@ export default async function AlumniPage() { className="scroll-mt-24" >
- {story.name}
- {article.title} }; + +async function lookupUpload(segments: string[]) { + const absolutePath = resolveStoredUploadPath(segments); + if (!absolutePath) return null; + + try { + const info = await stat(absolutePath); + if (!info.isFile()) return null; + const mime = mimeForUploadExt(path.extname(absolutePath)); + if (!mime) return null; + return { absolutePath, info, mime }; + } catch { + return null; + } +} + +function headersFor(file: { info: { size: number }; mime: string }) { + return { + "Content-Type": file.mime, + "Content-Length": String(file.info.size), + "Cache-Control": "public, max-age=31536000, immutable", + }; +} + +export async function GET(_request: Request, { params }: RouteParams) { + const { path: segments } = await params; + const file = await lookupUpload(segments); + if (!file) { + return new NextResponse("Not found", { status: 404 }); + } + const buffer = await readFile(file.absolutePath); + return new NextResponse(buffer, { + status: 200, + headers: headersFor(file), + }); +} + +export async function HEAD(_request: Request, { params }: RouteParams) { + const { path: segments } = await params; + const file = await lookupUpload(segments); + if (!file) { + return new NextResponse(null, { status: 404 }); + } + return new NextResponse(null, { + status: 200, + headers: headersFor(file), + }); +} diff --git a/src/components/atoms/CmsImage.tsx b/src/components/atoms/CmsImage.tsx new file mode 100644 index 0000000..0f717ab --- /dev/null +++ b/src/components/atoms/CmsImage.tsx @@ -0,0 +1,14 @@ +import Image, { type ImageProps } from "next/image"; +import { isRuntimeUploadSrc } from "@/lib/uploads/types"; + +/** + * next/image optimizer reads from `public/` at build time. Runtime uploads + * live outside that tree, so skip optimization for `/uploads/...`. + */ +export function CmsImage({ src, unoptimized, ...props }: ImageProps) { + const skipOptimize = + unoptimized ?? + (typeof src === "string" && isRuntimeUploadSrc(src)); + + return ; +} diff --git a/src/components/molecules/Cards.tsx b/src/components/molecules/Cards.tsx index a5dada4..5492372 100644 --- a/src/components/molecules/Cards.tsx +++ b/src/components/molecules/Cards.tsx @@ -1,5 +1,5 @@ -import Image from "next/image"; import Link from "next/link"; +import { CmsImage } from "@/components/atoms/CmsImage"; import { ArrowUpLeft, MapPin, Wifi } from "lucide-react"; import { Card, @@ -65,7 +65,7 @@ export function ArticleCard({ return (
- {title} +

{category}

@@ -101,7 +101,7 @@ export function ArticleCard({ featured ? "aspect-[16/10]" : "aspect-[4/3]", )} > - {title}
- {title} {hasBanner ? ( - - {alt}
{photo ? ( - {member.name} -
- پیش نمایش تصویر diff --git a/src/lib/uploads/image.ts b/src/lib/uploads/image.ts index 1104147..e95ad07 100644 --- a/src/lib/uploads/image.ts +++ b/src/lib/uploads/image.ts @@ -17,12 +17,53 @@ const MIME_TO_EXT = new Map([ ["image/gif", "gif"], ]); -/** Disk root for uploaded images. Override with UPLOAD_DIR for Docker volumes. */ +const EXT_TO_MIME = new Map([ + [".jpg", "image/jpeg"], + [".jpeg", "image/jpeg"], + [".png", "image/png"], + [".webp", "image/webp"], + [".gif", "image/gif"], +]); + +/** UUID filenames written by saveUploadedImage. */ +const STORED_FILENAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(jpg|jpeg|png|webp|gif)$/; + +/** + * Disk root for uploaded images. + * Keep this *outside* `public/` in production: Next standalone does not + * reliably serve files added to `public/` after the image is built. + * Override with UPLOAD_DIR for Docker volumes. + */ export function getUploadsRoot(): string { if (process.env.UPLOAD_DIR) { return path.resolve(process.env.UPLOAD_DIR); } - return path.join(process.cwd(), "public", "uploads"); + return path.join(process.cwd(), "uploads"); +} + +export function mimeForUploadExt(ext: string): string | undefined { + return EXT_TO_MIME.get(ext.toLowerCase()); +} + +/** + * Resolve `folder/uuid.ext` to an absolute path under the uploads root. + * Returns null for anything that is not a stored upload (traversal, extra + * segments, unknown folder, or unexpected filename). + */ +export function resolveStoredUploadPath(segments: string[]): string | null { + if (segments.length !== 2) return null; + const [folder, filename] = segments; + if (!folder || !filename) return null; + if (!isUploadFolder(folder)) return null; + if (!STORED_FILENAME.test(filename)) return null; + + const root = getUploadsRoot(); + const absolutePath = path.resolve(root, folder, filename); + const relative = path.relative(root, absolutePath); + if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) { + return null; + } + return absolutePath; } export function publicUrlFor(relativePath: string): string { diff --git a/src/lib/uploads/types.ts b/src/lib/uploads/types.ts index 4ac70ef..713a4a8 100644 --- a/src/lib/uploads/types.ts +++ b/src/lib/uploads/types.ts @@ -12,3 +12,8 @@ export type UploadFolder = (typeof UPLOAD_FOLDERS)[number]; export function isUploadFolder(value: string): value is UploadFolder { return (UPLOAD_FOLDERS as readonly string[]).includes(value); } + +/** True for images written at runtime (`/uploads/{folder}/{uuid}.ext`). */ +export function isRuntimeUploadSrc(src: string): boolean { + return src.startsWith("/uploads/"); +}