From 0b4d9a8463c75f35abb6a5cf11b12acfacff7e98 Mon Sep 17 00:00:00 2001 From: devops Date: Tue, 20 Oct 2026 06:31:22 +0000 Subject: [PATCH] fix(blog): harden freshness and authorship --- backend/src/admin/blogs.controller.spec.ts | 8 +++ backend/src/admin/blogs.service.spec.ts | 38 +++++++++++ backend/src/admin/blogs.service.ts | 67 ++++++++++++++++--- backend/src/blogs/blogs.service.spec.ts | 1 + backend/src/blogs/blogs.service.ts | 13 ++-- .../app/blog/[slug]/blog-slug-page.test.tsx | 21 +++++- frontend/application/app/blog/[slug]/page.tsx | 14 ++-- .../app/blog/rss.xml/route.test.ts | 2 +- .../application/app/blog/rss.xml/route.ts | 5 +- frontend/application/lib/blogDates.test.ts | 12 ++++ frontend/application/lib/blogDates.ts | 2 +- 11 files changed, 157 insertions(+), 26 deletions(-) create mode 100644 frontend/application/lib/blogDates.test.ts diff --git a/backend/src/admin/blogs.controller.spec.ts b/backend/src/admin/blogs.controller.spec.ts index 4d085566..8a721a3a 100644 --- a/backend/src/admin/blogs.controller.spec.ts +++ b/backend/src/admin/blogs.controller.spec.ts @@ -244,6 +244,14 @@ describe("BlogsController (Admin)", () => { expect(result).toEqual({ success: true, data: updatedBlog }); }); + it("propagates invalid content timestamp rejection without accepting createdAt", async () => { + const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" }; + mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt")); + + await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt"); + expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body); + }); + it("deleteBlog should delete blog and return success: true", async () => { const blogId = "blog-10"; mockBlogsService.deleteBlog.mockResolvedValue(undefined); diff --git a/backend/src/admin/blogs.service.spec.ts b/backend/src/admin/blogs.service.spec.ts index 62c9df90..9a9eeaa8 100644 --- a/backend/src/admin/blogs.service.spec.ts +++ b/backend/src/admin/blogs.service.spec.ts @@ -299,6 +299,44 @@ describe("Admin BlogsService", () => { }); }); + describe("updateBlog security and freshness validation", () => { + beforeEach(() => { + mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" }); + mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" }); + }); + + it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => { + await service.updateBlog("blog-1", { + title: "Allowed title", + createdAt: "2000-01-01T00:00:00.000Z", + serverOwned: "must-not-pass", + }); + + const payload = mockPrisma.blog.update.mock.calls[0][0].data; + expect(payload.title).toBe("Allowed title"); + expect(payload).not.toHaveProperty("createdAt"); + expect(payload).not.toHaveProperty("serverOwned"); + }); + + it("rejects an invalid explicit contentUpdatedAt", async () => { + await expect( + service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }), + ).rejects.toThrow("Invalid contentUpdatedAt"); + expect(mockPrisma.blog.update).not.toHaveBeenCalled(); + }); + + it("preserves explicit null clearing and markContentUpdated precedence", async () => { + await service.updateBlog("blog-1", { contentUpdatedAt: null }); + expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull(); + + await service.updateBlog("blog-1", { + contentUpdatedAt: "not-a-date", + markContentUpdated: true, + }); + expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date)); + }); + }); + describe("deleteBlog", () => { it("should throw NotFoundException if blog not found", async () => { mockPrisma.blog.findUnique.mockResolvedValue(null); diff --git a/backend/src/admin/blogs.service.ts b/backend/src/admin/blogs.service.ts index e785b091..3e967f36 100644 --- a/backend/src/admin/blogs.service.ts +++ b/backend/src/admin/blogs.service.ts @@ -1,4 +1,5 @@ import { + BadRequestException, Injectable, NotFoundException, OnModuleInit, @@ -226,7 +227,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy { if (!blog) throw new NotFoundException("Blog not found"); const { - tags, tagNames, categoryId, authorId, @@ -235,17 +235,64 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy { readingTime, markContentUpdated, contentUpdatedAt, - ...rest } = data; + const mutableScalarFields = [ + "title", + "slug", + "content", + "excerpt", + "authorTeam", + "authorRole", + "imageUrl", + "imageAlt", + "imageCaption", + "metaTitle", + "metaDescription", + "keywords", + "focusKeywords", + "canonicalUrl", + "noIndex", + "noFollow", + "schemaType", + "ogTitle", + "ogDescription", + "ogImage", + "status", + "isPublished", + "featured", + "allowComments", + "showOnHome", + "homeDisplayMode", + "relatedProductIds", + "relatedBlogIds", + ] as const; + const updatePayload: Prisma.BlogUpdateInput = {}; + for (const field of mutableScalarFields) { + if (data[field] !== undefined) { + (updatePayload as Record)[field] = data[field]; + } + } + const now = new Date(); - const updatePayload: Prisma.BlogUpdateInput = { - ...rest, - ...(markContentUpdated - ? { contentUpdatedAt: now } - : contentUpdatedAt !== undefined - ? { contentUpdatedAt: contentUpdatedAt ? new Date(contentUpdatedAt) : null } - : {}), + if (markContentUpdated) { + (updatePayload as Record).contentUpdatedAt = now; + } else if (contentUpdatedAt !== undefined) { + if (contentUpdatedAt === null || contentUpdatedAt === "") { + (updatePayload as Record).contentUpdatedAt = null; + } else { + const parsedContentUpdatedAt = new Date(contentUpdatedAt); + if (!Number.isFinite(parsedContentUpdatedAt.getTime())) { + throw new BadRequestException("Invalid contentUpdatedAt"); + } + (updatePayload as Record).contentUpdatedAt = parsedContentUpdatedAt; + } + } + + Object.assign(updatePayload, { + ...(readingTime !== undefined + ? { readingTime: Number(readingTime) } + : {}), ...(readingTime !== undefined ? { readingTime: Number(readingTime) } : {}), @@ -255,7 +302,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy { ? { category: { connect: { id: categoryId } } } : { category: { disconnect: true } } : {}), - }; + }); if (scheduledAt !== undefined) { const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null; diff --git a/backend/src/blogs/blogs.service.spec.ts b/backend/src/blogs/blogs.service.spec.ts index 7d2dd366..ba8b99da 100644 --- a/backend/src/blogs/blogs.service.spec.ts +++ b/backend/src/blogs/blogs.service.spec.ts @@ -51,6 +51,7 @@ describe("BlogsService", () => { expect(result.meta.total).toBe(1); const query = mockPrisma.blog.findMany.mock.calls[0][0]; expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } }); + expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]); }); it("should filter by categorySlug and search term", async () => { diff --git a/backend/src/blogs/blogs.service.ts b/backend/src/blogs/blogs.service.ts index 67549d95..616b1ddb 100644 --- a/backend/src/blogs/blogs.service.ts +++ b/backend/src/blogs/blogs.service.ts @@ -64,9 +64,12 @@ export class BlogsService { where: whereClause, skip, take: Number(limit), - orderBy: { - [sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder, - }, + orderBy: [ + { + [sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder, + }, + { id: "asc" }, + ], include: { author: { select: { id: true, firstName: true, lastName: true }, @@ -108,7 +111,7 @@ export class BlogsService { const selectedBlogs = await this.prisma.blog.findMany({ where: { ...baseWhere, showOnHome: true }, take: 4, - orderBy: { publishedAt: "desc" }, + orderBy: [{ publishedAt: "desc" }, { id: "asc" }], include: { author: { select: { id: true, firstName: true, lastName: true }, @@ -127,7 +130,7 @@ export class BlogsService { const newestBlogs = await this.prisma.blog.findMany({ where: baseWhere, take: 4, - orderBy: { publishedAt: "desc" }, + orderBy: [{ publishedAt: "desc" }, { id: "asc" }], include: { author: { select: { id: true, firstName: true, lastName: true }, diff --git a/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx b/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx index 6d813f83..20732c11 100644 --- a/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx +++ b/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import React from 'react'; -import BlogPostPage from './page'; +import BlogPostPage, { generateMetadata } from './page'; vi.mock('../../../lib/seo', () => ({ getSeoConfig: vi.fn().mockResolvedValue({ @@ -79,6 +79,25 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => { const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined(); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('تیم پژوهش و محتوای علمی کنینا'); }); + it('uses the stable Organization fallback visibly and in metadata', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ + slug: 'authorless', title: 'Authorless', content: '

