feat: add admin panel dto & validation

This commit is contained in:
2026-11-14 22:43:12 +03:30
parent 2d32e2679b
commit 8d6834f44c
18 changed files with 1832 additions and 52 deletions
+413
View File
@@ -0,0 +1,413 @@
# مستند فارسی اصلاح امنیت و یکپارچگی داده در AdminJS
تاریخ تهیه: ۹ نوامبر ۲۰۲۶
## دامنهٔ این مستند
این سند تغییرات مرحلهٔ اخیر اصلاح AdminJS را توضیح می‌دهد: ۱۰ فایل موجود ویرایش شد و ۶ فایل کد و تست اضافه شد. تغییرات قبلی گفتگو در زمینهٔ محدودسازی درخواست‌ها، OTP و refresh token در این مرحله تغییر نکرده‌اند و موضوع این سند نیستند.
برای هر فایل، وظیفهٔ آن، مشکل قبلی، تغییر انجام‌شده و اثر تغییر توضیح داده شده است. پیوندهای فایل‌ها نسبت به محل همین سند هستند.
## ۱. مشکل اولیه چه بود؟
در مسیر عادی API، درخواست ابتدا وارد Controller می‌شود، DTO اعتبارسنجی می‌شود و سپس Service و Provider قوانین کسب‌وکار را اجرا می‌کنند.
اما پنل قبلی Entityها را به‌صورت خودکار به AdminJS معرفی می‌کرد. آداپتر TypeORM پنل می‌توانست مستقیماً روی Entity بنویسد. بنابراین اجرای قواعدی مثل بررسی انتشار آزمون، بررسی مسیرها، جلوگیری از هم‌پوشانی بازه‌ها، افزایش شمارندهٔ سؤال و هش‌کردن رمز تضمین نمی‌شد.
مخفی‌کردن یک فیلد در رابط کاربری هم به‌تنهایی محافظت سمت سرور نیست؛ هم باید جلوی نوشتن نامجاز گرفته شود و هم دادهٔ حساس از پاسخ واقعی حذف شود.
مسیر جدید برای عملیات ساخت و ویرایش کاتالوگ:
```text
درخواست AdminJS
→ بررسی نقش فعلی کاربر در دیتابیس
→ کنترل دسترسی اکشن
→ AdminPanelResource
→ کنترل هم‌زمانی نوشتن‌های پنل
→ بررسی فیلدهای مجاز و تبدیل داده‌های فرم
→ کنترل قفل ساختار و وابستگی‌ها
→ اعتبارسنجی DTO
→ Service موجود
→ Command Provider و Validatorهای موجود
→ ذخیره در دیتابیس
→ حذف اطلاعات حساس از پاسخ
```
حذف، DTO ساخت را اجرا نمی‌کند؛ پس از بررسی مجوز، قفل ساختار و وابستگی‌ها، به متد حذف Service مربوطه واگذار می‌شود.
## ۲. فهرست تمام فایل‌های کد و تست این تغییر
| ردیف | فایل | وضعیت | مسئولیت اصلی |
|---|---|---|---|
| ۱ | [admin-panel.setup.ts](../src/modules/admin-panel/admin-panel.setup.ts) | ویرایش | اتصال تنظیمات جدید به پنل |
| ۲ | [admin-panel.resource.ts](../src/modules/admin-panel/admin-panel.resource.ts) | جدید | جلوگیری از نوشتن مستقیم آداپتر |
| ۳ | [admin-panel.validation.ts](../src/modules/admin-panel/admin-panel.validation.ts) | جدید | تبدیل فرم، اعتبارسنجی و حذف اطلاعات حساس |
| ۴ | [admin-panel.resources.ts](../src/modules/admin-panel/admin-panel.resources.ts) | جدید | تعریف منابع، مجوزها و مسیر نوشتن |
| ۵ | [validate-metadata.helper.ts](../src/modules/questions/helpers/validate-metadata.helper.ts) | ویرایش | اعتبارسنجی metadata سؤال |
| ۶ | [questions-command.provider.ts](../src/modules/questions/providers/questions-command.provider.ts) | ویرایش | عملیات نوشتن سؤال |
| ۷ | [choices-command.provider.ts](../src/modules/questions/providers/choices/choices-command.provider.ts) | ویرایش | عملیات نوشتن گزینه |
| ۸ | [question-range-rule-command.provider.ts](../src/modules/questions/providers/range-rule/question-range-rule-command.provider.ts) | ویرایش | قوانین بازه‌ای سؤال |
| ۹ | [question-transition-command.provider.ts](../src/modules/questions/providers/transition/question-transition-command.provider.ts) | ویرایش | مسیرهای بین سؤال‌ها |
| ۱۰ | [question-transition-type.validator.ts](../src/modules/questions/validators/question-transition-type.validator.ts) | ویرایش | بررسی سازگاری نوع مسیر و شرط آن |
| ۱۱ | [result-range-command.provider.ts](../src/modules/scoring/providers/result-range-command.provider.ts) | ویرایش | بازه‌های نتیجهٔ آزمون |
| ۱۲ | [test.entity.ts](../src/modules/tests/entities/test.entity.ts) | ویرایش | تعریف ستون قفل ساختار آزمون |
| ۱۳ | [tests-command.provider.ts](../src/modules/tests/providers/tests-command.provider.ts) | ویرایش | ذخیره و انتشار آزمون |
| ۱۴ | [LockPublishedTestStructure](../src/migrations/1794182400000-LockPublishedTestStructure.ts) | جدید | migration ستون جدید |
| ۱۵ | [admin-panel.resources.spec.ts](../src/modules/admin-panel/admin-panel.resources.spec.ts) | جدید | تست منابع، امنیت و مجوزهای پنل |
| ۱۶ | [admin-panel.ranges.spec.ts](../src/modules/admin-panel/admin-panel.ranges.spec.ts) | جدید | تست اصلاح بازه‌ها و روابط |
## ۳. توضیح فایل‌به‌فایل
### فایل ۱: `src/modules/admin-panel/admin-panel.setup.ts`
**وظیفه:** راه‌اندازی AdminJS روی Express، معرفی آداپتر TypeORM، تنظیم زبان و ظاهر، اتصال احراز هویت و Session Store مبتنی بر Redis.
**قبل:** تمام Entityهای واقعی دیتابیس به‌صورت خودکار وارد پنل می‌شدند. علاوه بر آن، `User` جداگانه نیز معرفی می‌شد و امکان معرفی تکراری آن وجود داشت. تنظیم رمز در این محل عمدتاً مربوط به نمایش ستون بود.
**تغییر:** ساخت منابع به `buildAdminPanelResources(app)` سپرده شد و ثبت خودکار Entityها حذف شد.
**اثر:** منابع پنل اکنون فهرست مشخص دارند. افزودن یک Entity جدید به پروژه، آن را خودکار در پنل قابل مشاهده یا قابل تغییر نمی‌کند. `User` فقط یک بار ثبت می‌شود. نحوهٔ ورود، Redis Session Store و محل نصب Router در این تغییر بازنویسی نشده‌اند.
### فایل ۲: `src/modules/admin-panel/admin-panel.resource.ts`
**وظیفه:** آداپتر محافظت‌شدهٔ پنل است؛ از `Resource` آداپتر TypeORM ارث‌بری می‌کند.
**اجزای مهم:**
- `PanelWrite`: قرارداد تابعی است که یک عملیات `new`، `edit` یا `delete` را اجرا می‌کند.
- `persist`: ورودی مشترک نوشتن است؛ شناسه را بررسی می‌کند، مسیرهای فیلد شامل `__proto__`، `prototype` و `constructor` را رد می‌کند و دادهٔ تخت AdminJS را باز می‌کند.
- `create`، `update` و `delete`: به تابع `write` واگذار می‌شوند؛ به متد نوشتن آداپتر اصلی برنمی‌گردند.
- اگر منبع تابع `write` نداشته باشد، عملیات نوشتن حتی در صورت فراخوانی مستقیم متد Resource هم رد می‌شود.
- `findOne`، `find` و `findMany`: پس از خواندن، هش `password` را از پارامترهای رکورد حذف می‌کنند.
- `redact`: علاوه بر حذف هش رمز، `metadata` و `condition` شیئی را به متن JSON مناسب فرم تبدیل می‌کند.
**مثال بازکردن فیلد تخت:**
```ts
// ورودی AdminJS
{ 'test.id': '2' }
// پس از بازکردن ساختار
{ test: { id: '2' } }
```
**اثر:** بستن دکمه در UI تنها لایهٔ دفاعی نیست؛ خود مسیر ذخیره نیز محافظت می‌شود. حذف رمز از خواندن‌های چندرکوردی برای جست‌وجو و پرکردن روابط هم اهمیت دارد.
### فایل ۳: `src/modules/admin-panel/admin-panel.validation.ts`
**وظیفه:** ابزارهای مشترک تبدیل و اعتبارسنجی ورودی پنل را فراهم می‌کند.
**`panelValues`:**
- فقط فیلدهای معرفی‌شده در `PanelField` را قابل تغییر می‌داند.
- فیلد خارج از فهرست را رد می‌کند؛ اگر فیلد موجودی مثل شناسه یا تاریخ بدون تغییر همراه فرم برگشته باشد، آن را نادیده می‌گیرد.
- مقدار عددی را به عدد صحیح امن تبدیل می‌کند؛ مقدار اعشاری، نامتناهی یا خارج از محدودهٔ امن JavaScript رد می‌شود.
- مرجع عددی `{ id: '2' }` را نیز می‌شناسد.
- ورودی خالی مرجع عددی را به `null` تبدیل می‌کند؛ DTO و Provider تصمیم می‌گیرند این مقدار مجاز است یا نه.
- فقط `true`، `false`، `'true'` و `'false'` را برای فیلد بولی می‌پذیرد. بنابراین رشتهٔ `'false'` اشتباهاً به `true` تبدیل نمی‌شود.
- متن JSON را تجزیه می‌کند و JSON نامعتبر را رد می‌کند.
- نام فرم را به نام DTO نگاشت می‌کند؛ مثلاً `questionId` به `question`.
**`validatePanelDto`:**
- با `plainToInstance` از ورودی، DTO می‌سازد.
- `class-validator` را با `whitelist`، `forbidNonWhitelisted` و `forbidUnknownValues` اجرا می‌کند.
- خطاهای تودرتو را به خطاهای فیلدی AdminJS تبدیل می‌کند.
- نام فیلد خطا را به نام فرم برمی‌گرداند؛ مثلاً خطای `password` روی `newPassword` نمایش داده می‌شود.
- پیام‌های i18n را به فارسی ترجمه می‌کند. پیام خام i18n شامل JSON و مقدار ورودی است؛ مقدار ورودی حذف می‌شود و متن خام به مرورگر برنمی‌گردد.
**`redactPanelSecrets`:** پاسخ‌ها و روابط تودرتو را پیمایش می‌کند و `password`، `newPassword` و `confirmPassword` را حذف می‌کند. بخش `errors` نگه داشته می‌شود چون خطاها پیش‌تر به پیام‌های امن تبدیل شده‌اند و برای نمایش خطای فرم لازم‌اند.
### فایل ۴: `src/modules/admin-panel/admin-panel.resources.ts`
**وظیفه:** مرکز سیاست‌گذاری و اتصال منابع پنل به Serviceهای پروژه است.
**`authorize`:** قبل از اکشن، کاربر جاری را از دیتابیس می‌خواند. نقش داخل Session به‌تنهایی ملاک نیست. اگر حساب حذف شده یا نقش فعلی دیگر `ADMIN` یا `SUPERUSER` نباشد، درخواست رد می‌شود. کنترل‌های دسترسی بعدی از نقش تازه استفاده می‌کنند.
**`resource`:** برای هر Entity، فیلدهای قابل ویرایش، کنترل دسترسی اکشن‌ها، Hookهای بررسی نقش و حذف اطلاعات حساس را تعریف می‌کند. `bulkDelete` برای تمام منابع غیرفعال است.
**`protectTest`:** برای تغییر ساختار یا حذف، وضعیت آزمون را بررسی می‌کند. آزمون منتشرشده، آزمون دارای `structureLocked` یا آزمون دارای هر Submission پایدار از این عملیات محافظت می‌شود.
**`serialize`:** نوشتن‌های پنل را بین نمونه‌های برنامه با قفل مشورتی PostgreSQL هماهنگ می‌کند:
```sql
SELECT pg_try_advisory_lock(724091, 1) AS acquired;
```
این قفل به‌صورت غیرمنتظر عمل می‌کند. اگر نوشتن دیگری از پنل در حال اجرا باشد، درخواست جدید پیام تلاش مجدد می‌گیرد. پس از اتمام یا خطا، قفل در `finally` آزاد و اتصال QueryRunner رها می‌شود.
قفل روی یک Session دیتابیس نگه داشته می‌شود؛ Providerها همچنان Repositoryها و Transactionهای قبلی خود را استفاده می‌کنند. این طراحی نوشتن‌های پنل را پشت سر هم انجام می‌دهد، اما تمام فراخوانی‌های Provider را در یک Transaction جدید قرار نمی‌دهد و عملیات مستقیم SQL یا APIهای دیگر را قفل نمی‌کند.
**`catalog`:** منطق مشترک سؤال، گزینه، قوانین بازه، مسیرها و بازهٔ نتیجه است:
1. رکورد فعلی را هنگام ویرایش یا حذف می‌خواند.
2. دادهٔ فرم را تبدیل و فیلدهای مجاز را بررسی می‌کند.
3. در ویرایش، دادهٔ فعلی را با تغییرات ترکیب می‌کند.
4. جابه‌جایی رکورد به والد دیگر را رد می‌کند.
5. آزمون والد و قفل ساختار را بررسی می‌کند.
6. قواعد اضافی وابستگی را اجرا می‌کند.
7. برای ساخت و ویرایش، دادهٔ کامل را با DTO ساخت اعتبارسنجی می‌کند و به Service موجود می‌دهد.
8. برای حذف، به متد `deleteOne` همان Service مراجعه می‌کند.
**قواعد اضافی وابستگی:**
- گزینه فقط برای سؤال تک‌انتخابی یا چندانتخابی قابل تعریف است.
- قانون بازه فقط برای سؤال عددی قابل تعریف است.
- نوع سؤال دارای گزینه، قانون بازه یا مسیر ورودی/خروجی قابل تغییر نیست.
- گزینه‌ای که شناسه‌اش در شرط مسیر استفاده شده، قبل از اصلاح مسیر قابل حذف نیست؛ چون شناسه داخل JSON الزاماً با Foreign Key محافظت نمی‌شود.
**منبع آزمون:** ساخت از `CreateTestDTO` و ویرایش از دادهٔ کامل و سپس `UpdateTestDTO` عبور می‌کند. آزمون جدید باید پیش‌نویس باشد. فعال‌بودن برای آزمون منتشرنشده رد می‌شود. مبلغ عددی فرم به رشته تبدیل می‌شود و سقف `bigint` دیتابیس بررسی می‌شود. انتشار از `TestsService` و اعتبارسنج گراف موجود عبور می‌کند.
**منبع کاربر:** فقط نام، نام خانوادگی، رمز جدید و تأیید آن قابل تغییر است. رمز خالی به معنی عدم تغییر است. رمز و تأیید باید با هم وارد شوند. محدودیت ۷۲ بایت UTF-8 برای جلوگیری از قطع‌شدن ورودی bcrypt بررسی می‌شود. سپس `UpdateProfileDTO` و `UsersService.updateProfile` اجرا می‌شوند؛ هش‌کردن را همان `UserProfileProvider` انجام می‌دهد.
**فهرست منابع:** شش منبع کاتالوگ، یک منبع کاربر و پنج منبع فقط‌خواندنی سوابق ثبت می‌شوند. OTP در فهرست وجود ندارد.
**مدیریت خطا:** خطای اعتبارسنجی قابل نمایش نگه داشته می‌شود؛ خطاهای معمول HTTP ترجمه می‌شوند؛ خطاهای داخلی ذخیره‌سازی به پیام عمومی تبدیل می‌شوند تا جزئیات SQL و داده‌های داخلی وارد پاسخ پنل نشوند.
### فایل ۵: `src/modules/questions/helpers/validate-metadata.helper.ts`
**وظیفه:** براساس نوع سؤال، DTO مناسب metadata را انتخاب و اعتبارسنجی می‌کند؛ مثلاً `NumericMetadataDTO` برای سؤال عددی.
**تغییر:** نوع پارامتر `metadata` اکنون `null` و `undefined` را هم می‌پذیرد. تابع از قبل در نبود metadata آرایهٔ خطای خالی برمی‌گرداند؛ امضای TypeScript با این رفتار هماهنگ شد.
**اثر:** فراخوانی جدید Provider ساخت سؤال با metadata خالی بدون ناسازگاری نوع انجام می‌شود. این تغییر به‌تنهایی metadata را اجباری نمی‌کند و قاعدهٔ جدیدی برای حداقل، حداکثر یا گام عددی اضافه نکرده است.
### فایل ۶: `src/modules/questions/providers/questions-command.provider.ts`
**وظیفه:** ساخت، ویرایش و حذف سؤال و هماهنگی شمارندهٔ سؤال‌های آزمون.
**تغییر اول:** `createOne` مستقیماً `validateMetadata` را اجرا می‌کند. اگر نوع مشخص نشده باشد، نوع پیش‌فرض تک‌انتخابی در این بررسی لحاظ می‌شود. metadata نامعتبر قبل از ذخیره رد می‌شود.
**تغییر دوم:** تغییر آزمون والد در `updateOne` رد می‌شود. صرف معتبر بودن شناسهٔ آزمون مقصد کافی نبود؛ انتقال می‌توانست شمارنده‌ها و مسیرهای قبلی را ناسازگار کند.
**تغییر سوم:** فیلد DTO به نام `test` قبل از `Object.assign` کنار گذاشته می‌شود؛ شناسهٔ عددی نباید به‌عنوان شیء رابطه روی Entity نوشته شود.
**اثر:** پنل از Transaction موجود ساخت/حذف سؤال و افزایش/کاهش شمارنده استفاده می‌کند. قواعد جدید داخل همین Provider برای فراخوان‌های غیرپنلی آن نیز اجرا می‌شوند؛ اما قفل انتشار پنل داخل این Provider منتقل نشده است.
### فایل ۷: `src/modules/questions/providers/choices/choices-command.provider.ts`
**وظیفه:** ساخت، ویرایش و حذف گزینه و بررسی وجود سؤال و محدودیت ترتیب گزینه‌ها.
**قبل:** `Object.assign(choice, updateChoiceDto)` ممکن بود مقدار عددی `question` در DTO را مستقیماً روی رابطهٔ `choice.question` بگذارد، در حالی که Entity ستون صریح `questionId` هم دارد.
**تغییر:** فیلد `question` جدا می‌شود؛ سایر تغییرات اعمال می‌شوند و در صورت وجود شناسهٔ والد، هر دو مقدار زیر هماهنگ تنظیم می‌شوند:
```ts
choice.questionId = questionId;
choice.question = { id: questionId } as Question;
```
**اثر:** رابطه و Foreign Key هنگام ذخیره با یکدیگر سازگار می‌مانند. خود Provider همچنان انتقال به یک سؤال معتبر را پشتیبانی می‌کند؛ ممنوعیت جابه‌جایی در این مرحله، سیاست لایهٔ AdminJS است.
### فایل ۸: `src/modules/questions/providers/range-rule/question-range-rule-command.provider.ts`
**وظیفه:** مدیریت بازه‌های عددی و امتیاز مربوط به آن‌ها برای سؤال.
**مشکل قبلی:** هنگام ویرایش، منطق قدیمی فرض می‌کرد یکی از بازه‌های هم‌پوشان همان رکورد جاری است و یک هم‌پوشانی را مجاز می‌دانست. اگر بازه به جای دیگری منتقل می‌شد، تنها نتیجهٔ Query می‌توانست رکورد دیگری باشد و به‌اشتباه پذیرفته شود.
**تغییر:** پارامتر بولی `excludeSelf` به شناسهٔ دقیق `excludeId` تبدیل شد. Query رکورد جاری را با شرط `rule.id != :excludeId` کنار می‌گذارد؛ هر نتیجهٔ باقی‌مانده به معنی تداخل است.
همچنین در ذخیرهٔ ویرایش، `question` به شکل `{ id: questionId }` و ستون `questionId` به همان مقدار تنظیم می‌شوند.
**مثال:** اگر بازهٔ رکورد ۷ از `[0, 5]` به `[20, 30]` تغییر کند و رکورد ۹۹ از قبل `[25, 35]` باشد، ویرایش رد می‌شود؛ حتی اگر فقط همین یک هم‌پوشانی پیدا شود.
### فایل ۹: `src/modules/questions/providers/transition/question-transition-command.provider.ts`
**وظیفه:** ذخیرهٔ مسیرهای سؤال‌ها پس از اجرای `QuestionTransitionValidatorProvider` و مدیریت خطاهای محدودیت‌های دیتابیس.
**قبل:** شناسه‌های گزینه‌ها در شرط مسیر چندانتخابی هنگام ساخت مرتب می‌شدند، اما هنگام ویرایش این رفتار وجود نداشت.
**تغییر:** در `updateOne` نیز برای نوع `MULTI_CHOICE`، یک کپی از `choiceIds` ساخته و به صورت عددی مرتب می‌شود. در ساخت نیز نوع شیء شرط برای TypeScript صریح‌تر شده است.
**اثر:** ترتیب ذخیرهٔ یک مجموعهٔ یکسان در ساخت و ویرایش هماهنگ می‌شود؛ مثلاً `[8, 2, 5]` به `[2, 5, 8]` تبدیل می‌شود. بررسی تعلق گزینه‌ها به سؤال، نوع مسیر و سایر قواعد همچنان به Validator موجود سپرده می‌شود.
### فایل ۱۰: `src/modules/questions/validators/question-transition-type.validator.ts`
**وظیفه:** بررسی شکل معتبر هر نوع مسیر، مانند START، END، تک‌انتخابی، چندانتخابی و بازهٔ عددی.
**قبل:** در مسیر تک‌انتخابی، خواندن مستقیم `conditionValue.choiceId` در نبود شرط می‌توانست `TypeError` ایجاد کند و به‌جای خطای ورودی، خطای داخلی بدهد.
**تغییر:** خواندن `choiceId` با optional chaining انجام می‌شود. نبود شرط به `undefined` می‌رسد و همان بررسی نوع موجود، خطای اعتبارسنجی مناسب می‌دهد.
**اثر:** ورودی ناقص به‌صورت کنترل‌شده رد می‌شود؛ معتبر بودن گزینه یا تعلق آن به سؤال همچنان جداگانه بررسی می‌شود.
### فایل ۱۱: `src/modules/scoring/providers/result-range-command.provider.ts`
**وظیفه:** مدیریت بازه‌های امتیازی که عنوان و توضیح نتیجهٔ آزمون را تعیین می‌کنند.
**تغییر اول:** مشابه قوانین بازهٔ سؤال، رکورد ویرایش‌شده با شناسه از بررسی هم‌پوشانی خارج می‌شود؛ وجود یک رکورد متداخل دیگر هم برای رد عملیات کافی است.
**تغییر دوم:** شرط هم‌پوشانی ساده و گروه‌بندی شد:
```text
existing.minScore <= new.maxScore
AND
existing.maxScore >= new.minScore
```
این شرط زیر فیلتر آزمون قرار دارد. عبارت OR قبلی بدون گروه‌بندی کامل می‌توانست به‌علت تقدم AND و OR، بخشی از شرط‌ها را خارج از فیلتر آزمون اعمال کند.
**تغییر سوم:** رابطهٔ `test` و ستون `testId` با هم تنظیم می‌شوند.
**نکته:** دو بازه با مرز مشترک، مثل `[0, 10]` و `[10, 20]`، همچنان متداخل محسوب می‌شوند. معنی مرزهای بسته در این اصلاح عوض نشده است.
### فایل ۱۲: `src/modules/tests/entities/test.entity.ts`
**وظیفه:** تعریف ساختار Entity آزمون در TypeORM.
**تغییر:** ستون بولی زیر با پیش‌فرض `false` اضافه شده است:
```ts
@Column({ type: 'boolean', default: false })
structureLocked!: boolean;
```
**اثر:** قفل ساختار مستقل از وضعیت فعلی انتشار ذخیره می‌شود. اگر آزمونی منتشر و بعد دوباره پیش‌نویس شود، سابقهٔ قفل از بین نمی‌رود.
**علت:** پروژه Snapshot یا نسخهٔ جداگانه برای ساختار هر نوبت پاسخ ندارد. جلسه‌های مهمان نیز در Redis هستند و الزاماً Submission دیتابیسی ندارند. بازکردن ساختار صرفاً با تغییر وضعیت، می‌توانست جلسهٔ جاری یا تفسیر سوابق را خراب کند.
**محدودیت:** این ستون به‌تنهایی یک محدودیت یا Trigger دیتابیس برای جلوگیری از تغییر سؤال‌ها نیست؛ تصمیم جلوگیری از تغییر را لایهٔ پنل می‌گیرد.
### فایل ۱۳: `src/modules/tests/providers/tests-command.provider.ts`
**وظیفه:** ساخت، ویرایش، حذف و انتشار آزمون.
**قیمت:** تفاوت بین `undefined` و `null` حفظ شد. `undefined` یعنی قیمت ارسال نشده و مقدار قبلی بماند؛ `null` یعنی حذف صریح قیمت. استفادهٔ قبلی از `??` این دو را یکسان می‌کرد.
**سازگاری قیمت و نوع دسترسی:** بررسی اکنون بر نبود/وجود مقدار استوار است، نه صرف truthy بودن مقدار. آزمون پولی باید قیمت داشته باشد و آزمون غیرپولی نباید قیمت داشته باشد. این تغییر به‌خودی‌خود شرط «قیمت حتماً بزرگ‌تر از صفر باشد» اضافه نمی‌کند.
**انتشار:** پس از ترکیب تغییرات، اگر وضعیت حاصل `PUBLISHED` باشد، اعتبارسنج انتشار اجرا می‌شود؛ حتی وقتی فیلد `status` در درخواست جدید ارسال نشده باشد.
**قفل:** پس از موفقیت اعتبارسنج انتشار، `structureLocked = true` همراه آزمون ذخیره می‌شود. مسیر عادی ویرایش، آن را هنگام پیش‌نویس‌شدن دوباره `false` نمی‌کند.
**اثر:** انتشار همچنان از اعتبارسنج گراف موجود استفاده می‌کند؛ شامل قواعد START، دسترسی‌پذیری سؤال‌ها، چرخه‌ها، رسیدن مسیرها به پایان و قواعد مسیرهای چندانتخابی.
### فایل ۱۴: `src/migrations/1794182400000-LockPublishedTestStructure.ts`
**وظیفه:** هماهنگ‌کردن Schema واقعی PostgreSQL با ستون جدید Entity.
**`up`:**
1. ستون `structureLocked` را با `NOT NULL DEFAULT false` اضافه می‌کند.
2. برای آزمون‌های فعلاً منتشرشده، مقدار را `true` می‌کند.
3. برای آزمون‌هایی که هر Submission دیتابیسی دارند نیز مقدار را `true` می‌کند.
**`down`:** ستون را حذف می‌کند؛ این کار سابقهٔ قفل ذخیره‌شده را نیز از بین می‌برد.
**محدودیت تشخیص گذشته:** اگر آزمونی قبلاً منتشر شده ولی اکنون پیش‌نویس است، Submission پایدار ندارد و هیچ سابقهٔ انتشار دیگری ذخیره نشده است، migration نمی‌تواند انتشار گذشته را حدس بزند. در صورت وجود چنین آزمون‌هایی باید وضعیت حفظ ساختارشان پیش از اجازهٔ ویرایش تعیین شود.
**وضعیت اجرا:** این migration در جریان اصلاحات به‌صورت خودکار روی دیتابیس اجرا نشده است.
### فایل ۱۵: `src/modules/admin-panel/admin-panel.resources.spec.ts`
**وظیفه:** ۱۵ تست برای مسیر منابع و سیاست‌های پنل.
تست‌ها Metadata واقعی TypeORM را بدون اتصال دیتابیس می‌سازند و یک AdminJS واقعی با منابع جدید ایجاد می‌کنند. فراخوانی‌های دیتابیس و Serviceها Mock هستند.
پوشش تست‌ها:
- نبود منبع تکراری و نبود OTP در پنل؛
- تبدیل عدد، بولی و JSON و ارجاع به Provider؛
- رد DTO نامعتبر و جعل فیلد سیستمی؛
- رد نوشتن هم‌زمان در صورت اشغال قفل؛
- تبدیل مرجع `test.id` و انتهای خالی مسیر؛
- قفل آزمون منتشرشده و حفظ قفل پس از خروج از انتشار؛
- حفاظت آزمون دارای Submission و جلوگیری از حذف آبشاری از پنل؛
- رد انتقال سؤال بین آزمون‌ها؛
- فقط‌خواندنی بودن سوابق و رد ساخت/حذف کاربر؛
- عبور تغییر رمز از مسیر پروفایل؛
- بررسی نقش فعلی دیتابیس به‌جای نقش Session؛
- حذف رمز از پاسخ تودرتو و خطای فرم؛
- جلوگیری از افشای رمز در پیام خام i18n؛
- تبدیل صحیح `'false'` و رد اعداد نامناسب.
تست تغییر رمز، فراخوانی مسیر پروفایل را بررسی می‌کند؛ اجرای واقعی bcrypt یا ابطال همهٔ Sessionها را اثبات نمی‌کند. تست قفل نیز نتیجهٔ Mock را بررسی می‌کند، نه زمان‌بندی واقعی PostgreSQL.
### فایل ۱۶: `src/modules/admin-panel/admin-panel.ranges.spec.ts`
**وظیفه:** تست مشترک برای Provider بازهٔ نتیجه و Provider قانون بازهٔ سؤال.
دو سناریو برای هر Provider اجرا می‌شود؛ در مجموع ۴ تست:
1. پس از جابه‌جایی بازه، حتی یک رکورد دیگر با هم‌پوشانی باید موجب خطا شود؛ شناسهٔ جاری نیز باید صریحاً از Query کنار گذاشته شود.
2. ویرایش بدون هم‌پوشانی باید ذخیره شود و شیء رابطه و Foreign Key با هم سازگار بمانند.
این تست‌ها Provider واقعی را با Repository و QueryBuilder شبیه‌سازی‌شده اجرا می‌کنند؛ اجرای SQL روی PostgreSQL واقعی نیستند.
## ۴. کدام قواعد بازاستفاده شدند و کدام‌ها جدیدند؟
| قاعده | محل اجرا | منشأ |
|---|---|---|
| شکل و نوع فیلدهای DTO | `validatePanelDto` و DTOهای موجود | بازاستفاده |
| اعتبارسنجی انتشار و گراف آزمون | `TestsService` و Provider انتشار | بازاستفاده |
| اعتبارسنجی metadata سؤال | Helper و DTOهای metadata | بازاستفاده؛ فراخوانی در ساخت Provider اضافه شد |
| شمارندهٔ سؤال در ساخت/حذف | Transactionهای QuestionsCommandProvider | بازاستفاده |
| وجود والد و محدودیت‌های ترتیب | Providerهای موجود | بازاستفاده |
| نوع مسیر، تعلق گزینه و محدودیت START/END | Providerها و Validatorهای مسیر | بازاستفاده |
| هم‌پوشانی بازه‌ها | دو Command Provider بازه | بازاستفاده همراه اصلاح خطا |
| سیاست رمز و هش‌کردن | UpdateProfileDTO و UserProfileProvider | بازاستفاده |
| قفل دائمی ساختار پس از انتشار | Entity، Provider آزمون و پنل | جدید |
| محدودیت نقش و محافظت از سوابق در پنل | `admin-panel.resources.ts` | جدید |
| هماهنگی هم‌زمانی نوشتن‌های پنل | قفل مشورتی PostgreSQL | جدید |
| حذف رازها از پاسخ و خطای فرم | Resource و Validation helper | جدید |
## ۵. مجوزهای نهایی پنل
| منبع/عملیات | ADMIN | SUPERUSER |
|---|---|---|
| مشاهدهٔ کاتالوگ آزمون و اجزای آن | مجاز | مجاز |
| ساخت/ویرایش/حذف اجزای پیش‌نویس بدون سابقه و قفل | با اعتبارسنجی | با اعتبارسنجی |
| تغییر ساختار یا حذف آزمون قفل‌شده/دارای سابقه | ممنوع | ممنوع |
| تغییر اطلاعات عمومی، وضعیت و فعال‌بودن آزمون | با اعتبارسنجی | با اعتبارسنجی |
| مشاهدهٔ کاربران | ممنوع | مجاز |
| تغییر نام و رمز کاربران | ممنوع | با اعتبارسنجی |
| تغییر شماره تلفن یا نقش از پنل | ممنوع | ممنوع |
| ساخت و حذف مستقیم حساب | ممنوع | ممنوع |
| مشاهدهٔ پاسخ‌ها، نتایج و مکالمه‌ها | ممنوع | مجاز |
| ویرایش/حذف پاسخ‌ها، نتایج و مکالمه‌ها | ممنوع | ممنوع |
| حذف گروهی | ممنوع | ممنوع |
| دسترسی به OTP از منابع پنل | منبع ثبت نشده | منبع ثبت نشده |
## ۶. محدودهٔ تضمین‌ها و محدودیت‌ها
- کنترل قفل ساختار و کنترل هم‌زمانی فعلاً متعلق به مسیر AdminJS هستند؛ تمام Command Providerها این سیاست را مستقلاً اجرا نمی‌کنند.
- قفل مشورتی همهٔ نوشتن‌های پنل را هماهنگ می‌کند، حتی اگر روی دو آزمون متفاوت باشند. درخواست دوم باید دوباره تلاش کند.
- نوشتن مستقیم SQL، ابزارهای دیتابیس یا مسیر API مستقل، خودکار تحت این قفل نیستند.
- اگر `AdminModule` فعلاً غیرفعال بعداً فعال شود، باید سیاست حفاظت ساختار و هم‌زمانی به مسیرهای آن هم اعمال شود.
- اصلاح Query هم‌پوشانی، به‌تنهایی جای محدودیت دیتابیسی برای رقابت تمام نویسنده‌های ممکن را نمی‌گیرد.
- قفل انتشار Snapshot نمی‌سازد. عنوان و توضیح عمومی آزمون همچنان قابل تغییرند؛ این تغییر نسخه‌بندی کامل تاریخچه نیست.
- تغییر رمز از رفتار فعلی پروفایل استفاده می‌کند و ابطال سراسری access token، refresh token و Sessionهای قبلی به این مرحله اضافه نشده است.
- وجود ساختار خراب در داده‌های قدیمی به‌صورت خودکار اصلاح نشده است. ذخیرهٔ بعدی ممکن است به‌درستی با خطای اعتبارسنجی متوقف شود.
- هیچ پاسخ، نتیجه یا مکالمهٔ موجود در این اصلاح به‌صورت خودکار حذف یا بازنویسی نشده است.
## ۷. نصب، استقرار و بررسی
برای محیط توسعه، پیش از اجرای برنامه با Schema جدید:
```bash
npm run migration:run:dev
```
برای تولید، ابتدا خروجی نسخهٔ جدید را بسازید و سپس migration را روی دیتابیس مقصد اجرا کنید؛ پیش از سرویس‌دهی نسخهٔ جدید باید ستون وجود داشته باشد:
```bash
npm run build
npm run migration:run:prod
```
ساخت برنامه به‌تنهایی migration را اجرا نمی‌کند.
فرمان‌های بررسی کد و تست:
```bash
npx tsc --noEmit --incremental false
npm test -- --runInBand
```
در آخرین بررسی اجرای اصلاحات، TypeScript و ESLint فایل‌های تغییرکرده موفق بودند. ۴ مجموعه تست و مجموعاً ۲۹ تست موفق شدند: ۱۹ تست جدید این مرحله و ۱۰ تست قبلی OTP و refresh token.
بررسی‌های انجام‌نشده شامل اجرای migration روی دیتابیس زنده، رفتار واقعی قفل در PostgreSQL، تست بار و بررسی رابط پنل در مرورگر است. پس از استقرار، ساخت پیش‌نویس، تعریف سؤال و مسیر، انتشار، تغییر رمز و رد ویرایش ساختار قفل‌شده باید در محیط مقصد بررسی شوند.
## ۸. فایل‌های مستندات
`docs/admin-panel-integrity.md` خلاصهٔ انگلیسی معماری، مجوزها، محدودیت‌ها و استقرار را نگه می‌دارد. فایل حاضر، `docs/admin-panel-integrity.fa.md`، توضیح فارسی فایل‌به‌فایل همین تغییرات است. این دو فایل در رفتار اجرایی برنامه نقشی ندارند.
+89
View File
@@ -0,0 +1,89 @@
# AdminJS data integrity
مستند دقیق فارسی و توضیح فایل‌به‌فایل: [admin-panel-integrity.fa.md](admin-panel-integrity.fa.md).
## Write path
AdminJS uses an explicit resource list in `admin-panel.resources.ts`. Every resource
uses `AdminPanelResource`; its create/update/delete methods never call the raw
TypeORM adapter. Catalog writes are normalized, validated with the existing create
DTO (merged with the current record on edit), then delegated to the existing
TestsService, QuestionsService, ChoicesService, QuestionRangeRuleService,
QuestionTransitionService or ResultRangeService. Their command/query/validation
providers remain responsible for business rules and persistence.
The panel converts numeric references and booleans explicitly (`"false"` remains
false), parses JSON fields, rejects unexpected fields, checks integer bounds and
retains the TypeORM-generated `test.id` reference for transitions. Read-only values
sent back unchanged by an edit form are accepted; attempts to change them fail.
## Permissions and sensitive records
- ADMIN and SUPERUSER can manage draft catalog records.
- User accounts are visible/editable only to SUPERUSER. The panel can change
first/last name and an explicitly confirmed new password through UsersService
and UserProfileProvider. Password policy is reused and bcrypt input is capped at
72 UTF-8 bytes. Phone and role cannot be changed here. Account creation/deletion
requires a separate workflow and is disabled in this panel.
- Submissions, answers, results, conversations and messages are read-only and
visible only to SUPERUSER. Bulk deletion is disabled for every resource.
- OTP is not registered. New entity classes are not automatically exposed.
- The actor's role is reloaded from the database before every resource action;
a role stored in an old admin session does not retain revoked privileges.
- Password hashes are removed from adapter reads and response payloads, including
populated references. New-password/confirmation values are scrubbed from form
responses. i18n validation messages are rendered without returning their raw
JSON payload, which otherwise contains the submitted value.
## Published structure and history
Question/choice/range/transition writes and catalog deletions are refused once the
test is published, permanently structure-locked, or has any persisted submission.
Publishing sets `Test.structureLocked`; unpublishing does not clear it. This also
protects guest sessions that do not have a persisted Submission row. To change
structure, create a new test. Normal test metadata/status/activation changes remain
available, with publication validation reused; only published tests may be active.
The migration marks currently published tests and tests with submissions as locked.
Previously published tests that are already drafts, have no persisted submissions,
and have no stored publication history cannot be identified retrospectively. If
such tests exist and must be preserved, lock them before allowing panel edits.
Moving child records between parents is blocked. Changing question type while it
has choices, range rules or transitions is blocked. Deleting a choice referenced
by a transition condition is blocked. This avoids dangling references inside JSON.
Panel writes across instances use one PostgreSQL session advisory lock. Acquisition
is nonblocking: a simultaneous panel write is rejected with a retry message instead
of filling the connection pool with lock waiters. Providers keep their existing
transactions. This is serialization, not a new transaction around all providers;
it does not serialize direct SQL or other API write paths. If the currently disabled
AdminModule is enabled later, apply the same structure/locking policy there too.
## Shared provider fixes
- Range-overlap updates exclude the edited ID explicitly instead of allowing one
overlap. Scoring overlap SQL is grouped under the test filter.
- Relationship updates persist proper relation objects and FK columns. Question
movement between tests is rejected so counts/transitions cannot silently drift.
- Question creation also runs metadata validation in its command provider.
- Single-choice transition validation rejects missing conditions cleanly;
multi-choice IDs are sorted on update as well as creation.
- Test updates preserve an explicit null price and validate the resulting published
state. The existing publication graph validator is reused.
No existing history is deleted or rewritten. Password changes follow the existing
profile behavior; this change does not add global token/session revocation.
## Deployment and verification
Build the new application and run `npm run migration:run:prod` before serving it
(development: `npm run migration:run:dev`). The migration is
`1794182400000-LockPublishedTestStructure.ts`. It has not been run automatically.
Tests build real TypeORM metadata and real AdminJS resource configuration without
database connections. Provider calls and database operations are mocked. They cover
DTO conversion/validation, permission refresh, immutable records, secret redaction,
generated references, lock contention and range-update regressions. Browser UI,
live PostgreSQL advisory-lock behavior and migration execution still require a
deployment smoke test.
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class LockPublishedTestStructure1794182400000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "test" ADD "structureLocked" boolean NOT NULL DEFAULT false`,
);
await queryRunner.query(`UPDATE "test" SET "structureLocked" = true
WHERE "status" = 'published' OR EXISTS (
SELECT 1 FROM "submission" WHERE "submission"."testId" = "test"."id"
)`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "test" DROP COLUMN "structureLocked"`);
}
}
@@ -0,0 +1,76 @@
import { describe, expect, it, jest } from '@jest/globals';
import { Repository } from 'typeorm';
import { I18nService } from 'nestjs-i18n';
import { TestsService } from '@/modules/tests/providers/tests.service';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { ResultRangeCommandProvider } from '@/modules/scoring/providers/result-range-command.provider';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionRangeRuleCommandProvider } from '@/modules/questions/providers/range-rule/question-range-rule-command.provider';
describe.each(['result', 'question'] as const)('%s range updates', (kind) => {
function setup(overlaps: unknown[]) {
const andWhere = jest.fn<(...args: unknown[]) => unknown>();
const builder = {
where: jest.fn<(...args: unknown[]) => unknown>(),
andWhere,
getMany: jest.fn<() => Promise<unknown[]>>().mockResolvedValue(overlaps),
};
builder.where.mockReturnValue(builder);
andWhere.mockReturnValue(builder);
const save = jest
.fn<(value: unknown) => Promise<unknown>>()
.mockImplementation((value) => Promise.resolve(value));
const repository = {
createQueryBuilder: () => builder,
findOne: () =>
Promise.resolve({
id: 7,
test: { id: 2 },
question: { id: 3 },
minScore: 0,
maxScore: 5,
min: 0,
max: 5,
}),
save,
};
const update =
kind === 'result'
? () =>
new ResultRangeCommandProvider(
repository as unknown as Repository<ResultRange>,
{} as TestsService,
{} as I18nService,
).updateOne(7, { minScore: 20, maxScore: 30 })
: () =>
new QuestionRangeRuleCommandProvider(
repository as unknown as Repository<QuestionRangeRule>,
{} as Repository<Question>,
{} as I18nService,
).updateOne(7, { min: 20, max: 30 });
return { update, andWhere, save };
}
it('rejects even one overlapping different record after moving a range', async () => {
const { update, andWhere, save } = setup([{ id: 99 }]);
await expect(update()).rejects.toThrow();
expect(andWhere).toHaveBeenCalledWith(
expect.stringContaining('id != :excludeId'),
{ excludeId: 7 },
);
expect(save).not.toHaveBeenCalled();
});
it('allows non-overlapping edits and preserves entity relations', async () => {
const { update, save } = setup([]);
await update();
expect(save).toHaveBeenCalledWith(
expect.objectContaining(
kind === 'result'
? { test: { id: 2 }, testId: 2, minScore: 20, maxScore: 30 }
: { question: { id: 3 }, questionId: 3, min: 20, max: 30 },
),
);
});
});
@@ -0,0 +1,103 @@
import { Resource } from '@adminjs/typeorm';
import { BaseRecord, Filter, ValidationError, flat } from 'adminjs';
import { BaseEntity } from 'typeorm';
export type PanelWrite = (
operation: 'new' | 'edit' | 'delete',
params: Record<string, unknown>,
id?: number,
) => Promise<Record<string, unknown>>;
/** No AdminJS write is allowed to fall back to the raw TypeORM adapter. */
export class AdminPanelResource extends Resource {
constructor(
model: typeof BaseEntity,
private readonly write?: PanelWrite,
) {
super(model);
}
private async persist(
operation: 'new' | 'edit' | 'delete',
params: Record<string, unknown>,
id?: string | number,
) {
if (!this.write)
throw new ValidationError({}, { message: 'این منبع فقط خواندنی است.' });
if (
id !== undefined &&
(!Number.isSafeInteger(Number(id)) || Number(id) < 1)
) {
throw new ValidationError({}, { message: 'شناسه نامعتبر است.' });
}
if (
Object.keys(params).some((key) =>
key
.split('.')
.some((part) =>
['__proto__', 'prototype', 'constructor'].includes(part),
),
)
) {
throw new ValidationError({}, { message: 'فیلد نامعتبر است.' });
}
const unflatten = (
flat as unknown as {
unflatten: (input: Record<string, unknown>) => Record<string, unknown>;
}
).unflatten;
return this.write(
operation,
unflatten(params),
id === undefined ? undefined : Number(id),
);
}
override create(params: Record<string, unknown>) {
return this.persist('new', params);
}
override update(id: string | number, params: Record<string, unknown> = {}) {
return this.persist('edit', params, id);
}
override delete(id: string | number) {
return this.persist('delete', {}, id);
}
// Visibility settings only affect the UI. Remove credentials from the
// actual records too, including reference-population and search responses.
private redact(record: BaseRecord | null) {
if (record) {
delete record.params.password;
for (const key of ['metadata', 'condition']) {
const value: unknown = record.get(key);
if (value && typeof value === 'object') {
Object.keys(record.params)
.filter((path) => path === key || path.startsWith(`${key}.`))
.forEach((path) => {
delete record.params[path];
});
record.params[key] = JSON.stringify(value);
}
}
}
return record;
}
override async findOne(id: string | number) {
return this.redact(await super.findOne(id));
}
override async find(filter: Filter, params: unknown) {
const records = await super.find(filter, params);
records.forEach((record) => this.redact(record));
return records;
}
override async findMany(ids: Array<string | number>) {
const records = await super.findMany(ids);
records.forEach((record) => this.redact(record));
return records;
}
}
@@ -0,0 +1,371 @@
import {
beforeAll,
beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals';
import AdminJS, {
ActionContext,
ActionRequest,
ResourceWithOptions,
} from 'adminjs';
import { INestApplication } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { I18nService } from 'nestjs-i18n';
import { Role } from '@/common/enums/roles.enum';
import { User } from '@/modules/users/entities/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
import { Test } from '@/modules/tests/entities/test.entity';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { Submission } from '@/modules/submissions/entities/submission.entity';
import { SubmissionAnswer } from '@/modules/submissions/entities/submission-answer.entity';
import { SubmissionResult } from '@/modules/submissions/entities/submission-result.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { Message } from '@/modules/conversation/entities/message.entity';
import { buildAdminPanelResources } from './admin-panel.resources';
import { AdminPanelResource } from './admin-panel.resource';
import { panelValues, redactPanelSecrets } from './admin-panel.validation';
describe('AdminJS validated resources', () => {
const database = new DataSource({
type: 'postgres',
entities: [
User,
Test,
Question,
Choice,
QuestionRangeRule,
QuestionTransition,
ResultRange,
Submission,
SubmissionAnswer,
SubmissionResult,
Conversation,
Message,
],
});
let definitions: ResourceWithOptions[];
let query: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
let commands: {
createOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
updateOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
deleteOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
};
let users: {
findOneById: jest.Mock<UsersService['findOneById']>;
updateProfile: jest.Mock<UsersService['updateProfile']>;
};
const resource = (name: string) =>
definitions.find(
({ resource: entry }) => (entry as AdminPanelResource).id() === name,
)!.resource as AdminPanelResource;
beforeAll(async () => {
// Build real TypeORM relation metadata without connecting to a database.
await (
database as unknown as { buildMetadatas(): Promise<void> }
).buildMetadatas();
});
beforeEach(() => {
jest.restoreAllMocks();
commands = {
createOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue({ data: { id: 11 } }),
updateOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue({ id: 11 }),
deleteOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue(undefined),
};
users = {
findOneById: jest.fn<UsersService['findOneById']>().mockResolvedValue(
Object.assign(new User(), {
id: 1,
phone: '09121111111',
role: Role.USER,
password: 'secret-hash',
}),
),
updateProfile: jest
.fn<UsersService['updateProfile']>()
.mockResolvedValue({ message: 'updated' }),
};
query = jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue([{ acquired: true }]);
jest.spyOn(database, 'createQueryRunner').mockReturnValue({
connect: () => Promise.resolve(undefined),
query,
release: () => Promise.resolve(undefined),
} as unknown as ReturnType<DataSource['createQueryRunner']>);
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), { id: 2, status: TestStatus.IN_PROGRESS }),
);
jest
.spyOn(database.getRepository(Submission), 'existsBy')
.mockResolvedValue(false);
jest
.spyOn(database.getRepository(Question), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Question(), {
id: 11,
testId: 2,
type: QuestionType.SINGLE_CHOICE,
content: 'Question',
weight: 1,
required: true,
metadata: null,
}),
);
const app = {
get: (token: unknown) =>
token === DataSource
? database
: token === UsersService
? users
: token === I18nService
? { translate: (message: string) => message }
: commands,
} as unknown as INestApplication;
definitions = buildAdminPanelResources(app);
});
it('builds the real AdminJS schema without duplicates or an OTP resource', () => {
const admin = new AdminJS({ resources: definitions });
const ids = admin.resources.map((entry) => entry.id());
expect(new Set(ids).size).toBe(ids.length);
expect(ids).not.toContain('OTP');
expect(
resource('QuestionTransition')
.properties()
.map((property) => property.path()),
).toContain('test.id');
});
it('validates and converts form values before using the question provider', async () => {
await resource('Question').create({
testId: '2',
content: 'New question',
type: QuestionType.SINGLE_CHOICE,
required: 'false',
weight: '2',
metadata: '{"allowOther":false}',
});
expect(commands.createOne).toHaveBeenCalledWith(
expect.objectContaining({
test: 2,
required: false,
weight: 2,
metadata: { allowOther: false },
}),
);
expect(query.mock.calls.map(([sql]) => sql)).toEqual([
'SELECT pg_try_advisory_lock(724091, 1) AS acquired',
'SELECT pg_advisory_unlock(724091, 1)',
]);
});
it('rejects invalid DTOs and forged system fields without calling providers', async () => {
await expect(
resource('Question').create({ testId: 2, content: '' }),
).rejects.toThrow();
await expect(
resource('Test').create({
title: 'Test',
description: 'Description',
questionsCount: 999,
}),
).rejects.toThrow();
expect(commands.createOne).not.toHaveBeenCalled();
});
it('rejects concurrent panel writes without waiting and holding the connection pool', async () => {
query.mockResolvedValue([{ acquired: false }]);
await expect(
resource('Question').create({ testId: 2, content: 'Question' }),
).rejects.toThrow();
expect(commands.createOne).not.toHaveBeenCalled();
expect(query).toHaveBeenCalledTimes(1);
});
it('converts the generated test.id reference and null transition endpoints', async () => {
await resource('QuestionTransition').create({
'test.id': '2',
fromQuestionId: '',
toQuestionId: '11',
type: 'start',
condition: '',
});
expect(commands.createOne).toHaveBeenCalledWith(
expect.objectContaining({
test: 2,
fromQuestion: null,
toQuestion: 11,
conditionValue: null,
}),
);
});
it('blocks structural changes to published tests', async () => {
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), { id: 2, status: TestStatus.PUBLISHED }),
);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('keeps previously published structure locked even after unpublishing', async () => {
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), {
id: 2,
status: TestStatus.IN_PROGRESS,
structureLocked: true,
}),
);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('blocks structural changes and cascaded deletion when a test has submissions', async () => {
jest
.spyOn(database.getRepository(Submission), 'existsBy')
.mockResolvedValue(true);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
await expect(resource('Test').delete(2)).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
expect(commands.deleteOne).not.toHaveBeenCalled();
});
it('rejects moving questions between tests', async () => {
await expect(
resource('Question').update(11, { testId: 3 }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('disables direct writes to history, conversations and users creation/deletion', async () => {
for (const name of [
'Submission',
'SubmissionAnswer',
'SubmissionResult',
'Conversation',
'Message',
]) {
await expect(resource(name).update(1, {})).rejects.toThrow();
await expect(resource(name).delete(1)).rejects.toThrow();
}
await expect(resource('User').create({})).rejects.toThrow();
await expect(resource('User').delete(1)).rejects.toThrow();
});
it('routes password changes through profile validation and hashing provider path', async () => {
const result = await resource('User').update(1, {
newPassword: 'StrongPass1!',
confirmPassword: 'StrongPass1!',
});
expect(users.updateProfile).toHaveBeenCalledWith(
expect.objectContaining({ id: 1 }),
expect.objectContaining({
password: 'StrongPass1!',
confirmPassword: 'StrongPass1!',
}),
);
expect(result).not.toHaveProperty('password');
await expect(
resource('User').update(1, { role: Role.SUPERUSER }),
).rejects.toThrow();
await expect(
resource('User').update(1, { newPassword: 'StrongPass1!' }),
).rejects.toThrow();
});
it('rechecks the current database role instead of trusting the session', async () => {
jest
.spyOn(database.getRepository(User), 'findOneBy')
.mockResolvedValue(Object.assign(new User(), { id: 1, role: Role.USER }));
const action = definitions.find(
({ resource: entry }) => (entry as AdminPanelResource).id() === 'Test',
)!.options.actions!.list!;
const context = {
currentAdmin: { id: '1', role: Role.SUPERUSER },
} as unknown as ActionContext;
const before = action.before as (
request: ActionRequest,
context: ActionContext,
) => Promise<ActionRequest>;
await expect(
before(
{ method: 'get', params: { resourceId: 'Test', action: 'list' } },
context,
),
).rejects.toThrow();
});
it('does not leak secrets through nested or failed-form responses', () => {
const response = {
record: {
params: {
password: 'hash',
newPassword: 'plain',
confirmPassword: 'plain',
firstName: 'Name',
},
populated: { user: { params: { password: 'hash' } } },
},
};
redactPanelSecrets(response);
expect(JSON.stringify(response)).not.toMatch(/hash|plain/);
expect(response.record.params.firstName).toBe('Name');
});
it('does not leak submitted passwords through i18n validation errors', async () => {
try {
await resource('User').update(1, {
newPassword: 'secret',
confirmPassword: 'secret',
});
throw new Error('Expected validation failure');
} catch (error) {
expect(error).toHaveProperty('propertyErrors.newPassword');
expect(JSON.stringify(error)).not.toContain('secret');
}
expect(users.updateProfile).not.toHaveBeenCalled();
});
it('rejects false-like boolean coercion and unsafe numeric values', () => {
expect(
panelValues([{ name: 'required', kind: 'boolean' }], {
required: 'false',
}),
).toEqual({ required: false });
expect(() =>
panelValues([{ name: 'weight', kind: 'number' }], { weight: '1.5' }),
).toThrow();
expect(() =>
panelValues([{ name: 'required', kind: 'boolean' }], { required: 'no' }),
).toThrow();
});
});
@@ -0,0 +1,553 @@
import { HttpException, INestApplication } from '@nestjs/common';
import { BaseEntity, DataSource } from 'typeorm';
import { ClassConstructor } from 'class-transformer';
import {
ActionContext,
ActionRequest,
ActionResponse,
ForbiddenError,
ResourceWithOptions,
ValidationError,
} from 'adminjs';
import { I18nService } from 'nestjs-i18n';
import { Role } from '@/common/enums/roles.enum';
import { User } from '@/modules/users/entities/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
import { UpdateProfileDTO } from '@/modules/users/dtos/update-profile.dto';
import { Test } from '@/modules/tests/entities/test.entity';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { TestsService } from '@/modules/tests/providers/tests.service';
import { CreateTestDTO } from '@/modules/tests/dtos/create-test.dto';
import { UpdateTestDTO } from '@/modules/tests/dtos/update-test.dto';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { QuestionsService } from '@/modules/questions/providers/questions.service';
import { ChoicesService } from '@/modules/questions/providers/choices/choices.service';
import { QuestionRangeRuleService } from '@/modules/questions/providers/range-rule/question-range-rule.service';
import { QuestionTransitionService } from '@/modules/questions/providers/transition/question-transition.service';
import { CreateQuestionDTO } from '@/modules/questions/dtos/create-question.dto';
import { CreateChoiceDTO } from '@/modules/questions/dtos/create-choice.dto';
import { CreateQuestionRangeRuleDTO } from '@/modules/questions/dtos/create-question-range-rule.dto';
import { CreateQuestionTransitionDTO } from '@/modules/questions/dtos/create-question-transition.dto';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { ResultRangeService } from '@/modules/scoring/providers/result-range.service';
import { CreateResultRangeDTO } from '@/modules/scoring/dtos/create-result-range.dto';
import { Submission } from '@/modules/submissions/entities/submission.entity';
import { SubmissionAnswer } from '@/modules/submissions/entities/submission-answer.entity';
import { SubmissionResult } from '@/modules/submissions/entities/submission-result.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { Message } from '@/modules/conversation/entities/message.entity';
import { AdminPanelResource, PanelWrite } from './admin-panel.resource';
import {
panelValues,
PanelField,
redactPanelSecrets,
validatePanelDto,
} from './admin-panel.validation';
const field = (
name: string,
kind?: PanelField['kind'],
dto?: string,
): PanelField => ({ name, kind, dto });
const reject = (message: string): never => {
throw new ValidationError({}, { message });
};
export function buildAdminPanelResources(
app: INestApplication,
): ResourceWithOptions[] {
const database = app.get(DataSource);
const users = app.get(UsersService);
const i18n: I18nService = app.get(I18nService);
const authorize = async (request: ActionRequest, context: ActionContext) => {
const id = Number(context.currentAdmin?.id);
const actor = Number.isSafeInteger(id)
? await database.getRepository(User).findOneBy({ id })
: null;
if (!actor || ![Role.ADMIN, Role.SUPERUSER].includes(actor.role))
throw new ForbiddenError('دسترسی مدیریت ندارید.');
// Refresh authorization on every request rather than trusting a stale session.
context.currentAdmin = { ...context.currentAdmin!, role: actor.role };
return request;
};
const staff = ({ currentAdmin }: ActionContext) =>
[Role.ADMIN, Role.SUPERUSER].includes(currentAdmin?.role as Role);
const superuser = ({ currentAdmin }: ActionContext) =>
currentAdmin?.role === Role.SUPERUSER;
const redact = (response: ActionResponse) => {
redactPanelSecrets(response);
return response;
};
const protectTest = async (id: number, structure: boolean) => {
const test = await database.getRepository(Test).findOneByOrFail({ id });
if (
structure &&
(test.structureLocked || test.status === TestStatus.PUBLISHED)
)
reject(
'ساختار آزمونی که منتشر شده قابل تغییر یا حذف نیست؛ آزمون جدید بسازید.',
);
if (await database.getRepository(Submission).existsBy({ testId: id }))
reject(
'این آزمون سابقه پاسخ دارد؛ برای تغییر ساختار یا حذف، آزمون جدید بسازید.',
);
};
// Providers use their own repositories. A shared session-level advisory lock
// serializes all panel writes across app instances without bypassing providers.
const serialize =
(write: PanelWrite): PanelWrite =>
async (...args) => {
const runner = database.createQueryRunner();
await runner.connect();
let locked = false;
try {
const locks = (await runner.query(
'SELECT pg_try_advisory_lock(724091, 1) AS acquired',
)) as Array<{ acquired: boolean }>;
if (!locks[0]?.acquired)
reject(
'درخواست مدیریتی دیگری در حال ذخیره‌سازی است؛ دوباره تلاش کنید.',
);
locked = true;
return await write(...args);
} catch (error) {
if (error instanceof ValidationError) throw error;
if (error instanceof HttpException && error.getStatus() < 500) {
const response = error.getResponse();
const details =
typeof response === 'string'
? { message: response }
: (response as {
message?: string;
params?: Record<string, unknown>;
});
const message = i18n.translate(details.message ?? error.message, {
lang: 'fa',
args: details.params,
});
return reject(String(message));
}
// Do not expose SQL, password hashes or database internals to the browser.
return reject(
'ذخیره‌سازی انجام نشد؛ داده‌ها و وابستگی‌های رکورد را بررسی کنید.',
);
} finally {
try {
if (locked)
await runner.query('SELECT pg_advisory_unlock(724091, 1)');
} finally {
await runner.release();
}
}
};
function resource(
model: typeof BaseEntity,
fields: PanelField[],
write?: PanelWrite,
sensitive = false,
): ResourceWithOptions {
const canRead = sensitive ? superuser : staff;
return {
resource: new AdminPanelResource(model, write && serialize(write)),
options: {
editProperties: fields.map(({ name }) =>
name === 'test' ? 'test.id' : name,
),
properties: {
password: { isVisible: false },
newPassword: {
type: 'password',
isVisible: {
list: false,
filter: false,
show: false,
edit: model === User,
},
},
confirmPassword: {
type: 'password',
isVisible: {
list: false,
filter: false,
show: false,
edit: model === User,
},
},
...(model === QuestionTransition
? { condition: { type: 'textarea' } }
: {}),
...(model === Question ? { metadata: { type: 'textarea' } } : {}),
},
actions: {
list: { before: authorize, after: redact, isAccessible: canRead },
show: { before: authorize, after: redact, isAccessible: canRead },
search: { before: authorize, after: redact, isAccessible: canRead },
new: {
before: authorize,
after: redact,
isAccessible: write && model !== User ? staff : false,
},
edit: {
before: authorize,
after: redact,
isAccessible: write ? (model === User ? superuser : staff) : false,
},
// Destructive cascades and account removal need a dedicated workflow.
delete: {
before: authorize,
after: redact,
isAccessible: write && model !== User ? staff : false,
},
bulkDelete: { isAccessible: false, isVisible: false },
},
},
};
}
function catalog<T extends object>(
model: typeof BaseEntity,
fields: PanelField[],
dto: ClassConstructor<T>,
commands: {
createOne: (values: T) => Promise<unknown>;
updateOne: (id: number, values: T) => Promise<unknown>;
deleteOne: (id: number) => Promise<unknown>;
},
) {
return resource(model, fields, async (operation, params, id) => {
const repository = database.getRepository(model);
const existing =
id === undefined
? undefined
: await repository.findOneByOrFail({ id } as never);
const current = (existing ?? {}) as unknown as Record<string, unknown>;
const input = panelValues(fields, params, current);
const original = panelValues(
fields,
Object.fromEntries(
fields
.filter(({ name }) => Object.hasOwn(current, name))
.map(({ name }) => [name, current[name]]),
),
);
// The generated transition FK is named test.id by TypeORM.
if (model === QuestionTransition && existing) {
const transition = await database
.getRepository(QuestionTransition)
.findOneOrFail({ where: { id }, relations: { test: true } });
original.test = transition.test.id;
}
const merged = { ...original, ...input };
const parent =
model === Question ||
model === ResultRange ||
model === QuestionTransition
? 'test'
: 'question';
if (
existing &&
input[parent] !== undefined &&
merged[parent] !== undefined
) {
const previous = original[parent];
if (Number(input[parent]) !== Number(previous))
reject(
'جابجایی این رکورد به آزمون یا سؤال دیگر مجاز نیست؛ رکورد جدید بسازید.',
);
}
const parentId = Number(merged[parent]);
const testId =
parent === 'test'
? parentId
: (
await database
.getRepository(Question)
.findOneByOrFail({ id: parentId })
).testId;
await protectTest(testId, true);
if (model === Choice || model === QuestionRangeRule) {
const question = await database
.getRepository(Question)
.findOneByOrFail({ id: parentId });
if (
model === Choice &&
![QuestionType.SINGLE_CHOICE, QuestionType.MULTI_CHOICE].includes(
question.type,
)
)
reject('گزینه فقط برای سؤال انتخابی قابل تعریف است.');
if (
model === QuestionRangeRule &&
question.type !== QuestionType.NUMERIC
)
reject('قانون بازه فقط برای سؤال عددی قابل تعریف است.');
}
if (model === Question && existing && merged.type !== current.type) {
const question = await database.getRepository(Question).findOneOrFail({
where: { id },
relations: {
choices: true,
rangeRules: true,
outgoingTransitions: true,
incomingTransitions: true,
},
});
if (
question.choices.length ||
question.rangeRules?.length ||
question.outgoingTransitions.length ||
question.incomingTransitions.length
)
reject(
'قبل از تغییر نوع سؤال، گزینه‌ها، قوانین و مسیرهای وابسته را تعیین تکلیف کنید.',
);
}
if (operation === 'delete') {
if (model === Choice) {
const transitions = await database
.getRepository(QuestionTransition)
.findBy({ fromQuestionId: parentId });
if (
transitions.some(
({ condition }) =>
condition &&
(('choiceId' in condition && condition.choiceId === id) ||
('choiceIds' in condition &&
condition.choiceIds.includes(id!))),
)
)
reject(
'این گزینه در شرط یک مسیر استفاده شده است؛ ابتدا مسیر را اصلاح کنید.',
);
}
await commands.deleteOne(id!);
return {};
}
const validated = await validatePanelDto(
dto,
merged,
i18n,
Object.fromEntries(
fields.map(({ name, dto: dtoName }) => [
dtoName ?? name,
name === 'test' ? 'test.id' : name,
]),
),
);
const result =
operation === 'new'
? await commands.createOne(validated)
: await commands.updateOne(id!, validated);
if (operation === 'edit')
return (await repository.findOneByOrFail({
id,
} as never)) as unknown as Record<string, unknown>;
const entity =
result && typeof result === 'object' && 'data' in result
? result.data
: result;
return entity as Record<string, unknown>;
});
}
const tests = app.get(TestsService);
const testFields = [
field('title'),
field('description'),
field('accessType'),
field('price'),
field('isActive', 'boolean'),
field('status'),
];
const testResource = resource(
Test,
testFields,
async (operation, params, id) => {
const existing =
id === undefined
? undefined
: await database.getRepository(Test).findOneByOrFail({ id });
const values = panelValues(
testFields,
params,
existing as unknown as Record<string, unknown>,
);
if (typeof values.price === 'number') {
if (!Number.isSafeInteger(values.price))
reject('مبلغ را به صورت عدد صحیح وارد کنید.');
values.price = values.price.toString();
}
if (operation === 'delete') {
await protectTest(id!, true);
await tests.deleteOne(id!);
return {};
}
const complete = {
...(existing &&
panelValues(
testFields,
Object.fromEntries(
testFields.map(({ name }) => [
name,
(existing as unknown as Record<string, unknown>)[name],
]),
),
)),
...values,
};
const status = complete.status;
delete complete.status;
const validated = await validatePanelDto(CreateTestDTO, complete, i18n);
if (
validated.price != null &&
BigInt(validated.price) > 9223372036854775807n
)
reject('مبلغ خارج از محدوده مجاز است.');
if (
validated.isActive &&
(status ?? TestStatus.IN_PROGRESS) !== TestStatus.PUBLISHED
)
reject('فقط آزمون منتشرشده می‌تواند فعال باشد.');
if (operation === 'new') {
if (status !== undefined && status !== TestStatus.IN_PROGRESS)
reject('آزمون جدید باید ابتدا پیش‌نویس باشد.');
return (await tests.createOne(validated)).data as unknown as Record<
string,
unknown
>;
}
const update = await validatePanelDto(
UpdateTestDTO,
{
...validated,
status,
},
i18n,
);
return (await tests.updateOne(id!, update)) as unknown as Record<
string,
unknown
>;
},
);
const userFields = [
field('firstName'),
field('lastName'),
field('newPassword', undefined, 'password'),
field('confirmPassword'),
];
const userResource = resource(
User,
userFields,
async (operation, params, id) => {
if (operation !== 'edit')
reject('ساخت و حذف مستقیم حساب کاربری مجاز نیست.');
const user = await users.findOneById(id!);
const input = panelValues(
userFields,
params,
user as unknown as Record<string, unknown>,
);
if (input.password === '') delete input.password;
if (input.confirmPassword === '') delete input.confirmPassword;
if (input.password !== undefined && input.confirmPassword === undefined)
reject('تکرار رمز عبور الزامی است.');
if (input.password === undefined && input.confirmPassword !== undefined)
reject('رمز عبور جدید را هم وارد کنید.');
if (
typeof input.password === 'string' &&
Buffer.byteLength(input.password, 'utf8') > 72
)
reject('رمز عبور نباید بیشتر از ۷۲ بایت باشد.');
const validated = await validatePanelDto(UpdateProfileDTO, input, i18n, {
password: 'newPassword',
});
if (Object.keys(input).length) await users.updateProfile(user, validated);
const updated = await users.findOneById(id!);
const safe = { ...updated };
delete safe.password;
return safe;
},
true,
);
return [
testResource,
catalog(
Question,
[
field('testId', 'number', 'test'),
field('type'),
field('content'),
field('weight', 'number'),
field('required', 'boolean'),
field('metadata', 'json'),
],
CreateQuestionDTO,
app.get(QuestionsService),
),
catalog(
Choice,
[
field('questionId', 'number', 'question'),
field('text'),
field('order', 'number'),
field('score', 'number'),
],
CreateChoiceDTO,
app.get(ChoicesService),
),
catalog(
QuestionRangeRule,
[
field('questionId', 'number', 'question'),
field('min', 'number'),
field('max', 'number'),
field('score', 'number'),
],
CreateQuestionRangeRuleDTO,
app.get(QuestionRangeRuleService),
),
catalog(
QuestionTransition,
[
field('test', 'number'),
field('fromQuestionId', 'number', 'fromQuestion'),
field('toQuestionId', 'number', 'toQuestion'),
field('type'),
field('condition', 'json', 'conditionValue'),
],
CreateQuestionTransitionDTO,
app.get(QuestionTransitionService),
),
catalog(
ResultRange,
[
field('testId', 'number', 'test'),
field('minScore', 'number'),
field('maxScore', 'number'),
field('title'),
field('description'),
],
CreateResultRangeDTO,
app.get(ResultRangeService),
),
userResource,
...[
Submission,
SubmissionAnswer,
SubmissionResult,
Conversation,
Message,
].map((model) => resource(model, [], undefined, true)),
];
}
+2 -32
View File
@@ -5,7 +5,7 @@ import type { Express, Request, Response, NextFunction } from 'express';
import AdminJS from 'adminjs';
import AdminJSExpress from '@adminjs/express';
import { Database, Resource } from '@adminjs/typeorm';
import { User } from '@/modules/users/entities/user.entity';
import { buildAdminPanelResources } from './admin-panel.resources';
import { RedisService } from '@/common/modules/redis/providers/redis.service';
import { AdminPanelAuthenticator } from './providers/admin-panel-auth.provider';
import { AdminPanelSessionStore } from './admin-panel-session.store';
@@ -72,18 +72,6 @@ export class AdminPanelSetup {
baseEntity.useDataSource?.(dataSource);
}
// Register every real entity automatically (new entities show up without
// any change here). Auto-generated ManyToMany junction metadatas have no
// entity class behind them and are skipped — they are managed through the
// owning relation instead.
const autoResources = dataSource.entityMetadatas
.map((m) => m.target)
.filter(
(target) =>
typeof (target as { getRepository?: unknown }).getRepository ===
'function',
);
const adminJs = new AdminJS({
rootPath: configService.get<string>('admin.rootPath'),
locale: {
@@ -95,25 +83,7 @@ export class AdminPanelSetup {
withMadeWithLove: false,
logo: false,
},
resources: [
...autoResources,
{
resource: User,
options: {
properties: {
// Never expose password hashes in tables and detail views
password: {
isVisible: {
list: false,
filter: false,
show: false,
edit: true,
},
},
},
},
},
],
resources: buildAdminPanelResources(app),
});
const authenticator = app.get(AdminPanelAuthenticator);
@@ -0,0 +1,136 @@
import { plainToInstance, ClassConstructor } from 'class-transformer';
import { validate, ValidationError as DtoError } from 'class-validator';
import { ValidationError } from 'adminjs';
import { I18nService } from 'nestjs-i18n';
export async function validatePanelDto<T extends object>(
type: ClassConstructor<T>,
values: Record<string, unknown>,
i18n?: I18nService,
aliases: Record<string, string> = {},
): Promise<T> {
const dto = plainToInstance(type, values);
const errors = await validate(dto, {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
});
if (errors.length) {
const fields: Record<string, { message: string }> = {};
const collect = (items: DtoError[], prefix = '') => {
for (const error of items) {
const key = prefix + (aliases[error.property] ?? error.property);
if (error.constraints)
fields[key] = {
message: Object.values(error.constraints)
.map((message) => {
const separator = message.indexOf('|');
if (separator < 0) return message;
const translationKey = message.slice(0, separator);
// i18nValidationMessage embeds the submitted value in JSON.
// Never return that raw payload (especially for passwords).
const args = JSON.parse(message.slice(separator + 1)) as Record<
string,
unknown
>;
delete args.value;
return i18n
? String(i18n.translate(translationKey, { lang: 'fa', args }))
: 'مقدار این فیلد معتبر نیست.';
})
.join('؛ '),
};
collect(error.children ?? [], `${key}.`);
}
};
collect(errors);
throw new ValidationError(fields, {
message: 'اطلاعات فرم معتبر نیست؛ فیلدهای مشخص‌شده را بررسی کنید.',
});
}
return dto;
}
export type PanelField = {
name: string;
dto?: string;
kind?: 'number' | 'boolean' | 'json';
};
export function redactPanelSecrets(value: unknown): void {
if (!value || typeof value !== 'object') return;
for (const [key, nested] of Object.entries(value)) {
// Validation errors contain safe, rendered messages, not submitted values.
if (key === 'errors') continue;
if (
['password', 'newPassword', 'confirmPassword'].includes(key.split('.')[0])
)
delete (value as Record<string, unknown>)[key];
else redactPanelSecrets(nested);
}
}
/** Convert only declared editable fields; reject mass assignment server-side. */
export function panelValues(
fields: PanelField[],
params: Record<string, unknown>,
existing: Record<string, unknown> = {},
) {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(params)) {
const field = fields.find((item) => item.name === key);
if (!field) {
const previous = existing[key];
const comparable = (input: unknown) =>
input instanceof Date ? input.toISOString() : String(input);
if (
Object.hasOwn(existing, key) &&
comparable(previous) === comparable(value)
)
continue;
throw new ValidationError({
[key]: { message: 'تغییر این فیلد مجاز نیست.' },
});
}
if (value === undefined) continue;
let converted: unknown = value;
if (field.kind === 'number' && value !== null && value !== '') {
const numeric =
value &&
typeof value === 'object' &&
Object.keys(value).length === 1 &&
'id' in value
? value.id
: value;
converted =
typeof numeric === 'number'
? numeric
: typeof numeric === 'string'
? Number(numeric)
: NaN;
if (!Number.isFinite(converted) || !Number.isSafeInteger(converted))
throw new ValidationError({
[key]: { message: 'عدد صحیح معتبر وارد کنید.' },
});
}
if (field.kind === 'number' && value === '') converted = null;
if (field.kind === 'boolean') {
if (![true, false, 'true', 'false'].includes(value as boolean))
throw new ValidationError({
[key]: { message: 'مقدار بولی معتبر وارد کنید.' },
});
converted = value === true || value === 'true';
}
if (field.kind === 'json' && typeof value === 'string') {
try {
converted = value === '' ? null : (JSON.parse(value) as unknown);
} catch {
throw new ValidationError({
[key]: { message: 'JSON معتبر وارد کنید.' },
});
}
}
result[field.dto ?? key] = converted;
}
return result;
}
@@ -8,7 +8,7 @@ import { ValidationError } from '@nestjs/common';
export const validateMetadata = async (
type: QuestionType,
metadata: QuestionMetadata,
metadata: QuestionMetadata | null | undefined,
): Promise<ValidationError[]> => {
if (!metadata) {
return [];
@@ -100,7 +100,12 @@ export class ChoicesCommandProvider {
}
}
Object.assign(choice, updateChoiceDto);
const { question: questionId, ...changes } = updateChoiceDto;
Object.assign(choice, changes);
if (questionId !== undefined) {
choice.questionId = questionId;
choice.question = { id: questionId } as Question;
}
try {
const updatedChoice = await this.choicesRepository.save(choice);
@@ -12,6 +12,7 @@ import { UpdateQuestionDTO } from '../dtos/update-question.dto';
import { validateMetadata } from '../helpers/validate-metadata.helper';
import { AppException } from '@/common/exceptions/app.exception';
import { Test } from '@/modules/tests/entities/test.entity';
import { QuestionType } from '../enums/question-type.enum';
@Injectable()
export class QuestionsCommandProvider {
@@ -39,6 +40,16 @@ export class QuestionsCommandProvider {
) {}
public async createOne(createQuestionDto: CreateQuestionDTO) {
const metadataErrors = await validateMetadata(
createQuestionDto.type ?? QuestionType.SINGLE_CHOICE,
createQuestionDto.metadata ?? null,
);
if (metadataErrors.length)
throw new AppException(
'validation.wrongFieldFormat',
HttpStatus.BAD_REQUEST,
{ field: '$t(questions.fields.metadata)' },
);
const test = await this.testsService.adminGetOne(createQuestionDto.test);
const newQuestion = this.questionsRepository.create({
@@ -84,7 +95,11 @@ export class QuestionsCommandProvider {
}
if (updateQuestionDto.test) {
await this.testsService.adminGetOne(updateQuestionDto.test);
if (updateQuestionDto.test !== question.testId) {
throw new ConflictException(
'جابجایی سؤال به آزمون دیگر مجاز نیست؛ سؤال جدید بسازید.',
);
}
}
const type =
@@ -107,7 +122,9 @@ export class QuestionsCommandProvider {
);
}
Object.assign(question, updateQuestionDto);
const changes = { ...updateQuestionDto };
delete changes.test;
Object.assign(question, changes);
try {
return await this.questionsRepository.save(question);
@@ -57,7 +57,7 @@ export class QuestionRangeRuleCommandProvider {
question: number,
min: number,
max: number,
excludeSelf: boolean = false,
excludeId?: number,
): Promise<void> {
const queryBuilder = this.questionRangeRulesRepository
.createQueryBuilder('rule')
@@ -72,6 +72,9 @@ export class QuestionRangeRuleCommandProvider {
{ min, max },
);
if (excludeId !== undefined)
queryBuilder.andWhere('rule.id != :excludeId', { excludeId });
let overlappingRules: Array<QuestionRangeRule>;
try {
@@ -80,7 +83,7 @@ export class QuestionRangeRuleCommandProvider {
throw new AppTimeoutException(err);
}
if (overlappingRules.length > (excludeSelf ? 1 : 0)) {
if (overlappingRules.length > 0) {
throw new AppException(
'questions.errors.rangeRuleIntersectionConstraint',
HttpStatus.CONFLICT,
@@ -178,9 +181,14 @@ export class QuestionRangeRuleCommandProvider {
);
}
await this.checkRangeOverlap(questionId, min, max, true);
await this.checkRangeOverlap(questionId, min, max, id);
Object.assign(questionRangeRule, updateQuestionRangeRuleDto);
const changes = { ...updateQuestionRangeRuleDto };
delete changes.question;
Object.assign(questionRangeRule, changes, {
question: { id: questionId },
questionId,
});
try {
return await this.questionRangeRulesRepository.save(questionRangeRule);
@@ -50,7 +50,7 @@ export class QuestionTransitionCommandProvider {
type !== QuestionTransitionType.MULTI_CHOICE
? conditionValue
: {
...conditionValue,
...(conditionValue as MultiChoiceCondition),
choiceIds: [
...(conditionValue as MultiChoiceCondition).choiceIds,
].sort((a, b) => a - b),
@@ -88,7 +88,15 @@ export class QuestionTransitionCommandProvider {
transition.fromQuestion = fromQuestion;
transition.toQuestion = toQuestion;
transition.type = type;
transition.condition = conditionValue;
transition.condition =
type === QuestionTransitionType.MULTI_CHOICE
? {
...(conditionValue as MultiChoiceCondition),
choiceIds: [
...(conditionValue as MultiChoiceCondition).choiceIds,
].sort((a, b) => a - b),
}
: conditionValue;
try {
await this.transitionsRepository.save(transition);
@@ -117,7 +117,9 @@ export class QuestionTransitionTypeValidator {
);
}
const choiceId = (conditionValue as SingleChoiceCondition).choiceId;
const choiceId = (
conditionValue as SingleChoiceCondition | null | undefined
)?.choiceId;
if (typeof choiceId !== 'number') {
throw new AppException(
@@ -34,16 +34,19 @@ export class ResultRangeCommandProvider {
test: number,
minScore: number,
maxScore: number,
excludeSelf: boolean = false,
excludeId?: number,
): Promise<void> {
const queryBuilder = this.resultRangeRepository
.createQueryBuilder('resultRange')
.where('resultRange.testId = :test', { test })
.andWhere(
'(resultRange.minScore BETWEEN :minScore AND :maxScore) OR (resultRange.maxScore BETWEEN :minScore AND :maxScore) OR (:minScore BETWEEN resultRange.minScore AND resultRange.maxScore) OR (:maxScore BETWEEN resultRange.minScore AND resultRange.maxScore)',
'(resultRange.minScore <= :maxScore AND resultRange.maxScore >= :minScore)',
{ minScore, maxScore },
);
if (excludeId !== undefined)
queryBuilder.andWhere('resultRange.id != :excludeId', { excludeId });
let overlappingRanges: Array<ResultRange>;
try {
@@ -52,7 +55,7 @@ export class ResultRangeCommandProvider {
throw new AppTimeoutException(err);
}
if (overlappingRanges.length > (excludeSelf ? 1 : 0)) {
if (overlappingRanges.length > 0) {
throw new AppException(
'scoring.errors.resultRangeOverlappingConstraint',
HttpStatus.CONFLICT,
@@ -145,9 +148,11 @@ export class ResultRangeCommandProvider {
);
}
await this.checkRangeOverlap(testId, minScore, maxScore, true);
await this.checkRangeOverlap(testId, minScore, maxScore, id);
Object.assign(resultRange, updateResultRangeDto);
const changes = { ...updateResultRangeDto };
delete changes.test;
Object.assign(resultRange, changes, { test: { id: testId }, testId });
try {
return await this.resultRangeRepository.save(resultRange);
@@ -69,6 +69,11 @@ export class Test extends BaseEntity {
@Column({ type: 'int', nullable: false, default: 0 })
questionsCount!: number;
// Published questionnaires have no versioned snapshots. Keep their structure
// immutable even after unpublishing, including for active guest sessions.
@Column({ type: 'boolean', default: false })
structureLocked!: boolean;
@OneToMany(() => ResultRange, (range) => range.test)
resultRanges!: Array<ResultRange>;
@@ -72,19 +72,21 @@ export class TestsCommandProvider {
}
const accessType = updateTestDto.accessType ?? test.accessType;
const price = updateTestDto.price ?? test.price;
const price =
updateTestDto.price !== undefined ? updateTestDto.price : test.price;
if (
(accessType === AccessType.PAID && !price) ||
(accessType !== AccessType.PAID && price)
(accessType === AccessType.PAID && price == null) ||
(accessType !== AccessType.PAID && price != null)
) {
throw new BadRequestException('tests.errors.priceAccessConstraint');
}
Object.assign(test, updateTestDto);
if (updateTestDto.status === TestStatus.PUBLISHED) {
if (test.status === TestStatus.PUBLISHED) {
await this.publishTestValidatorProvider.validate(test.id);
test.structureLocked = true;
}
try {