16 Commits

Author SHA1 Message Date
Anton
16b5af3365 feat: export LlmService interface
Made-with: Cursor
2026-03-04 14:39:04 +03:00
Anton
39721e37ff feat: log LLM metadata to question_cache_meta
Made-with: Cursor
2026-03-04 14:38:44 +03:00
Anton
0baeb1104a feat: add LLM retry and fallback
Made-with: Cursor
2026-03-04 14:37:18 +03:00
Anton
04ad02be5e feat: add LLM question generation
Made-with: Cursor
2026-03-04 14:36:50 +03:00
Anton
0172b4518d feat: add LlmService base
Made-with: Cursor
2026-03-04 14:17:15 +03:00
Anton
f7e865721a feat: add stats to profile response
Made-with: Cursor
2026-03-04 14:16:59 +03:00
Anton
6530e81402 feat: add profile routes
Made-with: Cursor
2026-03-04 14:16:23 +03:00
Anton
b7573acbed feat: add UserService
Made-with: Cursor
2026-03-04 14:15:49 +03:00
Anton
bf544b3e5b feat: add subscription middleware
Made-with: Cursor
2026-03-04 14:15:09 +03:00
Anton
c5a4e26f33 feat: register auth routes in app
Made-with: Cursor
2026-03-04 14:12:24 +03:00
Anton
682885ce5a feat: add rate limiting to auth endpoints
Made-with: Cursor
2026-03-04 14:11:29 +03:00
Anton
78809a064e feat: add email verification and password reset
Made-with: Cursor
2026-03-04 14:07:45 +03:00
Anton
e2baa14814 feat: add auth routes
Made-with: Cursor
2026-03-04 14:07:03 +03:00
Anton
181be58a60 feat: add auth plugin
Made-with: Cursor
2026-03-04 14:06:28 +03:00
Anton
8551d5f6d2 feat: add AuthService
Made-with: Cursor
2026-03-04 14:05:34 +03:00
Anton
5cd13cd8ea feat: add password hashing and JWT utils
Made-with: Cursor
2026-03-04 14:04:24 +03:00
15 changed files with 1164 additions and 0 deletions

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "samreshu_docs"]
path = samreshu_docs
url = https://git.vakanaut.ru/admin/samreshu_docs.git

1
samreshu_docs Submodule

Submodule samreshu_docs added at 99cd8ae727

View File

@@ -4,6 +4,9 @@ import databasePlugin from './plugins/database.js';
import redisPlugin from './plugins/redis.js'; import redisPlugin from './plugins/redis.js';
import securityPlugin from './plugins/security.js'; import securityPlugin from './plugins/security.js';
import rateLimitPlugin from './plugins/rateLimit.js'; import rateLimitPlugin from './plugins/rateLimit.js';
import authPlugin from './plugins/auth.js';
import subscriptionPlugin from './plugins/subscription.js';
import { authRoutes } from './routes/auth.js';
import { env } from './config/env.js'; import { env } from './config/env.js';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
@@ -69,6 +72,9 @@ export async function buildApp(): Promise<FastifyInstance> {
await app.register(databasePlugin); await app.register(databasePlugin);
await app.register(securityPlugin); await app.register(securityPlugin);
await app.register(rateLimitPlugin); await app.register(rateLimitPlugin);
await app.register(authPlugin);
await app.register(subscriptionPlugin);
await app.register(authRoutes, { prefix: '/auth' });
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() })); app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));

View File

@@ -14,9 +14,11 @@ const envSchema = z.object({
LLM_BASE_URL: z.string().url().default('http://localhost:11434/v1'), LLM_BASE_URL: z.string().url().default('http://localhost:11434/v1'),
LLM_MODEL: z.string().default('qwen2.5:14b'), LLM_MODEL: z.string().default('qwen2.5:14b'),
LLM_FALLBACK_MODEL: z.string().optional(),
LLM_API_KEY: z.string().optional(), LLM_API_KEY: z.string().optional(),
LLM_TIMEOUT_MS: z.coerce.number().default(15000), LLM_TIMEOUT_MS: z.coerce.number().default(15000),
LLM_MAX_RETRIES: z.coerce.number().min(0).default(1), LLM_MAX_RETRIES: z.coerce.number().min(0).default(1),
LLM_RETRY_DELAY_MS: z.coerce.number().min(0).default(1000),
LLM_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.7), LLM_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.7),
LLM_MAX_TOKENS: z.coerce.number().default(2048), LLM_MAX_TOKENS: z.coerce.number().default(2048),

