fix(blog): harden freshness and authorship
This commit is contained in:
1 parent
51ca8c7e34
commit
0b4d9a8463
11 files changed
+157
-26
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<string, unknown>)[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<string, unknown>).contentUpdatedAt = now;
|
||||
} else if (contentUpdatedAt !== undefined) {
|
||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
||||
} else {
|
||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
||||
}
|
||||
(updatePayload as Record<string, unknown>).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;
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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: '<p>x</p>', 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',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(`<pubDate>${new Date("2026-01-01T00:00:00Z").toUTCString()}</pubDate>`);expect(xml).toContain(`<lastBuildDate>${new Date("2026-01-03T00:00:00Z").toUTCString()}</lastBuildDate>`);});});
|
||||
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(`<pubDate>${new Date("2026-01-01T00:00:00Z").toUTCString()}</pubDate>`);expect(xml).toContain(`<lastBuildDate>${new Date("2026-01-03T00:00:00Z").toUTCString()}</lastBuildDate>`);});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("<author>تیم پژوهش و محتوای علمی کنینا</author>");});});
|
||||
@@ -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 `
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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)) : ""; }
|
||||
Reference in new issue
Block a user