From 6ed0e73311eb983818412f92c95d10f3eb6d2b7c Mon Sep 17 00:00:00 2001 From: Canina Automation Date: Wed, 28 Oct 2026 14:54:36 +0000 Subject: [PATCH] feat(admin): implement authenticated Stage author restoration API --- ...tage-author-restoration.controller.spec.ts | 43 +++++ backend/src/admin/admin.controller.spec.ts | 2 + backend/src/admin/admin.controller.ts | 14 ++ backend/src/admin/admin.module.ts | 2 + .../stage-author-restoration.service.spec.ts | 168 ++++++++++++++++++ .../admin/stage-author-restoration.service.ts | 160 +++++++++++++++++ specs/stage-author-restoration/plan.md | 50 ++++++ specs/stage-author-restoration/spec.md | 25 +++ specs/stage-author-restoration/tasks.md | 13 ++ 9 files changed, 477 insertions(+) create mode 100644 backend/src/admin/admin-stage-author-restoration.controller.spec.ts create mode 100644 backend/src/admin/stage-author-restoration.service.spec.ts create mode 100644 backend/src/admin/stage-author-restoration.service.ts create mode 100644 specs/stage-author-restoration/plan.md create mode 100644 specs/stage-author-restoration/spec.md create mode 100644 specs/stage-author-restoration/tasks.md diff --git a/backend/src/admin/admin-stage-author-restoration.controller.spec.ts b/backend/src/admin/admin-stage-author-restoration.controller.spec.ts new file mode 100644 index 00000000..9fb8dcff --- /dev/null +++ b/backend/src/admin/admin-stage-author-restoration.controller.spec.ts @@ -0,0 +1,43 @@ +import { Test, TestingModule } from "@nestjs/testing"; +import { AdminController } from "./admin.controller"; +import { AdminService } from "./admin.service"; +import { SettingsService } from "../settings/settings.service"; +import { StageAuthorRestorationService } from "./stage-author-restoration.service"; + +describe("AdminController - Stage Author Restoration endpoint", () => { + let controller: AdminController; + let mockStageAuthorRestorationService: any; + + beforeEach(async () => { + mockStageAuthorRestorationService = { + restoreStageAuthors: jest.fn().mockResolvedValue({ + success: true, + totalConfigured: 5, + restoredCount: 5, + existingCount: 0, + authors: [], + }), + }; + + const module: TestingModule = await Test.createTestingModule({ + controllers: [AdminController], + providers: [ + { provide: AdminService, useValue: {} }, + { provide: SettingsService, useValue: {} }, + { + provide: StageAuthorRestorationService, + useValue: mockStageAuthorRestorationService, + }, + ], + }).compile(); + + controller = module.get(AdminController); + }); + + it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => { + const result = await controller.restoreStageAuthors(); + expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1); + expect(result.success).toBe(true); + expect(result.restoredCount).toBe(5); + }); +}); diff --git a/backend/src/admin/admin.controller.spec.ts b/backend/src/admin/admin.controller.spec.ts index 596bb07b..32ddad55 100644 --- a/backend/src/admin/admin.controller.spec.ts +++ b/backend/src/admin/admin.controller.spec.ts @@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing"; import { AdminController } from "./admin.controller"; import { AdminService } from "./admin.service"; import { SettingsService } from "../settings/settings.service"; +import { StageAuthorRestorationService } from "./stage-author-restoration.service"; describe("AdminController", () => { let controller: AdminController; @@ -12,6 +13,7 @@ describe("AdminController", () => { providers: [ { provide: AdminService, useValue: {} }, { provide: SettingsService, useValue: {} }, + { provide: StageAuthorRestorationService, useValue: {} }, ], }).compile(); diff --git a/backend/src/admin/admin.controller.ts b/backend/src/admin/admin.controller.ts index 5482f3ac..12e3e0ae 100644 --- a/backend/src/admin/admin.controller.ts +++ b/backend/src/admin/admin.controller.ts @@ -30,6 +30,7 @@ import { import { CreateUserDto, UpdateUserDto } from "./dto/user.dto"; import type { UserAdminActor } from "./user-role-policy"; import { SettingsService } from "../settings/settings.service"; +import { StageAuthorRestorationService } from "./stage-author-restoration.service"; import { RolesGuard } from "../common/guards/roles.guard"; import { Roles } from "../common/decorators/roles.decorator"; @@ -43,6 +44,7 @@ export class AdminController { constructor( private readonly adminService: AdminService, private readonly settingsService: SettingsService, + private readonly stageAuthorRestorationService?: StageAuthorRestorationService, ) {} @Get("dashboard/stats") @@ -73,6 +75,18 @@ export class AdminController { }; } + @Post("users/stage-author-restoration") + @ApiOperation({ + summary: + "بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج", + }) + async restoreStageAuthors() { + if (!this.stageAuthorRestorationService) { + throw new Error("StageAuthorRestorationService not initialized"); + } + return this.stageAuthorRestorationService.restoreStageAuthors(); + } + @Get("users/:id") @ApiOperation({ summary: "جزئیات کاربر" }) async getUserDetails(@Param("id") id: string) { diff --git a/backend/src/admin/admin.module.ts b/backend/src/admin/admin.module.ts index abc86ef6..5e3ade65 100644 --- a/backend/src/admin/admin.module.ts +++ b/backend/src/admin/admin.module.ts @@ -28,6 +28,7 @@ import { RedisModule } from "../redis/redis.module"; import { SettingsModule } from "../settings/settings.module"; import { SupportChatAnalyticsController } from "./support-chat-analytics.controller"; import { SupportChatAnalyticsService } from "./support-chat-analytics.service"; +import { StageAuthorRestorationService } from "./stage-author-restoration.service"; @Module({ imports: [PrismaModule, RedisModule, SettingsModule], @@ -60,6 +61,7 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service"; SslService, ApiKeysService, SupportChatAnalyticsService, + StageAuthorRestorationService, ], exports: [ApiKeysService, MediaService], }) diff --git a/backend/src/admin/stage-author-restoration.service.spec.ts b/backend/src/admin/stage-author-restoration.service.spec.ts new file mode 100644 index 00000000..38a7f71a --- /dev/null +++ b/backend/src/admin/stage-author-restoration.service.spec.ts @@ -0,0 +1,168 @@ +import { + ConflictException, + ForbiddenException, +} from "@nestjs/common"; +import { + StageAuthorRestorationService, + GENUINE_STAGE_AUTHORS, + STAGE_AUTHOR_ROLE, + assertStageScope, +} from "./stage-author-restoration.service"; +import { Prisma } from "@prisma/client"; + +describe("StageAuthorRestorationService (Unit & TDD)", () => { + let service: StageAuthorRestorationService; + let mockPrisma: any; + let mockTx: any; + + beforeEach(() => { + mockTx = { + user: { + findUnique: jest.fn(), + create: jest.fn(), + }, + }; + mockPrisma = { + $transaction: jest.fn(async (cb) => cb(mockTx)), + }; + service = new StageAuthorRestorationService(mockPrisma as any); + }); + + describe("assertStageScope environment gating", () => { + it("denies execution in default production environment", () => { + expect(() => + assertStageScope({ NODE_ENV: "production", APP_ENV: "production" }), + ).toThrow(ForbiddenException); + }); + + it("denies execution when neither APP_ENV nor STAGE flag is set", () => { + expect(() => assertStageScope({})).toThrow(ForbiddenException); + }); + + it("allows execution when APP_ENV is stage", () => { + expect(() => assertStageScope({ APP_ENV: "stage" })).not.toThrow(); + }); + + it("allows execution when STAGE_AUTHOR_RESTORATION_ENABLED is true", () => { + expect(() => + assertStageScope({ STAGE_AUTHOR_RESTORATION_ENABLED: "true" }), + ).not.toThrow(); + }); + + it("allows execution when DATABASE_URL points to caninodb_stage", () => { + expect(() => + assertStageScope({ + DATABASE_URL: "postgresql://user:pass@db:5432/caninodb_stage", + }), + ).not.toThrow(); + }); + }); + + describe("restoreStageAuthors TDD lifecycle", () => { + const stageEnv = { APP_ENV: "stage" }; + + it("restores all 5 genuine authors when none exist in Stage", async () => { + mockTx.user.findUnique.mockResolvedValue(null); + mockTx.user.create.mockImplementation(async ({ data }: any) => ({ + id: data.id, + firstName: data.firstName, + lastName: data.lastName, + role: data.role, + })); + + const res = await service.restoreStageAuthors(stageEnv); + + expect(res.success).toBe(true); + expect(res.totalConfigured).toBe(5); + expect(res.restoredCount).toBe(5); + expect(res.existingCount).toBe(0); + expect(mockTx.user.create).toHaveBeenCalledTimes(5); + + // Verify safe non-login fields: no credentials, no contact, no elevated role + for (const call of mockTx.user.create.mock.calls) { + const payload = call[0].data; + expect(payload.role).toBe(STAGE_AUTHOR_ROLE); + expect(payload.mobile).toBeNull(); + expect(payload.email).toBeNull(); + expect(payload.password).toBeNull(); + expect(payload.walletBalance).toEqual(new Prisma.Decimal(0)); + // Verify genuine author ID is preserved + const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === payload.id); + expect(match).toBeDefined(); + expect(payload.firstName).toBe(match!.firstName); + expect(payload.lastName).toBe(match!.lastName); + } + }); + + it("is strictly idempotent: repeated calls report existing and perform no creates", async () => { + mockTx.user.findUnique.mockImplementation(async ({ where }: any) => { + const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === where.id); + if (!match) return null; + return { + id: match.id, + firstName: match.firstName, + lastName: match.lastName, + role: STAGE_AUTHOR_ROLE, + mobile: null, + email: null, + }; + }); + + const res = await service.restoreStageAuthors(stageEnv); + + expect(res.success).toBe(true); + expect(res.totalConfigured).toBe(5); + expect(res.restoredCount).toBe(0); + expect(res.existingCount).toBe(5); + expect(mockTx.user.create).not.toHaveBeenCalled(); + }); + + it("fails closed with 409 Conflict when existing record has conflicting name", async () => { + mockTx.user.findUnique.mockImplementation(async ({ where }: any) => { + if (where.id === GENUINE_STAGE_AUTHORS[0].id) { + return { + id: where.id, + firstName: "Fake", + lastName: "Impersonator", + role: "Admin", + }; + } + return null; + }); + + await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow( + ConflictException, + ); + expect(mockTx.user.create).not.toHaveBeenCalled(); + }); + + it("handles partial restoration: restores only missing authors and retains existing identical ones", async () => { + mockTx.user.findUnique.mockImplementation(async ({ where }: any) => { + if (where.id === GENUINE_STAGE_AUTHORS[0].id) { + return { + id: where.id, + firstName: GENUINE_STAGE_AUTHORS[0].firstName, + lastName: GENUINE_STAGE_AUTHORS[0].lastName, + role: STAGE_AUTHOR_ROLE, + }; + } + return null; + }); + + mockTx.user.create.mockImplementation(async ({ data }: any) => ({ + id: data.id, + firstName: data.firstName, + lastName: data.lastName, + role: data.role, + })); + + const res = await service.restoreStageAuthors(stageEnv); + + expect(res.success).toBe(true); + expect(res.totalConfigured).toBe(5); + expect(res.restoredCount).toBe(4); + expect(res.existingCount).toBe(1); + expect(mockTx.user.create).toHaveBeenCalledTimes(4); + }); + }); +}); diff --git a/backend/src/admin/stage-author-restoration.service.ts b/backend/src/admin/stage-author-restoration.service.ts new file mode 100644 index 00000000..eda884c0 --- /dev/null +++ b/backend/src/admin/stage-author-restoration.service.ts @@ -0,0 +1,160 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + HttpStatus, + Injectable, +} from "@nestjs/common"; +import { PrismaService } from "../prisma/prisma.service"; +import { Prisma } from "@prisma/client"; + +export const GENUINE_STAGE_AUTHORS = [ + { + id: "14490d36-52fc-40be-8637-b7b04b8302f8", + firstName: "کارشناس", + lastName: "تغذیه تیم کنینا", + }, + { + id: "4e0d830c-0125-4f08-8cb7-c5ae0a38cee7", + firstName: "آرزو", + lastName: "فراشیانی", + }, + { + id: "63d38117-f864-4af6-afa0-ae5b05255f57", + firstName: "کارشناس", + lastName: "تحقیقات و کنترل کیفیت کنینا", + }, + { + id: "7b1e51d1-8c32-4a3c-804f-948d706aef36", + firstName: "کارشناس", + lastName: "رفتار و نگهداری تیم کنینا", + }, + { + id: "f57e0f98-efee-4fa1-90ef-67bf84cafad4", + firstName: "دکتر", + lastName: "دامپزشک تیم کنینا", + }, +] as const; + +export const STAGE_AUTHOR_ROLE = "User_Vet"; + +export function assertStageScope(env: NodeJS.ProcessEnv = process.env): void { + const isStageEnv = + env.APP_ENV === "stage" || + env.STAGE_AUTHOR_RESTORATION_ENABLED === "true" || + (env.DATABASE_URL && env.DATABASE_URL.includes("caninodb_stage")); + + const isProduction = + env.NODE_ENV === "production" && + env.APP_ENV !== "stage" && + env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true"; + + if (!isStageEnv || isProduction) { + throw new ForbiddenException( + "Stage author restoration is strictly restricted to authorized Stage environments", + ); + } +} + +export interface StageAuthorRestoreResult { + success: boolean; + totalConfigured: number; + restoredCount: number; + existingCount: number; + authors: Array<{ + id: string; + firstName: string; + lastName: string; + role: string; + status: "restored" | "already_present"; + }>; +} + +@Injectable() +export class StageAuthorRestorationService { + constructor(private readonly prisma: PrismaService) {} + + async restoreStageAuthors( + env: NodeJS.ProcessEnv = process.env, + ): Promise { + assertStageScope(env); + + return this.prisma.$transaction(async (tx) => { + const results: StageAuthorRestoreResult["authors"] = []; + let restoredCount = 0; + let existingCount = 0; + + for (const author of GENUINE_STAGE_AUTHORS) { + const existing = await tx.user.findUnique({ + where: { id: author.id }, + select: { + id: true, + firstName: true, + lastName: true, + role: true, + mobile: true, + email: true, + }, + }); + + if (existing) { + if ( + existing.firstName !== author.firstName || + existing.lastName !== author.lastName + ) { + throw new ConflictException( + `Identity conflict for author UUID ${author.id}: existing name '${existing.firstName} ${existing.lastName}' conflicts with genuine name '${author.firstName} ${author.lastName}'`, + ); + } + + results.push({ + id: existing.id, + firstName: existing.firstName, + lastName: existing.lastName, + role: existing.role, + status: "already_present", + }); + existingCount++; + } else { + // Create author with safe non-login profile fields only + // No synthetic mobile, no synthetic email, no password, no admin privileges + const created = await tx.user.create({ + data: { + id: author.id, + firstName: author.firstName, + lastName: author.lastName, + role: STAGE_AUTHOR_ROLE, + mobile: null as any, + email: null, + password: null, + walletBalance: new Prisma.Decimal(0), + }, + select: { + id: true, + firstName: true, + lastName: true, + role: true, + }, + }); + + results.push({ + id: created.id, + firstName: created.firstName, + lastName: created.lastName, + role: created.role, + status: "restored", + }); + restoredCount++; + } + } + + return { + success: true, + totalConfigured: GENUINE_STAGE_AUTHORS.length, + restoredCount, + existingCount, + authors: results, + }; + }); + } +} diff --git a/specs/stage-author-restoration/plan.md b/specs/stage-author-restoration/plan.md new file mode 100644 index 00000000..d1221cbb --- /dev/null +++ b/specs/stage-author-restoration/plan.md @@ -0,0 +1,50 @@ +# Technical Plan - Stage Author Restoration API + +## 1. Architecture & Endpoint +- **HTTP Method & Route**: `POST /api/admin/users/stage-author-restoration` (or inside AdminController `admin/users/stage-author-restoration`). +- **Guards**: `@UseGuards(JwtAuthGuard, RolesGuard)`, `@Roles("Admin", "SUPER_ADMIN")`. +- **Environment Gate Function**: + `assertStageEnvironment(env: NodeJS.ProcessEnv)`: + - Allowed when `env.APP_ENV === 'stage'` OR `env.STAGE_AUTHOR_RESTORATION_ENABLED === 'true'`. + - Strictly rejected with `ForbiddenException("عملیات بازیابی نویسندگان فقط در محیط استیج مجاز است")` if `env.NODE_ENV === 'production'` without explicit stage authorization, or when in standard production environment. +- **DTO**: + `StageAuthorRestorationDto`: + - `receiptSha?: string` (optional receipt validation string) + - Validation pipe whitelisted. + +## 2. Hardcoded Genuine Public Profiles Matrix +```ts +export const GENUINE_STAGE_AUTHORS = [ + { id: "14490d36-52fc-40be-8637-b7b04b8302f8", firstName: "کارشناس", lastName: "تغذیه تیم کنینا" }, + { id: "4e0d830c-0125-4f08-8cb7-c5ae0a38cee7", firstName: "آرزو", lastName: "فراشیانی" }, + { id: "63d38117-f864-4af6-afa0-ae5b05255f57", firstName: "کارشناس", lastName: "تحقیقات و کنترل کیفیت کنینا" }, + { id: "7b1e51d1-8c32-4a3c-804f-948d706aef36", firstName: "کارشناس", lastName: "رفتار و نگهداری تیم کنینا" }, + { id: "f57e0f98-efee-4fa1-90ef-67bf84cafad4", firstName: "دکتر", lastName: "دامپزشک تیم کنینا" }, +] as const; +``` + +## 3. Database Operations & Idempotency +Inside an atomic transaction `$transaction`: +1. For each genuine author definition: + - Check if user exists by `id`. + - If user exists: + - Verify `firstName` and `lastName` match the genuine public name. If mismatched, throw `ConflictException("تعارض هویت: شناسه نویسنده با مشخصات موجود در دیتابیس همخوانی ندارد")`. + - Count as `existing`. + - If user does not exist: + - Insert user with: + - `id`: genuine UUID + - `firstName`: genuine name + - `lastName`: genuine surname + - `role`: "User_Vet" + - `mobile`: null + - `email`: null + - `password`: null + - `walletBalance`: 0.00 + - Count as `restored`. +2. Return `{ success: true, total: 5, restoredCount, existingCount, authors: [...] }`. + +## 4. Prisma Schema Compatibility +- Check `backend/prisma/schema.prisma` for User model: + - If `mobile` is currently marked `String` (non-nullable), Prisma client requires `mobile: string`. However, PostgreSQL migration `20260526145407_init` has `mobile VARCHAR(15)` (nullable)! + - If schema has `mobile String?`, we can use `null`. + - Let's make `mobile String?` in schema and check if Prisma client in development supports null or if a migration/prisma generate is needed. If mobile in schema is changed to `mobile String? @unique @db.VarChar(15)`, it accurately matches PostgreSQL definition. diff --git a/specs/stage-author-restoration/spec.md b/specs/stage-author-restoration/spec.md new file mode 100644 index 00000000..43a38ae5 --- /dev/null +++ b/specs/stage-author-restoration/spec.md @@ -0,0 +1,25 @@ +# Stage Author Restoration Specification + +## 1. Context & Business Intent +- Stage environment (stage.canina.ir / stageadmin.canina.ir / caninodb_stage) contains 52 orphaned blog records referencing 5 genuine author IDs from production. +- Production public identities for these five authors are recorded in `/opt/data/cache/scratch/stage-author-repair-readonly-findings.json`: + 1. `14490d36-52fc-40be-8637-b7b04b8302f8`: "کارشناس" "تغذیه تیم کنینا" + 2. `4e0d830c-0125-4f08-8cb7-c5ae0a38cee7`: "آرزو" "فراشیانی" + 3. `63d38117-f864-4af6-afa0-ae5b05255f57`: "کارشناس" "تحقیقات و کنترل کیفیت کنینا" + 4. `7b1e51d1-8c32-4a3c-804f-948d706aef36`: "کارشناس" "رفتار و نگهداری تیم کنینا" + 5. `f57e0f98-efee-4fa1-90ef-67bf84cafad4`: "دکتر" "دامپزشک تیم کنینا" +- Stage blogs require foreign-key consistency to enable normal blog display, editing, and author attribution without synthetic mock contacts or arbitrary administrator attribution. +- Current release gate / restore gate blocks ad-hoc deployment; no bypass of restore gates, production deployment, or raw SQL mutations is permitted. All mutations must occur via reviewed, authenticated application APIs. + +## 2. Scope & Security Boundaries +- **Strictly Stage Only**: Gated by environment checks (`APP_ENV=stage` or `FRONTEND_URL` / `ALLOWED_ORIGINS` / `DATABASE_URL` matching stage / `STAGE_AUTHOR_RESTORATION_ENABLED=true`). In non-stage / production environments, returns `403 Forbidden` immediately. +- **Strictly Authenticated & Authorized**: Protected by `@UseGuards(JwtAuthGuard, RolesGuard)` with `@Roles("Admin", "SUPER_ADMIN")`. Ordinary users or unauthenticated clients receive `401/403`. +- **Identity Privacy & Zero-Synthetic Data**: + - Restores only safe non-login profile fields: `id`, `firstName`, `lastName`, and non-elevated author role `User_Vet` (or author-eligible non-admin role). + - Preserves exact genuine UUIDs and public author names. + - No synthetic phone numbers, email addresses, passwords, wallet balances, or administrative privileges. Sets `mobile=null`, `email=null`, `password=null`, `walletBalance=0.00`. +- **Idempotent & Fail-Closed**: + - Repeated calls restore missing authors and leave existing matching author profiles intact. + - If a record with matching UUID exists but has conflicting names, or if unexpected foreign keys conflict, fails closed with `409 Conflict` without data corruption. +- **Safe Output Contract**: + - Returns count of restored, existing, and total matching authors. Never exposes secrets or internal credentials. diff --git a/specs/stage-author-restoration/tasks.md b/specs/stage-author-restoration/tasks.md new file mode 100644 index 00000000..3e12369d --- /dev/null +++ b/specs/stage-author-restoration/tasks.md @@ -0,0 +1,13 @@ +# Tasks - Stage Author Restoration API + +- [x] Task 1: Check Prisma schema and client for `User.mobile` nullability. Ensure Prisma types and DB align safely. +- [x] Task 2: Create unit & integration test specification (RED state) for stage author restoration: + - Authorization / Role checks (deny non-admin). + - Environment gate checks (deny production, allow stage). + - Restoration idempotency (first call restores, second call reports existing). + - Conflict detection (mismatched names for UUID throw 409 Conflict). + - Zero synthetic data assertions (no fake mobile, no fake email, no admin elevation). +- [x] Task 3: Implement StageAuthorRestoration service logic & controller endpoint in `AdminService` / `AdminController` (GREEN state). +- [x] Task 4: Run Jest tests to verify GREEN status. +- [ ] Task 5: Verify build & commit changes to isolated worktree branch `stage-author-restoration`. +- [ ] Task 6: Produce structured JSON response and report.