42
src/plugins/auth.ts Normal file
View File

@@ -0,0 +1,42 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import fp from 'fastify-plugin';
import { verifyToken, isAccessPayload } from '../utils/jwt.js';
import { unauthorized } from '../utils/errors.js';
declare module 'fastify' {
interface FastifyInstance {
authenticate: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
}
interface FastifyRequest {
user?: { id: string; email: string };
}
}
export async function authenticate(req: FastifyRequest, _reply: FastifyReply): Promise<void> {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
throw unauthorized('Missing or invalid authorization header');
}
const token = authHeader.slice(7);
try {
const payload = await verifyToken(token);
if (!isAccessPayload(payload)) {
throw unauthorized('Invalid token type');
}
req.user = { id: payload.sub, email: payload.email };
} catch {
throw unauthorized('Invalid or expired token');
}
}
const authPlugin = async (app: FastifyInstance) => {
app.decorateRequest('user', undefined);
app.decorate('authenticate', authenticate);
};
export default fp(authPlugin, { name: 'auth' });

View File

@@ -29,6 +29,7 @@ const rateLimitPlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
app.decorate('rateLimitOptions', options); app.decorate('rateLimitOptions', options);
await app.register(rateLimit, { await app.register(rateLimit, {
global: false,
max: options.apiGuest.max, max: options.apiGuest.max,
timeWindow: options.apiGuest.timeWindow, timeWindow: options.apiGuest.timeWindow,
keyGenerator: (req) => { keyGenerator: (req) => {

View File

@@ -0,0 +1,71 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import fp from 'fastify-plugin';
import { eq } from 'drizzle-orm';
import { subscriptions } from '../db/schema/subscriptions.js';
import { forbidden } from '../utils/errors.js';
export type SubscriptionInfo = {
plan: 'free' | 'pro';
status: 'active' | 'trialing' | 'cancelled' | 'expired';
isPro: boolean;
expiresAt: Date | null;
};
declare module 'fastify' {
interface FastifyRequest {
subscription?: SubscriptionInfo | null;
}
interface FastifyInstance {
withSubscription: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
requirePro: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
}
}
async function loadSubscription(db: FastifyInstance['db'], userId: string): Promise<SubscriptionInfo | null> {
const [sub] = await db
.select()
.from(subscriptions)
.where(eq(subscriptions.userId, userId))
.limit(1);
if (!sub) return null;
const now = new Date();
const isExpired = sub.expiresAt && sub.expiresAt < now;
const isPro =
sub.plan === 'pro' &&
(sub.status === 'active' || sub.status === 'trialing') &&
!isExpired;
return {
plan: sub.plan as 'free' | 'pro',
status: sub.status as SubscriptionInfo['status'],
isPro,
expiresAt: sub.expiresAt,
};
}
export async function requirePro(req: FastifyRequest, _reply: FastifyReply): Promise<void> {
const sub = req.subscription;
if (!sub?.isPro) {
throw forbidden('Pro subscription required');
}
}
const subscriptionPlugin = async (app: FastifyInstance) => {
app.decorateRequest('subscription', undefined);
app.decorate('withSubscription', async (req: FastifyRequest, _reply: FastifyReply) => {
if (!req.user?.id) return;
const sub = await loadSubscription(app.db, req.user.id);
req.subscription = sub;
});
app.decorate('requirePro', requirePro);
};
export default fp(subscriptionPlugin, {
name: 'subscription',
dependencies: ['database', 'auth'],
});

168
src/routes/auth.ts Normal file
View File

@@ -0,0 +1,168 @@
import type { FastifyInstance } from 'fastify';
import { AuthService } from '../services/auth/auth.service.js';
const registerSchema = {
body: {
type: 'object',
required: ['email', 'password', 'nickname'],
properties: {
email: { type: 'string', minLength: 1 },
password: { type: 'string', minLength: 8 },
nickname: { type: 'string', minLength: 2, maxLength: 30 },
},
},
};
const loginSchema = {
body: {
type: 'object',
required: ['email', 'password'],
properties: {
email: { type: 'string', minLength: 1 },
password: { type: 'string' },
},
},
};
const refreshTokenSchema = {
body: {
type: 'object',
required: ['refreshToken'],
properties: {
refreshToken: { type: 'string' },
},
},
};
const logoutSchema = refreshTokenSchema;
const verifyEmailSchema = {
body: {
type: 'object',
required: ['userId', 'code'],
properties: {
userId: { type: 'string', minLength: 1 },
code: { type: 'string', minLength: 1, maxLength: 10 },
},
},
};
const forgotPasswordSchema = {
body: {
type: 'object',
required: ['email'],
properties: {
email: { type: 'string', minLength: 1 },
},
},
};
const resetPasswordSchema = {
body: {
type: 'object',
required: ['token', 'newPassword'],
properties: {
token: { type: 'string' },
newPassword: { type: 'string', minLength: 8 },
},
},
};
export async function authRoutes(app: FastifyInstance) {
const authService = new AuthService(app.db);
const { rateLimitOptions } = app;
app.post(
'/register',
{ schema: registerSchema, config: { rateLimit: rateLimitOptions.register } },
async (req, reply) => {
const body = req.body as { email: string; password: string; nickname: string };
const { userId, verificationCode } = await authService.register(body);
return reply.status(201).send({
userId,
message: 'Registration successful. Please verify your email.',
verificationCode,
});
},
);
app.post(
'/login',
{ schema: loginSchema, config: { rateLimit: rateLimitOptions.login } },
async (req, reply) => {
const body = req.body as { email: string; password: string };
const userAgent = req.headers['user-agent'];
const ipAddress = req.ip;
const result = await authService.login({
email: body.email,
password: body.password,
userAgent,
ipAddress,
});
return reply.send(result);
},
);
app.post(
'/logout',
{ schema: logoutSchema, config: { rateLimit: rateLimitOptions.apiGuest } },
async (req, reply) => {
const body = req.body as { refreshToken: string };
await authService.logout(body.refreshToken);
return reply.status(204).send();
},
);
app.post(
'/refresh',
{ schema: refreshTokenSchema, config: { rateLimit: rateLimitOptions.apiGuest } },
async (req, reply) => {
const body = req.body as { refreshToken: string };
const userAgent = req.headers['user-agent'];
const ipAddress = req.ip;
const result = await authService.refresh({
refreshToken: body.refreshToken,
userAgent,
ipAddress,
});
return reply.send(result);
},
);
app.post(
'/verify-email',
{ schema: verifyEmailSchema, config: { rateLimit: rateLimitOptions.verifyEmail } },
async (req, reply) => {
const body = req.body as { userId: string; code: string };
await authService.verifyEmail(body.userId, body.code);
return reply.send({ message: 'Email verified successfully' });
},
);
app.post(
'/forgot-password',
{ schema: forgotPasswordSchema, config: { rateLimit: rateLimitOptions.forgotPassword } },
async (req, reply) => {
const body = req.body as { email: string };
await authService.forgotPassword(body.email);
return reply.send({
message: 'If the email exists, a reset link has been sent.',
});
},
);
app.post(
'/reset-password',
{ schema: resetPasswordSchema, config: { rateLimit: rateLimitOptions.forgotPassword } },
async (req, reply) => {
const body = req.body as { token: string; newPassword: string };
await authService.resetPassword(body.token, body.newPassword);
return reply.send({ message: 'Password reset successfully' });
},
);
}

73
src/routes/profile.ts Normal file
View File

@@ -0,0 +1,73 @@
import type { FastifyInstance } from 'fastify';
import { UserService } from '../services/user/user.service.js';
const patchProfileSchema = {
body: {
type: 'object',
properties: {
nickname: { type: 'string', minLength: 2, maxLength: 30 },
avatarUrl: { type: ['string', 'null'], maxLength: 500 },
country: { type: ['string', 'null'], maxLength: 100 },
city: { type: ['string', 'null'], maxLength: 100 },
selfLevel: { type: ['string', 'null'], enum: ['jun', 'mid', 'sen'] },
isPublic: { type: 'boolean' },
},
additionalProperties: false,
},
};
const usernameParamsSchema = {
params: {
type: 'object',
required: ['username'],
properties: {
username: { type: 'string', minLength: 2, maxLength: 30 },
},
},
};
export async function profileRoutes(app: FastifyInstance) {
const userService = new UserService(app.db);
const { rateLimitOptions } = app;
app.get(
'/',
{
config: { rateLimit: rateLimitOptions.apiAuthed },
preHandler: [app.authenticate, app.withSubscription],
},
async (req, reply) => {
const userId = req.user!.id;
const profile = await userService.getPrivateProfile(userId);
return reply.send(profile);
},
);
app.patch(
'/',
{
schema: patchProfileSchema,
config: { rateLimit: rateLimitOptions.apiAuthed },
preHandler: [app.authenticate],
},
async (req, reply) => {
const userId = req.user!.id;
const body = req.body as Parameters<UserService['updateProfile']>[1];
const profile = await userService.updateProfile(userId, body);
return reply.send(profile);
},
);
app.get(
'/:username',
{
schema: usernameParamsSchema,
config: { rateLimit: rateLimitOptions.apiGuest },
},
async (req, reply) => {
const { username } = req.params as { username: string };
const profile = await userService.getPublicProfile(username);
return reply.send(profile);
},
);
}

View File

@@ -0,0 +1,304 @@
import { eq, and, gt } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type * as schema from '../../db/schema/index.js';
import { users, sessions, emailVerificationCodes, passwordResetTokens } from '../../db/schema/index.js';
import { hashPassword, verifyPassword } from '../../utils/password.js';
import {
signAccessToken,
signRefreshToken,
verifyToken,
isRefreshPayload,
hashToken,
} from '../../utils/jwt.js';
import {
AppError,
conflict,
unauthorized,
notFound,
ERROR_CODES,
} from '../../utils/errors.js';
import { randomBytes, randomUUID } from 'node:crypto';
type Db = NodePgDatabase<typeof schema>;
export interface RegisterInput {
email: string;
password: string;
nickname: string;
}
export interface LoginInput {
email: string;
password: string;
userAgent?: string;
ipAddress?: string;
}
export interface LoginResult {
accessToken: string;
refreshToken: string;
expiresIn: number;
}
export interface RefreshInput {
refreshToken: string;
userAgent?: string;
ipAddress?: string;
}
export interface ForgotPasswordResult {
token: string;
expiresAt: Date;
}
const REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const VERIFICATION_CODE_LENGTH = 6;
const VERIFICATION_CODE_TTL_MS = 15 * 60 * 1000;
const RESET_TOKEN_TTL_MS = 60 * 60 * 1000;
export class AuthService {
constructor(private readonly db: Db) {}
async register(input: RegisterInput): Promise<{ userId: string; verificationCode: string }> {
const [existing] = await this.db
.select()
.from(users)
.where(eq(users.email, input.email.toLowerCase().trim()))
.limit(1);
if (existing) {
throw conflict(ERROR_CODES.EMAIL_TAKEN, 'Email already registered');
}
const [nicknameConflict] = await this.db
.select()
.from(users)
.where(eq(users.nickname, input.nickname.trim()))
.limit(1);
if (nicknameConflict) {
throw conflict(ERROR_CODES.NICKNAME_TAKEN, 'Nickname already taken');
}
const passwordHash = await hashPassword(input.password);
const [user] = await this.db
.insert(users)
.values({
email: input.email.toLowerCase().trim(),
passwordHash,
nickname: input.nickname.trim(),
})
.returning({ id: users.id });
if (!user) {
throw new AppError(ERROR_CODES.INTERNAL_ERROR, 'Failed to create user', 500);
}
const code = randomBytes(VERIFICATION_CODE_LENGTH)
.toString('hex')
.slice(0, VERIFICATION_CODE_LENGTH)
.toUpperCase();
const expiresAt = new Date(Date.now() + VERIFICATION_CODE_TTL_MS);
await this.db.insert(emailVerificationCodes).values({
userId: user.id,
code,
expiresAt,
});
return { userId: user.id, verificationCode: code };
}
async login(input: LoginInput): Promise<LoginResult> {
const [user] = await this.db
.select()
.from(users)
.where(eq(users.email, input.email.toLowerCase().trim()))
.limit(1);
if (!user || !(await verifyPassword(user.passwordHash, input.password))) {
throw unauthorized('Invalid email or password');
}
const [accessToken, refreshToken] = await Promise.all([
signAccessToken({ sub: user.id, email: user.email }),
signRefreshToken({ sub: user.id, sid: randomUUID() }),
]);
const refreshHash = hashToken(refreshToken);
const expiresAt = new Date(Date.now() + REFRESH_TTL_MS);
await this.db.insert(sessions).values({
userId: user.id,
refreshTokenHash: refreshHash,
userAgent: input.userAgent ?? null,
ipAddress: input.ipAddress ?? null,
expiresAt,
});
return {
accessToken,
refreshToken,
expiresIn: Math.floor(REFRESH_TTL_MS / 1000),
};
}
async logout(refreshToken: string): Promise<void> {
const hash = hashToken(refreshToken);
await this.db.delete(sessions).where(eq(sessions.refreshTokenHash, hash));
}
async refresh(input: RefreshInput): Promise<LoginResult> {
const payload = await verifyToken(input.refreshToken);
if (!isRefreshPayload(payload)) {
throw unauthorized('Invalid refresh token');
}
const hash = hashToken(input.refreshToken);
const [session] = await this.db
.select()
.from(sessions)
.where(and(eq(sessions.refreshTokenHash, hash), gt(sessions.expiresAt, new Date())))
.limit(1);
if (!session) {
throw new AppError(ERROR_CODES.INVALID_REFRESH_TOKEN, 'Invalid or expired refresh token', 401);
}
await this.db.delete(sessions).where(eq(sessions.id, session.id));
const [user] = await this.db.select().from(users).where(eq(users.id, session.userId)).limit(1);
if (!user) {
throw notFound('User not found');
}
const [accessToken, newRefreshToken] = await Promise.all([
signAccessToken({ sub: user.id, email: user.email }),
signRefreshToken({ sub: user.id, sid: randomUUID() }),
]);
const newHash = hashToken(newRefreshToken);
const expiresAt = new Date(Date.now() + REFRESH_TTL_MS);
await this.db.insert(sessions).values({
userId: user.id,
refreshTokenHash: newHash,
userAgent: input.userAgent ?? session.userAgent,
ipAddress: input.ipAddress ?? session.ipAddress,
expiresAt,
});
return {
accessToken,
refreshToken: newRefreshToken,
expiresIn: Math.floor(REFRESH_TTL_MS / 1000),
};
}
async verifyEmail(userId: string, verificationCode: string): Promise<void> {
const codeUpper = verificationCode.toUpperCase();
const [record] = await this.db
.select()
.from(emailVerificationCodes)
.where(
and(
eq(emailVerificationCodes.userId, userId),
eq(emailVerificationCodes.code, codeUpper),
),
)
.limit(1);
if (!record) {
throw new AppError(ERROR_CODES.INVALID_CODE, 'Invalid or expired verification code', 400);
}
if (record.expiresAt < new Date()) {
await this.db
.delete(emailVerificationCodes)
.where(eq(emailVerificationCodes.id, record.id));
throw new AppError(ERROR_CODES.INVALID_CODE, 'Verification code expired', 400);
}
const [user] = await this.db.select().from(users).where(eq(users.id, userId)).limit(1);
if (!user) {
throw notFound('User not found');
}
if (user.emailVerifiedAt) {
throw new AppError(ERROR_CODES.ALREADY_VERIFIED, 'Email already verified', 400);
}
await this.db
.update(users)
.set({ emailVerifiedAt: new Date(), updatedAt: new Date() })
.where(eq(users.id, userId));
await this.db
.delete(emailVerificationCodes)
.where(eq(emailVerificationCodes.userId, userId));
}
async forgotPassword(email: string): Promise<ForgotPasswordResult> {
const [user] = await this.db
.select()
.from(users)
.where(eq(users.email, email.toLowerCase().trim()))
.limit(1);
if (!user) {
return {
token: '',
expiresAt: new Date(Date.now() + RESET_TOKEN_TTL_MS),
};
}
const token = randomBytes(32).toString('hex');
const tokenHash = hashToken(token);
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_MS);
await this.db.insert(passwordResetTokens).values({
userId: user.id,
tokenHash,
expiresAt,
});
return { token, expiresAt };
}
async resetPassword(token: string, newPassword: string): Promise<void> {
const tokenHash = hashToken(token);
const [record] = await this.db
.select()
.from(passwordResetTokens)
.where(eq(passwordResetTokens.tokenHash, tokenHash))
.limit(1);
if (!record) {
throw new AppError(ERROR_CODES.INVALID_RESET_TOKEN, 'Invalid or expired reset token', 400);
}
if (record.expiresAt < new Date()) {
await this.db
.delete(passwordResetTokens)
.where(eq(passwordResetTokens.id, record.id));
throw new AppError(ERROR_CODES.INVALID_RESET_TOKEN, 'Reset token expired', 400);
}
const passwordHash = await hashPassword(newPassword);
await this.db
.update(users)
.set({ passwordHash, updatedAt: new Date() })
.where(eq(users.id, record.userId));
await this.db
.delete(passwordResetTokens)
.where(eq(passwordResetTokens.id, record.id));
}
}

View File

@@ -0,0 +1,9 @@
export {
LlmService,
type ILlmService,
type LlmConfig,
type LlmGenerationMeta,
type GenerateQuestionsInput,
type GenerateQuestionsResult,
type GeneratedQuestion,
} from './llm.service.js';

View File

@@ -0,0 +1,242 @@
import { z } from 'zod';
import { createHash } from 'node:crypto';
import { env } from '../../config/env.js';
import type { Stack, Level, QuestionType } from '../../db/schema/enums.js';
export interface LlmConfig {
baseUrl: string;
model: string;
fallbackModel?: string;
apiKey?: string;
timeoutMs: number;
temperature: number;
maxTokens: number;
maxRetries: number;
retryDelayMs: number;
}
export interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface ChatCompletionResponse {
choices: Array<{
message?: { content: string };
text?: string;
}>;
}
const QUESTION_TYPES: QuestionType[] = ['single_choice', 'multiple_select', 'true_false', 'short_text'];
const optionSchema = z.object({
key: z.string().min(1),
text: z.string().min(1),
});
const generatedQuestionSchema = z.object({
questionText: z.string().min(1),
type: z.enum(QUESTION_TYPES as [string, ...string[]]),
options: z.array(optionSchema).optional(),
correctAnswer: z.union([z.string(), z.array(z.string())]),
explanation: z.string().min(1),
});
const generateQuestionsResponseSchema = z.object({
questions: z.array(generatedQuestionSchema),
});
export type GeneratedQuestion = z.infer<typeof generatedQuestionSchema> & {
stack: Stack;
level: Level;
};
export interface GenerateQuestionsInput {
stack: Stack;
level: Level;
count: number;
types?: QuestionType[];
}
/** Metadata for persisting to question_cache_meta (used by QuestionService) */
export interface LlmGenerationMeta {
llmModel: string;
promptHash: string;
generationTimeMs: number;
rawResponse: unknown;
}
export interface GenerateQuestionsResult {
questions: GeneratedQuestion[];
meta: LlmGenerationMeta;
}
/** Interface for QuestionService dependency injection and testing */
export interface ILlmService {
generateQuestions(input: GenerateQuestionsInput): Promise<GenerateQuestionsResult>;
}
export class LlmService implements ILlmService {
private readonly config: LlmConfig;
constructor(config?: Partial<LlmConfig>) {
this.config = {
baseUrl: config?.baseUrl ?? env.LLM_BASE_URL,
model: config?.model ?? env.LLM_MODEL,
fallbackModel: config?.fallbackModel ?? env.LLM_FALLBACK_MODEL,
apiKey: config?.apiKey ?? env.LLM_API_KEY,
timeoutMs: config?.timeoutMs ?? env.LLM_TIMEOUT_MS,
temperature: config?.temperature ?? env.LLM_TEMPERATURE,
maxTokens: config?.maxTokens ?? env.LLM_MAX_TOKENS,
maxRetries: config?.maxRetries ?? env.LLM_MAX_RETRIES,
retryDelayMs: config?.retryDelayMs ?? env.LLM_RETRY_DELAY_MS,
};
}
async chat(messages: ChatMessage[]): Promise<string> {
const { content } = await this.chatWithMeta(messages);
return content;
}
/** Returns content and model used (for logging to question_cache_meta) */
async chatWithMeta(messages: ChatMessage[]): Promise<{ content: string; model: string }> {
let lastError: Error | null = null;
const modelsToTry = [this.config.model];
if (this.config.fallbackModel) {
modelsToTry.push(this.config.fallbackModel);
}
for (const model of modelsToTry) {
for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
try {
const content = await this.executeChat(messages, model);
return { content, model };
} catch (err) {
lastError = err instanceof Error ? err : new Error('LLM request failed');
if (attempt < this.config.maxRetries) {
const delayMs = this.config.retryDelayMs * Math.pow(2, attempt);
await sleep(delayMs);
}
}
}
}
throw lastError ?? new Error('LLM request failed');
}
private async executeChat(messages: ChatMessage[], model: string): Promise<string> {
const url = `${this.config.baseUrl.replace(/\/$/, '')}/chat/completions`;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (this.config.apiKey) {
headers['Authorization'] = `Bearer ${this.config.apiKey}`;
}
const body = {
model,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
temperature: this.config.temperature,
max_tokens: this.config.maxTokens,
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.config.timeoutMs);
try {
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!res.ok) {
const text = await res.text();
throw new Error(`LLM request failed: ${res.status} ${res.statusText} - ${text}`);
}
const data = (await res.json()) as ChatCompletionResponse;
const choice = data.choices?.[0];
const content = choice?.message?.content ?? choice?.text ?? '';
return content.trim();
} catch (err) {
clearTimeout(timeoutId);
if (err instanceof Error) {
throw err;
}
throw new Error('LLM request failed');
}
}
async generateQuestions(input: GenerateQuestionsInput): Promise<GenerateQuestionsResult> {
const { stack, level, count, types = QUESTION_TYPES } = input;
const typeList = types.join(', ');
const systemPrompt = `You are a technical interview question generator. Generate exactly ${count} programming/tech questions.
Return ONLY valid JSON in this exact format (no markdown, no code blocks):
{"questions":[{"questionText":"...","type":"single_choice|multiple_select|true_false|short_text","options":[{"key":"a","text":"..."}],"correctAnswer":"a" or ["a","b"],"explanation":"..."}]}
Rules: type must be one of: ${typeList}. For single_choice/multiple_select: options array required with key (a,b,c,d). For true_false: options [{"key":"true","text":"True"},{"key":"false","text":"False"}]. For short_text: options omitted, correctAnswer is string.`;
const userPrompt = `Generate ${count} questions for stack="${stack}", level="${level}". Use types: ${typeList}.`;
const promptForHash = systemPrompt + '\n---\n' + userPrompt;
const promptHash = createHash('sha256').update(promptForHash).digest('hex');
const start = Date.now();
const { content: raw, model } = await this.chatWithMeta([
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt },
]);
const generationTimeMs = Date.now() - start;
const jsonStr = extractJson(raw);
const parsed = JSON.parse(jsonStr) as unknown;
const result = generateQuestionsResponseSchema.safeParse(parsed);
if (!result.success) {
throw new Error(`LLM response validation failed: ${result.error.message}`);
}
const questions: GeneratedQuestion[] = result.data.questions.map((q) => ({
...q,
stack,
level,
}));
for (const q of questions) {
if ((q.type === 'single_choice' || q.type === 'multiple_select') && (!q.options || q.options.length === 0)) {
throw new Error(`Question validation failed: ${q.type} requires options`);
}
if (q.type === 'true_false' && (!q.options || q.options.length < 2)) {
throw new Error(`Question validation failed: true_false requires true/false options`);
}
}
return {
questions,
meta: {
llmModel: model,
promptHash,
generationTimeMs,
rawResponse: parsed,
},
};
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function extractJson(text: string): string {
const trimmed = text.trim();
const match = trimmed.match(/\{[\s\S]*\}/);
return match ? match[0]! : trimmed;
}

View File

@@ -0,0 +1,175 @@
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type * as schema from '../../db/schema/index.js';
import { users, userStats } from '../../db/schema/index.js';
import { notFound, conflict, ERROR_CODES } from '../../utils/errors.js';
import type { User } from '../../db/schema/users.js';
import type { SelfLevel } from '../../db/schema/index.js';
type Db = NodePgDatabase<typeof schema>;
export type UserStatItem = {
stack: string;
level: string;
totalQuestions: number;
correctAnswers: number;
testsTaken: number;
lastTestAt: string | null;
};
export type ProfileStats = {
byStack: UserStatItem[];
totalTestsTaken: number;
totalQuestions: number;
correctAnswers: number;
accuracy: number | null;
};
export type ProfileUpdateInput = {
nickname?: string;
avatarUrl?: string | null;
country?: string | null;
city?: string | null;
selfLevel?: SelfLevel | null;
isPublic?: boolean;
};
export type PublicProfile = {
id: string;
nickname: string;
avatarUrl: string | null;
country: string | null;
city: string | null;
selfLevel: string | null;
isPublic: boolean;
stats: ProfileStats;
};
export type PrivateProfile = PublicProfile & {
email: string;
emailVerifiedAt: string | null;
createdAt: string;
updatedAt: string;
};
async function getStatsForUser(db: Db, userId: string): Promise<ProfileStats> {
const rows = await db
.select()
.from(userStats)
.where(eq(userStats.userId, userId));
const byStack: UserStatItem[] = rows.map((r) => ({
stack: r.stack,
level: r.level,
totalQuestions: r.totalQuestions,
correctAnswers: r.correctAnswers,
testsTaken: r.testsTaken,
lastTestAt: r.lastTestAt?.toISOString() ?? null,
}));
const totalTestsTaken = rows.reduce((sum, r) => sum + r.testsTaken, 0);
const totalQuestions = rows.reduce((sum, r) => sum + r.totalQuestions, 0);
const correctAnswers = rows.reduce((sum, r) => sum + r.correctAnswers, 0);
const accuracy = totalQuestions > 0 ? correctAnswers / totalQuestions : null;
return { byStack, totalTestsTaken, totalQuestions, correctAnswers, accuracy };
}
function toPublicProfile(user: User, stats: ProfileStats): PublicProfile {
return {
id: user.id,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
country: user.country,
city: user.city,
selfLevel: user.selfLevel,
isPublic: user.isPublic,
stats,
};
}
function toPrivateProfile(user: User, stats: ProfileStats): PrivateProfile {
return {
...toPublicProfile(user, stats),
email: user.email,
emailVerifiedAt: user.emailVerifiedAt?.toISOString() ?? null,
createdAt: user.createdAt.toISOString(),
updatedAt: user.updatedAt.toISOString(),
};
}
export class UserService {
constructor(private readonly db: Db) {}
async getById(userId: string): Promise<User | null> {
const [user] = await this.db.select().from(users).where(eq(users.id, userId)).limit(1);
return user ?? null;
}
async getByNickname(nickname: string): Promise<User | null> {
const [user] = await this.db
.select()
.from(users)
.where(eq(users.nickname, nickname.trim()))
.limit(1);
return user ?? null;
}
async getPrivateProfile(userId: string): Promise<PrivateProfile> {
const [user, stats] = await Promise.all([this.getById(userId), getStatsForUser(this.db, userId)]);
if (!user) {
throw notFound('User not found');
}
return toPrivateProfile(user, stats);
}
async getPublicProfile(username: string): Promise<PublicProfile> {
const user = await this.getByNickname(username);
if (!user) {
throw notFound('User not found');
}
if (!user.isPublic) {
throw notFound('User not found');
}
const stats = await getStatsForUser(this.db, user.id);
return toPublicProfile(user, stats);
}
async updateProfile(userId: string, input: ProfileUpdateInput): Promise<PrivateProfile> {
const updateData: Partial<typeof users.$inferInsert> = {
updatedAt: new Date(),
};
if (input.nickname !== undefined) {
const trimmed = input.nickname.trim();
const [existing] = await this.db
.select({ id: users.id })
.from(users)
.where(eq(users.nickname, trimmed))
.limit(1);
if (existing && existing.id !== userId) {
throw conflict(ERROR_CODES.NICKNAME_TAKEN, 'Nickname already taken');
}
updateData.nickname = trimmed;
}
if (input.avatarUrl !== undefined) updateData.avatarUrl = input.avatarUrl;
if (input.country !== undefined) updateData.country = input.country;
if (input.city !== undefined) updateData.city = input.city;
if (input.selfLevel !== undefined) updateData.selfLevel = input.selfLevel;
if (input.isPublic !== undefined) updateData.isPublic = input.isPublic;
const [updated] = await this.db
.update(users)
.set(updateData)
.where(eq(users.id, userId))
.returning();
if (!updated) {
throw notFound('User not found');
}
const stats = await getStatsForUser(this.db, userId);
return toPrivateProfile(updated, stats);
}
}

52
src/utils/jwt.ts Normal file
View File

@@ -0,0 +1,52 @@
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import { env } from '../config/env.js';
export function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
export interface AccessPayload {
sub: string;
email: string;
type: 'access';
}
export interface RefreshPayload {
sub: string;
sid: string;
type: 'refresh';
}
type JwtPayload = AccessPayload | RefreshPayload;
const secret = new TextEncoder().encode(env.JWT_SECRET);
export async function signAccessToken(payload: Omit<AccessPayload, 'type'>): Promise<string> {
return new jose.SignJWT({ ...payload, type: 'access' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(env.JWT_ACCESS_TTL)
.sign(secret);
}
export async function signRefreshToken(payload: Omit<RefreshPayload, 'type'>): Promise<string> {
return new jose.SignJWT({ ...payload, type: 'refresh' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(env.JWT_REFRESH_TTL)
.sign(secret);
}
export async function verifyToken(token: string): Promise<JwtPayload> {
const { payload } = await jose.jwtVerify(token, secret);
return payload as unknown as JwtPayload;
}
export function isAccessPayload(p: JwtPayload): p is AccessPayload {
return p.type === 'access';
}
export function isRefreshPayload(p: JwtPayload): p is RefreshPayload {
return p.type === 'refresh';
}

15
src/utils/password.ts Normal file
View File

@@ -0,0 +1,15 @@
import * as argon2 from 'argon2';
const HASH_OPTIONS: argon2.Options = {
type: argon2.argon2id,
memoryCost: 19456,
timeCost: 2,
};
export async function hashPassword(plain: string): Promise<string> {
return argon2.hash(plain, HASH_OPTIONS);
}
export async function verifyPassword(hash: string, plain: string): Promise<boolean> {
return argon2.verify(hash, plain);
}