Ship Novya PWA with backend for deployable production use.
Fix production TypeScript builds and add DEPLOY.md so the app can be hosted from this repo. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { createApp } from '../src/app.js';
|
||||
import * as prismaModule from '../src/lib/prisma.js';
|
||||
|
||||
describe('application', () => {
|
||||
it('initializes createApp without throwing', () => {
|
||||
const app = createApp();
|
||||
assert.ok(app);
|
||||
assert.equal(typeof app.fetch, 'function');
|
||||
});
|
||||
|
||||
it('GET /health returns success', async () => {
|
||||
const app = createApp();
|
||||
const response = await app.fetch(new Request('http://localhost/health'));
|
||||
assert.equal(response.status, 200);
|
||||
|
||||
const body = (await response.json()) as {
|
||||
success: boolean;
|
||||
data: { status: string; service: string };
|
||||
meta: { requestId: string };
|
||||
};
|
||||
|
||||
assert.equal(body.success, true);
|
||||
assert.equal(body.data.status, 'ok');
|
||||
assert.equal(body.data.service, 'Novya API');
|
||||
assert.ok(body.meta.requestId);
|
||||
});
|
||||
|
||||
it('GET /ready succeeds when database is available', async (t) => {
|
||||
const app = createApp();
|
||||
const response = await app.fetch(new Request('http://localhost/ready'));
|
||||
|
||||
if (response.status === 503) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
const body = (await response.json()) as {
|
||||
success: boolean;
|
||||
data: { status: string; checks: { database: string } };
|
||||
};
|
||||
assert.equal(body.success, true);
|
||||
assert.equal(body.data.status, 'ready');
|
||||
assert.equal(body.data.checks.database, 'ok');
|
||||
});
|
||||
|
||||
it('GET /ready fails safely when database is unavailable', async () => {
|
||||
const app = createApp({
|
||||
checkDatabaseHealth: async () => false,
|
||||
});
|
||||
const response = await app.fetch(new Request('http://localhost/ready'));
|
||||
assert.equal(response.status, 503);
|
||||
|
||||
const body = (await response.json()) as {
|
||||
success: boolean;
|
||||
error: { code: string; message: string };
|
||||
meta: { requestId: string };
|
||||
};
|
||||
|
||||
assert.equal(body.success, false);
|
||||
assert.equal(body.error.code, 'DATABASE_UNAVAILABLE');
|
||||
assert.equal(body.error.message, 'Database is not available');
|
||||
assert.ok(body.meta.requestId);
|
||||
assert.doesNotMatch(JSON.stringify(body), /mysql:\/\//i);
|
||||
assert.doesNotMatch(JSON.stringify(body), /DATABASE_URL/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('prisma connectivity', () => {
|
||||
before(async () => {
|
||||
try {
|
||||
await prismaModule.connectPrisma();
|
||||
} catch {
|
||||
// handled per test
|
||||
}
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await prismaModule.disconnectPrisma();
|
||||
});
|
||||
|
||||
it('can connect when MySQL is available', async (t) => {
|
||||
const healthy = await prismaModule.checkDatabaseHealth();
|
||||
if (!healthy) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
assert.equal(healthy, true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { AuthProvider } from '@prisma/client';
|
||||
import { prisma } from '../src/lib/prisma.js';
|
||||
import { GENERIC_CREDENTIALS_MESSAGE } from '../src/modules/auth/auth.service.js';
|
||||
import { isArgon2idHash } from '../src/modules/auth/password.js';
|
||||
import { hashSessionToken } from '../src/modules/auth/sessionToken.js';
|
||||
import {
|
||||
assertNoSecrets,
|
||||
authHeader,
|
||||
createTestApp,
|
||||
isDatabaseAvailable,
|
||||
requestJson,
|
||||
} from './helpers.js';
|
||||
|
||||
const app = createTestApp();
|
||||
const createdUserIds: bigint[] = [];
|
||||
|
||||
async function registerUser(email: string, password: string) {
|
||||
return requestJson(app, '/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
}
|
||||
|
||||
describe('authentication API', () => {
|
||||
let dbAvailable = false;
|
||||
|
||||
before(async () => {
|
||||
dbAvailable = await isDatabaseAvailable();
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (dbAvailable && createdUserIds.length > 0) {
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
|
||||
}
|
||||
});
|
||||
|
||||
async function trackUser(externalId: string | undefined) {
|
||||
if (!externalId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { externalId } });
|
||||
if (user) {
|
||||
createdUserIds.push(user.id);
|
||||
}
|
||||
}
|
||||
|
||||
it('registers a valid email/password user', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const email = `reg-${Date.now()}@example.com`;
|
||||
const { status, body, raw } = await registerUser(email, 'password12');
|
||||
|
||||
assert.equal(status, 201);
|
||||
assert.equal(body.success, true);
|
||||
assert.equal(body.data?.user && (body.data.user as { email: string }).email, email);
|
||||
assert.equal((body.data?.user as { isGuest: boolean }).isGuest, false);
|
||||
assert.equal((body.data?.user as { profileComplete: boolean }).profileComplete, false);
|
||||
assert.equal(typeof body.data?.sessionToken, 'string');
|
||||
assertNoSecrets(raw);
|
||||
await trackUser((body.data?.user as { id: string }).id);
|
||||
|
||||
const identity = await prisma.authIdentity.findFirst({
|
||||
where: { email, provider: AuthProvider.password },
|
||||
});
|
||||
assert.ok(identity?.passwordHash);
|
||||
assert.equal(isArgon2idHash(identity.passwordHash), true);
|
||||
assert.notEqual(identity.passwordHash, 'password12');
|
||||
});
|
||||
|
||||
it('rejects duplicate email', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const email = `dup-${Date.now()}@example.com`;
|
||||
const first = await registerUser(email, 'password12');
|
||||
await trackUser((first.body.data?.user as { id: string }).id);
|
||||
|
||||
const second = await registerUser(email.toUpperCase(), 'password12');
|
||||
assert.equal(second.status, 409);
|
||||
assert.equal(second.body.error?.code, 'CONFLICT');
|
||||
assertNoSecrets(second.raw);
|
||||
});
|
||||
|
||||
it('rejects invalid email', async () => {
|
||||
const { status, body, raw } = await registerUser('not-an-email', 'password12');
|
||||
assert.equal(status, 422);
|
||||
assert.equal(body.error?.code, 'VALIDATION_ERROR');
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('rejects invalid password', async () => {
|
||||
const { status, body, raw } = await registerUser('short@example.com', 'short');
|
||||
assert.equal(status, 422);
|
||||
assert.equal(body.error?.code, 'VALIDATION_ERROR');
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('does not return password on registration', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const email = `nopw-${Date.now()}@example.com`;
|
||||
const { raw, body } = await registerUser(email, 'password12');
|
||||
await trackUser((body.data?.user as { id: string }).id);
|
||||
assert.doesNotMatch(raw, /password/i);
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('logs in with valid credentials', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const email = `login-${Date.now()}@example.com`;
|
||||
const registered = await registerUser(email, 'password12');
|
||||
await trackUser((registered.body.data?.user as { id: string }).id);
|
||||
|
||||
const { status, body, raw } = await requestJson(app, '/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password: 'password12' }),
|
||||
});
|
||||
|
||||
assert.equal(status, 200);
|
||||
assert.equal(typeof body.data?.sessionToken, 'string');
|
||||
assert.equal((body.data?.user as { email: string }).email, email);
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('rejects wrong password and unknown email with the same message', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const email = `enum-${Date.now()}@example.com`;
|
||||
const registered = await registerUser(email, 'password12');
|
||||
await trackUser((registered.body.data?.user as { id: string }).id);
|
||||
|
||||
const wrongPassword = await requestJson(app, '/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password: 'wrong-password' }),
|
||||
});
|
||||
const unknownEmail = await requestJson(app, '/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: `missing-${Date.now()}@example.com`, password: 'password12' }),
|
||||
});
|
||||
|
||||
assert.equal(wrongPassword.status, 401);
|
||||
assert.equal(unknownEmail.status, 401);
|
||||
assert.equal(wrongPassword.body.error?.code, 'INVALID_CREDENTIALS');
|
||||
assert.equal(unknownEmail.body.error?.code, 'INVALID_CREDENTIALS');
|
||||
assert.equal(wrongPassword.body.error?.message, GENERIC_CREDENTIALS_MESSAGE);
|
||||
assert.equal(unknownEmail.body.error?.message, GENERIC_CREDENTIALS_MESSAGE);
|
||||
assert.equal(wrongPassword.body.error?.message, unknownEmail.body.error?.message);
|
||||
});
|
||||
|
||||
it('authenticates /auth/me with a valid token', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const email = `me-${Date.now()}@example.com`;
|
||||
const registered = await registerUser(email, 'password12');
|
||||
await trackUser((registered.body.data?.user as { id: string }).id);
|
||||
const token = registered.body.data?.sessionToken as string;
|
||||
|
||||
const { status, body, raw } = await requestJson(app, '/auth/me', {
|
||||
headers: authHeader(token),
|
||||
});
|
||||
|
||||
assert.equal(status, 200);
|
||||
assert.equal((body.data as { email: string }).email, email);
|
||||
assert.equal((body.data as { isGuest: boolean }).isGuest, false);
|
||||
assert.doesNotMatch(raw, /sessionToken/);
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('rejects a missing bearer token', async () => {
|
||||
const missing = await requestJson(app, '/auth/me');
|
||||
assert.equal(missing.status, 401);
|
||||
assert.equal(missing.body.error?.code, 'UNAUTHORIZED');
|
||||
assertNoSecrets(missing.raw);
|
||||
});
|
||||
|
||||
it('rejects missing, invalid, expired, and revoked sessions', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const missing = await requestJson(app, '/auth/me');
|
||||
assert.equal(missing.status, 401);
|
||||
|
||||
const invalid = await requestJson(app, '/auth/me', {
|
||||
headers: authHeader('not-a-valid-token'),
|
||||
});
|
||||
assert.equal(invalid.status, 401);
|
||||
|
||||
const email = `sess-${Date.now()}@example.com`;
|
||||
const registered = await registerUser(email, 'password12');
|
||||
const token = registered.body.data?.sessionToken as string;
|
||||
await trackUser((registered.body.data?.user as { id: string }).id);
|
||||
|
||||
const session = await prisma.authSession.findUnique({
|
||||
where: { tokenHash: hashSessionToken(token) },
|
||||
});
|
||||
assert.ok(session);
|
||||
|
||||
await prisma.authSession.update({
|
||||
where: { id: session.id },
|
||||
data: { expiresAt: new Date(Date.now() - 1000) },
|
||||
});
|
||||
|
||||
const expired = await requestJson(app, '/auth/me', { headers: authHeader(token) });
|
||||
assert.equal(expired.status, 401);
|
||||
|
||||
const second = await registerUser(`sess2-${Date.now()}@example.com`, 'password12');
|
||||
await trackUser((second.body.data?.user as { id: string }).id);
|
||||
const liveToken = second.body.data?.sessionToken as string;
|
||||
|
||||
const logout = await requestJson(app, '/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: authHeader(liveToken),
|
||||
});
|
||||
assert.equal(logout.status, 200);
|
||||
|
||||
const revoked = await requestJson(app, '/auth/me', { headers: authHeader(liveToken) });
|
||||
assert.equal(revoked.status, 401);
|
||||
|
||||
const repeatedLogout = await requestJson(app, '/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: authHeader(liveToken),
|
||||
});
|
||||
assert.equal(repeatedLogout.status, 401);
|
||||
});
|
||||
|
||||
it('creates a guest user with a session', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const { status, body, raw } = await requestJson(app, '/auth/guest', { method: 'POST' });
|
||||
assert.equal(status, 201);
|
||||
assert.equal((body.data?.user as { isGuest: boolean }).isGuest, true);
|
||||
assert.equal((body.data?.user as { email: string | null }).email, null);
|
||||
assert.equal(typeof body.data?.sessionToken, 'string');
|
||||
assert.doesNotMatch((body.data?.user as { id: string }).id, /^guest-/);
|
||||
assertNoSecrets(raw);
|
||||
await trackUser((body.data?.user as { id: string }).id);
|
||||
|
||||
const me = await requestJson(app, '/auth/me', {
|
||||
headers: authHeader(body.data?.sessionToken as string),
|
||||
});
|
||||
assert.equal(me.status, 200);
|
||||
assert.equal((me.body.data as { isGuest: boolean }).isGuest, true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { prisma } from '../src/lib/prisma.js';
|
||||
import { PCQ_QUESTION_IDS } from '../src/modules/assessments/scoring/index.js';
|
||||
import { COACH_SESSION_START_CUE } from '../src/modules/ai/coachPrompt.js';
|
||||
import { seedCourseSessions } from '../src/modules/sessions/sessions.service.js';
|
||||
import {
|
||||
assertNoSecrets,
|
||||
authHeader,
|
||||
createTestApp,
|
||||
isDatabaseAvailable,
|
||||
requestJson,
|
||||
} from './helpers.js';
|
||||
|
||||
const app = createTestApp();
|
||||
const createdUserIds: bigint[] = [];
|
||||
|
||||
function pcqAnswers(value: number) {
|
||||
return PCQ_QUESTION_IDS.map((questionId) => ({
|
||||
questionId,
|
||||
selectedValue: String(value),
|
||||
}));
|
||||
}
|
||||
|
||||
async function registerUser(suffix: string) {
|
||||
const email = `chat-${suffix}-${Date.now()}@example.com`;
|
||||
const { status, body } = await requestJson(app, '/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password: 'password12' }),
|
||||
});
|
||||
assert.equal(status, 201);
|
||||
const token = body.data?.sessionToken as string;
|
||||
const externalId = (body.data?.user as { id: string }).id;
|
||||
const user = await prisma.user.findUnique({ where: { externalId } });
|
||||
assert.ok(user);
|
||||
createdUserIds.push(user.id);
|
||||
return { token, user };
|
||||
}
|
||||
|
||||
async function completePreTest(token: string) {
|
||||
const pre = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ phase: 'pre', answers: pcqAnswers(4) }),
|
||||
});
|
||||
assert.equal(pre.status, 201);
|
||||
}
|
||||
|
||||
describe('chat persistence and AI runtime', () => {
|
||||
let dbAvailable = false;
|
||||
|
||||
before(async () => {
|
||||
dbAvailable = await isDatabaseAvailable();
|
||||
if (dbAvailable) {
|
||||
await seedCourseSessions();
|
||||
}
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (dbAvailable && createdUserIds.length > 0) {
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects unauthenticated chat access', async () => {
|
||||
const created = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
assert.equal(created.status, 401);
|
||||
});
|
||||
|
||||
it('does not leak AI secrets through public config', async () => {
|
||||
const { status, body, raw } = await requestJson(app, '/ai/config');
|
||||
assert.equal(status, 200);
|
||||
assert.equal(typeof body.data?.configured, 'boolean');
|
||||
assert.equal(typeof body.data?.provider, 'string');
|
||||
assert.ok((body.data?.provider as string).length > 0);
|
||||
assert.doesNotMatch(raw, /sk-/);
|
||||
assert.doesNotMatch(raw, /OPENAI_API_KEY/);
|
||||
assert.doesNotMatch(raw, /Bearer /);
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('lists AI runs for the authenticated user only', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const owner = await registerUser('runs-owner');
|
||||
const other = await registerUser('runs-other');
|
||||
await completePreTest(owner.token);
|
||||
|
||||
const created = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
body: JSON.stringify({ sessionOrder: 1 }),
|
||||
});
|
||||
assert.equal(created.status, 201);
|
||||
const chatId = created.body.data?.id as string;
|
||||
|
||||
await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
body: JSON.stringify({ content: 'سلام' }),
|
||||
});
|
||||
|
||||
const unauthorized = await requestJson(app, '/ai/runs');
|
||||
assert.equal(unauthorized.status, 401);
|
||||
|
||||
const runs = await requestJson(app, '/ai/runs?limit=10', {
|
||||
headers: authHeader(owner.token),
|
||||
});
|
||||
assert.equal(runs.status, 200);
|
||||
const ownerRuns = runs.body.data as {
|
||||
id: string;
|
||||
provider: string;
|
||||
chatSessionId: string | null;
|
||||
status: string;
|
||||
}[];
|
||||
assert.ok(Array.isArray(ownerRuns));
|
||||
assert.ok(ownerRuns.length >= 1);
|
||||
assert.ok(ownerRuns.every((run) => typeof run.provider === 'string' && run.provider.length > 0));
|
||||
assert.ok(ownerRuns.some((run) => run.chatSessionId === chatId));
|
||||
assert.doesNotMatch(JSON.stringify(runs.body), /sk-/);
|
||||
assert.doesNotMatch(JSON.stringify(runs.body), /OPENAI_API_KEY/);
|
||||
|
||||
const otherRuns = await requestJson(app, '/ai/runs', {
|
||||
headers: authHeader(other.token),
|
||||
});
|
||||
assert.equal(otherRuns.status, 200);
|
||||
const otherList = otherRuns.body.data as { chatSessionId: string | null }[];
|
||||
assert.equal(otherList.some((run) => run.chatSessionId === chatId), false);
|
||||
});
|
||||
|
||||
it('persists chat ownership, order, and history without exposing hidden prompts', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const owner = await registerUser('owner');
|
||||
const other = await registerUser('other');
|
||||
await completePreTest(owner.token);
|
||||
|
||||
const lockedFuture = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
body: JSON.stringify({ sessionOrder: 7 }),
|
||||
});
|
||||
assert.equal(lockedFuture.status, 403);
|
||||
|
||||
const created = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
body: JSON.stringify({ sessionOrder: 1 }),
|
||||
});
|
||||
assert.equal(created.status, 201);
|
||||
const chatId = created.body.data?.id as string;
|
||||
assert.ok(chatId);
|
||||
assert.equal(created.body.data?.sessionOrder, 1);
|
||||
assert.equal(created.body.data?.endedAt, null);
|
||||
|
||||
const listed = await requestJson(app, '/chat/sessions', {
|
||||
headers: authHeader(owner.token),
|
||||
});
|
||||
assert.equal(listed.status, 200);
|
||||
const listedSessions = listed.body.data as { id: string; sessionOrder: number }[];
|
||||
assert.ok(listedSessions.some((session) => session.id === chatId));
|
||||
|
||||
const start = await requestJson(app, `/chat/sessions/${chatId}/start`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
});
|
||||
assert.ok(start.status === 200 || start.status === 503);
|
||||
if (start.status === 200) {
|
||||
const startMessages =
|
||||
(start.body.data?.messages as { role: string; content: string }[]) ?? [];
|
||||
assert.equal(startMessages.some((message) => message.role === 'system'), false);
|
||||
assert.equal(
|
||||
startMessages.some((message) => message.content.includes(COACH_SESSION_START_CUE)),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
const first = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
body: JSON.stringify({ content: 'سلام، آماده هستم.' }),
|
||||
});
|
||||
assert.ok(first.status === 201 || first.status === 503);
|
||||
|
||||
const second = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(owner.token),
|
||||
body: JSON.stringify({ content: 'لطفا ادامه بده.' }),
|
||||
});
|
||||
assert.ok(second.status === 201 || second.status === 503);
|
||||
|
||||
const history = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
headers: authHeader(owner.token),
|
||||
});
|
||||
assert.equal(history.status, 200);
|
||||
const messages =
|
||||
(history.body.data?.messages as { role: string; content: string; createdAt: string }[]) ?? [];
|
||||
const userMessages = messages.filter((message) => message.role === 'user');
|
||||
assert.ok(userMessages.length >= 2);
|
||||
assert.equal(messages.some((message) => message.role === 'system'), false);
|
||||
assert.equal(
|
||||
messages.some((message) => message.content.includes(COACH_SESSION_START_CUE)),
|
||||
false,
|
||||
);
|
||||
assert.equal(userMessages[0]?.content, 'سلام، آماده هستم.');
|
||||
assert.equal(userMessages[1]?.content, 'لطفا ادامه بده.');
|
||||
assert.ok(new Date(userMessages[0].createdAt).getTime() <= new Date(userMessages[1].createdAt).getTime());
|
||||
|
||||
const otherRead = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
headers: authHeader(other.token),
|
||||
});
|
||||
assert.equal(otherRead.status, 404);
|
||||
|
||||
const otherWrite = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(other.token),
|
||||
body: JSON.stringify({ content: 'پیام غیرمجاز' }),
|
||||
});
|
||||
assert.equal(otherWrite.status, 404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { prisma } from '../src/lib/prisma.js';
|
||||
import { PCQ_QUESTION_IDS } from '../src/modules/assessments/scoring/index.js';
|
||||
import { exampleCompletionSignal } from '../src/modules/ai/sessionCompletion.js';
|
||||
import { buildAiCoachSessionContext } from '../src/modules/ai/sessionContext.js';
|
||||
import { getSessionByOrder, PROGRAM_SESSION_COUNT } from '../src/modules/sessions/catalog.js';
|
||||
import { seedCourseSessions } from '../src/modules/sessions/sessions.service.js';
|
||||
import {
|
||||
assertNoSecrets,
|
||||
authHeader,
|
||||
createTestApp,
|
||||
isDatabaseAvailable,
|
||||
requestJson,
|
||||
} from './helpers.js';
|
||||
|
||||
const app = createTestApp();
|
||||
const createdUserIds: bigint[] = [];
|
||||
|
||||
function pcqAnswers(value: number) {
|
||||
return PCQ_QUESTION_IDS.map((questionId) => ({
|
||||
questionId,
|
||||
selectedValue: String(value),
|
||||
}));
|
||||
}
|
||||
|
||||
async function registerUser(suffix: string) {
|
||||
const email = `domain-${suffix}-${Date.now()}@example.com`;
|
||||
const { status, body } = await requestJson(app, '/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password: 'password12' }),
|
||||
});
|
||||
assert.equal(status, 201);
|
||||
const token = body.data?.sessionToken as string;
|
||||
const externalId = (body.data?.user as { id: string }).id;
|
||||
const user = await prisma.user.findUnique({ where: { externalId } });
|
||||
assert.ok(user);
|
||||
createdUserIds.push(user.id);
|
||||
return { token, user };
|
||||
}
|
||||
|
||||
describe('learning domain API', () => {
|
||||
let dbAvailable = false;
|
||||
|
||||
before(async () => {
|
||||
dbAvailable = await isDatabaseAvailable();
|
||||
if (dbAvailable) {
|
||||
await seedCourseSessions();
|
||||
}
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (dbAvailable && createdUserIds.length > 0) {
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
|
||||
}
|
||||
});
|
||||
|
||||
it('GET /ai/config is public and does not leak secrets', async () => {
|
||||
const { status, body, raw } = await requestJson(app, '/ai/config');
|
||||
assert.equal(status, 200);
|
||||
assert.equal(typeof body.data?.configured, 'boolean');
|
||||
assert.equal(typeof body.data?.model, 'string');
|
||||
assert.equal(typeof body.data?.provider, 'string');
|
||||
assert.doesNotMatch(raw, /sk-/);
|
||||
assert.doesNotMatch(raw, /OPENAI_API_KEY/);
|
||||
assertNoSecrets(raw);
|
||||
});
|
||||
|
||||
it('gates journey, assessments, sequential sessions, and chat persistence', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const { token, user } = await registerUser('flow');
|
||||
|
||||
const beforePre = await requestJson(app, '/journey', { headers: authHeader(token) });
|
||||
assert.equal(beforePre.status, 200);
|
||||
const beforePermissions = beforePre.body.data?.permissions as {
|
||||
canTakePreTest: boolean;
|
||||
canOpenTraining: boolean;
|
||||
canTakePostTest: boolean;
|
||||
isCompleted: boolean;
|
||||
};
|
||||
assert.equal(beforePermissions.canTakePreTest, true);
|
||||
assert.equal(beforePermissions.canOpenTraining, false);
|
||||
assert.equal(beforePermissions.canTakePostTest, false);
|
||||
|
||||
const lockedChat = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
assert.equal(lockedChat.status, 403);
|
||||
|
||||
const postTooSoon = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ phase: 'post', answers: pcqAnswers(4) }),
|
||||
});
|
||||
assert.equal(postTooSoon.status, 403);
|
||||
|
||||
const pre = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ phase: 'pre', answers: pcqAnswers(4) }),
|
||||
});
|
||||
assert.equal(pre.status, 201);
|
||||
assert.equal(pre.body.data?.scores && (pre.body.data.scores as { total: number }).total, 93);
|
||||
const reverseAnswer = (
|
||||
pre.body.data?.answers as { questionId: string; selectedValue: number; score: number }[]
|
||||
).find((answer) => answer.questionId === 'pcq_13');
|
||||
assert.equal(reverseAnswer?.selectedValue, 4);
|
||||
assert.equal(reverseAnswer?.score, 3);
|
||||
|
||||
const retake = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ phase: 'pre', answers: pcqAnswers(5) }),
|
||||
});
|
||||
assert.equal(retake.status, 409);
|
||||
assert.equal(retake.body.error?.code, 'CONFLICT');
|
||||
|
||||
const afterPre = await requestJson(app, '/journey', { headers: authHeader(token) });
|
||||
assert.equal((afterPre.body.data as { currentStep: string }).currentStep, 'training_in_progress');
|
||||
const afterPermissions = afterPre.body.data?.permissions as {
|
||||
canTakePreTest: boolean;
|
||||
canOpenTraining: boolean;
|
||||
canTakePostTest: boolean;
|
||||
};
|
||||
assert.equal(afterPermissions.canTakePreTest, false);
|
||||
assert.equal(afterPermissions.canOpenTraining, true);
|
||||
assert.equal(afterPermissions.canTakePostTest, false);
|
||||
|
||||
const sessions = await requestJson(app, '/sessions', { headers: authHeader(token) });
|
||||
assert.equal(sessions.status, 200);
|
||||
const list = sessions.body.data as unknown as { order: number; unlocked: boolean; completed: boolean }[];
|
||||
assert.equal(list.length, PROGRAM_SESSION_COUNT);
|
||||
assert.equal(list[0]?.unlocked, true);
|
||||
assert.equal(list[1]?.unlocked, false);
|
||||
|
||||
const sessionTwoComplete = await requestJson(app, '/sessions/2/complete', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({
|
||||
...exampleCompletionSignal(buildAiCoachSessionContext(getSessionByOrder(2)!)),
|
||||
}),
|
||||
});
|
||||
assert.equal(sessionTwoComplete.status, 403);
|
||||
|
||||
const chat = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ sessionOrder: 1 }),
|
||||
});
|
||||
assert.equal(chat.status, 201);
|
||||
const chatId = chat.body.data?.id as string;
|
||||
assert.ok(chatId);
|
||||
|
||||
const firstMessage = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ content: 'سلام، آماده هستم.' }),
|
||||
});
|
||||
assert.ok(firstMessage.status === 503 || firstMessage.status === 201);
|
||||
|
||||
const secondMessage = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ content: 'ادامه بده.' }),
|
||||
});
|
||||
assert.ok(secondMessage.status === 503 || secondMessage.status === 201);
|
||||
|
||||
const stored = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
headers: authHeader(token),
|
||||
});
|
||||
assert.equal(stored.status, 200);
|
||||
const storedMessages = (stored.body.data?.messages as { role: string; content: string }[]) ?? [];
|
||||
assert.ok(storedMessages.filter((message) => message.role === 'user').length >= 2);
|
||||
|
||||
const complete = await requestJson(app, '/sessions/1/complete', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({
|
||||
...exampleCompletionSignal(buildAiCoachSessionContext(getSessionByOrder(1)!)),
|
||||
chatSessionId: chatId,
|
||||
}),
|
||||
});
|
||||
assert.equal(complete.status, 200);
|
||||
const completedSessions = complete.body.data?.completedSessions as number[];
|
||||
assert.deepEqual(completedSessions, [1]);
|
||||
|
||||
const endedChat = await requestJson(app, `/chat/sessions/${chatId}/messages`, {
|
||||
headers: authHeader(token),
|
||||
});
|
||||
assert.equal(endedChat.status, 200);
|
||||
assert.ok((endedChat.body.data?.session as { endedAt: string | null }).endedAt);
|
||||
|
||||
const listed = await requestJson(app, '/chat/sessions?sessionOrder=1', {
|
||||
headers: authHeader(token),
|
||||
});
|
||||
assert.equal(listed.status, 200);
|
||||
const listedSessions = listed.body.data as { id: string; sessionOrder: number; endedAt: string | null }[];
|
||||
assert.ok(listedSessions.some((session) => session.id === chatId && session.endedAt));
|
||||
|
||||
const recomplete = await requestJson(app, '/sessions/1/complete', {
|
||||
method: 'POST',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({
|
||||
...exampleCompletionSignal(buildAiCoachSessionContext(getSessionByOrder(1)!)),
|
||||
chatSessionId: chatId,
|
||||
}),
|
||||
});
|
||||
assert.equal(recomplete.status, 200);
|
||||
assert.deepEqual(recomplete.body.data?.completedSessions as number[], [1]);
|
||||
|
||||
const afterSession = await requestJson(app, '/sessions', { headers: authHeader(token) });
|
||||
const afterList = afterSession.body.data as unknown as { order: number; unlocked: boolean }[];
|
||||
assert.equal(afterList[1]?.unlocked, true);
|
||||
|
||||
const stillNoPost = await requestJson(app, '/journey', { headers: authHeader(token) });
|
||||
assert.equal(
|
||||
(stillNoPost.body.data?.permissions as { canTakePostTest: boolean }).canTakePostTest,
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,316 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { prisma } from '../src/lib/prisma.js';
|
||||
import { ChatRole } from '@prisma/client';
|
||||
import { PCQ_QUESTION_IDS } from '../src/modules/assessments/scoring/index.js';
|
||||
import { exampleCompletionSignal } from '../src/modules/ai/sessionCompletion.js';
|
||||
import { buildAiCoachSessionContext } from '../src/modules/ai/sessionContext.js';
|
||||
import { getSessionByOrder, PROGRAM_SESSION_COUNT } from '../src/modules/sessions/catalog.js';
|
||||
import { seedCourseSessions } from '../src/modules/sessions/sessions.service.js';
|
||||
import {
|
||||
createTestApp,
|
||||
isDatabaseAvailable,
|
||||
requestJson,
|
||||
} from './helpers.js';
|
||||
|
||||
const app = createTestApp();
|
||||
const createdUserIds: bigint[] = [];
|
||||
|
||||
function pcqAnswers(value: number) {
|
||||
return PCQ_QUESTION_IDS.map((questionId) => ({
|
||||
questionId,
|
||||
selectedValue: String(value),
|
||||
}));
|
||||
}
|
||||
|
||||
function headers(token?: string, ip = 'e2e-qa'): HeadersInit {
|
||||
const next: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'x-real-ip': ip,
|
||||
};
|
||||
if (token) next.Authorization = `Bearer ${token}`;
|
||||
return next;
|
||||
}
|
||||
|
||||
async function registerUser(suffix: string, ip: string) {
|
||||
const email = `e2e-${suffix}-${Date.now()}@example.com`;
|
||||
const { status, body } = await requestJson(app, '/auth/register', {
|
||||
method: 'POST',
|
||||
headers: headers(undefined, ip),
|
||||
body: JSON.stringify({ email, password: 'password12' }),
|
||||
});
|
||||
assert.equal(status, 201, `register failed: ${JSON.stringify(body)}`);
|
||||
const token = body.data?.sessionToken as string;
|
||||
const externalId = (body.data?.user as { id: string }).id;
|
||||
const user = await prisma.user.findUnique({ where: { externalId } });
|
||||
assert.ok(user);
|
||||
createdUserIds.push(user.id);
|
||||
return { email, token, user, externalId };
|
||||
}
|
||||
|
||||
async function completeSession(token: string, ip: string, order: number, userId: bigint) {
|
||||
const chat = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ip),
|
||||
body: JSON.stringify({ sessionOrder: order }),
|
||||
});
|
||||
assert.equal(chat.status, 201, `chat create ${order} failed: ${JSON.stringify(chat.body)}`);
|
||||
const chatId = chat.body.data?.id as string;
|
||||
|
||||
await prisma.chatMessage.createMany({
|
||||
data: [
|
||||
{ chatSessionId: BigInt(chatId), role: ChatRole.user, content: `سلام جلسه ${order}` },
|
||||
{ chatSessionId: BigInt(chatId), role: ChatRole.user, content: `ادامه جلسه ${order}` },
|
||||
],
|
||||
});
|
||||
|
||||
const session = getSessionByOrder(order);
|
||||
assert.ok(session);
|
||||
const complete = await requestJson(app, `/sessions/${order}/complete`, {
|
||||
method: 'POST',
|
||||
headers: headers(token, ip),
|
||||
body: JSON.stringify({
|
||||
...exampleCompletionSignal(buildAiCoachSessionContext(session)),
|
||||
chatSessionId: chatId,
|
||||
}),
|
||||
});
|
||||
assert.equal(
|
||||
complete.status,
|
||||
200,
|
||||
`complete session ${order} failed: ${JSON.stringify(complete.body)}`,
|
||||
);
|
||||
|
||||
await prisma.sessionProgress.update({
|
||||
where: { userId_sessionOrder: { userId, sessionOrder: order } },
|
||||
data: { completedAt: new Date(Date.now() - 2 * 60 * 60 * 1000) },
|
||||
});
|
||||
|
||||
return { chatId, progress: complete.body.data, userId };
|
||||
}
|
||||
|
||||
describe('full E2E learning journey QA', () => {
|
||||
let dbAvailable = false;
|
||||
|
||||
before(async () => {
|
||||
dbAvailable = await isDatabaseAvailable();
|
||||
if (dbAvailable) {
|
||||
await seedCourseSessions();
|
||||
}
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (dbAvailable && createdUserIds.length > 0) {
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
|
||||
}
|
||||
});
|
||||
|
||||
it('covers auth, profile, assessments, sessions 1-11, post-test, isolation, and 401', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const ownerIp = `e2e-owner-${Date.now()}`;
|
||||
const otherIp = `e2e-other-${Date.now()}`;
|
||||
const owner = await registerUser('owner', ownerIp);
|
||||
|
||||
const me = await requestJson(app, '/auth/me', { headers: headers(owner.token, ownerIp) });
|
||||
assert.equal(me.status, 200);
|
||||
assert.equal((me.body.data as { id: string }).id, owner.externalId);
|
||||
|
||||
const profile = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: headers(owner.token, ownerIp),
|
||||
body: JSON.stringify({ name: 'آزمون', age: 28 }),
|
||||
});
|
||||
assert.equal(profile.status, 200, JSON.stringify(profile.body));
|
||||
assert.equal((profile.body.data as { profile: { name: string; age: number } }).profile.name, 'آزمون');
|
||||
assert.equal((profile.body.data as { profile: { name: string; age: number } }).profile.age, 28);
|
||||
|
||||
const profileAgain = await requestJson(app, '/users/me', {
|
||||
headers: headers(owner.token, ownerIp),
|
||||
});
|
||||
assert.equal(profileAgain.status, 200);
|
||||
assert.equal((profileAgain.body.data as { profileComplete: boolean }).profileComplete, true);
|
||||
|
||||
const badLogin = await requestJson(app, '/auth/login', {
|
||||
method: 'POST',
|
||||
headers: headers(undefined, ownerIp),
|
||||
body: JSON.stringify({ email: owner.email, password: 'wrong-password' }),
|
||||
});
|
||||
assert.equal(badLogin.status, 401);
|
||||
|
||||
const login = await requestJson(app, '/auth/login', {
|
||||
method: 'POST',
|
||||
headers: headers(undefined, ownerIp),
|
||||
body: JSON.stringify({ email: owner.email, password: 'password12' }),
|
||||
});
|
||||
assert.equal(login.status, 200);
|
||||
const token = login.body.data?.sessionToken as string;
|
||||
assert.ok(token);
|
||||
|
||||
const beforePre = await requestJson(app, '/journey', { headers: headers(token, ownerIp) });
|
||||
assert.equal(beforePre.status, 200);
|
||||
assert.equal((beforePre.body.data?.permissions as { canTakePreTest: boolean }).canTakePreTest, true);
|
||||
assert.equal((beforePre.body.data?.permissions as { canOpenTraining: boolean }).canOpenTraining, false);
|
||||
|
||||
const pre = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ phase: 'pre', answers: pcqAnswers(4) }),
|
||||
});
|
||||
assert.equal(pre.status, 201);
|
||||
assert.equal(typeof (pre.body.data?.scores as { total: number }).total, 'number');
|
||||
|
||||
const duplicatePre = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ phase: 'pre', answers: pcqAnswers(5) }),
|
||||
});
|
||||
assert.equal(duplicatePre.status, 409);
|
||||
|
||||
const afterPre = await requestJson(app, '/journey', { headers: headers(token, ownerIp) });
|
||||
assert.equal((afterPre.body.data?.permissions as { canOpenTraining: boolean }).canOpenTraining, true);
|
||||
assert.equal((afterPre.body.data?.permissions as { canTakePostTest: boolean }).canTakePostTest, false);
|
||||
assert.ok(afterPre.body.data?.preTestCompletedAt);
|
||||
|
||||
const sessions = await requestJson(app, '/sessions', { headers: headers(token, ownerIp) });
|
||||
const list = sessions.body.data as unknown as { order: number; unlocked: boolean; completed: boolean }[];
|
||||
assert.equal(list[0]?.unlocked, true);
|
||||
assert.equal(list[1]?.unlocked, false);
|
||||
assert.equal(list[4]?.unlocked, false);
|
||||
|
||||
const lockedFive = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ sessionOrder: 5 }),
|
||||
});
|
||||
assert.equal(lockedFive.status, 403);
|
||||
|
||||
const tooSoonComplete = await requestJson(app, '/sessions/1/complete', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify(exampleCompletionSignal(buildAiCoachSessionContext(getSessionByOrder(1)!))),
|
||||
});
|
||||
assert.equal(tooSoonComplete.status, 422);
|
||||
|
||||
const first = await completeSession(token, ownerIp, 1, owner.user.id);
|
||||
const liveMessage = await requestJson(app, `/chat/sessions/${first.chatId}/messages`, {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ content: 'یک پیام زنده برای پایداری گفتگو' }),
|
||||
});
|
||||
assert.ok(liveMessage.status === 201 || liveMessage.status === 503, `live chat ${liveMessage.status}`);
|
||||
const afterOne = await requestJson(app, '/sessions', { headers: headers(token, ownerIp) });
|
||||
const afterOneList = afterOne.body.data as unknown as { order: number; unlocked: boolean; completed: boolean }[];
|
||||
assert.equal(afterOneList[0]?.completed, true);
|
||||
assert.equal(afterOneList[1]?.unlocked, true);
|
||||
assert.equal(afterOneList[4]?.unlocked, false);
|
||||
|
||||
const history = await requestJson(app, `/chat/sessions/${first.chatId}/messages`, {
|
||||
headers: headers(token, ownerIp),
|
||||
});
|
||||
assert.equal(history.status, 200);
|
||||
const messages = (history.body.data?.messages as { role: string; content: string }[]) ?? [];
|
||||
assert.ok(messages.filter((m) => m.role === 'user').length >= 2);
|
||||
assert.equal(messages.some((m) => m.role === 'system'), false);
|
||||
|
||||
await completeSession(token, ownerIp, 2, owner.user.id);
|
||||
for (let order = 3; order <= PROGRAM_SESSION_COUNT - 2; order += 1) {
|
||||
await completeSession(token, ownerIp, order, owner.user.id);
|
||||
}
|
||||
await completeSession(token, ownerIp, PROGRAM_SESSION_COUNT - 1, owner.user.id);
|
||||
|
||||
const beforeFinal = await requestJson(app, '/journey', { headers: headers(token, ownerIp) });
|
||||
assert.equal(
|
||||
(beforeFinal.body.data?.permissions as { canTakePostTest: boolean }).canTakePostTest,
|
||||
false,
|
||||
);
|
||||
|
||||
await completeSession(token, ownerIp, PROGRAM_SESSION_COUNT, owner.user.id);
|
||||
|
||||
const afterTraining = await requestJson(app, '/journey', { headers: headers(token, ownerIp) });
|
||||
assert.ok(afterTraining.body.data?.trainingCompletedAt);
|
||||
assert.equal((afterTraining.body.data as { currentStep: string }).currentStep, 'training_completed');
|
||||
assert.equal(
|
||||
(afterTraining.body.data?.permissions as { canTakePostTest: boolean }).canTakePostTest,
|
||||
true,
|
||||
);
|
||||
|
||||
const postTooLateLocked = await requestJson(app, '/chat/sessions', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ sessionOrder: 1 }),
|
||||
});
|
||||
assert.ok(postTooLateLocked.status === 201 || postTooLateLocked.status === 403);
|
||||
|
||||
const post = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ phase: 'post', answers: pcqAnswers(5) }),
|
||||
});
|
||||
assert.equal(post.status, 201, JSON.stringify(post.body));
|
||||
|
||||
const duplicatePost = await requestJson(app, '/assessments/attempts', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
body: JSON.stringify({ phase: 'post', answers: pcqAnswers(6) }),
|
||||
});
|
||||
assert.equal(duplicatePost.status, 409);
|
||||
|
||||
const finished = await requestJson(app, '/journey', { headers: headers(token, ownerIp) });
|
||||
assert.equal((finished.body.data as { currentStep: string }).currentStep, 'completed');
|
||||
assert.equal((finished.body.data?.permissions as { isCompleted: boolean }).isCompleted, true);
|
||||
assert.ok(finished.body.data?.postTestCompletedAt);
|
||||
|
||||
const other = await registerUser('other', otherIp);
|
||||
const otherJourney = await requestJson(app, '/journey', {
|
||||
headers: headers(other.token, otherIp),
|
||||
});
|
||||
assert.equal(otherJourney.status, 200);
|
||||
assert.equal((otherJourney.body.data?.permissions as { canTakePreTest: boolean }).canTakePreTest, true);
|
||||
assert.equal(otherJourney.body.data?.preTestCompletedAt, null);
|
||||
|
||||
const otherChat = await requestJson(app, `/chat/sessions/${first.chatId}/messages`, {
|
||||
headers: headers(other.token, otherIp),
|
||||
});
|
||||
assert.equal(otherChat.status, 404);
|
||||
|
||||
const otherProfile = await requestJson(app, '/users/me', {
|
||||
headers: headers(other.token, otherIp),
|
||||
});
|
||||
assert.equal((otherProfile.body.data as { id: string }).id, other.externalId);
|
||||
assert.notEqual((otherProfile.body.data as { id: string }).id, owner.externalId);
|
||||
|
||||
const loggedOut = await requestJson(app, '/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: headers(token, ownerIp),
|
||||
});
|
||||
assert.equal(loggedOut.status, 200);
|
||||
|
||||
const expired = await requestJson(app, '/auth/me', { headers: headers(token, ownerIp) });
|
||||
assert.equal(expired.status, 401);
|
||||
|
||||
const ownerRow = await prisma.user.findUnique({
|
||||
where: { id: owner.user.id },
|
||||
include: {
|
||||
profile: true,
|
||||
journey: true,
|
||||
assessmentAttempts: true,
|
||||
sessionProgress: true,
|
||||
chatSessions: { include: { messages: true } },
|
||||
},
|
||||
});
|
||||
assert.ok(ownerRow?.profile);
|
||||
assert.ok(ownerRow.journey?.preTestCompletedAt);
|
||||
assert.ok(ownerRow.journey?.trainingCompletedAt);
|
||||
assert.ok(ownerRow.journey?.postTestCompletedAt);
|
||||
assert.equal(ownerRow.assessmentAttempts.length, 2);
|
||||
assert.equal(
|
||||
ownerRow.sessionProgress.filter((row) => row.status === 'completed').length,
|
||||
PROGRAM_SESSION_COUNT,
|
||||
);
|
||||
assert.ok(ownerRow.chatSessions.length >= 1);
|
||||
assert.ok(ownerRow.chatSessions.some((session) => session.messages.length >= 2));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { EnvValidationError, parseEnv } from '../src/config/env.js';
|
||||
|
||||
describe('environment validation', () => {
|
||||
it('accepts a valid configuration', () => {
|
||||
const env = parseEnv({
|
||||
NODE_ENV: 'test',
|
||||
DATABASE_URL: 'mysql://user:pass@localhost:3306/novya_test',
|
||||
LOG_LEVEL: 'silent',
|
||||
});
|
||||
|
||||
assert.equal(env.NODE_ENV, 'test');
|
||||
assert.equal(env.DATABASE_URL, 'mysql://user:pass@localhost:3306/novya_test');
|
||||
assert.equal(env.PORT, 3001);
|
||||
assert.equal(env.OPENAI_BASE_URL, 'https://api.gapgpt.app/v1');
|
||||
assert.equal(env.OPENAI_MODEL, 'gpt-4o-mini');
|
||||
assert.equal(env.OPENAI_API_KEY, '');
|
||||
});
|
||||
|
||||
it('fails clearly when DATABASE_URL is missing', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
parseEnv({
|
||||
NODE_ENV: 'test',
|
||||
}),
|
||||
(err: unknown) => {
|
||||
assert.ok(err instanceof EnvValidationError);
|
||||
assert.match(String(err.message), /DATABASE_URL.*Required/i);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('fails clearly when DATABASE_URL is not MySQL', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
parseEnv({
|
||||
NODE_ENV: 'test',
|
||||
DATABASE_URL: 'postgres://user:pass@localhost/db',
|
||||
}),
|
||||
(err: unknown) => {
|
||||
assert.ok(err instanceof EnvValidationError);
|
||||
assert.match(String(err.message), /MySQL connection string/);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { createApp } from '../src/app.js';
|
||||
import { checkDatabaseHealth } from '../src/lib/prisma.js';
|
||||
|
||||
export type JsonResponse = {
|
||||
success?: boolean;
|
||||
data?: Record<string, unknown>;
|
||||
error?: { code?: string; message?: string; details?: unknown };
|
||||
meta?: { requestId?: string };
|
||||
};
|
||||
|
||||
export function createTestApp() {
|
||||
return createApp();
|
||||
}
|
||||
|
||||
export async function isDatabaseAvailable(): Promise<boolean> {
|
||||
try {
|
||||
return await checkDatabaseHealth();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function authHeader(token: string): HeadersInit {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
}
|
||||
|
||||
export async function requestJson(
|
||||
app: ReturnType<typeof createApp>,
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<{ status: number; body: JsonResponse; raw: string }> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.body && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
|
||||
const response = await app.fetch(new Request(`http://localhost${path}`, { ...init, headers }));
|
||||
const raw = await response.text();
|
||||
let body: JsonResponse = {};
|
||||
try {
|
||||
body = JSON.parse(raw) as JsonResponse;
|
||||
} catch {
|
||||
body = {};
|
||||
}
|
||||
|
||||
return { status: response.status, body, raw };
|
||||
}
|
||||
|
||||
export function assertNoSecrets(raw: string): void {
|
||||
if (/passwordHash/i.test(raw) || /tokenHash/i.test(raw) || /\$argon2/i.test(raw)) {
|
||||
throw new Error(`Response leaked authentication secrets: ${raw}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { hashPassword, isArgon2idHash, verifyPassword } from '../src/modules/auth/password.js';
|
||||
import { generateSessionToken, hashSessionToken } from '../src/modules/auth/sessionToken.js';
|
||||
import { redactObject } from '../src/middleware/requestLogger.js';
|
||||
|
||||
describe('password hashing', () => {
|
||||
it('hashes with Argon2id and never stores plaintext', async () => {
|
||||
const password = 'correct-horse-battery';
|
||||
const hashed = await hashPassword(password);
|
||||
|
||||
assert.notEqual(hashed, password);
|
||||
assert.equal(isArgon2idHash(hashed), true);
|
||||
assert.equal(await verifyPassword(password, hashed), true);
|
||||
assert.equal(await verifyPassword('wrong-password', hashed), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('session tokens', () => {
|
||||
it('hashes opaque tokens with SHA-256', () => {
|
||||
const token = generateSessionToken();
|
||||
const hashed = hashSessionToken(token);
|
||||
|
||||
assert.notEqual(hashed, token);
|
||||
assert.match(hashed, /^[a-f0-9]{64}$/);
|
||||
assert.equal(hashSessionToken(token), hashed);
|
||||
});
|
||||
});
|
||||
|
||||
describe('log redaction', () => {
|
||||
it('redacts passwords, tokens, and authorization headers', () => {
|
||||
const redacted = redactObject({
|
||||
password: 'secret',
|
||||
passwordHash: 'hash',
|
||||
authorization: 'Bearer raw-session-token',
|
||||
token: 'raw-session-token',
|
||||
email: 'user@example.com',
|
||||
});
|
||||
|
||||
assert.equal(redacted.password, '[REDACTED]');
|
||||
assert.equal(redacted.passwordHash, '[REDACTED]');
|
||||
assert.equal(redacted.authorization, '[REDACTED]');
|
||||
assert.equal(redacted.token, '[REDACTED]');
|
||||
assert.equal(redacted.email, 'user@example.com');
|
||||
assert.doesNotMatch(JSON.stringify(redacted), /raw-session-token/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { prisma } from '../src/lib/prisma.js';
|
||||
import {
|
||||
assertNoSecrets,
|
||||
authHeader,
|
||||
createTestApp,
|
||||
isDatabaseAvailable,
|
||||
requestJson,
|
||||
} from './helpers.js';
|
||||
|
||||
const app = createTestApp();
|
||||
const createdUserIds: bigint[] = [];
|
||||
|
||||
describe('profile API', () => {
|
||||
let dbAvailable = false;
|
||||
|
||||
before(async () => {
|
||||
dbAvailable = await isDatabaseAvailable();
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (dbAvailable && createdUserIds.length > 0) {
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdUserIds } } });
|
||||
}
|
||||
});
|
||||
|
||||
async function createAuthenticatedUser() {
|
||||
const email = `profile-${Date.now()}-${Math.random().toString(16).slice(2)}@example.com`;
|
||||
const registered = await requestJson(app, '/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password: 'password12' }),
|
||||
});
|
||||
const id = (registered.body.data?.user as { id: string }).id;
|
||||
const user = await prisma.user.findUnique({ where: { externalId: id } });
|
||||
if (user) {
|
||||
createdUserIds.push(user.id);
|
||||
}
|
||||
|
||||
return {
|
||||
token: registered.body.data?.sessionToken as string,
|
||||
id,
|
||||
};
|
||||
}
|
||||
|
||||
it('rejects unauthenticated profile access', async () => {
|
||||
const missing = await requestJson(app, '/users/me');
|
||||
assert.equal(missing.status, 401);
|
||||
});
|
||||
|
||||
it('lets an authenticated user read and update their own profile', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const { token } = await createAuthenticatedUser();
|
||||
|
||||
const before = await requestJson(app, '/users/me', { headers: authHeader(token) });
|
||||
assert.equal(before.status, 200);
|
||||
assert.equal((before.body.data as { profile: unknown }).profile, null);
|
||||
assert.equal((before.body.data as { profileComplete: boolean }).profileComplete, false);
|
||||
|
||||
const updated = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: ' علی رضایی ', age: 29 }),
|
||||
});
|
||||
|
||||
assert.equal(updated.status, 200);
|
||||
assert.equal((updated.body.data as { profileComplete: boolean }).profileComplete, true);
|
||||
assert.equal((updated.body.data as { profile: { name: string; age: number } }).profile.name, 'علی رضایی');
|
||||
assert.equal((updated.body.data as { profile: { name: string; age: number } }).profile.age, 29);
|
||||
assertNoSecrets(updated.raw);
|
||||
});
|
||||
|
||||
it('validates name and requires an integer age', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const { token } = await createAuthenticatedUser();
|
||||
|
||||
const emptyName = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: ' ', age: 20 }),
|
||||
});
|
||||
assert.equal(emptyName.status, 422);
|
||||
|
||||
const decimalAge = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: 'Sara', age: 17.5 }),
|
||||
});
|
||||
assert.equal(decimalAge.status, 422);
|
||||
|
||||
const stringAge = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: 'Sara', age: '17' }),
|
||||
});
|
||||
assert.equal(stringAge.status, 422);
|
||||
|
||||
const underage = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: 'Sara', age: 17 }),
|
||||
});
|
||||
assert.equal(underage.status, 422);
|
||||
|
||||
const overage = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: 'Sara', age: 101 }),
|
||||
});
|
||||
assert.equal(overage.status, 422);
|
||||
});
|
||||
|
||||
it('does not expose a userId parameter for modifying another user', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const first = await createAuthenticatedUser();
|
||||
const second = await createAuthenticatedUser();
|
||||
|
||||
const missing = await requestJson(app, `/users/${second.id}/profile`, {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(first.token),
|
||||
body: JSON.stringify({ name: 'Hacker', age: 40 }),
|
||||
});
|
||||
assert.equal(missing.status, 404);
|
||||
|
||||
const other = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(first.token),
|
||||
body: JSON.stringify({ name: 'Only Me', age: 22 }),
|
||||
});
|
||||
assert.equal(other.status, 200);
|
||||
|
||||
const secondRead = await requestJson(app, '/users/me', { headers: authHeader(second.token) });
|
||||
assert.equal((secondRead.body.data as { profile: unknown }).profile, null);
|
||||
});
|
||||
|
||||
it('requires both name and age when creating a profile', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const { token } = await createAuthenticatedUser();
|
||||
const partial = await requestJson(app, '/users/me/profile', {
|
||||
method: 'PATCH',
|
||||
headers: authHeader(token),
|
||||
body: JSON.stringify({ name: 'Only Name' }),
|
||||
});
|
||||
assert.equal(partial.status, 422);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import {
|
||||
PCQ_QUESTION_IDS,
|
||||
applyReverseScoring,
|
||||
isReverseScored,
|
||||
parseLikertValue,
|
||||
scoreAnswer,
|
||||
scoreAssessment,
|
||||
ScoringValidationError,
|
||||
validateAnswers,
|
||||
} from '../src/modules/assessments/scoring/index.js';
|
||||
|
||||
function answersWithValue(value: string | number) {
|
||||
return PCQ_QUESTION_IDS.map((questionId) => ({ questionId, selectedValue: value }));
|
||||
}
|
||||
|
||||
describe('PCQ-24 scoring engine', () => {
|
||||
it('reverse-scores pcq_13, pcq_20, and pcq_23 with 7 - raw', () => {
|
||||
assert.equal(isReverseScored('pcq_13'), true);
|
||||
assert.equal(isReverseScored('pcq_20'), true);
|
||||
assert.equal(isReverseScored('pcq_23'), true);
|
||||
assert.equal(isReverseScored('pcq_01'), false);
|
||||
assert.equal(applyReverseScoring(1), 6);
|
||||
assert.equal(applyReverseScoring(6), 1);
|
||||
assert.equal(applyReverseScoring('4'), 3);
|
||||
});
|
||||
|
||||
it('keeps raw Likert and stores reverse-scored points separately', () => {
|
||||
const scored = scoreAnswer('pcq_13', '2');
|
||||
assert.ok(scored);
|
||||
assert.equal(scored.selectedValue, 2);
|
||||
assert.equal(scored.rawScore, 5);
|
||||
assert.equal(scored.dimension, 'resilience');
|
||||
assert.equal(scored.isReverseScored, true);
|
||||
});
|
||||
|
||||
it('scores a uniform Likert-4 attempt with known totals', () => {
|
||||
const result = scoreAssessment('pre', answersWithValue(4));
|
||||
assert.equal(result.totalScore, 93);
|
||||
assert.equal(result.dimensions.efficacy, 24);
|
||||
assert.equal(result.dimensions.hope, 24);
|
||||
assert.equal(result.dimensions.resilience, 23);
|
||||
assert.equal(result.dimensions.optimism, 22);
|
||||
|
||||
const reverse = result.answers.filter((answer) => answer.isReverseScored);
|
||||
assert.equal(reverse.length, 3);
|
||||
for (const answer of reverse) {
|
||||
assert.equal(answer.selectedValue, 4);
|
||||
assert.equal(answer.rawScore, 3);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects incomplete or out-of-range answers', () => {
|
||||
assert.equal(validateAnswers(answersWithValue(4).slice(0, 23)).isValid, false);
|
||||
assert.equal(parseLikertValue('7'), null);
|
||||
assert.throws(
|
||||
() => scoreAssessment('pre', answersWithValue(7)),
|
||||
(err: unknown) => err instanceof ScoringValidationError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { createDB } from 'mysql-memory-server';
|
||||
|
||||
process.env.NODE_ENV ??= 'test';
|
||||
process.env.LOG_LEVEL ??= 'silent';
|
||||
process.env.CORS_ORIGIN ??= 'http://localhost:5173';
|
||||
process.env.RATE_LIMIT_MAX ??= '10000';
|
||||
process.env.AUTH_RATE_LIMIT_MAX ??= '10000';
|
||||
process.env.AUTH_SESSION_TTL_HOURS ??= '168';
|
||||
|
||||
const DOCKER_TEST_URL = 'mysql://novya:novya@127.0.0.1:3306/novya_test';
|
||||
|
||||
type MemoryDb = Awaited<ReturnType<typeof createDB>>;
|
||||
|
||||
const globalForTestDb = globalThis as unknown as {
|
||||
__novyaMemoryDb?: MemoryDb;
|
||||
};
|
||||
|
||||
function migrateDeploy(): void {
|
||||
execSync('npx prisma generate --schema=./prisma/schema.prisma', {
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
});
|
||||
execSync('npx prisma migrate deploy --schema=./prisma/schema.prisma', {
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
});
|
||||
}
|
||||
|
||||
async function startTestDatabase(): Promise<void> {
|
||||
const preferMemory = process.env.USE_MEMORY_MYSQL === 'true';
|
||||
const dockerUrl = process.env.TEST_DATABASE_URL ?? DOCKER_TEST_URL;
|
||||
|
||||
if (!preferMemory) {
|
||||
process.env.DATABASE_URL = dockerUrl;
|
||||
try {
|
||||
migrateDeploy();
|
||||
return;
|
||||
} catch (err) {
|
||||
console.warn('Docker MySQL (novya_test) is not ready. Falling back if possible.');
|
||||
console.warn(err instanceof Error ? err.message : err);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.SKIP_MEMORY_MYSQL === 'true') {
|
||||
process.env.DATABASE_URL = dockerUrl;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const db = await createDB({
|
||||
version: '8.4.x',
|
||||
dbName: 'novya_test',
|
||||
username: 'root',
|
||||
xEnabled: 'OFF',
|
||||
logLevel: 'ERROR',
|
||||
downloadBinaryOnce: true,
|
||||
downloadRetries: 1,
|
||||
});
|
||||
|
||||
globalForTestDb.__novyaMemoryDb = db;
|
||||
process.env.DATABASE_URL = `mysql://root@127.0.0.1:${db.port}/novya_test`;
|
||||
migrateDeploy();
|
||||
|
||||
const stop = async () => {
|
||||
try {
|
||||
await db.stop();
|
||||
} catch {
|
||||
// ignore shutdown races
|
||||
}
|
||||
};
|
||||
|
||||
process.once('exit', () => {
|
||||
void stop();
|
||||
});
|
||||
process.once('SIGINT', () => {
|
||||
void stop();
|
||||
});
|
||||
process.once('SIGTERM', () => {
|
||||
void stop();
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
'MySQL is not running. Database tests will be skipped. Start Docker: docker compose -f docker-compose.dev.yml up -d',
|
||||
);
|
||||
console.warn(err instanceof Error ? err.message : err);
|
||||
process.env.DATABASE_URL ??= dockerUrl;
|
||||
}
|
||||
}
|
||||
|
||||
await startTestDatabase();
|
||||
@@ -0,0 +1,166 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, it } from 'node:test';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createPrismaClient } from '../src/lib/prisma.js';
|
||||
|
||||
const databaseUrl =
|
||||
process.env.DATABASE_URL ?? 'mysql://novya:novya@127.0.0.1:3306/novya_test';
|
||||
|
||||
describe('User and UserProfile persistence', () => {
|
||||
let prisma = createPrismaClient(databaseUrl);
|
||||
let dbAvailable = false;
|
||||
const createdUserIds: bigint[] = [];
|
||||
|
||||
before(async () => {
|
||||
try {
|
||||
await prisma.$connect();
|
||||
dbAvailable = await prisma.$queryRaw`SELECT 1`.then(() => true).catch(() => false);
|
||||
} catch {
|
||||
dbAvailable = false;
|
||||
}
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (dbAvailable) {
|
||||
if (createdUserIds.length > 0) {
|
||||
await prisma.user.deleteMany({
|
||||
where: { id: { in: createdUserIds } },
|
||||
});
|
||||
}
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
it('creates User with stable externalId', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.create({ data: {} });
|
||||
createdUserIds.push(user.id);
|
||||
|
||||
assert.ok(user.id);
|
||||
assert.match(user.externalId, /^[0-9a-f-]{36}$/i);
|
||||
assert.ok(user.createdAt instanceof Date);
|
||||
assert.ok(user.updatedAt instanceof Date);
|
||||
});
|
||||
|
||||
it('creates UserProfile with name and age', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
profile: {
|
||||
create: {
|
||||
name: 'علی رضایی',
|
||||
age: 29,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: { profile: true },
|
||||
});
|
||||
createdUserIds.push(user.id);
|
||||
|
||||
assert.ok(user.profile);
|
||||
assert.equal(user.profile.name, 'علی رضایی');
|
||||
assert.equal(user.profile.age, 29);
|
||||
});
|
||||
|
||||
it('loads User → UserProfile relation', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
profile: {
|
||||
create: {
|
||||
name: 'Sara Ahmadi',
|
||||
age: 34,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
createdUserIds.push(user.id);
|
||||
|
||||
const loaded = await prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
include: { profile: true },
|
||||
});
|
||||
|
||||
assert.ok(loaded?.profile);
|
||||
assert.equal(loaded.profile.name, 'Sara Ahmadi');
|
||||
assert.equal(loaded.profile.age, 34);
|
||||
});
|
||||
|
||||
it('persists name and age updates on profile', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
profile: {
|
||||
create: {
|
||||
name: 'Initial Name',
|
||||
age: 25,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: { profile: true },
|
||||
});
|
||||
createdUserIds.push(user.id);
|
||||
|
||||
const updated = await prisma.userProfile.update({
|
||||
where: { userId: user.id },
|
||||
data: {
|
||||
name: 'Updated Name',
|
||||
age: 26,
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(updated.name, 'Updated Name');
|
||||
assert.equal(updated.age, 26);
|
||||
});
|
||||
|
||||
it('prevents duplicate profile for one user', async (t) => {
|
||||
if (!dbAvailable) {
|
||||
t.skip('MySQL is not running');
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
profile: {
|
||||
create: {
|
||||
name: 'First Profile',
|
||||
age: 30,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
createdUserIds.push(user.id);
|
||||
|
||||
await assert.rejects(
|
||||
() =>
|
||||
prisma.userProfile.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
name: 'Duplicate Profile',
|
||||
age: 31,
|
||||
},
|
||||
}),
|
||||
(err: unknown) => {
|
||||
assert.ok(err instanceof Prisma.PrismaClientKnownRequestError);
|
||||
assert.equal(err.code, 'P2002');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user