wip(publisher): preserve narrow CI candidate and failing race regression

This commit is contained in:
devops committed 2026-11-12 11:25:12 +00:00
1 parent a9280459da
commit 4ff2fab0ba
8 files changed
+4099

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
name: Production publisher helper only
on:
push:
branches:
- ops/prod-publisher-helper-20261112
jobs:
publisher-helper:
runs-on: canina
steps:
- name: Exact reviewed one-file helper release
env:
GITHUB_ACTIONS: 'true'
GITHUB_REF: ${{ github.ref }}
RELEASE_SHA: ${{ github.sha }}
PUBLISHER_HELPER_APPROVED_SHA: ${{ secrets.PUBLISHER_HELPER_APPROVED_SHA }}
run: |
set -eu
[ "$GITHUB_REF" = refs/heads/ops/prod-publisher-helper-20261112 ]
case "$RELEASE_SHA" in *[!0-9a-f]*|'') exit 2 ;; esac
[ "${#RELEASE_SHA}" -eq 40 ]
[ "$RELEASE_SHA" = "$PUBLISHER_HELPER_APPROVED_SHA" ]
export http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY=
mkdir -p publisher-src
wget --no-proxy -qO source.tar.gz "https://git.parsaaghayi.ir/parsa/canina/archive/${RELEASE_SHA}.tar.gz"
tar -xzf source.tar.gz --strip-components=1 -C publisher-src
cd publisher-src
export CANINA_EDITORIAL_TEST_SOURCE="$PWD/scripts/publishers/e4c9b52eb040/fixtures"
python3 -m unittest discover -s scripts/publishers/e4c9b52eb040 -p 'test*.py' -v
python3 scripts/publishers/e4c9b52eb040/release_helper.py --sha "$RELEASE_SHA" --approval f5dfb28159010ae043009296006e91bafadd0f62b72681d22063b43d01e81880
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,182 @@
import {
Controller,
Get,
Post,
Put,
Patch,
Delete,
Body,
Param,
Query,
UseGuards,
Request,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { BlogsService } from "./blogs.service";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from "@nestjs/swagger";
import { PaginationDto } from "../common/dto/pagination.dto";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
@ApiTags("Admin - مدیریت مقالات (بلاگ)")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles("Admin", "SUPER_ADMIN")
@Controller("admin/blogs")
export class BlogsController {
constructor(private readonly blogsService: BlogsService) {}
@Get()
@ApiOperation({ summary: "لیست مقالات" })
@ApiQuery({ name: "page", required: false })
@ApiQuery({ name: "limit", required: false })
@ApiQuery({ name: "search", required: false })
@ApiQuery({ name: "status", required: false })
@ApiQuery({ name: "categoryId", required: false })
async getBlogs(
@Query()
query: PaginationDto & {
status?: string;
categoryId?: string;
tagId?: string;
},
) {
return this.blogsService.getBlogs(query);
}
@Get("authors")
@ApiOperation({ summary: "لیست کاربران برای انتخاب به عنوان نویسنده" })
async getAuthors() {
const data = await this.blogsService.getAuthors();
return { success: true, data };
}
@Get("categories")
@ApiOperation({ summary: "لیست دسته‌بندی‌های وبلاگ" })
async getBlogCategories() {
const data = await this.blogsService.getBlogCategories();
return { success: true, data };
}
@Post("categories")
@ApiOperation({ summary: "ایجاد دسته‌بندی جدید برای وبلاگ" })
async createBlogCategory(@Body() body: Prisma.BlogCategoryCreateInput) {
const data = await this.blogsService.createBlogCategory(body);
return { success: true, data };
}
@Put("categories/:id")
@ApiOperation({ summary: "ویرایش دسته‌بندی وبلاگ" })
async updateBlogCategory(
@Param("id") id: string,
@Body() body: Prisma.BlogCategoryUpdateInput,
) {
const data = await this.blogsService.updateBlogCategory(id, body);
return { success: true, data };
}
@Delete("categories/:id")
@ApiOperation({ summary: "حذف دسته‌بندی وبلاگ" })
async deleteBlogCategory(@Param("id") id: string) {
await this.blogsService.deleteBlogCategory(id);
return { success: true };
}
@Get("tags")
@ApiOperation({ summary: "لیست تگ‌های وبلاگ" })
async getBlogTags() {
const data = await this.blogsService.getBlogTags();
return { success: true, data };
}
@Post("tags")
@ApiOperation({ summary: "ایجاد تگ جدید برای وبلاگ" })
async createBlogTag(@Body() body: { name: string; slug?: string }) {
const data = await this.blogsService.createBlogTag(body);
return { success: true, data };
}
@Delete("tags/:id")
@ApiOperation({ summary: "حذف تگ وبلاگ" })
async deleteBlogTag(@Param("id") id: string) {
await this.blogsService.deleteBlogTag(id);
return { success: true };
}
@Get(":id")
@ApiOperation({ summary: "دریافت مشخصات یک مقاله" })
async getBlogById(@Param("id") id: string) {
const data = await this.blogsService.getBlogById(id);
return { success: true, data };
}
@Post()
@ApiOperation({ summary: "ایجاد مقاله جدید" })
async createBlog(
@Body() body: any,
@Request() req: { user: { id: string } },
) {
const data = await this.blogsService.createBlog(body, req.user.id);
return { success: true, data };
}
@Put(":id")
@ApiOperation({ summary: "ویرایش مقاله" })
async updateBlog(@Param("id") id: string, @Body() body: any) {
const data = await this.blogsService.updateBlog(id, body);
return { success: true, data };
}
@Delete(":id")
@ApiOperation({ summary: "حذف مقاله" })
async deleteBlog(@Param("id") id: string) {
await this.blogsService.deleteBlog(id);
return { success: true };
}
// Blog Comments endpoints
@Get("comments")
@ApiOperation({ summary: "لیست نظرات مقالات" })
@ApiQuery({
name: "status",
required: false,
description: "PENDING | APPROVED | REJECTED",
})
@ApiQuery({ name: "blogId", required: false })
@ApiQuery({ name: "page", required: false })
@ApiQuery({ name: "limit", required: false })
async getComments(
@Query()
query: {
page?: number;
limit?: number;
status?: string;
blogId?: string;
},
) {
return this.blogsService.getComments(query);
}
@Patch("comments/:id/status")
@ApiOperation({ summary: "تغییر وضعیت نظر (تأیید/رد)" })
async updateCommentStatus(
@Param("id") id: string,
@Body() body: { status: "APPROVED" | "REJECTED" },
) {
return this.blogsService.updateCommentStatus(id, body.status);
}
@Delete("comments/:id")
@ApiOperation({ summary: "حذف نظر" })
async deleteComment(@Param("id") id: string) {
await this.blogsService.deleteComment(id);
return { success: true };
}
}
@@ -0,0 +1,677 @@
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
OnModuleInit,
OnModuleDestroy,
Logger,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaService } from "../prisma/prisma.service";
import { PaginationDto } from "../common/dto/pagination.dto";
import { RevalidationService } from "../common/revalidation/revalidation.service";
@Injectable()
export class BlogsService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(BlogsService.name);
private schedulerTimer: NodeJS.Timeout | null = null;
constructor(
private prisma: PrismaService,
private revalidationService: RevalidationService,
) {}
async onModuleInit() {
await this.seedDefaultCategories();
// Start background scheduled publishing worker (every 60 seconds)
this.schedulerTimer = setInterval(() => {
this.publishDueScheduledBlogs().catch((err) => {
this.logger.error("Error in publishDueScheduledBlogs worker:", err);
});
}, 60000);
// Run an initial check on startup
this.publishDueScheduledBlogs().catch(() => {});
}
onModuleDestroy() {
if (this.schedulerTimer) {
clearInterval(this.schedulerTimer);
this.schedulerTimer = null;
}
}
private async seedDefaultCategories() {
try {
const defaultCategories = [
{ name: "تغذیه و رژیم غذایی", slug: "nutrition", order: 1 },
{ name: "سلامت گوارش و متابولیسم", slug: "digestion", order: 2 },
{ name: "مفاصل، استخوان و اسکلت", slug: "joints-bones", order: 3 },
{ name: "پوست، مو و آلرژی", slug: "skin-coat", order: 4 },
{
name: "ایمنی، پیشگیری و مراقبت بالینی",
slug: "health-prevention",
order: 5,
},
];
for (const cat of defaultCategories) {
await this.prisma.blogCategory.upsert({
where: { slug: cat.slug },
update: { name: cat.name, order: cat.order },
create: { name: cat.name, slug: cat.slug, order: cat.order },
});
}
} catch (err) {
console.warn(
"[BlogsService] Failed to seed default blog categories:",
err,
);
}
}
async getBlogs(
query: PaginationDto & {
status?: string;
categoryId?: string;
tagId?: string;
},
) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: Prisma.BlogWhereInput = {};
if (query.search) {
where.OR = [
{ title: { contains: query.search, mode: "insensitive" } },
{ excerpt: { contains: query.search, mode: "insensitive" } },
{ slug: { contains: query.search, mode: "insensitive" } },
];
}
if (query.status) {
where.status = query.status;
}
if (query.categoryId) {
where.categoryId = query.categoryId;
}
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
include: {
author: {
select: { id: true, firstName: true, lastName: true, email: true },
},
category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: true } },
},
}),
this.prisma.blog.count({ where }),
]);
return {
data,
meta: {
total,
page,
limit,
lastPage: Math.ceil(total / limit) || 1,
},
};
}
async getBlogById(id: string) {
const blog = await this.prisma.blog.findUnique({
where: { id },
include: {
author: { select: { id: true, firstName: true, lastName: true } },
category: true,
tags: true,
},
});
if (!blog) throw new NotFoundException("Blog not found");
return blog;
}
async createBlog(data: any, currentUserId: string) {
const {
tagNames,
categoryId,
authorId,
publishedAt,
scheduledAt,
readingTime,
markContentUpdated,
contentUpdatedAt,
} = data;
const parseOptionalDate = (value: unknown, field: string): Date | null => {
if (value === undefined || value === null || value === "") return null;
const parsed = new Date(value as string | number | Date);
if (!Number.isFinite(parsed.getTime())) {
throw new BadRequestException(`Invalid ${field}`);
}
return parsed;
};
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
const parsedContentUpdatedAt = markContentUpdated
? new Date()
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
// Connect or create tags
const tagConnectOrCreate = [];
if (Array.isArray(tagNames) && tagNames.length > 0) {
for (const tName of tagNames) {
const trimmed = String(tName).trim();
if (trimmed) {
const slug = trimmed
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\u0600-\u06FF-]+/g, "");
tagConnectOrCreate.push({
where: { name: trimmed },
create: { name: trimmed, slug: slug || `tag-${Date.now()}` },
});
}
}
}
const targetAuthorId = authorId || currentUserId;
const now = new Date();
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
let finalStatus = data.status || "PUBLISHED";
let finalIsPublished =
data.isPublished !== undefined ? data.isPublished : true;
let finalPublishedAt = parsedPublishedAt;
if (isFutureSchedule) {
finalStatus = "SCHEDULED";
finalIsPublished = false;
finalPublishedAt = null;
} else if (parsedScheduledAt && parsedScheduledAt <= now) {
finalStatus = "PUBLISHED";
finalIsPublished = true;
finalPublishedAt = parsedScheduledAt;
} else if (!finalPublishedAt && finalStatus === "PUBLISHED") {
finalPublishedAt = now;
}
const createPayload = {
title: data.title,
slug: data.slug,
content: data.content,
excerpt: data.excerpt,
authorTeam: data.authorTeam,
authorRole: data.authorRole,
imageUrl: data.imageUrl,
imageAlt: data.imageAlt,
imageCaption: data.imageCaption,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
keywords: data.keywords,
focusKeywords: data.focusKeywords,
canonicalUrl: data.canonicalUrl,
noIndex: data.noIndex,
noFollow: data.noFollow,
schemaType: data.schemaType,
ogTitle: data.ogTitle,
ogDescription: data.ogDescription,
ogImage: data.ogImage,
status: finalStatus,
isPublished: finalIsPublished,
featured: data.featured,
allowComments: data.allowComments,
showOnHome: data.showOnHome,
homeDisplayMode: data.homeDisplayMode,
relatedProductIds: data.relatedProductIds,
relatedBlogIds: data.relatedBlogIds,
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
publishedAt: finalPublishedAt,
scheduledAt: parsedScheduledAt,
contentUpdatedAt: parsedContentUpdatedAt,
author: { connect: { id: targetAuthorId } },
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
...(tagConnectOrCreate.length > 0
? { tags: { connectOrCreate: tagConnectOrCreate } }
: {}),
} satisfies Prisma.BlogCreateInput;
const created = await this.prisma.blog.create({
data: createPayload,
include: {
author: { select: { firstName: true, lastName: true } },
category: true,
tags: true,
},
});
let cacheRevalidation: "success" | "failed" = "failed";
try {
const revalidated = await this.revalidationService.revalidateBlog(created.slug);
cacheRevalidation = revalidated ? "success" : "failed";
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for created blog [${created.slug}]: ${err?.message}`,
);
cacheRevalidation = "failed";
}
return {
...created,
cacheRevalidation,
};
}
async updateBlog(id: string, data: any) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException("Blog not found");
const {
tagNames,
categoryId,
authorId,
publishedAt,
scheduledAt,
readingTime,
markContentUpdated,
contentUpdatedAt,
expectedUpdatedAt,
} = data;
const conflict = () => new ConflictException(
"CONCURRENT_MODIFICATION: Blog has been modified by another process",
);
let expectedTime: number | undefined;
if (expectedUpdatedAt !== undefined) {
// Only accept the millisecond, timezone-qualified ISO token returned by GET
// (or an equivalent offset). Avoid Date's coercion of null, numbers, arrays,
// and its normalization of impossible calendar dates.
const match = typeof expectedUpdatedAt === "string" && expectedUpdatedAt.match(
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/,
);
if (!match) throw conflict();
expectedTime = Date.parse(expectedUpdatedAt);
const calendar = new Date(`${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`);
if (!Number.isFinite(expectedTime) ||
calendar.toISOString().slice(0, 10) !== `${match[1]}-${match[2]}-${match[3]}` ||
Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
throw conflict();
}
}
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 materialContentFields = [
"title",
"content",
"excerpt",
"imageUrl",
"imageAlt",
"imageCaption",
] as const;
const hasMaterialContentChange = materialContentFields.some(
(field) => data[field] !== undefined && data[field] !== blog[field],
);
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
(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) }
: {}),
...(authorId ? { author: { connect: { id: authorId } } } : {}),
...(categoryId !== undefined
? categoryId
? { category: { connect: { id: categoryId } } }
: { category: { disconnect: true } }
: {}),
});
if (scheduledAt !== undefined) {
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
updatePayload.scheduledAt = parsedScheduledAt;
if (parsedScheduledAt && parsedScheduledAt > now) {
updatePayload.status = "SCHEDULED";
updatePayload.isPublished = false;
updatePayload.publishedAt = null;
} else if (parsedScheduledAt && parsedScheduledAt <= now) {
updatePayload.status = "PUBLISHED";
updatePayload.isPublished = true;
updatePayload.publishedAt = parsedScheduledAt;
}
} else if (publishedAt !== undefined) {
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
}
if (Array.isArray(tagNames)) {
const tagConnectOrCreate = [];
for (const tName of tagNames) {
const trimmed = String(tName).trim();
if (trimmed) {
const slug = trimmed
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\u0600-\u06FF-]+/g, "");
tagConnectOrCreate.push({
where: { name: trimmed },
create: { name: trimmed, slug: slug || `tag-${Date.now()}` },
});
}
}
updatePayload.tags = {
set: [], // clear previous relations
connectOrCreate: tagConnectOrCreate,
};
}
const include = {
author: { select: { firstName: true, lastName: true } },
category: true,
tags: true,
};
// Legacy UI requests without a token intentionally retain last-write-wins.
// Guarded requests claim the row using a DB predicate, not the earlier read.
const updated = expectedTime === undefined
? await this.prisma.blog.update({ where: { id }, data: updatePayload, include })
: await this.prisma.$transaction(async (tx) => {
// PostgreSQL timestamptz defaults to microseconds; JSON/JS Dates expose
// milliseconds. Match the entire represented millisecond, then move
// strictly beyond it (including same-ms writes and clock rollback).
const claimedAt = new Date(Math.max(Date.now(), expectedTime + 1));
const claim = await tx.blog.updateMany({
where: {
id,
updatedAt: {
gte: new Date(expectedTime),
lt: new Date(expectedTime + 1),
},
},
data: { updatedAt: claimedAt },
});
if (claim.count !== 1) throw conflict();
// The claim holds the row lock until this nested mutation commits.
// Any relation failure rolls back both the claim and all data writes.
return tx.blog.update({
where: { id },
data: { ...updatePayload, updatedAt: claimedAt },
include,
});
});
let cacheRevalidation: "success" | "failed" = "failed";
try {
const revalidated = await this.revalidationService.revalidateBlog(updated.slug);
cacheRevalidation = revalidated ? "success" : "failed";
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for updated blog [${updated.slug}]: ${err?.message}`,
);
cacheRevalidation = "failed";
}
return {
...updated,
cacheRevalidation,
};
}
async deleteBlog(id: string) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException("Blog not found");
const res = await this.prisma.blog.delete({ where: { id } });
try {
await this.revalidationService.revalidateBlog(blog.slug);
} catch (err: any) {
this.logger.warn(
`Cache revalidation failed for deleted blog [${blog.slug}]: ${err?.message}`,
);
}
return res;
}
// Authors (Users who can write)
async getAuthors() {
return this.prisma.user.findMany({
select: {
id: true,
firstName: true,
lastName: true,
email: true,
role: true,
},
orderBy: { firstName: "asc" },
});
}
// Blog Categories Management
async getBlogCategories() {
return this.prisma.blogCategory.findMany({
orderBy: { order: "asc" },
include: {
parent: true,
children: true,
_count: { select: { blogs: true } },
},
});
}
async createBlogCategory(data: Prisma.BlogCategoryCreateInput) {
return this.prisma.blogCategory.create({ data });
}
async updateBlogCategory(id: string, data: Prisma.BlogCategoryUpdateInput) {
return this.prisma.blogCategory.update({ where: { id }, data });
}
async deleteBlogCategory(id: string) {
return this.prisma.blogCategory.delete({ where: { id } });
}
// Blog Tags Management
async getBlogTags() {
return this.prisma.blogTag.findMany({
orderBy: { createdAt: "desc" },
include: {
_count: { select: { blogs: true } },
},
});
}
async createBlogTag(data: { name: string; slug?: string }) {
const slug =
data.slug ||
data.name
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\u0600-\u06FF-]+/g, "");
return this.prisma.blogTag.create({
data: { name: data.name, slug: slug || `tag-${Date.now()}` },
});
}
async deleteBlogTag(id: string) {
return this.prisma.blogTag.delete({ where: { id } });
}
// Blog Comments Management
async getComments(query: {
page?: number;
limit?: number;
status?: string;
blogId?: string;
}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 20;
const skip = (page - 1) * limit;
const where: Prisma.BlogCommentWhereInput = {};
if (query.status) where.status = query.status;
if (query.blogId) where.blogId = query.blogId;
const [data, total] = await Promise.all([
this.prisma.blogComment.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: "desc" },
include: {
blog: { select: { title: true, slug: true } },
user: { select: { firstName: true, lastName: true, mobile: true } },
},
}),
this.prisma.blogComment.count({ where }),
]);
return {
data,
meta: { total, page, limit, lastPage: Math.ceil(total / limit) || 1 },
};
}
async updateCommentStatus(id: string, status: "APPROVED" | "REJECTED") {
const comment = await this.prisma.blogComment.findUnique({
where: { id },
include: { blog: { select: { slug: true } } },
});
if (!comment) throw new NotFoundException("Comment not found");
const updated = await this.prisma.blogComment.update({
where: { id },
data: { status },
});
if (comment.blog?.slug) {
await this.revalidationService.revalidateBlog(comment.blog.slug);
}
return updated;
}
async deleteComment(id: string) {
const comment = await this.prisma.blogComment.findUnique({
where: { id },
include: { blog: { select: { slug: true } } },
});
if (!comment) throw new NotFoundException("Comment not found");
const res = await this.prisma.blogComment.delete({ where: { id } });
if (comment.blog?.slug) {
await this.revalidationService.revalidateBlog(comment.blog.slug);
}
return res;
}
/**
* Publishes blogs that have reached their scheduled publication date
*/
async publishDueScheduledBlogs(): Promise<number> {
const now = new Date();
const dueBlogs = await this.prisma.blog.findMany({
where: {
status: "SCHEDULED",
scheduledAt: { lte: now },
},
select: {
id: true,
slug: true,
title: true,
scheduledAt: true,
},
});
if (!dueBlogs || dueBlogs.length === 0) {
return 0;
}
this.logger.log(
`Found ${dueBlogs.length} due scheduled blog(s) to publish automatically.`,
);
let publishedCount = 0;
for (const blog of dueBlogs) {
try {
const publishDate = blog.scheduledAt || now;
await this.prisma.blog.update({
where: { id: blog.id },
data: {
status: "PUBLISHED",
isPublished: true,
publishedAt: publishDate,
},
});
publishedCount++;
this.logger.log(
`Successfully published scheduled blog [${blog.title}] (${blog.slug})`,
);
// Immediate cache & sitemap revalidation
await this.revalidationService.revalidateBlog(blog.slug);
} catch (err: any) {
this.logger.error(
`Failed to publish scheduled blog [${blog.id}] (${blog.slug}): ${err?.message}`,
);
}
}
return publishedCount;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,157 @@
import type { AxiosError,InternalAxiosRequestConfig } from 'axios';
import axios from 'axios';
import toast from 'react-hot-toast';
import { useAdminAuthStore } from '../store/adminAuthStore';
import type { ApiResponse,AuthResponseData } from '../types/admin';
export const BASE_DOMAIN = import.meta.env.VITE_API_URL
? import.meta.env.VITE_API_URL.replace(/\/api$/, '')
: (import.meta.env.DEV ? 'http://127.0.0.1:4400' : '');
const baseURL = `${BASE_DOMAIN}/api`;
export interface ApiErrorPayload {
success: boolean;
statusCode: number;
message: string;
code: string;
details?: Array<{ field: string; message: string }> | Record<string, unknown>;
timestamp?: string;
path?: string;
}
const api = axios.create({
baseURL,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
let isRefreshing = false;
let failedQueue: Array<{
resolve: (token: string) => void;
reject: (reason?: unknown) => void;
}> = [];
const processQueue = (error: unknown, token: string | null = null) => {
failedQueue.forEach((prom) => {
if (error) {
prom.reject(error);
} else if (token) {
prom.resolve(token);
}
});
failedQueue = [];
};
api.interceptors.request.use((config: InternalAxiosRequestConfig) => {
const token = useAdminAuthStore.getState().accessToken;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(response) => response,
async (error: AxiosError<ApiErrorPayload>) => {
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
const responseData = error.response?.data;
const status = error.response?.status;
const farsiMessage = responseData?.message || 'خطایی در ارتباط با سرور رخ داده است.';
if (status === 401 && originalRequest && !originalRequest._retry) {
const currentToken = useAdminAuthStore.getState().accessToken;
if (!currentToken || originalRequest.url?.includes('/auth/refresh') || originalRequest.url?.includes('/auth/admin-login') || originalRequest.url?.includes('/auth/verify-otp')) {
useAdminAuthStore.getState().clearAuth();
if (window.location.pathname !== '/login') {
toast.error('نشست کاری شما منقضی شده است. لطفاً مجدداً وارد شوید.');
window.location.href = '/login';
}
return Promise.reject(error);
}
if (isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject });
})
.then((token) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
return api(originalRequest);
})
.catch((err) => Promise.reject(err));
}
originalRequest._retry = true;
isRefreshing = true;
try {
let refreshResponse;
try {
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh`,
{},
{
withCredentials: true,
headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {}
}
);
} catch {
// If bearer-based refresh fails (e.g. access token fully expired), try cookie-based /auth/refresh-token
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh-token`,
{},
{ withCredentials: true }
);
}
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
const newToken = refreshResponse.data.data.accessToken;
const user = refreshResponse.data.data.user;
useAdminAuthStore.getState().setAuth(newToken, user);
processQueue(null, newToken);
originalRequest.headers.Authorization = `Bearer ${newToken}`;
return api(originalRequest);
} else {
throw new Error('Refresh failed');
}
} catch (refreshErr) {
processQueue(refreshErr, null);
useAdminAuthStore.getState().clearAuth();
if (window.location.pathname !== '/login') {
toast.error('نشست کاری شما منقضی شده است. لطفاً مجدداً وارد شوید.');
window.location.href = '/login';
}
return Promise.reject(refreshErr);
} finally {
isRefreshing = false;
}
}
if (status === 403) {
toast.error('دسترسی شما به این بخش از پنل ادمین مجاز نمی‌باشد.', { id: 'admin-403' });
(error as unknown as Record<string, boolean>)._toastShown = true;
} else if (status !== 401 && !(originalRequest as unknown as Record<string, boolean>)?.hideErrorToast) {
let fullMessage = farsiMessage;
if (responseData?.details && Array.isArray(responseData.details) && responseData.details.length > 0) {
const detailStrings = responseData.details
.map((d: unknown) => typeof d === 'string' ? d : ((d as Record<string, string>)?.message || (d as Record<string, string>)?.field))
.filter(Boolean);
if (detailStrings.length > 0) {
const joinedDetails = detailStrings.join('، ');
if (!farsiMessage.includes(joinedDetails)) {
fullMessage = `${farsiMessage} (${joinedDetails})`;
}
}
}
toast.error(fullMessage, { id: fullMessage });
(error as unknown as Record<string, boolean>)._toastShown = true;
}
return Promise.reject(error);
}
);
export default api;
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Exact one-file publisher release; called only by narrow CI, no site deployment."""
import argparse
import hashlib
import fcntl
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
TARGET = Path('/opt/data/publishers/e4c9b52eb040/editorial_evidence.py')
OLD = '99539a31b498d2fc922650a9971802e2caa077b6eb165f864f50e2c6c9073792'
def install(source, commit, approval, target=TARGET):
lock = target.parent / '.helper-release.lock'
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return _install(source, commit, approval, target)
finally:
os.close(fd)
def _install(source, commit, approval, target):
digest = hashlib.sha256(source).hexdigest()
if not re.fullmatch('[0-9a-f]{40}', commit) or approval != digest:
raise ValueError('Reviewed content digest required')
for p in (target, *target.parents):
if p.is_symlink():
raise ValueError('Symlink refused')
st = target.stat()
if st.st_uid != os.getuid() or st.st_nlink != 1:
raise ValueError('Runtime identity or hardlink mismatch')
current = hashlib.sha256(target.read_bytes()).hexdigest()
if current not in (OLD, digest):
raise ValueError('Unreviewed before-image')
compile(source, str(target), 'exec')
fd, name = tempfile.mkstemp(prefix='.editorial-release-', dir=target.parent)
try:
with os.fdopen(fd, 'wb') as f:
f.write(source)
f.flush()
os.fsync(f.fileno())
os.fchmod(f.fileno(), st.st_mode & 0o777)
if target.stat().st_ino != st.st_ino or hashlib.sha256(target.read_bytes()).hexdigest() != current:
raise ValueError('Concurrent before-image change')
os.replace(name, target)
finally:
if os.path.exists(name):
os.unlink(name)
actual = hashlib.sha256(target.read_bytes()).hexdigest()
if actual != digest:
raise ValueError('Readback mismatch')
return {'commit': commit, 'sha256': actual, 'target': str(target), 'site_deploy': False, 'gateway_restart': False}
def main():
p = argparse.ArgumentParser()
p.add_argument('--sha', required=True)
p.add_argument('--approval', required=True)
args = p.parse_args()
if os.environ.get('GITHUB_ACTIONS') != 'true' or os.environ.get('GITHUB_REF') != 'refs/heads/ops/prod-publisher-helper-20261112':
raise ValueError('Exact CI push route required')
root = Path(__file__).parent
source = (root/'editorial_evidence.py').read_bytes()
package = {'code': Path(__file__).read_text(), 'source': source.decode(), 'commit': args.sha, 'approval': args.approval}
code = "import json,sys; p=json.load(sys.stdin); ns={'__name__':'ci_release'}; exec(compile(p['code'],'<reviewed-ci-release>','exec'),ns); print(json.dumps(ns['install'](p['source'].encode(),p['commit'],p['approval'])))"
result = subprocess.check_output(['docker','exec','--user','10000:10000','-i','canina-hermes','/opt/hermes/.venv/bin/python','-B','-c',code], input=json.dumps(package), text=True, timeout=60)
print(result.strip())
if __name__ == '__main__':
main()
@@ -0,0 +1,136 @@
"""Offline release security regressions; all writes stay in temporary fixtures.
Acceptance: reviewed old/idempotent bytes install; unknown bytes, wrong digest,
lock contention and changes at either side of the final check fail closed.
These are post-implementation independent tests, not a TDD claim.
"""
import fcntl
import hashlib
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
import release_helper as helper
class ReleaseHelperTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix='helper-review-')
self.addCleanup(self.tmp.cleanup)
self.target = Path(self.tmp.name) / 'editorial_evidence.py'
self.old = b'# isolated reviewed beforeimage\n'
self.source = b'# isolated reviewed replacement\nvalue = 1\n'
self.target.write_bytes(self.old)
self.target.chmod(0o640)
self.approval = hashlib.sha256(self.source).hexdigest()
self.sha = 'a' * 40
patcher = mock.patch.object(helper, 'OLD', hashlib.sha256(self.old).hexdigest())
patcher.start()
self.addCleanup(patcher.stop)
def install(self, **kw):
return helper.install(self.source, kw.get('sha', self.sha),
kw.get('approval', self.approval), self.target)
def assert_no_temporary_release(self):
self.assertEqual(list(self.target.parent.glob('.editorial-release-*')), [])
def test_reviewed_install_and_idempotency_preserve_mode(self):
for _ in range(2):
result = self.install()
self.assertEqual(result['sha256'], self.approval)
self.assertFalse(result['site_deploy'])
self.assertFalse(result['gateway_restart'])
self.assertEqual(self.target.read_bytes(), self.source)
self.assertEqual(self.target.stat().st_mode & 0o777, 0o640)
self.assert_no_temporary_release()
def test_unknown_beforeimage_rejected(self):
self.target.write_bytes(b'unreviewed')
with self.assertRaisesRegex(ValueError, 'Unreviewed before-image'):
self.install()
self.assertEqual(self.target.read_bytes(), b'unreviewed')
self.assert_no_temporary_release()
def test_approval_mismatch_rejected(self):
with self.assertRaisesRegex(ValueError, 'Reviewed content digest required'):
self.install(approval='0' * 64)
self.assertEqual(self.target.read_bytes(), self.old)
def test_malformed_commit_rejected(self):
with self.assertRaises(ValueError):
self.install(sha='not-a-sha')
self.assertEqual(self.target.read_bytes(), self.old)
def test_contention_from_separate_process_rejected(self):
lock = self.target.parent / '.helper-release.lock'
code = ('import fcntl,sys; f=open(sys.argv[1],"a"); '
'fcntl.flock(f,fcntl.LOCK_EX); print("locked",flush=True); sys.stdin.read()')
process = subprocess.Popen([sys.executable, '-c', code, str(lock)],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
try:
assert process.stdout is not None
self.assertEqual(process.stdout.readline().strip(), 'locked')
with self.assertRaises(BlockingIOError):
self.install()
self.assertEqual(self.target.read_bytes(), self.old)
finally:
process.communicate(input='', timeout=5)
self.assertEqual(process.returncode, 0)
def test_change_during_staging_rejected_before_replace(self):
real_fsync = os.fsync
def mutate(fd):
real_fsync(fd)
self.target.write_bytes(b'concurrent edit')
with mock.patch.object(helper.os, 'fsync', side_effect=mutate):
with self.assertRaisesRegex(ValueError, 'Concurrent before-image change'):
self.install()
self.assertEqual(self.target.read_bytes(), b'concurrent edit')
self.assert_no_temporary_release()
def test_inode_swap_during_staging_rejected(self):
real_fsync = os.fsync
def mutate(fd):
real_fsync(fd)
alternate = self.target.parent / 'alternate'
alternate.write_bytes(self.old)
os.replace(alternate, self.target)
with mock.patch.object(helper.os, 'fsync', side_effect=mutate):
with self.assertRaisesRegex(ValueError, 'Concurrent before-image change'):
self.install()
self.assertEqual(self.target.read_bytes(), self.old)
self.assert_no_temporary_release()
def test_change_after_final_check_before_replace_must_not_be_erased(self):
real_replace = os.replace
def mutate_then_replace(src, dst):
self.target.write_bytes(b'late concurrent edit')
return real_replace(src, dst)
with mock.patch.object(helper.os, 'replace', side_effect=mutate_then_replace):
with self.assertRaisesRegex(ValueError, 'Concurrent before-image change'):
self.install()
self.assertEqual(self.target.read_bytes(), b'late concurrent edit')
self.assert_no_temporary_release()
def test_symlink_rejected(self):
actual = self.target.parent / 'actual'
self.target.rename(actual)
self.target.symlink_to(actual)
with self.assertRaisesRegex(ValueError, 'Symlink refused'):
self.install()
self.assertEqual(actual.read_bytes(), self.old)
def test_hardlink_rejected(self):
os.link(self.target, self.target.parent / 'hardlink')
with self.assertRaisesRegex(ValueError, 'hardlink mismatch'):
self.install()
self.assertEqual(self.target.read_bytes(), self.old)
if __name__ == '__main__':
unittest.main()