forked from mtusi2026/mtusi2026lab2
31 lines
88 KiB
JSON
31 lines
88 KiB
JSON
{
|
||
"baseline": {
|
||
"Auth/auth.service.ts": "import { Injectable } from '@nestjs/common';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { TextDecoder } from 'node:util';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { Prisma } from '../generated/prisma/client';\nimport { UserService } from '../User/user.service';\nimport type { User } from '../User/user.schema';\nimport { invalidRequest } from '../common/validation';\nimport { AuthException } from './auth.exception';\nimport { PasswordService, validPassword } from './password.service';\nimport type { Session } from './auth.schema';\n\n@Injectable()\nexport class AuthService {\n private readonly ttlSeconds: number;\n\n constructor(\n private readonly prisma: PrismaService,\n private readonly users: UserService,\n private readonly passwords: PasswordService,\n ) {\n this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);\n if (\n !Number.isSafeInteger(this.ttlSeconds) ||\n this.ttlSeconds <= 0 ||\n Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())\n ) {\n throw new Error(\n 'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',\n );\n }\n }\n\n async login(authorization: unknown, body: unknown): Promise<Session> {\n const { username, password } = this.basicCredentials(authorization);\n const user = await this.prisma.user.findUnique({ where: { username } });\n const verified = await this.passwords.verify(\n password,\n user?.passwordHash ?? null,\n );\n if (!user || !verified) throw new AuthException('Basic');\n if (body !== undefined)\n return invalidRequest('Вход через Basic не принимает тело запроса');\n const token = randomBytes(32).toString('base64url');\n const session = await this.prisma.session.create({\n data: {\n userId: user.id,\n tokenHash: this.tokenHash(token),\n expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),\n },\n });\n return {\n token,\n token_type: 'Bearer',\n expires_at: session.expiresAt.toISOString(),\n user: this.users.serialize(user),\n };\n }\n\n async authenticate(\n authorization: unknown,\n ): Promise<{ user: User; sessionId: string; chatsEpoch: string }> {\n const match =\n typeof authorization === 'string' &&\n /^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);\n if (!match) throw new AuthException('Bearer');\n const [session] = await this.prisma.$queryRaw<\n { id: string; userId: string; chatsEpoch: bigint }[]\n >(Prisma.sql`\n SELECT s.id, s.user_id AS \"userId\", u.chats_epoch AS \"chatsEpoch\"\n FROM sessions AS s\n JOIN users AS u ON u.id = s.user_id\n WHERE s.token_hash = ${this.tokenHash(match[1])}\n AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}\n LIMIT 1\n `);\n if (!session) throw new AuthException('Bearer');\n const user = await this.users.get(session.userId);\n if (!user) throw new AuthException('Bearer');\n return {\n user,\n sessionId: session.id,\n chatsEpoch: session.chatsEpoch.toString(),\n };\n }\n\n async logout(sessionId: string): Promise<void> {\n const now = new Date();\n const result = await this.prisma.session.updateMany({\n where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },\n data: { revokedAt: now },\n });\n if (result.count !== 1) throw new AuthException('Bearer');\n }\n\n private tokenHash(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n }\n\n private basicCredentials(authorization: unknown): {\n username: string;\n password: string;\n } {\n const match =\n typeof authorization === 'string' &&\n /^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);\n if (!match) throw new AuthException('Basic');\n try {\n const bytes = Buffer.from(match[1], 'base64');\n if (\n bytes.toString('base64').replace(/=+$/, '') !==\n match[1].replace(/=+$/, '')\n )\n throw new AuthException('Basic');\n const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n const colon = value.indexOf(':');\n const username = value.slice(0, colon);\n const password = value.slice(colon + 1);\n if (\n colon < 0 ||\n !/^[a-z0-9_]{3,32}$/.test(username) ||\n !validPassword(password)\n )\n throw new AuthException('Basic');\n return { username, password };\n } catch {\n throw new AuthException('Basic');\n }\n }\n}\n",
|
||
"User/user.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { Prisma, type User as StoredUser } from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport { objectBody, requiredText } from '../common/validation';\nimport {\n PasswordService,\n registrationPassword,\n} from '../Auth/password.service';\nimport type { User } from './user.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\n@Injectable()\nexport class UserService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly passwords: PasswordService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown): Promise<User> {\n const body = objectBody(value, ['username', 'display_name', 'password']);\n const username = body.username;\n if (typeof username !== 'string' || !/^[a-z0-9_]{3,32}$/.test(username)) {\n throw new ApiException(\n HttpStatus.BAD_REQUEST,\n 'invalid_request',\n 'Некорректный username',\n );\n }\n const displayName = requiredText(body.display_name, 'display_name', 100);\n const password = registrationPassword(body.password);\n const passwordHash = await this.passwords.hash(password);\n try {\n return this.serialize(\n await this.prisma.user.create({\n data: { username, displayName, passwordHash },\n }),\n );\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2002'\n ) {\n throw new ApiException(\n HttpStatus.CONFLICT,\n 'conflict',\n 'Username уже занят',\n );\n }\n throw error;\n }\n }\n\n async get(id: string): Promise<User | undefined> {\n return this.cache.remember(\n `user:${id}`,\n 'profile',\n CACHE_TTL.entity,\n async () => {\n const user = await this.prisma.user.findUnique({ where: { id } });\n return user ? this.serialize(user) : undefined;\n },\n );\n }\n\n serialize(user: StoredUser): User {\n return {\n id: user.id,\n username: user.username,\n display_name: user.displayName,\n created_at: user.createdAt.toISOString(),\n };\n }\n}\n",
|
||
"User/user.guard.ts": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport type { FastifyRequest } from 'fastify';\nimport { AuthService } from '../Auth/auth.service';\nimport type { User } from './user.schema';\n\nexport type AuthenticatedRequest = FastifyRequest & {\n currentUser: User;\n currentSessionId: string;\n currentChatsEpoch: string;\n};\n\n@Injectable()\nexport class UserGuard implements CanActivate {\n constructor(private readonly auth: AuthService) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<AuthenticatedRequest>();\n const session = await this.auth.authenticate(request.headers.authorization);\n request.currentUser = session.user;\n request.currentSessionId = session.sessionId;\n request.currentChatsEpoch = session.chatsEpoch;\n return true;\n }\n}\n",
|
||
"Chat/chat.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { randomUUID } from 'node:crypto';\nimport {\n Prisma,\n type Message as StoredMessage,\n} from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport {\n invalidRequest,\n objectBody,\n pageLimit,\n requiredText,\n uuid,\n} from '../common/validation';\nimport type { Chat, Message, Page } from './chat.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\ninterface Cursor {\n scope: string;\n created_at: string;\n id: string;\n}\n\nconst chatInclude = {\n members: { orderBy: { position: 'asc' as const } },\n} satisfies Prisma.ChatInclude;\ntype StoredChat = Prisma.ChatGetPayload<{ include: typeof chatInclude }>;\n\n@Injectable()\nexport class ChatService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown, userId: string): Promise<Chat> {\n const body = objectBody(value, ['title', 'member_ids']);\n const title = requiredText(body.title, 'title', 100);\n if (\n !Array.isArray(body.member_ids) ||\n body.member_ids.length < 1 ||\n body.member_ids.length > 100\n ) {\n return invalidRequest('Некорректный member_ids');\n }\n const memberIds = body.member_ids.map((id: unknown) =>\n uuid(id, 'member_ids'),\n );\n if (\n new Set(memberIds).size !== memberIds.length ||\n !memberIds.includes(userId)\n ) {\n return invalidRequest(\n 'Список участников содержит дубликат или не содержит вызывающего',\n );\n }\n try {\n const chat = await this.prisma.$transaction(async (tx) => {\n const count = await tx.user.count({ where: { id: { in: memberIds } } });\n if (count !== memberIds.length)\n return invalidRequest('Неизвестный участник чата');\n const created = await tx.chat.create({\n data: {\n title,\n members: {\n create: memberIds.map((userId, position) => ({\n userId,\n position,\n })),\n },\n },\n include: chatInclude,\n });\n await tx.$executeRaw(Prisma.sql`\n WITH locked AS MATERIALIZED (\n SELECT id FROM users\n WHERE id IN (${Prisma.join(memberIds.map((id) => Prisma.sql`${id}::uuid`))})\n ORDER BY id FOR UPDATE\n )\n UPDATE users AS u SET chats_epoch = u.chats_epoch + 1\n FROM locked WHERE u.id = locked.id\n `);\n return created;\n });\n return this.serializeChat(chat);\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2003'\n ) {\n return invalidRequest('Неизвестный участник чата');\n }\n throw error;\n }\n }\n\n async list(\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n epoch: string,\n ): Promise<Page<Chat>> {\n const limit = pageLimit(limitValue);\n const scope = `chats:${userId}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const chats = await this.prisma.chat.findMany({\n where: { members: { some: { userId } }, ...this.after(cursor) },\n include: chatInclude,\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n chats.map((chat) => this.serializeChat(chat)),\n limit,\n scope,\n );\n },\n epoch,\n );\n }\n\n async get(value: unknown, userId: string): Promise<Chat> {\n const { id } = await this.authorizeChat(value, userId);\n return this.getMetadata(id);\n }\n\n private async authorizeChat(value: unknown, userId: string) {\n const id = uuid(value, 'chat_id');\n const [membership] = await this.prisma.$queryRaw<\n { id: string; messagesEpoch: bigint }[]\n >(Prisma.sql`\n SELECT c.id, c.messages_epoch AS \"messagesEpoch\"\n FROM chat_members AS cm JOIN chats AS c ON c.id = cm.chat_id\n WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid\n `);\n if (!membership) {\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n }\n return membership;\n }\n\n private getMetadata(id: string): Promise<Chat> {\n return this.cache.remember(\n `chat:${id}`,\n 'metadata',\n CACHE_TTL.entity,\n async () => {\n const chat = await this.prisma.chat.findUnique({\n where: { id },\n include: chatInclude,\n });\n if (!chat)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeChat(chat);\n },\n );\n }\n\n async createMessage(\n chatId: unknown,\n value: unknown,\n userId: string,\n ): Promise<Message> {\n const id = uuid(chatId, 'chat_id');\n const body = objectBody(value, ['text']);\n const text = requiredText(body.text, 'text', 4000);\n const [message] = await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n WITH updated AS (\n UPDATE chats AS c\n SET messages_epoch = c.messages_epoch + 1\n WHERE c.id = ${id}::uuid\n AND EXISTS (\n SELECT 1 FROM chat_members AS cm\n WHERE cm.chat_id = c.id AND cm.user_id = ${userId}::uuid\n )\n RETURNING c.id\n )\n INSERT INTO messages (id, chat_id, sender_id, text)\n SELECT ${randomUUID()}::uuid, updated.id, ${userId}::uuid, ${text}\n FROM updated\n RETURNING id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n `);\n if (!message)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeMessage(message);\n }\n\n async listMessages(\n chatId: unknown,\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n ): Promise<Page<Message>> {\n const chat = await this.authorizeChat(chatId, userId);\n const limit = pageLimit(limitValue);\n const scope = `messages:${chat.id}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const messages = cursor\n ? await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n SELECT id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n FROM \"public\".\"messages\"\n WHERE chat_id = ${chat.id}::uuid\n AND (created_at, id) >\n (${new Date(cursor.created_at)}::timestamptz, ${cursor.id}::uuid)\n ORDER BY created_at ASC, id ASC\n LIMIT ${limit + 1}\n `)\n : await this.prisma.message.findMany({\n where: { chatId: chat.id },\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n messages.map((message) => this.serializeMessage(message)),\n limit,\n scope,\n );\n },\n chat.messagesEpoch.toString(),\n );\n }\n\n private after(cursor: Cursor | null) {\n if (!cursor) return {};\n const createdAt = new Date(cursor.created_at);\n return {\n OR: [\n { createdAt: { gt: createdAt } },\n { createdAt, id: { gt: cursor.id } },\n ],\n };\n }\n\n private serializeChat(chat: StoredChat): Chat {\n return {\n id: chat.id,\n title: chat.title,\n member_ids: chat.members.map((member) => member.userId),\n created_at: chat.createdAt.toISOString(),\n };\n }\n\n private serializeMessage(message: StoredMessage): Message {\n return {\n id: message.id,\n chat_id: message.chatId,\n sender_id: message.senderId,\n text: message.text,\n created_at: message.createdAt.toISOString(),\n };\n }\n\n private page<T extends { id: string; created_at: string }>(\n items: T[],\n limit: number,\n scope: string,\n ): Page<T> {\n const result = items.slice(0, limit);\n const last = result.at(-1);\n return {\n items: result,\n next_cursor:\n items.length > limit && last\n ? Buffer.from(\n JSON.stringify({\n scope,\n created_at: last.created_at,\n id: last.id,\n }),\n ).toString('base64url')\n : null,\n };\n }\n\n private decodeCursor(value: unknown, scope: string): Cursor | null {\n if (value === undefined) return null;\n if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))\n return invalidRequest('Некорректный cursor');\n try {\n const cursor: unknown = JSON.parse(\n Buffer.from(value, 'base64url').toString('utf8'),\n );\n if (\n typeof cursor !== 'object' ||\n cursor === null ||\n Array.isArray(cursor)\n )\n return invalidRequest('Некорректный cursor');\n const data = cursor as Record<string, unknown>;\n if (\n data.scope !== scope ||\n typeof data.created_at !== 'string' ||\n Number.isNaN(Date.parse(data.created_at)) ||\n typeof data.id !== 'string'\n ) {\n return invalidRequest('Некорректный cursor');\n }\n return {\n scope,\n created_at: data.created_at,\n id: uuid(data.id, 'cursor'),\n };\n } catch {\n return invalidRequest('Некорректный cursor');\n }\n }\n}\n",
|
||
"Chat/chat.controller.ts": "import {\n Body,\n Controller,\n Get,\n HttpCode,\n HttpStatus,\n Param,\n Post,\n Query,\n Req,\n UseGuards,\n} from '@nestjs/common';\nimport {\n ApiBody,\n ApiBearerAuth,\n ApiCreatedResponse,\n ApiOkResponse,\n ApiOperation,\n ApiQuery,\n ApiTags,\n} from '@nestjs/swagger';\nimport { UserGuard, type AuthenticatedRequest } from '../User/user.guard';\nimport {\n CreateChatDto,\n CreateMessageDto,\n Chat,\n Message,\n ChatPage,\n MessagePage,\n} from './chat.schema';\nimport { ChatService } from './chat.service';\n\n@ApiTags('chats')\n@ApiBearerAuth('bearerAuth')\n@UseGuards(UserGuard)\n@Controller('api/v1/chats')\nexport class ChatController {\n constructor(private readonly chats: ChatService) {}\n\n @Post()\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateChatDto })\n @ApiOperation({ operationId: 'createChat' })\n @ApiCreatedResponse({ type: Chat })\n create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {\n return this.chats.create(body, request.currentUser.id);\n }\n\n @Get()\n @ApiOperation({ operationId: 'listChats' })\n @ApiOkResponse({ type: ChatPage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n list(\n @Req() request: AuthenticatedRequest,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.list(\n request.currentUser.id,\n limit,\n cursor,\n request.currentChatsEpoch,\n );\n }\n\n @Get(':chat_id')\n @ApiOperation({ operationId: 'getChat' })\n @ApiOkResponse({ type: Chat })\n get(@Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string) {\n return this.chats.get(chatId, request.currentUser.id);\n }\n\n @Post(':chat_id/messages')\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateMessageDto })\n @ApiOperation({ operationId: 'createMessage' })\n @ApiCreatedResponse({ type: Message })\n createMessage(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Body() body: unknown,\n ) {\n return this.chats.createMessage(chatId, body, request.currentUser.id);\n }\n\n @Get(':chat_id/messages')\n @ApiOperation({ operationId: 'listMessages' })\n @ApiOkResponse({ type: MessagePage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n listMessages(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.listMessages(\n chatId,\n request.currentUser.id,\n limit,\n cursor,\n );\n }\n}\n"
|
||
},
|
||
"profile-join": {
|
||
"Auth/auth.service.ts": "import { Injectable } from '@nestjs/common';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { TextDecoder } from 'node:util';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { Prisma } from '../generated/prisma/client';\nimport { UserService } from '../User/user.service';\nimport type { User } from '../User/user.schema';\nimport { invalidRequest } from '../common/validation';\nimport { AuthException } from './auth.exception';\nimport { PasswordService, validPassword } from './password.service';\nimport type { Session } from './auth.schema';\n\n@Injectable()\nexport class AuthService {\n private readonly ttlSeconds: number;\n\n constructor(\n private readonly prisma: PrismaService,\n private readonly users: UserService,\n private readonly passwords: PasswordService,\n ) {\n this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);\n if (\n !Number.isSafeInteger(this.ttlSeconds) ||\n this.ttlSeconds <= 0 ||\n Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())\n ) {\n throw new Error(\n 'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',\n );\n }\n }\n\n async login(authorization: unknown, body: unknown): Promise<Session> {\n const { username, password } = this.basicCredentials(authorization);\n const user = await this.prisma.user.findUnique({ where: { username } });\n const verified = await this.passwords.verify(\n password,\n user?.passwordHash ?? null,\n );\n if (!user || !verified) throw new AuthException('Basic');\n if (body !== undefined)\n return invalidRequest('Вход через Basic не принимает тело запроса');\n const token = randomBytes(32).toString('base64url');\n const session = await this.prisma.session.create({\n data: {\n userId: user.id,\n tokenHash: this.tokenHash(token),\n expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),\n },\n });\n return {\n token,\n token_type: 'Bearer',\n expires_at: session.expiresAt.toISOString(),\n user: this.users.serialize(user),\n };\n }\n\n async authenticate(\n authorization: unknown,\n ): Promise<{ user: User; sessionId: string; chatsEpoch: string }> {\n const match =\n typeof authorization === 'string' &&\n /^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);\n if (!match) throw new AuthException('Bearer');\n const [session] = await this.prisma.$queryRaw<\n {\n id: string;\n userId: string;\n username: string;\n displayName: string;\n createdAt: Date;\n chatsEpoch: bigint;\n }[]\n >(Prisma.sql`\n SELECT s.id, s.user_id AS \"userId\", u.chats_epoch AS \"chatsEpoch\",\n u.username, u.display_name AS \"displayName\", u.created_at AS \"createdAt\"\n FROM sessions AS s\n JOIN users AS u ON u.id = s.user_id\n WHERE s.token_hash = ${this.tokenHash(match[1])}\n AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}\n LIMIT 1\n `);\n if (!session) throw new AuthException('Bearer');\n return {\n user: this.users.serialize({ ...session, id: session.userId }),\n sessionId: session.id,\n chatsEpoch: session.chatsEpoch.toString(),\n };\n }\n\n async logout(sessionId: string): Promise<void> {\n const now = new Date();\n const result = await this.prisma.session.updateMany({\n where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },\n data: { revokedAt: now },\n });\n if (result.count !== 1) throw new AuthException('Bearer');\n }\n\n private tokenHash(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n }\n\n private basicCredentials(authorization: unknown): {\n username: string;\n password: string;\n } {\n const match =\n typeof authorization === 'string' &&\n /^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);\n if (!match) throw new AuthException('Basic');\n try {\n const bytes = Buffer.from(match[1], 'base64');\n if (\n bytes.toString('base64').replace(/=+$/, '') !==\n match[1].replace(/=+$/, '')\n )\n throw new AuthException('Basic');\n const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n const colon = value.indexOf(':');\n const username = value.slice(0, colon);\n const password = value.slice(colon + 1);\n if (\n colon < 0 ||\n !/^[a-z0-9_]{3,32}$/.test(username) ||\n !validPassword(password)\n )\n throw new AuthException('Basic');\n return { username, password };\n } catch {\n throw new AuthException('Basic');\n }\n }\n}\n",
|
||
"User/user.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { Prisma, type User as StoredUser } from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport { objectBody, requiredText } from '../common/validation';\nimport {\n PasswordService,\n registrationPassword,\n} from '../Auth/password.service';\nimport type { User } from './user.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\n@Injectable()\nexport class UserService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly passwords: PasswordService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown): Promise<User> {\n const body = objectBody(value, ['username', 'display_name', 'password']);\n const username = body.username;\n if (typeof username !== 'string' || !/^[a-z0-9_]{3,32}$/.test(username)) {\n throw new ApiException(\n HttpStatus.BAD_REQUEST,\n 'invalid_request',\n 'Некорректный username',\n );\n }\n const displayName = requiredText(body.display_name, 'display_name', 100);\n const password = registrationPassword(body.password);\n const passwordHash = await this.passwords.hash(password);\n try {\n return this.serialize(\n await this.prisma.user.create({\n data: { username, displayName, passwordHash },\n }),\n );\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2002'\n ) {\n throw new ApiException(\n HttpStatus.CONFLICT,\n 'conflict',\n 'Username уже занят',\n );\n }\n throw error;\n }\n }\n\n async get(id: string): Promise<User | undefined> {\n return this.cache.remember(\n `user:${id}`,\n 'profile',\n CACHE_TTL.entity,\n async () => {\n const user = await this.prisma.user.findUnique({ where: { id } });\n return user ? this.serialize(user) : undefined;\n },\n );\n }\n\n serialize(\n user: Pick<StoredUser, 'id' | 'username' | 'displayName' | 'createdAt'>,\n ): User {\n return {\n id: user.id,\n username: user.username,\n display_name: user.displayName,\n created_at: user.createdAt.toISOString(),\n };\n }\n}\n",
|
||
"User/user.guard.ts": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport type { FastifyRequest } from 'fastify';\nimport { AuthService } from '../Auth/auth.service';\nimport type { User } from './user.schema';\n\nexport type AuthenticatedRequest = FastifyRequest & {\n currentUser: User;\n currentSessionId: string;\n currentChatsEpoch: string;\n};\n\n@Injectable()\nexport class UserGuard implements CanActivate {\n constructor(private readonly auth: AuthService) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<AuthenticatedRequest>();\n const session = await this.auth.authenticate(request.headers.authorization);\n request.currentUser = session.user;\n request.currentSessionId = session.sessionId;\n request.currentChatsEpoch = session.chatsEpoch;\n return true;\n }\n}\n",
|
||
"Chat/chat.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { randomUUID } from 'node:crypto';\nimport {\n Prisma,\n type Message as StoredMessage,\n} from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport {\n invalidRequest,\n objectBody,\n pageLimit,\n requiredText,\n uuid,\n} from '../common/validation';\nimport type { Chat, Message, Page } from './chat.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\ninterface Cursor {\n scope: string;\n created_at: string;\n id: string;\n}\n\nconst chatInclude = {\n members: { orderBy: { position: 'asc' as const } },\n} satisfies Prisma.ChatInclude;\ntype StoredChat = Prisma.ChatGetPayload<{ include: typeof chatInclude }>;\n\n@Injectable()\nexport class ChatService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown, userId: string): Promise<Chat> {\n const body = objectBody(value, ['title', 'member_ids']);\n const title = requiredText(body.title, 'title', 100);\n if (\n !Array.isArray(body.member_ids) ||\n body.member_ids.length < 1 ||\n body.member_ids.length > 100\n ) {\n return invalidRequest('Некорректный member_ids');\n }\n const memberIds = body.member_ids.map((id: unknown) =>\n uuid(id, 'member_ids'),\n );\n if (\n new Set(memberIds).size !== memberIds.length ||\n !memberIds.includes(userId)\n ) {\n return invalidRequest(\n 'Список участников содержит дубликат или не содержит вызывающего',\n );\n }\n try {\n const chat = await this.prisma.$transaction(async (tx) => {\n const count = await tx.user.count({ where: { id: { in: memberIds } } });\n if (count !== memberIds.length)\n return invalidRequest('Неизвестный участник чата');\n const created = await tx.chat.create({\n data: {\n title,\n members: {\n create: memberIds.map((userId, position) => ({\n userId,\n position,\n })),\n },\n },\n include: chatInclude,\n });\n await tx.$executeRaw(Prisma.sql`\n WITH locked AS MATERIALIZED (\n SELECT id FROM users\n WHERE id IN (${Prisma.join(memberIds.map((id) => Prisma.sql`${id}::uuid`))})\n ORDER BY id FOR UPDATE\n )\n UPDATE users AS u SET chats_epoch = u.chats_epoch + 1\n FROM locked WHERE u.id = locked.id\n `);\n return created;\n });\n return this.serializeChat(chat);\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2003'\n ) {\n return invalidRequest('Неизвестный участник чата');\n }\n throw error;\n }\n }\n\n async list(\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n epoch: string,\n ): Promise<Page<Chat>> {\n const limit = pageLimit(limitValue);\n const scope = `chats:${userId}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const chats = await this.prisma.chat.findMany({\n where: { members: { some: { userId } }, ...this.after(cursor) },\n include: chatInclude,\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n chats.map((chat) => this.serializeChat(chat)),\n limit,\n scope,\n );\n },\n epoch,\n );\n }\n\n async get(value: unknown, userId: string): Promise<Chat> {\n const { id } = await this.authorizeChat(value, userId);\n return this.getMetadata(id);\n }\n\n private async authorizeChat(value: unknown, userId: string) {\n const id = uuid(value, 'chat_id');\n const [membership] = await this.prisma.$queryRaw<\n { id: string; messagesEpoch: bigint }[]\n >(Prisma.sql`\n SELECT c.id, c.messages_epoch AS \"messagesEpoch\"\n FROM chat_members AS cm JOIN chats AS c ON c.id = cm.chat_id\n WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid\n `);\n if (!membership) {\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n }\n return membership;\n }\n\n private getMetadata(id: string): Promise<Chat> {\n return this.cache.remember(\n `chat:${id}`,\n 'metadata',\n CACHE_TTL.entity,\n async () => {\n const chat = await this.prisma.chat.findUnique({\n where: { id },\n include: chatInclude,\n });\n if (!chat)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeChat(chat);\n },\n );\n }\n\n async createMessage(\n chatId: unknown,\n value: unknown,\n userId: string,\n ): Promise<Message> {\n const id = uuid(chatId, 'chat_id');\n const body = objectBody(value, ['text']);\n const text = requiredText(body.text, 'text', 4000);\n const [message] = await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n WITH updated AS (\n UPDATE chats AS c\n SET messages_epoch = c.messages_epoch + 1\n WHERE c.id = ${id}::uuid\n AND EXISTS (\n SELECT 1 FROM chat_members AS cm\n WHERE cm.chat_id = c.id AND cm.user_id = ${userId}::uuid\n )\n RETURNING c.id\n )\n INSERT INTO messages (id, chat_id, sender_id, text)\n SELECT ${randomUUID()}::uuid, updated.id, ${userId}::uuid, ${text}\n FROM updated\n RETURNING id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n `);\n if (!message)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeMessage(message);\n }\n\n async listMessages(\n chatId: unknown,\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n ): Promise<Page<Message>> {\n const chat = await this.authorizeChat(chatId, userId);\n const limit = pageLimit(limitValue);\n const scope = `messages:${chat.id}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const messages = cursor\n ? await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n SELECT id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n FROM \"public\".\"messages\"\n WHERE chat_id = ${chat.id}::uuid\n AND (created_at, id) >\n (${new Date(cursor.created_at)}::timestamptz, ${cursor.id}::uuid)\n ORDER BY created_at ASC, id ASC\n LIMIT ${limit + 1}\n `)\n : await this.prisma.message.findMany({\n where: { chatId: chat.id },\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n messages.map((message) => this.serializeMessage(message)),\n limit,\n scope,\n );\n },\n chat.messagesEpoch.toString(),\n );\n }\n\n private after(cursor: Cursor | null) {\n if (!cursor) return {};\n const createdAt = new Date(cursor.created_at);\n return {\n OR: [\n { createdAt: { gt: createdAt } },\n { createdAt, id: { gt: cursor.id } },\n ],\n };\n }\n\n private serializeChat(chat: StoredChat): Chat {\n return {\n id: chat.id,\n title: chat.title,\n member_ids: chat.members.map((member) => member.userId),\n created_at: chat.createdAt.toISOString(),\n };\n }\n\n private serializeMessage(message: StoredMessage): Message {\n return {\n id: message.id,\n chat_id: message.chatId,\n sender_id: message.senderId,\n text: message.text,\n created_at: message.createdAt.toISOString(),\n };\n }\n\n private page<T extends { id: string; created_at: string }>(\n items: T[],\n limit: number,\n scope: string,\n ): Page<T> {\n const result = items.slice(0, limit);\n const last = result.at(-1);\n return {\n items: result,\n next_cursor:\n items.length > limit && last\n ? Buffer.from(\n JSON.stringify({\n scope,\n created_at: last.created_at,\n id: last.id,\n }),\n ).toString('base64url')\n : null,\n };\n }\n\n private decodeCursor(value: unknown, scope: string): Cursor | null {\n if (value === undefined) return null;\n if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))\n return invalidRequest('Некорректный cursor');\n try {\n const cursor: unknown = JSON.parse(\n Buffer.from(value, 'base64url').toString('utf8'),\n );\n if (\n typeof cursor !== 'object' ||\n cursor === null ||\n Array.isArray(cursor)\n )\n return invalidRequest('Некорректный cursor');\n const data = cursor as Record<string, unknown>;\n if (\n data.scope !== scope ||\n typeof data.created_at !== 'string' ||\n Number.isNaN(Date.parse(data.created_at)) ||\n typeof data.id !== 'string'\n ) {\n return invalidRequest('Некорректный cursor');\n }\n return {\n scope,\n created_at: data.created_at,\n id: uuid(data.id, 'cursor'),\n };\n } catch {\n return invalidRequest('Некорректный cursor');\n }\n }\n}\n",
|
||
"Chat/chat.controller.ts": "import {\n Body,\n Controller,\n Get,\n HttpCode,\n HttpStatus,\n Param,\n Post,\n Query,\n Req,\n UseGuards,\n} from '@nestjs/common';\nimport {\n ApiBody,\n ApiBearerAuth,\n ApiCreatedResponse,\n ApiOkResponse,\n ApiOperation,\n ApiQuery,\n ApiTags,\n} from '@nestjs/swagger';\nimport { UserGuard, type AuthenticatedRequest } from '../User/user.guard';\nimport {\n CreateChatDto,\n CreateMessageDto,\n Chat,\n Message,\n ChatPage,\n MessagePage,\n} from './chat.schema';\nimport { ChatService } from './chat.service';\n\n@ApiTags('chats')\n@ApiBearerAuth('bearerAuth')\n@UseGuards(UserGuard)\n@Controller('api/v1/chats')\nexport class ChatController {\n constructor(private readonly chats: ChatService) {}\n\n @Post()\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateChatDto })\n @ApiOperation({ operationId: 'createChat' })\n @ApiCreatedResponse({ type: Chat })\n create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {\n return this.chats.create(body, request.currentUser.id);\n }\n\n @Get()\n @ApiOperation({ operationId: 'listChats' })\n @ApiOkResponse({ type: ChatPage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n list(\n @Req() request: AuthenticatedRequest,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.list(\n request.currentUser.id,\n limit,\n cursor,\n request.currentChatsEpoch,\n );\n }\n\n @Get(':chat_id')\n @ApiOperation({ operationId: 'getChat' })\n @ApiOkResponse({ type: Chat })\n get(@Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string) {\n return this.chats.get(chatId, request.currentUser.id);\n }\n\n @Post(':chat_id/messages')\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateMessageDto })\n @ApiOperation({ operationId: 'createMessage' })\n @ApiCreatedResponse({ type: Message })\n createMessage(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Body() body: unknown,\n ) {\n return this.chats.createMessage(chatId, body, request.currentUser.id);\n }\n\n @Get(':chat_id/messages')\n @ApiOperation({ operationId: 'listMessages' })\n @ApiOkResponse({ type: MessagePage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n listMessages(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.listMessages(\n chatId,\n request.currentUser.id,\n limit,\n cursor,\n );\n }\n}\n"
|
||
},
|
||
"access-join": {
|
||
"Auth/auth.service.ts": "import { Injectable } from '@nestjs/common';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { TextDecoder } from 'node:util';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { Prisma } from '../generated/prisma/client';\nimport { UserService } from '../User/user.service';\nimport type { User } from '../User/user.schema';\nimport { invalidRequest, uuid, uuidPattern } from '../common/validation';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport { AuthException } from './auth.exception';\nimport { PasswordService, validPassword } from './password.service';\nimport type { Session } from './auth.schema';\n\nexport interface ChatAccess {\n chatId: string;\n userId: string;\n messagesEpoch: string;\n}\n\n@Injectable()\nexport class AuthService {\n private readonly ttlSeconds: number;\n\n constructor(\n private readonly prisma: PrismaService,\n private readonly users: UserService,\n private readonly passwords: PasswordService,\n ) {\n this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);\n if (\n !Number.isSafeInteger(this.ttlSeconds) ||\n this.ttlSeconds <= 0 ||\n Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())\n ) {\n throw new Error(\n 'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',\n );\n }\n }\n\n async login(authorization: unknown, body: unknown): Promise<Session> {\n const { username, password } = this.basicCredentials(authorization);\n const user = await this.prisma.user.findUnique({ where: { username } });\n const verified = await this.passwords.verify(\n password,\n user?.passwordHash ?? null,\n );\n if (!user || !verified) throw new AuthException('Basic');\n if (body !== undefined)\n return invalidRequest('Вход через Basic не принимает тело запроса');\n const token = randomBytes(32).toString('base64url');\n const session = await this.prisma.session.create({\n data: {\n userId: user.id,\n tokenHash: this.tokenHash(token),\n expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),\n },\n });\n return {\n token,\n token_type: 'Bearer',\n expires_at: session.expiresAt.toISOString(),\n user: this.users.serialize(user),\n };\n }\n\n async authenticate(\n authorization: unknown,\n chatId?: unknown,\n ): Promise<{\n user: User;\n sessionId: string;\n chatsEpoch: string;\n chatAccess?: ChatAccess;\n }> {\n const match =\n typeof authorization === 'string' &&\n /^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);\n if (!match) throw new AuthException('Bearer');\n const requestedChat =\n typeof chatId === 'string' && uuidPattern.test(chatId)\n ? chatId.toLowerCase()\n : null;\n const [session] = await this.prisma.$queryRaw<\n {\n id: string;\n userId: string;\n username: string;\n displayName: string;\n createdAt: Date;\n chatsEpoch: bigint;\n chatId: string | null;\n messagesEpoch: bigint | null;\n }[]\n >(Prisma.sql`\n SELECT s.id, s.user_id AS \"userId\", u.chats_epoch AS \"chatsEpoch\",\n u.username, u.display_name AS \"displayName\", u.created_at AS \"createdAt\",\n ${\n chatId === undefined\n ? Prisma.sql`NULL::uuid AS \"chatId\", NULL::bigint AS \"messagesEpoch\"`\n : Prisma.sql`c.id AS \"chatId\", c.messages_epoch AS \"messagesEpoch\"`\n }\n FROM sessions AS s\n JOIN users AS u ON u.id = s.user_id\n ${\n chatId === undefined\n ? Prisma.empty\n : Prisma.sql`\n LEFT JOIN chat_members AS cm\n ON cm.user_id = s.user_id AND cm.chat_id = ${requestedChat}::uuid\n LEFT JOIN chats AS c ON c.id = cm.chat_id\n `\n }\n WHERE s.token_hash = ${this.tokenHash(match[1])}\n AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}\n LIMIT 1\n `);\n if (!session) throw new AuthException('Bearer');\n if (chatId !== undefined) {\n uuid(chatId, 'chat_id');\n if (session.chatId === null || session.messagesEpoch === null)\n throw new ApiException(404, 'not_found', 'Объект не найден');\n }\n return {\n user: this.users.serialize({ ...session, id: session.userId }),\n sessionId: session.id,\n chatsEpoch: session.chatsEpoch.toString(),\n chatAccess:\n session.chatId !== null && session.messagesEpoch !== null\n ? {\n chatId: session.chatId,\n userId: session.userId,\n messagesEpoch: session.messagesEpoch.toString(),\n }\n : undefined,\n };\n }\n\n async logout(sessionId: string): Promise<void> {\n const now = new Date();\n const result = await this.prisma.session.updateMany({\n where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },\n data: { revokedAt: now },\n });\n if (result.count !== 1) throw new AuthException('Bearer');\n }\n\n private tokenHash(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n }\n\n private basicCredentials(authorization: unknown): {\n username: string;\n password: string;\n } {\n const match =\n typeof authorization === 'string' &&\n /^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);\n if (!match) throw new AuthException('Basic');\n try {\n const bytes = Buffer.from(match[1], 'base64');\n if (\n bytes.toString('base64').replace(/=+$/, '') !==\n match[1].replace(/=+$/, '')\n )\n throw new AuthException('Basic');\n const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n const colon = value.indexOf(':');\n const username = value.slice(0, colon);\n const password = value.slice(colon + 1);\n if (\n colon < 0 ||\n !/^[a-z0-9_]{3,32}$/.test(username) ||\n !validPassword(password)\n )\n throw new AuthException('Basic');\n return { username, password };\n } catch {\n throw new AuthException('Basic');\n }\n }\n}\n",
|
||
"User/user.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { Prisma, type User as StoredUser } from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport { objectBody, requiredText } from '../common/validation';\nimport {\n PasswordService,\n registrationPassword,\n} from '../Auth/password.service';\nimport type { User } from './user.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\n@Injectable()\nexport class UserService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly passwords: PasswordService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown): Promise<User> {\n const body = objectBody(value, ['username', 'display_name', 'password']);\n const username = body.username;\n if (typeof username !== 'string' || !/^[a-z0-9_]{3,32}$/.test(username)) {\n throw new ApiException(\n HttpStatus.BAD_REQUEST,\n 'invalid_request',\n 'Некорректный username',\n );\n }\n const displayName = requiredText(body.display_name, 'display_name', 100);\n const password = registrationPassword(body.password);\n const passwordHash = await this.passwords.hash(password);\n try {\n return this.serialize(\n await this.prisma.user.create({\n data: { username, displayName, passwordHash },\n }),\n );\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2002'\n ) {\n throw new ApiException(\n HttpStatus.CONFLICT,\n 'conflict',\n 'Username уже занят',\n );\n }\n throw error;\n }\n }\n\n async get(id: string): Promise<User | undefined> {\n return this.cache.remember(\n `user:${id}`,\n 'profile',\n CACHE_TTL.entity,\n async () => {\n const user = await this.prisma.user.findUnique({ where: { id } });\n return user ? this.serialize(user) : undefined;\n },\n );\n }\n\n serialize(\n user: Pick<StoredUser, 'id' | 'username' | 'displayName' | 'createdAt'>,\n ): User {\n return {\n id: user.id,\n username: user.username,\n display_name: user.displayName,\n created_at: user.createdAt.toISOString(),\n };\n }\n}\n",
|
||
"User/user.guard.ts": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport type { FastifyRequest } from 'fastify';\nimport { AuthService, type ChatAccess } from '../Auth/auth.service';\nimport type { User } from './user.schema';\n\nexport type AuthenticatedRequest = FastifyRequest & {\n currentUser: User;\n currentSessionId: string;\n currentChatsEpoch: string;\n currentChatAccess?: ChatAccess;\n};\n\n@Injectable()\nexport class UserGuard implements CanActivate {\n constructor(private readonly auth: AuthService) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<AuthenticatedRequest>();\n const chatId =\n request.method === 'GET' &&\n request.routeOptions.url === '/api/v1/chats/:chat_id/messages'\n ? (request.params as { chat_id: string }).chat_id\n : undefined;\n const session = await this.auth.authenticate(\n request.headers.authorization,\n chatId,\n );\n request.currentUser = session.user;\n request.currentSessionId = session.sessionId;\n request.currentChatsEpoch = session.chatsEpoch;\n request.currentChatAccess = session.chatAccess;\n return true;\n }\n}\n",
|
||
"Chat/chat.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { randomUUID } from 'node:crypto';\nimport type { ChatAccess } from '../Auth/auth.service';\nimport {\n Prisma,\n type Message as StoredMessage,\n} from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport {\n invalidRequest,\n objectBody,\n pageLimit,\n requiredText,\n uuid,\n} from '../common/validation';\nimport type { Chat, Message, Page } from './chat.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\ninterface Cursor {\n scope: string;\n created_at: string;\n id: string;\n}\n\nconst chatInclude = {\n members: { orderBy: { position: 'asc' as const } },\n} satisfies Prisma.ChatInclude;\ntype StoredChat = Prisma.ChatGetPayload<{ include: typeof chatInclude }>;\n\n@Injectable()\nexport class ChatService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown, userId: string): Promise<Chat> {\n const body = objectBody(value, ['title', 'member_ids']);\n const title = requiredText(body.title, 'title', 100);\n if (\n !Array.isArray(body.member_ids) ||\n body.member_ids.length < 1 ||\n body.member_ids.length > 100\n ) {\n return invalidRequest('Некорректный member_ids');\n }\n const memberIds = body.member_ids.map((id: unknown) =>\n uuid(id, 'member_ids'),\n );\n if (\n new Set(memberIds).size !== memberIds.length ||\n !memberIds.includes(userId)\n ) {\n return invalidRequest(\n 'Список участников содержит дубликат или не содержит вызывающего',\n );\n }\n try {\n const chat = await this.prisma.$transaction(async (tx) => {\n const count = await tx.user.count({ where: { id: { in: memberIds } } });\n if (count !== memberIds.length)\n return invalidRequest('Неизвестный участник чата');\n const created = await tx.chat.create({\n data: {\n title,\n members: {\n create: memberIds.map((userId, position) => ({\n userId,\n position,\n })),\n },\n },\n include: chatInclude,\n });\n await tx.$executeRaw(Prisma.sql`\n WITH locked AS MATERIALIZED (\n SELECT id FROM users\n WHERE id IN (${Prisma.join(memberIds.map((id) => Prisma.sql`${id}::uuid`))})\n ORDER BY id FOR UPDATE\n )\n UPDATE users AS u SET chats_epoch = u.chats_epoch + 1\n FROM locked WHERE u.id = locked.id\n `);\n return created;\n });\n return this.serializeChat(chat);\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2003'\n ) {\n return invalidRequest('Неизвестный участник чата');\n }\n throw error;\n }\n }\n\n async list(\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n epoch: string,\n ): Promise<Page<Chat>> {\n const limit = pageLimit(limitValue);\n const scope = `chats:${userId}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const chats = await this.prisma.chat.findMany({\n where: { members: { some: { userId } }, ...this.after(cursor) },\n include: chatInclude,\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n chats.map((chat) => this.serializeChat(chat)),\n limit,\n scope,\n );\n },\n epoch,\n );\n }\n\n async get(value: unknown, userId: string): Promise<Chat> {\n const { id } = await this.authorizeChat(value, userId);\n return this.getMetadata(id);\n }\n\n private async authorizeChat(value: unknown, userId: string) {\n const id = uuid(value, 'chat_id');\n const [membership] = await this.prisma.$queryRaw<\n { id: string; messagesEpoch: bigint }[]\n >(Prisma.sql`\n SELECT c.id, c.messages_epoch AS \"messagesEpoch\"\n FROM chat_members AS cm JOIN chats AS c ON c.id = cm.chat_id\n WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid\n `);\n if (!membership) {\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n }\n return membership;\n }\n\n private getMetadata(id: string): Promise<Chat> {\n return this.cache.remember(\n `chat:${id}`,\n 'metadata',\n CACHE_TTL.entity,\n async () => {\n const chat = await this.prisma.chat.findUnique({\n where: { id },\n include: chatInclude,\n });\n if (!chat)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeChat(chat);\n },\n );\n }\n\n async createMessage(\n chatId: unknown,\n value: unknown,\n userId: string,\n ): Promise<Message> {\n const id = uuid(chatId, 'chat_id');\n const body = objectBody(value, ['text']);\n const text = requiredText(body.text, 'text', 4000);\n const [message] = await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n WITH updated AS (\n UPDATE chats AS c\n SET messages_epoch = c.messages_epoch + 1\n WHERE c.id = ${id}::uuid\n AND EXISTS (\n SELECT 1 FROM chat_members AS cm\n WHERE cm.chat_id = c.id AND cm.user_id = ${userId}::uuid\n )\n RETURNING c.id\n )\n INSERT INTO messages (id, chat_id, sender_id, text)\n SELECT ${randomUUID()}::uuid, updated.id, ${userId}::uuid, ${text}\n FROM updated\n RETURNING id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n `);\n if (!message)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeMessage(message);\n }\n\n async listMessages(\n chatId: unknown,\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n access?: ChatAccess,\n ): Promise<Page<Message>> {\n const id = uuid(chatId, 'chat_id');\n const chat =\n access?.chatId === id && access.userId === userId\n ? { id, messagesEpoch: access.messagesEpoch }\n : await this.authorizeChat(id, userId);\n const limit = pageLimit(limitValue);\n const scope = `messages:${chat.id}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const messages = cursor\n ? await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n SELECT id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n FROM \"public\".\"messages\"\n WHERE chat_id = ${chat.id}::uuid\n AND (created_at, id) >\n (${new Date(cursor.created_at)}::timestamptz, ${cursor.id}::uuid)\n ORDER BY created_at ASC, id ASC\n LIMIT ${limit + 1}\n `)\n : await this.prisma.message.findMany({\n where: { chatId: chat.id },\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n messages.map((message) => this.serializeMessage(message)),\n limit,\n scope,\n );\n },\n chat.messagesEpoch.toString(),\n );\n }\n\n private after(cursor: Cursor | null) {\n if (!cursor) return {};\n const createdAt = new Date(cursor.created_at);\n return {\n OR: [\n { createdAt: { gt: createdAt } },\n { createdAt, id: { gt: cursor.id } },\n ],\n };\n }\n\n private serializeChat(chat: StoredChat): Chat {\n return {\n id: chat.id,\n title: chat.title,\n member_ids: chat.members.map((member) => member.userId),\n created_at: chat.createdAt.toISOString(),\n };\n }\n\n private serializeMessage(message: StoredMessage): Message {\n return {\n id: message.id,\n chat_id: message.chatId,\n sender_id: message.senderId,\n text: message.text,\n created_at: message.createdAt.toISOString(),\n };\n }\n\n private page<T extends { id: string; created_at: string }>(\n items: T[],\n limit: number,\n scope: string,\n ): Page<T> {\n const result = items.slice(0, limit);\n const last = result.at(-1);\n return {\n items: result,\n next_cursor:\n items.length > limit && last\n ? Buffer.from(\n JSON.stringify({\n scope,\n created_at: last.created_at,\n id: last.id,\n }),\n ).toString('base64url')\n : null,\n };\n }\n\n private decodeCursor(value: unknown, scope: string): Cursor | null {\n if (value === undefined) return null;\n if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))\n return invalidRequest('Некорректный cursor');\n try {\n const cursor: unknown = JSON.parse(\n Buffer.from(value, 'base64url').toString('utf8'),\n );\n if (\n typeof cursor !== 'object' ||\n cursor === null ||\n Array.isArray(cursor)\n )\n return invalidRequest('Некорректный cursor');\n const data = cursor as Record<string, unknown>;\n if (\n data.scope !== scope ||\n typeof data.created_at !== 'string' ||\n Number.isNaN(Date.parse(data.created_at)) ||\n typeof data.id !== 'string'\n ) {\n return invalidRequest('Некорректный cursor');\n }\n return {\n scope,\n created_at: data.created_at,\n id: uuid(data.id, 'cursor'),\n };\n } catch {\n return invalidRequest('Некорректный cursor');\n }\n }\n}\n",
|
||
"Chat/chat.controller.ts": "import {\n Body,\n Controller,\n Get,\n HttpCode,\n HttpStatus,\n Param,\n Post,\n Query,\n Req,\n UseGuards,\n} from '@nestjs/common';\nimport {\n ApiBody,\n ApiBearerAuth,\n ApiCreatedResponse,\n ApiOkResponse,\n ApiOperation,\n ApiQuery,\n ApiTags,\n} from '@nestjs/swagger';\nimport { UserGuard, type AuthenticatedRequest } from '../User/user.guard';\nimport {\n CreateChatDto,\n CreateMessageDto,\n Chat,\n Message,\n ChatPage,\n MessagePage,\n} from './chat.schema';\nimport { ChatService } from './chat.service';\n\n@ApiTags('chats')\n@ApiBearerAuth('bearerAuth')\n@UseGuards(UserGuard)\n@Controller('api/v1/chats')\nexport class ChatController {\n constructor(private readonly chats: ChatService) {}\n\n @Post()\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateChatDto })\n @ApiOperation({ operationId: 'createChat' })\n @ApiCreatedResponse({ type: Chat })\n create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {\n return this.chats.create(body, request.currentUser.id);\n }\n\n @Get()\n @ApiOperation({ operationId: 'listChats' })\n @ApiOkResponse({ type: ChatPage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n list(\n @Req() request: AuthenticatedRequest,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.list(\n request.currentUser.id,\n limit,\n cursor,\n request.currentChatsEpoch,\n );\n }\n\n @Get(':chat_id')\n @ApiOperation({ operationId: 'getChat' })\n @ApiOkResponse({ type: Chat })\n get(@Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string) {\n return this.chats.get(chatId, request.currentUser.id);\n }\n\n @Post(':chat_id/messages')\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateMessageDto })\n @ApiOperation({ operationId: 'createMessage' })\n @ApiCreatedResponse({ type: Message })\n createMessage(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Body() body: unknown,\n ) {\n return this.chats.createMessage(chatId, body, request.currentUser.id);\n }\n\n @Get(':chat_id/messages')\n @ApiOperation({ operationId: 'listMessages' })\n @ApiOkResponse({ type: MessagePage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n listMessages(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.listMessages(\n chatId,\n request.currentUser.id,\n limit,\n cursor,\n request.currentChatAccess,\n );\n }\n}\n"
|
||
},
|
||
"striped": {
|
||
"Auth/auth.service.ts": "import { Injectable } from '@nestjs/common';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { TextDecoder } from 'node:util';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { Prisma } from '../generated/prisma/client';\nimport { UserService } from '../User/user.service';\nimport type { User } from '../User/user.schema';\nimport { invalidRequest, uuid, uuidPattern } from '../common/validation';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport { AuthException } from './auth.exception';\nimport { PasswordService, validPassword } from './password.service';\nimport type { Session } from './auth.schema';\n\nexport interface ChatAccess {\n chatId: string;\n userId: string;\n messagesEpoch: string;\n}\n\n@Injectable()\nexport class AuthService {\n private readonly ttlSeconds: number;\n\n constructor(\n private readonly prisma: PrismaService,\n private readonly users: UserService,\n private readonly passwords: PasswordService,\n ) {\n this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);\n if (\n !Number.isSafeInteger(this.ttlSeconds) ||\n this.ttlSeconds <= 0 ||\n Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())\n ) {\n throw new Error(\n 'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',\n );\n }\n }\n\n async login(authorization: unknown, body: unknown): Promise<Session> {\n const { username, password } = this.basicCredentials(authorization);\n const user = await this.prisma.user.findUnique({ where: { username } });\n const verified = await this.passwords.verify(\n password,\n user?.passwordHash ?? null,\n );\n if (!user || !verified) throw new AuthException('Basic');\n if (body !== undefined)\n return invalidRequest('Вход через Basic не принимает тело запроса');\n const token = randomBytes(32).toString('base64url');\n const session = await this.prisma.session.create({\n data: {\n userId: user.id,\n tokenHash: this.tokenHash(token),\n expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),\n },\n });\n return {\n token,\n token_type: 'Bearer',\n expires_at: session.expiresAt.toISOString(),\n user: this.users.serialize(user),\n };\n }\n\n async authenticate(\n authorization: unknown,\n chatId?: unknown,\n ): Promise<{\n user: User;\n sessionId: string;\n chatsEpoch: string;\n chatAccess?: ChatAccess;\n }> {\n const match =\n typeof authorization === 'string' &&\n /^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);\n if (!match) throw new AuthException('Bearer');\n const requestedChat =\n typeof chatId === 'string' && uuidPattern.test(chatId)\n ? chatId.toLowerCase()\n : null;\n const [session] = await this.prisma.$queryRaw<\n {\n id: string;\n userId: string;\n username: string;\n displayName: string;\n createdAt: Date;\n chatsEpoch: bigint;\n chatId: string | null;\n messagesEpoch: bigint | null;\n }[]\n >(Prisma.sql`\n SELECT s.id, s.user_id AS \"userId\", u.chats_epoch AS \"chatsEpoch\",\n u.username, u.display_name AS \"displayName\", u.created_at AS \"createdAt\",\n ${\n chatId === undefined\n ? Prisma.sql`NULL::uuid AS \"chatId\", NULL::bigint AS \"messagesEpoch\"`\n : Prisma.sql`c.id AS \"chatId\", COALESCE((SELECT SUM(e.epoch) FROM \"epoch_variants_0302fea1e5264f72a02693f65cb217b7\".chat_message_epochs AS e WHERE e.chat_id = c.id), 0)::bigint AS \"messagesEpoch\"`\n }\n FROM sessions AS s\n JOIN users AS u ON u.id = s.user_id\n ${\n chatId === undefined\n ? Prisma.empty\n : Prisma.sql`\n LEFT JOIN chat_members AS cm\n ON cm.user_id = s.user_id AND cm.chat_id = ${requestedChat}::uuid\n LEFT JOIN chats AS c ON c.id = cm.chat_id\n `\n }\n WHERE s.token_hash = ${this.tokenHash(match[1])}\n AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}\n LIMIT 1\n `);\n if (!session) throw new AuthException('Bearer');\n if (chatId !== undefined) {\n uuid(chatId, 'chat_id');\n if (session.chatId === null || session.messagesEpoch === null)\n throw new ApiException(404, 'not_found', 'Объект не найден');\n }\n return {\n user: this.users.serialize({ ...session, id: session.userId }),\n sessionId: session.id,\n chatsEpoch: session.chatsEpoch.toString(),\n chatAccess:\n session.chatId !== null && session.messagesEpoch !== null\n ? {\n chatId: session.chatId,\n userId: session.userId,\n messagesEpoch: session.messagesEpoch.toString(),\n }\n : undefined,\n };\n }\n\n async logout(sessionId: string): Promise<void> {\n const now = new Date();\n const result = await this.prisma.session.updateMany({\n where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },\n data: { revokedAt: now },\n });\n if (result.count !== 1) throw new AuthException('Bearer');\n }\n\n private tokenHash(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n }\n\n private basicCredentials(authorization: unknown): {\n username: string;\n password: string;\n } {\n const match =\n typeof authorization === 'string' &&\n /^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);\n if (!match) throw new AuthException('Basic');\n try {\n const bytes = Buffer.from(match[1], 'base64');\n if (\n bytes.toString('base64').replace(/=+$/, '') !==\n match[1].replace(/=+$/, '')\n )\n throw new AuthException('Basic');\n const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n const colon = value.indexOf(':');\n const username = value.slice(0, colon);\n const password = value.slice(colon + 1);\n if (\n colon < 0 ||\n !/^[a-z0-9_]{3,32}$/.test(username) ||\n !validPassword(password)\n )\n throw new AuthException('Basic');\n return { username, password };\n } catch {\n throw new AuthException('Basic');\n }\n }\n}\n",
|
||
"User/user.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { Prisma, type User as StoredUser } from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport { objectBody, requiredText } from '../common/validation';\nimport {\n PasswordService,\n registrationPassword,\n} from '../Auth/password.service';\nimport type { User } from './user.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\n@Injectable()\nexport class UserService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly passwords: PasswordService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown): Promise<User> {\n const body = objectBody(value, ['username', 'display_name', 'password']);\n const username = body.username;\n if (typeof username !== 'string' || !/^[a-z0-9_]{3,32}$/.test(username)) {\n throw new ApiException(\n HttpStatus.BAD_REQUEST,\n 'invalid_request',\n 'Некорректный username',\n );\n }\n const displayName = requiredText(body.display_name, 'display_name', 100);\n const password = registrationPassword(body.password);\n const passwordHash = await this.passwords.hash(password);\n try {\n return this.serialize(\n await this.prisma.user.create({\n data: { username, displayName, passwordHash },\n }),\n );\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2002'\n ) {\n throw new ApiException(\n HttpStatus.CONFLICT,\n 'conflict',\n 'Username уже занят',\n );\n }\n throw error;\n }\n }\n\n async get(id: string): Promise<User | undefined> {\n return this.cache.remember(\n `user:${id}`,\n 'profile',\n CACHE_TTL.entity,\n async () => {\n const user = await this.prisma.user.findUnique({ where: { id } });\n return user ? this.serialize(user) : undefined;\n },\n );\n }\n\n serialize(\n user: Pick<StoredUser, 'id' | 'username' | 'displayName' | 'createdAt'>,\n ): User {\n return {\n id: user.id,\n username: user.username,\n display_name: user.displayName,\n created_at: user.createdAt.toISOString(),\n };\n }\n}\n",
|
||
"User/user.guard.ts": "import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport type { FastifyRequest } from 'fastify';\nimport { AuthService, type ChatAccess } from '../Auth/auth.service';\nimport type { User } from './user.schema';\n\nexport type AuthenticatedRequest = FastifyRequest & {\n currentUser: User;\n currentSessionId: string;\n currentChatsEpoch: string;\n currentChatAccess?: ChatAccess;\n};\n\n@Injectable()\nexport class UserGuard implements CanActivate {\n constructor(private readonly auth: AuthService) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const request = context.switchToHttp().getRequest<AuthenticatedRequest>();\n const chatId =\n request.method === 'GET' &&\n request.routeOptions.url === '/api/v1/chats/:chat_id/messages'\n ? (request.params as { chat_id: string }).chat_id\n : undefined;\n const session = await this.auth.authenticate(\n request.headers.authorization,\n chatId,\n );\n request.currentUser = session.user;\n request.currentSessionId = session.sessionId;\n request.currentChatsEpoch = session.chatsEpoch;\n request.currentChatAccess = session.chatAccess;\n return true;\n }\n}\n",
|
||
"Chat/chat.service.ts": "import { HttpStatus, Injectable } from '@nestjs/common';\nimport { randomUUID } from 'node:crypto';\nimport type { ChatAccess } from '../Auth/auth.service';\nimport {\n Prisma,\n type Message as StoredMessage,\n} from '../generated/prisma/client';\nimport { PrismaService } from '../prisma/prisma.service';\nimport { ApiException } from '../common/exceptions/api.exception';\nimport {\n invalidRequest,\n objectBody,\n pageLimit,\n requiredText,\n uuid,\n} from '../common/validation';\nimport type { Chat, Message, Page } from './chat.schema';\nimport { CacheService, CACHE_TTL } from '../cache/cache.service';\n\ninterface Cursor {\n scope: string;\n created_at: string;\n id: string;\n}\n\nconst chatInclude = {\n members: { orderBy: { position: 'asc' as const } },\n} satisfies Prisma.ChatInclude;\ntype StoredChat = Prisma.ChatGetPayload<{ include: typeof chatInclude }>;\n\n@Injectable()\nexport class ChatService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly cache: CacheService,\n ) {}\n\n async create(value: unknown, userId: string): Promise<Chat> {\n const body = objectBody(value, ['title', 'member_ids']);\n const title = requiredText(body.title, 'title', 100);\n if (\n !Array.isArray(body.member_ids) ||\n body.member_ids.length < 1 ||\n body.member_ids.length > 100\n ) {\n return invalidRequest('Некорректный member_ids');\n }\n const memberIds = body.member_ids.map((id: unknown) =>\n uuid(id, 'member_ids'),\n );\n if (\n new Set(memberIds).size !== memberIds.length ||\n !memberIds.includes(userId)\n ) {\n return invalidRequest(\n 'Список участников содержит дубликат или не содержит вызывающего',\n );\n }\n try {\n const chat = await this.prisma.$transaction(async (tx) => {\n const count = await tx.user.count({ where: { id: { in: memberIds } } });\n if (count !== memberIds.length)\n return invalidRequest('Неизвестный участник чата');\n const created = await tx.chat.create({\n data: {\n title,\n members: {\n create: memberIds.map((userId, position) => ({\n userId,\n position,\n })),\n },\n },\n include: chatInclude,\n });\n await tx.$executeRaw(Prisma.sql`\n WITH locked AS MATERIALIZED (\n SELECT id FROM users\n WHERE id IN (${Prisma.join(memberIds.map((id) => Prisma.sql`${id}::uuid`))})\n ORDER BY id FOR UPDATE\n )\n UPDATE users AS u SET chats_epoch = u.chats_epoch + 1\n FROM locked WHERE u.id = locked.id\n `);\n return created;\n });\n return this.serializeChat(chat);\n } catch (error) {\n if (\n error instanceof Prisma.PrismaClientKnownRequestError &&\n error.code === 'P2003'\n ) {\n return invalidRequest('Неизвестный участник чата');\n }\n throw error;\n }\n }\n\n async list(\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n epoch: string,\n ): Promise<Page<Chat>> {\n const limit = pageLimit(limitValue);\n const scope = `chats:${userId}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const chats = await this.prisma.chat.findMany({\n where: { members: { some: { userId } }, ...this.after(cursor) },\n include: chatInclude,\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n chats.map((chat) => this.serializeChat(chat)),\n limit,\n scope,\n );\n },\n epoch,\n );\n }\n\n async get(value: unknown, userId: string): Promise<Chat> {\n const { id } = await this.authorizeChat(value, userId);\n return this.getMetadata(id);\n }\n\n private async authorizeChat(value: unknown, userId: string) {\n const id = uuid(value, 'chat_id');\n const [membership] = await this.prisma.$queryRaw<\n { id: string; messagesEpoch: bigint }[]\n >(Prisma.sql`\n SELECT c.id, COALESCE((SELECT SUM(e.epoch) FROM \"epoch_variants_0302fea1e5264f72a02693f65cb217b7\".chat_message_epochs AS e WHERE e.chat_id = c.id), 0)::bigint AS \"messagesEpoch\"\n FROM chat_members AS cm JOIN chats AS c ON c.id = cm.chat_id\n WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid\n `);\n if (!membership) {\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n }\n return membership;\n }\n\n private getMetadata(id: string): Promise<Chat> {\n return this.cache.remember(\n `chat:${id}`,\n 'metadata',\n CACHE_TTL.entity,\n async () => {\n const chat = await this.prisma.chat.findUnique({\n where: { id },\n include: chatInclude,\n });\n if (!chat)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeChat(chat);\n },\n );\n }\n\n async createMessage(\n chatId: unknown,\n value: unknown,\n userId: string,\n ): Promise<Message> {\n const id = uuid(chatId, 'chat_id');\n const body = objectBody(value, ['text']);\n const text = requiredText(body.text, 'text', 4000);\n const messageId = randomUUID();\n const bucket = parseInt(messageId.slice(0, 2), 16) % 16;\n const [message] = await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n WITH updated AS (\n INSERT INTO \"epoch_variants_0302fea1e5264f72a02693f65cb217b7\".chat_message_epochs AS e (chat_id, bucket, epoch)\n SELECT cm.chat_id, ${bucket}::smallint, 1 FROM chat_members AS cm\n WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid\n ON CONFLICT (chat_id, bucket) DO UPDATE SET epoch = e.epoch + 1\n RETURNING chat_id\n )\n INSERT INTO messages (id, chat_id, sender_id, text)\n SELECT ${messageId}::uuid, updated.chat_id, ${userId}::uuid, ${text} FROM updated\n RETURNING id, chat_id AS \"chatId\", sender_id AS \"senderId\", text, created_at AS \"createdAt\"\n `);\n if (!message)\n throw new ApiException(\n HttpStatus.NOT_FOUND,\n 'not_found',\n 'Объект не найден',\n );\n return this.serializeMessage(message);\n }\n\n async listMessages(\n chatId: unknown,\n userId: string,\n limitValue: unknown,\n cursorValue: unknown,\n access?: ChatAccess,\n ): Promise<Page<Message>> {\n const id = uuid(chatId, 'chat_id');\n const chat =\n access?.chatId === id && access.userId === userId\n ? { id, messagesEpoch: access.messagesEpoch }\n : await this.authorizeChat(id, userId);\n const limit = pageLimit(limitValue);\n const scope = `messages:${chat.id}`;\n const cursor = this.decodeCursor(cursorValue, scope);\n return this.cache.remember(\n scope,\n { limit, cursor },\n CACHE_TTL.page,\n async () => {\n const messages = cursor\n ? await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`\n SELECT id, chat_id AS \"chatId\", sender_id AS \"senderId\",\n text, created_at AS \"createdAt\"\n FROM \"public\".\"messages\"\n WHERE chat_id = ${chat.id}::uuid\n AND (created_at, id) >\n (${new Date(cursor.created_at)}::timestamptz, ${cursor.id}::uuid)\n ORDER BY created_at ASC, id ASC\n LIMIT ${limit + 1}\n `)\n : await this.prisma.message.findMany({\n where: { chatId: chat.id },\n orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],\n take: limit + 1,\n });\n return this.page(\n messages.map((message) => this.serializeMessage(message)),\n limit,\n scope,\n );\n },\n chat.messagesEpoch.toString(),\n );\n }\n\n private after(cursor: Cursor | null) {\n if (!cursor) return {};\n const createdAt = new Date(cursor.created_at);\n return {\n OR: [\n { createdAt: { gt: createdAt } },\n { createdAt, id: { gt: cursor.id } },\n ],\n };\n }\n\n private serializeChat(chat: StoredChat): Chat {\n return {\n id: chat.id,\n title: chat.title,\n member_ids: chat.members.map((member) => member.userId),\n created_at: chat.createdAt.toISOString(),\n };\n }\n\n private serializeMessage(message: StoredMessage): Message {\n return {\n id: message.id,\n chat_id: message.chatId,\n sender_id: message.senderId,\n text: message.text,\n created_at: message.createdAt.toISOString(),\n };\n }\n\n private page<T extends { id: string; created_at: string }>(\n items: T[],\n limit: number,\n scope: string,\n ): Page<T> {\n const result = items.slice(0, limit);\n const last = result.at(-1);\n return {\n items: result,\n next_cursor:\n items.length > limit && last\n ? Buffer.from(\n JSON.stringify({\n scope,\n created_at: last.created_at,\n id: last.id,\n }),\n ).toString('base64url')\n : null,\n };\n }\n\n private decodeCursor(value: unknown, scope: string): Cursor | null {\n if (value === undefined) return null;\n if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))\n return invalidRequest('Некорректный cursor');\n try {\n const cursor: unknown = JSON.parse(\n Buffer.from(value, 'base64url').toString('utf8'),\n );\n if (\n typeof cursor !== 'object' ||\n cursor === null ||\n Array.isArray(cursor)\n )\n return invalidRequest('Некорректный cursor');\n const data = cursor as Record<string, unknown>;\n if (\n data.scope !== scope ||\n typeof data.created_at !== 'string' ||\n Number.isNaN(Date.parse(data.created_at)) ||\n typeof data.id !== 'string'\n ) {\n return invalidRequest('Некорректный cursor');\n }\n return {\n scope,\n created_at: data.created_at,\n id: uuid(data.id, 'cursor'),\n };\n } catch {\n return invalidRequest('Некорректный cursor');\n }\n }\n}\n",
|
||
"Chat/chat.controller.ts": "import {\n Body,\n Controller,\n Get,\n HttpCode,\n HttpStatus,\n Param,\n Post,\n Query,\n Req,\n UseGuards,\n} from '@nestjs/common';\nimport {\n ApiBody,\n ApiBearerAuth,\n ApiCreatedResponse,\n ApiOkResponse,\n ApiOperation,\n ApiQuery,\n ApiTags,\n} from '@nestjs/swagger';\nimport { UserGuard, type AuthenticatedRequest } from '../User/user.guard';\nimport {\n CreateChatDto,\n CreateMessageDto,\n Chat,\n Message,\n ChatPage,\n MessagePage,\n} from './chat.schema';\nimport { ChatService } from './chat.service';\n\n@ApiTags('chats')\n@ApiBearerAuth('bearerAuth')\n@UseGuards(UserGuard)\n@Controller('api/v1/chats')\nexport class ChatController {\n constructor(private readonly chats: ChatService) {}\n\n @Post()\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateChatDto })\n @ApiOperation({ operationId: 'createChat' })\n @ApiCreatedResponse({ type: Chat })\n create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {\n return this.chats.create(body, request.currentUser.id);\n }\n\n @Get()\n @ApiOperation({ operationId: 'listChats' })\n @ApiOkResponse({ type: ChatPage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n list(\n @Req() request: AuthenticatedRequest,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.list(\n request.currentUser.id,\n limit,\n cursor,\n request.currentChatsEpoch,\n );\n }\n\n @Get(':chat_id')\n @ApiOperation({ operationId: 'getChat' })\n @ApiOkResponse({ type: Chat })\n get(@Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string) {\n return this.chats.get(chatId, request.currentUser.id);\n }\n\n @Post(':chat_id/messages')\n @HttpCode(HttpStatus.CREATED)\n @ApiBody({ type: CreateMessageDto })\n @ApiOperation({ operationId: 'createMessage' })\n @ApiCreatedResponse({ type: Message })\n createMessage(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Body() body: unknown,\n ) {\n return this.chats.createMessage(chatId, body, request.currentUser.id);\n }\n\n @Get(':chat_id/messages')\n @ApiOperation({ operationId: 'listMessages' })\n @ApiOkResponse({ type: MessagePage })\n @ApiQuery({\n name: 'limit',\n required: false,\n schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n })\n @ApiQuery({ name: 'cursor', required: false, type: String })\n listMessages(\n @Req() request: AuthenticatedRequest,\n @Param('chat_id') chatId: string,\n @Query('limit') limit: unknown,\n @Query('cursor') cursor: unknown,\n ) {\n return this.chats.listMessages(\n chatId,\n request.currentUser.id,\n limit,\n cursor,\n request.currentChatAccess,\n );\n }\n}\n"
|
||
}
|
||
}
|