Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ff2fab0ba | ||
|
|
a9280459da |
No files matched your search
@@ -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
|
||||
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline completeness gate, NOT medical/SEO approval or live verification.
|
||||
No network, credentials, publisher-state operations or article mutations.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from html.parser import HTMLParser
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
SOURCES = {
|
||||
'admin': 'frontend/admin-panel/src/pages/Blogs.tsx',
|
||||
'client': 'frontend/admin-panel/src/services/api.ts',
|
||||
'controller': 'backend/src/admin/blogs.controller.ts',
|
||||
'service': 'backend/src/admin/blogs.service.ts',
|
||||
'schema': 'backend/prisma/schema.prisma',
|
||||
}
|
||||
SYSTEM = {'id', 'viewCount', 'createdAt', 'updatedAt'}
|
||||
RELATIONS = {'author', 'category', 'tags', 'comments'}
|
||||
DISPOSITIONS = {'verified_value', 'system_derived', 'not_applicable', 'evidence_unavailable_empty'}
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def manifest(root):
|
||||
root = Path(root)
|
||||
sources = {k: {'path': v, 'sha256': sha(root / v)} for k, v in SOURCES.items()}
|
||||
schema = (root / SOURCES['schema']).read_text()
|
||||
block = re.search(r'model Blog\s*\{(.*?)\n\}', schema, re.S)
|
||||
if not block:
|
||||
raise ValueError('Blog model missing')
|
||||
fields = {}
|
||||
for line in block.group(1).splitlines():
|
||||
m = re.match(r'\s*(\w+)\s+([\w\[\]?]+)', line)
|
||||
if not m:
|
||||
continue
|
||||
name, typ = m.groups()
|
||||
fields[name] = {'type': typ, 'kind': 'system' if name in SYSTEM else 'relation' if name in RELATIONS else 'scalar'}
|
||||
# tagNames is a transport alias, not a Prisma field; do not send tags/tagIds.
|
||||
fields['tagNames'] = {'type': 'String[]', 'kind': 'transport_alias', 'readback': 'tags[].name'}
|
||||
fields['markContentUpdated'] = {'type': 'Boolean', 'kind': 'transport_control', 'readback': 'contentUpdatedAt'}
|
||||
# Optional UPDATE concurrency precondition; never a persisted Blog scalar.
|
||||
fields['expectedUpdatedAt'] = {'type': 'String', 'kind': 'transport_control', 'actions': ['UPDATE'], 'persisted': False}
|
||||
for role, needles in {
|
||||
'admin': ["api.post('/admin/blogs', payload)", 'tagNames', 'relatedBlogIds'],
|
||||
'controller': ['@Controller("admin/blogs")', '@Get("tags")', '@Post()'],
|
||||
'service': ['tagNames', 'connectOrCreate', 'relatedBlogIds', 'contentUpdatedAt'],
|
||||
'client': ['axios'],
|
||||
}.items():
|
||||
text = (root / SOURCES[role]).read_text()
|
||||
if any(n not in text for n in needles):
|
||||
raise ValueError(f'{role} contract changed: review parser and manifest manually')
|
||||
return {'scope': 'LOCAL_SOURCE_CONTRACT_NOT_DEPLOYMENT_PROOF', 'sources': sources, 'fields': fields}
|
||||
|
||||
|
||||
class Links(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.hrefs = set()
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag == 'a':
|
||||
href = dict(attrs).get('href', '')
|
||||
u = urlsplit(href)
|
||||
if (not u.netloc and href.startswith('/') and not href.startswith('//')) or u.netloc == 'canina.ir':
|
||||
self.hrefs.add(href)
|
||||
|
||||
|
||||
CITATION = re.compile(r'\[\s*([0-9۰-۹٠-٩]+(?:\s*[,،;؛–-]\s*[0-9۰-۹٠-٩]+)*)\s*\]')
|
||||
|
||||
|
||||
class CitationHTML(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.stack = []
|
||||
self.anchors = []
|
||||
self.raw = []
|
||||
self.targets = {}
|
||||
def handle_starttag(self, tag, attrs):
|
||||
attrs = dict(attrs)
|
||||
self.stack.append((tag, attrs))
|
||||
if attrs.get('id'):
|
||||
self.targets.setdefault(attrs['id'], set())
|
||||
if tag == 'a':
|
||||
self.anchors.append({'href': attrs.get('href', ''), 'text': ''})
|
||||
attrs['_anchor'] = self.anchors[-1]
|
||||
for _, parent in self.stack:
|
||||
if parent.get('id'):
|
||||
self.targets.setdefault(parent['id'], set()).add(attrs.get('href', ''))
|
||||
if tag in {'br', 'img', 'hr', 'input', 'meta', 'link'}:
|
||||
self.stack.pop()
|
||||
def handle_endtag(self, tag):
|
||||
for i in range(len(self.stack)-1, -1, -1):
|
||||
if self.stack[i][0] == tag:
|
||||
del self.stack[i:]
|
||||
break
|
||||
def handle_data(self, text):
|
||||
anchors = [attrs['_anchor'] for _, attrs in self.stack if '_anchor' in attrs]
|
||||
if anchors:
|
||||
anchors[-1]['text'] += text
|
||||
else:
|
||||
self.raw.append(text)
|
||||
|
||||
|
||||
def validate_citations(content, sources):
|
||||
"""Map numeric inline anchors to retrieved source URLs; no network claims."""
|
||||
parser = CitationHTML()
|
||||
parser.feed(content)
|
||||
errors = []
|
||||
if CITATION.search(''.join(parser.raw)):
|
||||
errors.append('citations: raw unlinked numbered bracket citation')
|
||||
for anchor in parser.anchors:
|
||||
for match in CITATION.finditer(anchor['text']):
|
||||
numbers = re.split(r'\s*[,،;؛–-]\s*', match[1])
|
||||
for number in numbers:
|
||||
key = str(int(number))
|
||||
source = sources.get(key, {})
|
||||
url = source.get('url', '')
|
||||
href = anchor['href']
|
||||
if not (urlsplit(url).scheme in {'http', 'https'} and urlsplit(url).netloc and source.get('retrieved') is True):
|
||||
errors.append('citations: missing retrieved source mapping ' + key)
|
||||
elif href != url and not (href == '#ref-' + key and url in parser.targets.get('ref-' + key, set())):
|
||||
errors.append('citations: anchor does not resolve to mapped source ' + key)
|
||||
return errors
|
||||
|
||||
|
||||
def validate(packet, root, base):
|
||||
"""Errors are cumulative. Evidence assertions still require independent review."""
|
||||
errors = []
|
||||
def require(ok, message):
|
||||
if not ok:
|
||||
errors.append(message)
|
||||
expected = manifest(root)
|
||||
require(packet.get('manifest') == expected, 'current complete source-derived manifest/hash mismatch')
|
||||
payload = packet.get('payload', {})
|
||||
errors.extend(validate_citations(payload.get('content', ''), packet.get('citation_sources', {})))
|
||||
action = packet.get('action')
|
||||
require(action in {'NEW', 'UPDATE', 'READ_ONLY_ACCEPTANCE'}, 'explicit action required')
|
||||
if action in {'UPDATE', 'READ_ONLY_ACCEPTANCE'}:
|
||||
require(bool(packet.get('record_id')), 'existing-record action requires record_id')
|
||||
fields = packet.get('field_dispositions', {})
|
||||
require(set(fields) == set(expected['fields']), 'every manifest field/control needs exactly one disposition')
|
||||
allowed = set(expected['fields']) - SYSTEM - RELATIONS
|
||||
require(not (set(payload) - allowed), 'unknown/system/readback-only payload keys: ' + ','.join(sorted(set(payload) - allowed)))
|
||||
for key, field in fields.items():
|
||||
require(field.get('disposition') in DISPOSITIONS, f'{key}: invalid disposition')
|
||||
require(bool(field.get('reason')), f'{key}: reason required')
|
||||
require(bool(field.get('evidence')), f'{key}: evidence references required')
|
||||
if field.get('disposition') == 'verified_value':
|
||||
require('value' in field, f'{key}: verified_value needs explicit value')
|
||||
if key in allowed:
|
||||
require(key in payload, f'{key}: verified writable value must be in payload; omission needs explicit disposition')
|
||||
if key in payload:
|
||||
require(field.get('value') == payload[key], f'{key}: disposition value differs from payload')
|
||||
if field.get('disposition') in {'not_applicable', 'evidence_unavailable_empty'} and key in payload:
|
||||
require(payload[key] in (None, '', []), f'{key}: deliberately empty disposition has nonempty payload')
|
||||
if expected['fields'].get(key, {}).get('kind') == 'transport_control':
|
||||
require(field.get('disposition') != 'verified_value', f'{key}: transport control is not a fetched scalar; use an explicit no-mutation/system-derived disposition')
|
||||
if key in SYSTEM:
|
||||
require(field.get('disposition') == 'system_derived', f'{key}: must be system-derived, not authored')
|
||||
evidence = packet.get('evidence', {})
|
||||
for key, entry in evidence.items():
|
||||
path = Path(base) / entry.get('path', '')
|
||||
require(path.is_file(), f'{key}: missing evidence file')
|
||||
if path.is_file():
|
||||
require(sha(path) == entry.get('sha256'), f'{key}: evidence hash mismatch')
|
||||
require(bool(entry.get('readAt')), f'{key}: evidence readAt required')
|
||||
def refs(refs, context):
|
||||
require(bool(refs) and all(ref in evidence for ref in refs), context + ': unresolved evidence references')
|
||||
for key, field in fields.items():
|
||||
refs(field.get('evidence', []), key)
|
||||
refs(packet.get('artifact_evidence', []), 'immutable artifact')
|
||||
# Acceptance must bind dispositions to actual saved authenticated JSON, not
|
||||
# a reconstructed payload that invents absent relations or transport fields.
|
||||
if action == 'READ_ONLY_ACCEPTANCE':
|
||||
binding = packet.get('acceptance_readback', {})
|
||||
ref = binding.get('evidence')
|
||||
require(ref in evidence, 'acceptance_readback: authenticated record evidence required')
|
||||
if ref in evidence:
|
||||
try:
|
||||
fetched = json.loads((Path(base) / evidence[ref]['path']).read_text())
|
||||
require(fetched.get('status') == 200, 'acceptance_readback: authenticated 200 required')
|
||||
record = fetched['body']['data']
|
||||
require(record.get('id') == packet.get('record_id'), 'acceptance_readback: record identity mismatch')
|
||||
for key, field in fields.items():
|
||||
kind = expected['fields'].get(key, {}).get('kind')
|
||||
if kind == 'transport_control':
|
||||
require(key not in record, key + ': unexpected transport readback requires contract review')
|
||||
continue
|
||||
if key == 'tagNames':
|
||||
actual = [tag['name'] for tag in record.get('tags', [])]
|
||||
require(field.get('value') == actual, key + ': readback alias differs')
|
||||
elif key not in record:
|
||||
require(field.get('disposition') in {'not_applicable', 'evidence_unavailable_empty'}, key + ': absent from fetched record; cannot claim fetched/system-derived value')
|
||||
require(field.get('value') in (None, '', []), key + ': absent fetched field must be explicitly empty')
|
||||
else:
|
||||
require(field.get('value') == record[key], key + ': disposition differs from actual authenticated record')
|
||||
except (ValueError, OSError, KeyError, TypeError):
|
||||
require(False, 'acceptance_readback: invalid authenticated record evidence')
|
||||
# Bind reviewed article to exact payload bytes, not merely a nearby draft.
|
||||
artifact = packet.get('artifact', {})
|
||||
path = Path(base) / artifact.get('path', '')
|
||||
require(path.is_file(), 'immutable payload artifact missing')
|
||||
if path.is_file():
|
||||
require(sha(path) == artifact.get('sha256'), 'immutable payload artifact hash mismatch')
|
||||
try:
|
||||
require(json.loads(path.read_text()) == payload, 'immutable artifact differs from payload')
|
||||
except (ValueError, OSError):
|
||||
require(False, 'immutable artifact is not payload JSON')
|
||||
relations = packet.get('relations', {})
|
||||
for key, value in [('authorId', payload.get('authorId')), ('categoryId', payload.get('categoryId'))]:
|
||||
item = relations.get(key, {})
|
||||
require(item.get('selected') == value, key + ': selection mismatch')
|
||||
require(bool(item.get('reason')), key + ': attribution/category rationale missing')
|
||||
refs(item.get('evidence', []), key + ' authenticated read')
|
||||
require(item.get('authenticated') is True and item.get('status') == 200, key + ': authenticated 200 read required')
|
||||
for key in ['tagNames', 'relatedBlogIds', 'relatedProductIds']:
|
||||
item = relations.get(key, {})
|
||||
selected = payload.get(key, [])
|
||||
require(item.get('selected') == selected, key + ': selection mismatch')
|
||||
require(bool(item.get('reason')), key + ': deliberate disposition required even when empty')
|
||||
refs(item.get('evidence', []), key + ' inventory/destination review')
|
||||
require(item.get('authenticated') is True and item.get('status') == 200, key + ': authenticated inventory read required')
|
||||
require(item.get('inventory_complete') is True, key + ': complete inventory required')
|
||||
require(isinstance(selected, list) and len(selected) == len(set(selected)), key + ': unique array required')
|
||||
require(set(selected or []) <= set(item.get('available', [])), key + ': selection absent from verified inventory')
|
||||
if key == 'relatedBlogIds':
|
||||
require(packet.get('record_id') not in selected, 'self related-article forbidden')
|
||||
parser = Links()
|
||||
parser.feed(payload.get('content', ''))
|
||||
links = packet.get('internal_links', {})
|
||||
candidates = links.get('reviewed_destinations', [])
|
||||
require(bool(candidates), 'contextual link destination shortlist not reviewed')
|
||||
for item in candidates:
|
||||
refs(item.get('evidence', []), 'destination ' + item.get('href', '?'))
|
||||
require(bool(item.get('reason')), 'destination suitability/medical-safety rationale required')
|
||||
require(item.get('identity_verified') is True and item.get('content_reviewed') is True, 'destination content/identity not verified (HTTP 200 insufficient)')
|
||||
selected_links = links.get('selected', [])
|
||||
require(set(selected_links) == parser.hrefs, 'contextual body links differ from reviewed selections')
|
||||
suitable = {item.get('href') for item in candidates if item.get('suitable') is True}
|
||||
require(set(selected_links) <= suitable, 'selected link has no suitable reviewed destination')
|
||||
if not selected_links:
|
||||
require(bool(links.get('zero_link_reason')) and links.get('disclose_in_report') is True, 'zero contextual links need justified exception and report disclosure')
|
||||
require(not suitable, 'zero-link exception contradicts suitable destinations')
|
||||
return errors
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=['manifest', 'validate'])
|
||||
parser.add_argument('--source-root', required=True)
|
||||
parser.add_argument('--packet')
|
||||
args = parser.parse_args()
|
||||
if args.action == 'manifest':
|
||||
print(json.dumps(manifest(args.source_root), ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
if not args.packet:
|
||||
parser.error('validate requires --packet')
|
||||
path = Path(args.packet)
|
||||
try:
|
||||
errors = validate(json.loads(path.read_text()), args.source_root, path.parent)
|
||||
except (ValueError, OSError, KeyError, TypeError, AttributeError) as exc:
|
||||
errors = ['invalid/incomplete evidence packet: ' + str(exc)]
|
||||
print(json.dumps({'result': 'EDITORIAL_EVIDENCE_FAILED' if errors else 'EDITORIAL_EVIDENCE_COMPLETE', 'errors': errors, 'not_approval': 'Independent RD/Vet, SEO/Editorial, final QA, current live identity/relations, backup and public browser verification still mandatory.'}, ensure_ascii=False, indent=2))
|
||||
return 1 if errors else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
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,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline synthetic unit fixtures only: never publication evidence."""
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from editorial_evidence import manifest, sha, validate
|
||||
|
||||
# Frozen publisher-owned contract fixture; not deployment/publication evidence.
|
||||
# Override explicitly when testing a maintained source checkout. Never depend on
|
||||
# a deleted scratch worktree. All generated evidence remains in self.base.
|
||||
import os
|
||||
ROOT = os.environ.get('CANINA_EDITORIAL_TEST_SOURCE', str(
|
||||
Path(__file__).parent / 'runs/20261104/content/source'))
|
||||
|
||||
|
||||
class EditorialEvidenceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(dir='/opt/data/cache/scratch')
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.m = manifest(ROOT)
|
||||
self.payload = {'title': 'SYNTHETIC UNIT TEST ONLY', 'content': '<p>test</p>', 'authorId': 'test-author', 'categoryId': 'test-category', 'tagNames': [], 'relatedBlogIds': [], 'relatedProductIds': []}
|
||||
(self.base / 'payload.json').write_text(json.dumps(self.payload))
|
||||
self.packet = {
|
||||
'action': 'NEW', 'manifest': self.m, 'payload': self.payload,
|
||||
'artifact': {'path': 'payload.json', 'sha256': sha(self.base / 'payload.json')},
|
||||
'artifact_evidence': ['test'],
|
||||
'evidence': {'test': {'path': 'payload.json', 'sha256': sha(self.base / 'payload.json'), 'readAt': 'UNIT_TEST_NOT_A_LIVE_READ'}},
|
||||
'field_dispositions': {k: {'disposition': 'system_derived' if v['kind'] == 'system' else 'verified_value' if k in self.payload else 'not_applicable', 'reason': 'synthetic unit fixture only', 'evidence': ['test'], 'value': self.payload.get(k)} for k, v in self.m['fields'].items()},
|
||||
'relations': {k: {'selected': self.payload[k], 'reason': 'synthetic unit fixture only', 'evidence': ['test'], 'status': 200, 'authenticated': True, 'inventory_complete': True, 'available': []} for k in ['authorId', 'categoryId', 'tagNames', 'relatedBlogIds', 'relatedProductIds']},
|
||||
'internal_links': {'reviewed_destinations': [{'href': '/blog/test', 'identity_verified': True, 'content_reviewed': True, 'suitable': False, 'reason': 'synthetic medically unsuitable destination', 'evidence': ['test']}], 'selected': [], 'zero_link_reason': 'reviewed destination unsuitable', 'disclose_in_report': True},
|
||||
}
|
||||
def sync_artifact(self):
|
||||
(self.base / 'payload.json').write_text(json.dumps(self.payload))
|
||||
digest = sha(self.base / 'payload.json')
|
||||
self.packet['artifact']['sha256'] = digest
|
||||
self.packet['evidence']['test']['sha256'] = digest
|
||||
def errors(self):
|
||||
return validate(self.packet, ROOT, self.base)
|
||||
def test_transport_control_cannot_claim_fetched_value(self):
|
||||
self.payload['markContentUpdated'] = False
|
||||
self.packet['field_dispositions']['markContentUpdated'].update(disposition='verified_value', value=False)
|
||||
self.sync_artifact()
|
||||
self.assertTrue(any('transport control is not a fetched scalar' in e for e in self.errors()))
|
||||
def test_acceptance_requires_readback_binding(self):
|
||||
self.packet.update(action='READ_ONLY_ACCEPTANCE', record_id='test-id')
|
||||
self.assertTrue(any('acceptance_readback' in e for e in self.errors()))
|
||||
def test_acceptance_absent_comments_rejects_invented_include(self):
|
||||
self.packet.update(action='READ_ONLY_ACCEPTANCE', record_id='test-id', acceptance_readback={'evidence':'readback'})
|
||||
record = {'id':'test-id', 'tags':[]}
|
||||
(self.base/'readback.json').write_text(json.dumps({'status':200,'body':{'data':record}}))
|
||||
self.packet['evidence']['readback']={'path':'readback.json','sha256':sha(self.base/'readback.json'),'readAt':'SYNTHETIC_ONLY'}
|
||||
self.packet['field_dispositions']['comments'].update(disposition='system_derived',value=None)
|
||||
self.assertTrue(any('comments: absent from fetched record' in e for e in self.errors()))
|
||||
def test_verified_value_requires_value(self):
|
||||
del self.packet['field_dispositions']['title']['value']
|
||||
self.assertTrue(any('explicit value' in e for e in self.errors()))
|
||||
def test_omitted_verified_writable_value_rejected(self):
|
||||
self.packet['field_dispositions']['ogImage']['disposition'] = 'verified_value'
|
||||
self.assertTrue(any('must be in payload' in e for e in self.errors()))
|
||||
def test_update_identity_required(self):
|
||||
self.packet['action'] = 'UPDATE'
|
||||
self.assertTrue(any('requires record_id' in e for e in self.errors()))
|
||||
def test_related_membership_with_coherent_payload(self):
|
||||
self.payload['relatedBlogIds'] = ['missing']
|
||||
self.packet['relations']['relatedBlogIds']['selected'] = ['missing']
|
||||
self.packet['field_dispositions']['relatedBlogIds']['value'] = ['missing']
|
||||
self.sync_artifact()
|
||||
self.assertTrue(any('absent from verified inventory' in e for e in self.errors()))
|
||||
def test_valid_selected_body_link(self):
|
||||
self.payload['content'] = '<a href="/blog/test">test</a>'
|
||||
self.packet['field_dispositions']['content']['value'] = self.payload['content']
|
||||
self.packet['internal_links']['selected'] = ['/blog/test']
|
||||
self.packet['internal_links']['reviewed_destinations'][0]['suitable'] = True
|
||||
self.sync_artifact()
|
||||
self.assertEqual([], self.errors())
|
||||
def test_missing_action_rejected(self):
|
||||
del self.packet['action']
|
||||
self.assertTrue(any('explicit action' in e for e in self.errors()))
|
||||
def test_complete_structure_is_not_publication_approval(self):
|
||||
self.assertEqual([], self.errors())
|
||||
def test_manifest_includes_all_43_scalars_relations_controls(self):
|
||||
self.assertIn('homeDisplayMode', self.m['fields'])
|
||||
self.assertIn('comments', self.m['fields'])
|
||||
self.assertIn('markContentUpdated', self.m['fields'])
|
||||
self.assertIn('tagNames', self.m['fields'])
|
||||
def test_acceptance_missing_manifest_is_rejected(self):
|
||||
self.packet['manifest'] = {}
|
||||
self.assertTrue(self.errors())
|
||||
def test_missing_disposition_rejected(self):
|
||||
del self.packet['field_dispositions']['ogImage']
|
||||
self.assertTrue(self.errors())
|
||||
def test_wrong_transport_tagIds_rejected(self):
|
||||
self.payload['tagIds'] = []
|
||||
self.assertTrue(any('payload keys' in e for e in self.errors()))
|
||||
def test_unjustified_empty_taxonomy_rejected(self):
|
||||
for key in ['tagNames', 'relatedBlogIds', 'relatedProductIds']:
|
||||
packet = copy.deepcopy(self.packet)
|
||||
self.packet['relations'][key]['reason'] = ''
|
||||
self.assertTrue(self.errors())
|
||||
self.packet = packet
|
||||
def test_missing_authenticated_tag_inventory_rejected(self):
|
||||
self.packet['relations']['tagNames']['authenticated'] = False
|
||||
self.assertTrue(self.errors())
|
||||
def test_nonexisting_related_id_rejected(self):
|
||||
self.packet['relations']['relatedBlogIds']['selected'] = ['missing']
|
||||
self.assertTrue(self.errors())
|
||||
def test_automatic_cards_do_not_replace_body_links(self):
|
||||
self.packet['internal_links'] = {}
|
||||
self.assertTrue(self.errors())
|
||||
def test_zero_link_disclosure_required(self):
|
||||
self.packet['internal_links']['disclose_in_report'] = False
|
||||
self.assertTrue(self.errors())
|
||||
def test_reject_zero_when_suitable_destination_exists(self):
|
||||
self.packet['internal_links']['reviewed_destinations'][0]['suitable'] = True
|
||||
self.assertTrue(self.errors())
|
||||
def test_http_success_not_identity(self):
|
||||
self.packet['internal_links']['reviewed_destinations'][0]['identity_verified'] = False
|
||||
self.assertTrue(self.errors())
|
||||
def test_tampered_artifact_rejected(self):
|
||||
(self.base / 'payload.json').write_text('{}')
|
||||
self.assertTrue(self.errors())
|
||||
def test_unreviewed_body_link_rejected(self):
|
||||
self.payload['content'] = '<a href="/blog/unreviewed">test</a>'
|
||||
self.assertTrue(any('contextual body links' in e for e in self.errors()))
|
||||
def test_missing_evidence_rejected(self):
|
||||
self.packet['evidence'] = {}
|
||||
self.assertTrue(self.errors())
|
||||
def test_false_and_null_are_values_not_missing(self):
|
||||
self.payload['noIndex'] = False
|
||||
self.payload['scheduledAt'] = None
|
||||
for k in ['noIndex', 'scheduledAt']:
|
||||
self.packet['field_dispositions'][k]['value'] = self.payload[k]
|
||||
self.packet['field_dispositions'][k]['disposition'] = 'verified_value'
|
||||
(self.base / 'payload.json').write_text(json.dumps(self.payload))
|
||||
digest = sha(self.base / 'payload.json')
|
||||
self.packet['artifact']['sha256'] = digest
|
||||
self.packet['evidence']['test']['sha256'] = digest
|
||||
self.assertEqual([], self.errors())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Offline regression only; never publication evidence."""
|
||||
import os
|
||||
import unittest
|
||||
from editorial_evidence import manifest
|
||||
|
||||
class ManifestTransportTests(unittest.TestCase):
|
||||
def test_update_only_expected_updated_at_is_explicit_request_control(self):
|
||||
fields = manifest(os.environ['CANINA_EDITORIAL_TEST_SOURCE'])['fields']
|
||||
self.assertIn('expectedUpdatedAt', fields)
|
||||
self.assertEqual(fields['expectedUpdatedAt'], {
|
||||
'type': 'String', 'kind': 'transport_control',
|
||||
'actions': ['UPDATE'], 'persisted': False,
|
||||
})
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.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()
|
||||
@@ -0,0 +1 @@
|
||||
Base: 4d41a5bbf70e9bf9f9ead2412822668998b2c2cf; clean detached isolated worktree. Publisher validator currently untracked in application repository; preserve exact live baseline before minimal fix. Graph hash 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af; graph is unbound navigation only. Direct source confirms transport control; no backend/frontend edits. Dependencies: manifest -> field dispositions -> validate -> independent QA. Existing push workflow deploys site and restarts bot, forbidden in this scope. Do not push develop through that workflow; report publisher-only release boundary to parent.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Production publisher manifest repair
|
||||
The complete Blog contract must include optional UPDATE-only expectedUpdatedAt. NEW must explicitly disposition it not applicable and omit it from its payload. Preserve request-only semantics and independent approvals. No site deployment, gateway restart, Stage publisher or shared skill modifications.
|
||||
Acceptance: regression fails before fix and passes after; existing editorial tests pass. Activate only through an authorized publisher-only CI/CD route; current site deploy workflow is not acceptable.
|
||||
@@ -0,0 +1,5 @@
|
||||
1. Preserve live validator/test source unchanged in Git.
|
||||
2. RED: exercise expectedUpdatedAt manifest completeness on exact archived/current source.
|
||||
3. GREEN: minimal update-only request-control manifest fix; full isolated editorial suite.
|
||||
4. Record source hash and tests; commit isolated change without triggering prohibited site deploy.
|
||||
5. Publisher-only CI/CD deployment, source/runtime mapping and exact-hash SEO/final QA remain prerequisites to cron create.
|
||||
Reference in new issue
Block a user