x

', publishedAt: '2026-01-01T00:00:00Z', author: { firstName: '', lastName: '' }, + }) })); + + const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'authorless' }) }); + expect((metadata.openGraph as any)?.authors).toEqual(['تیم پژوهش و محتوای علمی کنینا']); + + const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'authorless' }) }); + const children = React.Children.toArray(jsx.props.children) as any[]; + const client = children.find((child) => child?.props?.authorName); + expect(client.props.authorName).toBe('تیم پژوهش و محتوای علمی کنینا'); + const article = JSON.parse(children[0].props.dangerouslySetInnerHTML.__html); + expect(article.author).toMatchObject({ + '@type': 'Organization', + name: 'تیم پژوهش و محتوای علمی کنینا', + }); + }); + it('does not inject FAQPage schema when article does not have FAQs', async () => { const blogData = { slug: 'nutrition', diff --git a/frontend/application/app/blog/[slug]/page.tsx b/frontend/application/app/blog/[slug]/page.tsx index 0ef1586c..2877c415 100644 --- a/frontend/application/app/blog/[slug]/page.tsx +++ b/frontend/application/app/blog/[slug]/page.tsx @@ -91,9 +91,10 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str siteUrl.includes('test') || siteUrl.includes('dev'); - const authorName = blog.author - ? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() || 'نویسنده کنینا' - : 'نویسنده و پژوهشگر کنینا'; + const personAuthorName = blog.author + ? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() + : ''; + const authorName = personAuthorName || BLOG_TEAM_FALLBACK; const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt); const modifiedTime = safeIso(validContentUpdatedAt(blog)); @@ -173,9 +174,10 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug: const rawSiteUrl = process.env.NEXT_PUBLIC_SITE_URL || config.canonicalBaseUrl || 'https://canina.ir'; const siteUrl = rawSiteUrl.replace(/\/+$/, ''); - const authorName = blog.author - ? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() || 'نویسنده کنینا' - : 'نویسنده و پژوهشگر کنینا'; + const personAuthorName = blog.author + ? `${blog.author.firstName || ''} ${blog.author.lastName || ''}`.trim() + : ''; + const authorName = personAuthorName || BLOG_TEAM_FALLBACK; const publishedDate = safeLocalDate(blog.publishedAt) || safeLocalDate(blog.createdAt); const canonicalUrl = blog.canonicalUrl diff --git a/frontend/application/app/blog/rss.xml/route.test.ts b/frontend/application/app/blog/rss.xml/route.test.ts index b72a5254..258e53f8 100644 --- a/frontend/application/app/blog/rss.xml/route.test.ts +++ b/frontend/application/app/blog/rss.xml/route.test.ts @@ -1,4 +1,4 @@ import { afterEach,describe,expect,it,vi } from "vitest"; import { GET } from "./route"; afterEach(()=>{vi.unstubAllGlobals();vi.unstubAllEnvs()}); -describe("blog RSS dates",()=>{it("keeps pubDate immutable and derives lastBuildDate from real valid dates",async()=>{vi.stubEnv("NEXT_PUBLIC_SITE_URL","https://canina.ir");vi.stubGlobal("fetch",vi.fn().mockResolvedValue({ok:true,json:async()=>({data:[{slug:"a",title:"A",status:"PUBLISHED",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-03T00:00:00Z",updatedAt:"2026-01-04T00:00:00Z"}]})}));const xml=await (await GET()).text();expect(xml).toContain(`${new Date("2026-01-01T00:00:00Z").toUTCString()}`);expect(xml).toContain(`${new Date("2026-01-03T00:00:00Z").toUTCString()}`);});}); +describe("blog RSS dates",()=>{it("keeps pubDate immutable and derives lastBuildDate from real valid dates",async()=>{vi.stubEnv("NEXT_PUBLIC_SITE_URL","https://canina.ir");vi.stubGlobal("fetch",vi.fn().mockResolvedValue({ok:true,json:async()=>({data:[{slug:"a",title:"A",status:"PUBLISHED",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-03T00:00:00Z",updatedAt:"2026-01-04T00:00:00Z"}]})}));const xml=await (await GET()).text();expect(xml).toContain(`${new Date("2026-01-01T00:00:00Z").toUTCString()}`);expect(xml).toContain(`${new Date("2026-01-03T00:00:00Z").toUTCString()}`);});it("uses the stable fallback author for authorless posts",async()=>{vi.stubGlobal("fetch",vi.fn().mockResolvedValue({ok:true,json:async()=>({data:[{slug:"a",title:"A",status:"PUBLISHED",publishedAt:"2026-01-01T00:00:00Z",author:{firstName:"",lastName:""}}]})}));const xml=await (await GET()).text();expect(xml).toContain("تیم پژوهش و محتوای علمی کنینا");});}); diff --git a/frontend/application/app/blog/rss.xml/route.ts b/frontend/application/app/blog/rss.xml/route.ts index 6a8ae3da..dce545f1 100644 --- a/frontend/application/app/blog/rss.xml/route.ts +++ b/frontend/application/app/blog/rss.xml/route.ts @@ -1,4 +1,4 @@ -import { validContentUpdatedAt, publicationDate } from '../../../lib/blogDates'; +import { BLOG_TEAM_FALLBACK, validContentUpdatedAt, publicationDate } from '../../../lib/blogDates'; import { NextResponse } from 'next/server'; export const dynamic = 'force-dynamic'; @@ -25,7 +25,8 @@ export async function GET() { const link = `${baseUrl}/blog/${b.slug}`; const description = escapeXml(b.excerpt || b.metaDescription || ''); const pubDate = new Date(publicationDate(b)!).toUTCString(); - const author = escapeXml(b.author ? `${b.author.firstName || ''} ${b.author.lastName || ''}`.trim() : 'کنینا فارما'); + const personName = b.author ? `${b.author.firstName || ''} ${b.author.lastName || ''}`.trim() : ''; + const author = escapeXml(personName || BLOG_TEAM_FALLBACK); const category = escapeXml(b.category?.name || 'دانشنامه سلامت حیوانات'); return ` diff --git a/frontend/application/lib/blogDates.test.ts b/frontend/application/lib/blogDates.test.ts new file mode 100644 index 00000000..d1e10914 --- /dev/null +++ b/frontend/application/lib/blogDates.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; +import { persianDate } from "./blogDates"; + +describe("persianDate", () => { + it("uses the Persian calendar and Asia/Tehran at a UTC near-midnight boundary", () => { + const value = "2026-03-20T21:00:00.000Z"; + const expected = new Intl.DateTimeFormat("fa-IR-u-ca-persian", { + year: "numeric", month: "numeric", day: "numeric", timeZone: "Asia/Tehran", + }).format(new Date(value)); + expect(persianDate(value)).toBe(expected); + }); +}); diff --git a/frontend/application/lib/blogDates.ts b/frontend/application/lib/blogDates.ts index 9c6718d6..0fd5be5f 100644 --- a/frontend/application/lib/blogDates.ts +++ b/frontend/application/lib/blogDates.ts @@ -2,4 +2,4 @@ export const BLOG_TEAM_FALLBACK = "تیم پژوهش و محتوای علمی ک export function publicationDate(blog:any): string | undefined { return blog?.publishedAt || blog?.createdAt; } function persianDay(value:string): string { return new Intl.DateTimeFormat("fa-IR-u-ca-persian-nu-latn",{year:"numeric",month:"2-digit",day:"2-digit",timeZone:"Asia/Tehran"}).format(new Date(value)); } export function validContentUpdatedAt(blog:any): string | undefined { const published=publicationDate(blog), updated=blog?.contentUpdatedAt; if(!published||!updated) return undefined; const p=new Date(published),u=new Date(updated); return Number.isFinite(p.getTime())&&Number.isFinite(u.getTime())&&u>p&&persianDay(updated)!==persianDay(published)?updated:undefined; } -export function persianDate(value?:string): string { return value ? new Date(value).toLocaleDateString("fa-IR") : ""; } +export function persianDate(value?:string): string { return value ? new Intl.DateTimeFormat("fa-IR-u-ca-persian", { year: "numeric", month: "numeric", day: "numeric", timeZone: "Asia/Tehran" }).format(new Date(value)) : ""; }