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
@@ -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();
});
});