diff --git a/apps/api/eslint.config.mjs b/apps/api/eslint.config.mjs index 4e9f8271..914cd4e2 100644 --- a/apps/api/eslint.config.mjs +++ b/apps/api/eslint.config.mjs @@ -29,7 +29,28 @@ export default tseslint.config( '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-floating-promises': 'warn', '@typescript-eslint/no-unsafe-argument': 'warn', - "prettier/prettier": ["error", { endOfLine: "auto" }], + 'prettier/prettier': ['error', { endOfLine: 'auto' }], + }, + }, + { + files: ['**/*.spec.ts', 'test/**/*.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', + '@typescript-eslint/no-this-alias': 'off', + '@typescript-eslint/require-await': 'off', + '@typescript-eslint/unbound-method': 'off', + }, + }, + { + files: ['src/modules/global/database/migrations/**/*.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', }, }, ); diff --git a/apps/api/src/modules/auction/auction-realtime-serializer.ts b/apps/api/src/modules/auction/auction-realtime-serializer.ts index 2a3c75de..4630de63 100644 --- a/apps/api/src/modules/auction/auction-realtime-serializer.ts +++ b/apps/api/src/modules/auction/auction-realtime-serializer.ts @@ -74,13 +74,11 @@ function serializeRealtimeAuctionPlayer( return player; } - const { - masteries: _masteries, - puuid: _puuid, - recentStatsSummary: _recentStatsSummary, - tierHistory: _tierHistory, - ...lightweightPlayer - } = player; + const lightweightPlayer = { ...player }; + delete lightweightPlayer.masteries; + delete lightweightPlayer.puuid; + delete lightweightPlayer.recentStatsSummary; + delete lightweightPlayer.tierHistory; return lightweightPlayer; } diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index f71d7cf0..fc5951f9 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -13,7 +13,7 @@ import { } from '@nestjs/websockets'; import mongoose from 'mongoose'; import type { JWTPayload } from 'jose'; -import { Namespace, Socket } from 'socket.io'; +import type { DefaultEventsMap, Namespace, Socket } from 'socket.io'; import { AuthService } from '../auth/auth.service'; import { IdentityService } from '../auth/identity.service'; import { JwtService } from '../auth/jwt.service'; @@ -78,6 +78,20 @@ interface BidRateLimitState { windowStartedAtTimestampMS: number; } +interface AuctionSocketData { + auctionBidRateLimit?: BidRateLimitState; + identity?: IdentityDocument; + matchId?: string; + user?: UserDocument; +} + +type AuctionSocket = Socket< + DefaultEventsMap, + DefaultEventsMap, + DefaultEventsMap, + AuctionSocketData +>; + const BID_RATE_LIMIT_WINDOW_MS = 1000; const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8; const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED'; @@ -112,14 +126,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { this.auctionEventBusService.attachAuctionNamespace(server); } - public async handleConnection(socket: Socket) { + public async handleConnection(socket: AuctionSocket) { try { await this.authenticateSocket(socket); this.logger.debug(`Auction client connected: ${socket.id}`); } catch (err) { this.logger.warn( `Auction client authentication failed: ${ - err instanceof Error ? err.message : err + err instanceof Error ? err.message : String(err) }`, ); socket.disconnect(true); @@ -128,7 +142,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('join') public async handleJoin( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: JoinAuctionPayload, ) { if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { @@ -156,7 +170,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('bid') public async handleBid( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: BidPayload, @Ack() ack?: (response: Record) => void, ) { @@ -220,7 +234,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { error, ); const bidServerTiming = this.extractBidServerTiming(rejectionAckFields); - this.emitError(socket, String(rejectionAckFields.message ?? '')); + this.emitError( + socket, + typeof rejectionAckFields.message === 'string' + ? rejectionAckFields.message + : '', + ); ack?.({ ...rejectionAckFields, bidRequestId, @@ -263,7 +282,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('open-bidding') public async handleOpenBidding( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { @@ -292,7 +311,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('sold') public async handleSold( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: SoldPayload, @Ack() ack?: (response: Record) => void, ) { @@ -322,7 +341,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('next') public async handleNext( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { @@ -351,7 +370,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('passed') public async handlePassed( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { @@ -380,7 +399,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('chat-message') public async handleChatMessage( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: ChatMessagePayload, ) { const matchId = this.requireJoinedMatchId(socket); @@ -406,7 +425,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { } } - private requireJoinedMatchId(socket: Socket): string | null { + private requireJoinedMatchId(socket: AuctionSocket): string | null { const matchId = this.getSocketMatchId(socket); if (!matchId) { this.emitError(socket, 'Join a match room before sending events.'); @@ -415,11 +434,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { return matchId; } - private consumeBidRateLimit(socket: Socket): boolean { + private consumeBidRateLimit(socket: AuctionSocket): boolean { const currentTimestampMS = Date.now(); - const previousState = socket.data.auctionBidRateLimit as - | BidRateLimitState - | undefined; + const previousState = socket.data.auctionBidRateLimit; if ( !previousState || currentTimestampMS - previousState.windowStartedAtTimestampMS >= @@ -437,10 +454,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW; } - private getSocketMatchId(socket: Socket): string | undefined { - return typeof socket.data.matchId === 'string' - ? socket.data.matchId - : undefined; + private getSocketMatchId(socket: AuctionSocket): string | undefined { + return socket.data.matchId; } private toAuctionActionRequest(payload?: AuctionActionPayload) { @@ -464,8 +479,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }; } - private readHandshakeUserId(socket: Socket): string | undefined { - const authUserId = socket.handshake.auth['x-auth-user-id']; + private readHandshakeUserId(socket: AuctionSocket): string | undefined { + const handshakeAuth = socket.handshake.auth as Record; + const authUserId = handshakeAuth['x-auth-user-id']; if (typeof authUserId === 'string') return authUserId; const header = socket.handshake.headers['x-auth-user-id']; @@ -473,16 +489,16 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { } private resolveSocketUserId( - socket: Socket, + socket: AuctionSocket, ): mongoose.Types.ObjectId | undefined { - return (socket.data.user as UserDocument | undefined)?._id; + return socket.data.user?._id; } private resolveChatDisplayName( - socket: Socket, + socket: AuctionSocket, fallbackDisplayName?: string, ): string { - const user = socket.data.user as UserDocument | undefined; + const user = socket.data.user; const primaryRiotAccount = user?.riotAccounts.find((entry) => entry.isPrimary) ?? user?.riotAccounts[0]; @@ -495,14 +511,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { if (user?.kakaoTalkNickname) return user.kakaoTalkNickname; if (user?.discordNickname) return user.discordNickname; - const identity = socket.data.identity as IdentityDocument | undefined; + const identity = socket.data.identity; if (identity?.displayName) return identity.displayName; if (identity?.email) return identity.email; return fallbackDisplayName ?? '관전자'; } - private async authenticateSocket(socket: Socket): Promise { + private async authenticateSocket(socket: AuctionSocket): Promise { const fallback = await this.authService.resolveDevUserById( this.readHandshakeUserId(socket), ); @@ -532,14 +548,20 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }); } - private readHandshakeToken(socket: Socket): string | undefined { - const authToken = socket.handshake.auth.token; + private readHandshakeToken(socket: AuctionSocket): string | undefined { + const handshakeAuth = socket.handshake.auth as Record; + const authToken = handshakeAuth.token; if (typeof authToken === 'string' && authToken.trim()) { return authToken.trim().replace(/^Bearer\s+/i, ''); } - const header = socket.handshake.headers.authorization; - const authorization = Array.isArray(header) ? header[0] : header; + const header: unknown = socket.handshake.headers.authorization; + const authorization = + typeof header === 'string' + ? header + : Array.isArray(header) && typeof header[0] === 'string' + ? header[0] + : undefined; if (authorization?.startsWith('Bearer ')) { return authorization.slice('Bearer '.length).trim(); } @@ -547,10 +569,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { } private async resolveSocketUserForMatch( - socket: Socket, + socket: AuctionSocket, matchId: string, ): Promise { if (socket.data.user || !socket.data.identity) return; + const identity = socket.data.identity; const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(matchId).select({ @@ -559,10 +582,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { if (!match) return; const UserModel = await this.connectionService.getModel('user'); - socket.data.user = await UserModel.findOne({ + const user = await UserModel.findOne({ communityId: match.communityId, - identityId: (socket.data.identity as IdentityDocument)._id, + identityId: identity._id, }).exec(); + socket.data.user = user ?? undefined; } private requireStringClaim(payload: JWTPayload, key: string): string { @@ -596,7 +620,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { this.server.to(matchId).emit('match-side-effect', delta); } - private emitChatHistory(socket: Socket, auction: AuctionDocument) { + private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) { socket.emit('chat-history', { messages: (auction.chatMessages ?? []).map((message) => this.serializeChatMessage(message), @@ -604,16 +628,21 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }); } - private emitKnownError(socket: Socket, error: unknown) { + private emitKnownError(socket: AuctionSocket, error: unknown) { this.emitError(socket, this.resolveErrorPayload(error).message); } - private emitError(socket: Socket, message: string) { + private emitError(socket: AuctionSocket, message: string) { socket.emit('error', { message }); } - private serializeAuction(auction: AuctionStateResponse) { - return JSON.parse(JSON.stringify(auction)); + private serializeAuction( + auction: AuctionStateResponse, + ): Record { + const serialized: unknown = JSON.parse(JSON.stringify(auction)); + return typeof serialized === 'object' && serialized !== null + ? (serialized as Record) + : {}; } /** @@ -721,7 +750,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { bidDelta: Record | null, ): Record | null { if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta; - const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta; + const publicBidDelta = { ...bidDelta }; + delete publicBidDelta.bidServerTiming; return publicBidDelta; } @@ -729,10 +759,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { auction: AuctionStateResponse, bidRequestId?: string, ): Record | null { - const serialized = this.serializeAuction(auction) as Record< - string, - unknown - >; + const serialized = this.serializeAuction(auction); const revision = Number(serialized.revision); const currentHighestBidPointAmount = Number( serialized.currentHighestBidPointAmount ?? serialized.currentBid, @@ -747,11 +774,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { ? Date.parse(serialized.currentDeadline) : 0), ); - const redisBidHistory = Array.isArray(serialized.auctionBidHistory) - ? serialized.auctionBidHistory + const redisBidHistory: unknown[] = Array.isArray( + serialized.auctionBidHistory, + ) + ? (serialized.auctionBidHistory as unknown[]) : []; - const legacyBidHistory = Array.isArray(serialized.bids) - ? serialized.bids + const legacyBidHistory: unknown[] = Array.isArray(serialized.bids) + ? (serialized.bids as unknown[]) : []; const auctionBidHistoryEntry = redisBidHistory[redisBidHistory.length - 1] ?? @@ -810,7 +839,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }; } - private serializeChatMessage(message: AuctionChatMessage) { - return JSON.parse(JSON.stringify(message)); + private serializeChatMessage( + message: AuctionChatMessage, + ): Record { + const serialized: unknown = JSON.parse(JSON.stringify(message)); + return typeof serialized === 'object' && serialized !== null + ? (serialized as Record) + : {}; } } diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 695e8b49..ef9974a4 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -158,12 +158,11 @@ describe('AuctionService', () => { it('rejects non-positive or fractional bid amounts before loading auction state', async () => { const matchId = new mongoose.Types.ObjectId(); const auctionFindOne = jest.fn(); - const { service, auctionRedisCommandService, auctionRedisService } = - createService({ - auction: { - findOne: auctionFindOne, - }, - }); + const { service, auctionRedisCommandService } = createService({ + auction: { + findOne: auctionFindOne, + }, + }); await expect( service.placeBid({ diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts index 593446d8..cff926bf 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts @@ -151,7 +151,7 @@ export class AuctionRedisStateReaderService { revision: number; }, shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, - structureState: JSON.parse(structureStateJson) as Record, + structureState: parseJsonRecord(structureStateJson), }); view.matchId = matchId; if (options.includeInternalLiveStateFields) { @@ -170,12 +170,9 @@ export class AuctionRedisStateReaderService { if (typeof structureStateJson !== 'string' || !structureStateJson) { return undefined; } - const structureState = JSON.parse(structureStateJson) as Record< - string, - unknown - >; - const auctionTeams = Array.isArray(structureState.auctionTeams) - ? structureState.auctionTeams + const structureState = parseJsonRecord(structureStateJson); + const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams) + ? (structureState.auctionTeams as unknown[]) : []; const bidderTeam = auctionTeams.find((entry) => { if (!entry || typeof entry !== 'object') return false; @@ -192,6 +189,13 @@ function stringValue(value: unknown): string | undefined { return typeof value === 'string' && value ? value : undefined; } +function parseJsonRecord(json: string): Record { + const value: unknown = JSON.parse(json); + return typeof value === 'object' && value !== null + ? (value as Record) + : {}; +} + function parseHashReply( reply: unknown, options: { includeInternalLiveStateFields?: boolean } = {}, diff --git a/apps/api/src/modules/auction/redis/auction-redis.module.ts b/apps/api/src/modules/auction/redis/auction-redis.module.ts index d3b1b3a9..5623f363 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.module.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.module.ts @@ -74,9 +74,11 @@ async function readFirstSecret( const logger = new Logger('AuctionRedisClient'); const client = createClient(auctionRedisOptions); - client.on('error', (error) => { + client.on('error', (error: unknown) => { logger.error( - `Auction Redis client error: ${error?.message ?? error}`, + `Auction Redis client error: ${ + error instanceof Error ? error.message : String(error) + }`, ); }); diff --git a/apps/api/src/modules/auction/redis/auction-redis.service.ts b/apps/api/src/modules/auction/redis/auction-redis.service.ts index 91ba3cae..0240afb3 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.service.ts @@ -85,9 +85,15 @@ export class AuctionRedisService implements OnModuleDestroy { if (!isNoscriptError(error)) throw error; } - const loadedSha = String( - await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]), - ); + const loadedShaReply = await this.client.sendCommand([ + 'SCRIPT', + 'LOAD', + params.script, + ]); + if (typeof loadedShaReply !== 'string') { + throw new Error('Redis SCRIPT LOAD returned a non-string SHA.'); + } + const loadedSha = loadedShaReply; return (await this.client.sendCommand( buildEvalShaCommand(loadedSha, params.keys, params.values), )) as T; @@ -111,7 +117,7 @@ export class AuctionRedisService implements OnModuleDestroy { token: string, ttlMS: number, ): Promise { - const result = await this.client.sendCommand([ + const result = await this.client.sendCommand([ 'SET', key, token, @@ -119,7 +125,7 @@ export class AuctionRedisService implements OnModuleDestroy { String(ttlMS), 'NX', ]); - return String(result) === 'OK'; + return result === 'OK'; } public async releaseTokenLock(key: string, token: string): Promise { diff --git a/apps/api/src/modules/auction/redis/auction-redis.state.ts b/apps/api/src/modules/auction/redis/auction-redis.state.ts index 477a7396..8e6aad6f 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.state.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.state.ts @@ -78,9 +78,7 @@ export function assembleAuctionViewFromRedisState( return { ...params.structureState, ...params.liveState, - auctionBidHistory: params.auctionBidHistoryEntries.map((entry) => - JSON.parse(entry), - ), + auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue), canPlaceBidInCurrentBidRound: !isExpiring, currentServerTimestampMS: params.currentServerTimestampMS, isAuctionStateTransitionInProgress: isExpiring, @@ -90,6 +88,11 @@ export function assembleAuctionViewFromRedisState( }; } +function parseJsonValue(json: string): unknown { + const value: unknown = JSON.parse(json); + return value; +} + export function buildHydrateAuctionStateScriptInvocation( keys: AuctionRedisKeys, input: HydrateAuctionStateScriptInput, diff --git a/apps/api/src/modules/auth/jwt.guard.ts b/apps/api/src/modules/auth/jwt.guard.ts index 97b73d0d..0018b7cd 100644 --- a/apps/api/src/modules/auth/jwt.guard.ts +++ b/apps/api/src/modules/auth/jwt.guard.ts @@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, [context.getHandler(), context.getClass()], ); - const authz = request.headers?.authorization; - const authzHeader = Array.isArray(authz) ? authz[0] : authz; + const authzHeader = request.get('authorization'); if (!authzHeader) { const fallback = @@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate { private pickIdPFromToken(token: string): IdentityProviderName { try { - const { iss } = decodeJwt(token) as { iss?: string }; + const { iss } = decodeJwt(token); if (!iss) { throw new Error('Token has no issuer (iss) claim'); } diff --git a/apps/api/src/modules/auth/jwt.service.ts b/apps/api/src/modules/auth/jwt.service.ts index 166ca211..729be1a6 100644 --- a/apps/api/src/modules/auth/jwt.service.ts +++ b/apps/api/src/modules/auth/jwt.service.ts @@ -35,11 +35,13 @@ export class JwtService { throw new Error('Empty token'); } - if (identityProvider !== 'MICROSOFT_ENTRAID') { - throw new Error(`Identity provider not configured: ${identityProvider}`); + const provider = + identityProvider === 'MICROSOFT_ENTRAID' + ? await this.getEntraConfig() + : undefined; + if (!provider) { + throw new Error('Identity provider not configured.'); } - - const provider = await this.getEntraConfig(); const result = await jwtVerify(token, provider.jwks, { issuer: provider.issuer, audience: provider.audience, @@ -48,14 +50,22 @@ export class JwtService { }); const { payload, protectedHeader } = result; - if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) { + if (!provider.allowedAlgs.includes(protectedHeader.alg)) { throw new Error(`Unexpected alg: ${protectedHeader.alg}`); } - if (payload.ver && payload.ver !== '2.0') { - throw new Error(`Unsupported Entra token version: ${payload.ver}`); + if ( + payload.ver !== undefined && + (typeof payload.ver !== 'string' || payload.ver !== '2.0') + ) { + throw new Error( + `Unsupported Entra token version: ${formatClaimValue(payload.ver)}`, + ); } - if (payload.tid && payload.tid !== provider.tenantId) { - throw new Error(`Unexpected tenant: ${payload.tid}`); + if ( + payload.tid !== undefined && + (typeof payload.tid !== 'string' || payload.tid !== provider.tenantId) + ) { + throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`); } return result; @@ -98,3 +108,16 @@ export class JwtService { return this.entraConfig; } } + +function formatClaimValue(value: unknown): string { + if ( + typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' || + typeof value === 'bigint' + ) { + return String(value); + } + if (value === null) return 'null'; + return JSON.stringify(value) ?? typeof value; +} diff --git a/apps/api/src/modules/auth/roles.guard.ts b/apps/api/src/modules/auth/roles.guard.ts index 6e76e87d..0c01989d 100644 --- a/apps/api/src/modules/auth/roles.guard.ts +++ b/apps/api/src/modules/auth/roles.guard.ts @@ -7,7 +7,7 @@ import { } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import type { Request } from 'express'; -import { CommunityRole, UserDocument } from '../global/database/schema'; +import type { CommunityRole } from '../global/database/schema'; import { ROLES_KEY } from './roles.decorator'; import './auth-request'; @@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate { if (!requiredRoles || requiredRoles.length === 0) return true; const req = context.switchToHttp().getRequest(); - const user = req.user as UserDocument | undefined; + const user = req.user; if (!user && req.identity) { throw new ForbiddenException('No membership in this community.'); } diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts index 2d50765a..d454e329 100644 --- a/apps/api/src/modules/community-stats/community-stats-cache.service.ts +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -34,16 +34,29 @@ export class CommunityStatsCacheService { let deleted = 0; do { - const reply = (await client.sendCommand([ + const reply = await client.sendCommand([ 'SCAN', cursor, 'MATCH', match, 'COUNT', '100', - ])) as [string, string[]]; - cursor = reply[0]; - const keys = reply[1] ?? []; + ]); + if (!Array.isArray(reply)) { + throw new Error('Redis SCAN returned an invalid response.'); + } + const values = reply as unknown[]; + const nextCursor = values[0]; + const rawKeys = values[1]; + if (typeof nextCursor !== 'string') { + throw new Error('Redis SCAN returned an invalid cursor.'); + } + cursor = nextCursor; + const keys = Array.isArray(rawKeys) + ? (rawKeys as unknown[]).filter( + (key): key is string => typeof key === 'string', + ) + : []; if (keys.length > 0) { deleted += await client.del(keys); } diff --git a/apps/api/src/modules/community-stats/match-stats.repository.spec.ts b/apps/api/src/modules/community-stats/match-stats.repository.spec.ts index b9a8c6ef..6513d10f 100644 --- a/apps/api/src/modules/community-stats/match-stats.repository.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats.repository.spec.ts @@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => { if ( stored && - stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) && - stored.sourceRevision! <= fragment.sourceRevision! + stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) && + stored.sourceRevision <= fragment.sourceRevision ) { stored = fragment; return { matchedCount: 1, upsertedCount: 0 }; diff --git a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts index 5a26cdf3..423d8bb6 100644 --- a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts +++ b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts @@ -485,11 +485,7 @@ function createHarness( let competitionCall = 0; const competitionModel = { findOneAndUpdate: jest.fn( - ( - _filter: unknown, - update: { $setOnInsert: InsertPayload }, - _queryOptions: unknown, - ) => { + (_filter: unknown, update: { $setOnInsert: InsertPayload }) => { insertedPayloads.push(update.$setOnInsert); const selected = options.competitionResults?.[competitionCall++]; if (selected instanceof Error) return rejectedQuery(selected); diff --git a/apps/api/src/modules/dakao/dakao-user.service.spec.ts b/apps/api/src/modules/dakao/dakao-user.service.spec.ts index a8b98cd0..ed34dd5c 100644 --- a/apps/api/src/modules/dakao/dakao-user.service.spec.ts +++ b/apps/api/src/modules/dakao/dakao-user.service.spec.ts @@ -105,7 +105,7 @@ describe('DakaoUserService', () => { tagLine: 'KR2', isPrimary: false, }); - expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({ + expect(result.user.riotAccounts[0]).toMatchObject({ puuid: 'puuid-1', isPrimary: true, }); diff --git a/apps/api/src/modules/dakao/dakao-user.service.ts b/apps/api/src/modules/dakao/dakao-user.service.ts index 15b31553..be5707a4 100644 --- a/apps/api/src/modules/dakao/dakao-user.service.ts +++ b/apps/api/src/modules/dakao/dakao-user.service.ts @@ -87,7 +87,7 @@ export class DakaoUserService { if (!community) { throw new DakaoUserError('community_not_found', dakaoProjectId); } - return community._id as mongoose.Types.ObjectId; + return community._id; } public async upsertUser(params: { diff --git a/apps/api/src/modules/dakao/dakao.subscriber.ts b/apps/api/src/modules/dakao/dakao.subscriber.ts index c875cbff..1df57846 100644 --- a/apps/api/src/modules/dakao/dakao.subscriber.ts +++ b/apps/api/src/modules/dakao/dakao.subscriber.ts @@ -301,7 +301,7 @@ export class DakaoSubscriber implements OnModuleInit { text: index === this.usageCommands.length - 1 ? ` ${command}` - : ` ${command} \n`, + : ` ${command}\u3000\n`, } as const, ]); } diff --git a/apps/api/src/modules/dakao/idempotency.cache.ts b/apps/api/src/modules/dakao/idempotency.cache.ts index 01dffeca..a45b80af 100644 --- a/apps/api/src/modules/dakao/idempotency.cache.ts +++ b/apps/api/src/modules/dakao/idempotency.cache.ts @@ -20,8 +20,8 @@ export class IdempotencyCache { public remember(key: string): void { this.evictExpired(); if (this.entries.size >= MAX_ENTRIES) { - const oldestKey = this.entries.keys().next().value; - if (oldestKey !== undefined) this.entries.delete(oldestKey); + const oldestKey: unknown = this.entries.keys().next().value; + if (typeof oldestKey === 'string') this.entries.delete(oldestKey); } this.entries.set(key, Date.now() + TTL_MS); } diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.ts b/apps/api/src/modules/double-elimination/double-elimination.util.ts index 73dd5c58..fe807410 100644 --- a/apps/api/src/modules/double-elimination/double-elimination.util.ts +++ b/apps/api/src/modules/double-elimination/double-elimination.util.ts @@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket( teamIndex, })); const bracket: DoubleEliminationBracket = { - teamCount: seededTeamIndexes.length as 4 | 8, + teamCount: seededTeamIndexes.length, resetFinalEnabled: options.resetFinalEnabled, resetFinalCreated: false, seeds, diff --git a/apps/api/src/modules/global/database/database.module.ts b/apps/api/src/modules/global/database/database.module.ts index a4b5e918..2b9d722a 100644 --- a/apps/api/src/modules/global/database/database.module.ts +++ b/apps/api/src/modules/global/database/database.module.ts @@ -1,4 +1,4 @@ -import { DynamicModule, Module } from '@nestjs/common'; +import { Module } from '@nestjs/common'; import { ConnectionService } from './connection.service'; @Module({ diff --git a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts index 970e60ff..111402c9 100644 --- a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts +++ b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts @@ -330,6 +330,9 @@ function legacyAuctionLifecycleId(value: unknown): string { function stringifyId(value: unknown): string | undefined { if (value === undefined || value === null) return undefined; + // MongoDB ObjectId and migration fixture IDs intentionally rely on their + // stable string representation. + // eslint-disable-next-line @typescript-eslint/no-base-to-string return typeof value === 'string' ? value : String(value); } diff --git a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts index b8e457af..a3065972 100644 --- a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts +++ b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts @@ -1,11 +1,4 @@ -type TournamentCodeState = - | 'available' - | 'reserved' - | 'used' - | 'released' - | 'expired' - | 'voided' - | string; +type TournamentCodeState = string; type AnyDoc = Record & { _id: unknown }; type IndexKey = Record; @@ -36,7 +29,7 @@ interface MigrationCollection { $unset?: Record; }, options?: { ordered?: boolean }, - ): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>; + ): Promise; indexes?(): Promise; dropIndex?(name: string): Promise; createIndex?( @@ -516,15 +509,17 @@ function summarizeGroups( function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary { return { bracketMatchId: - doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId), - code: doc.code === undefined ? undefined : String(doc.code), + doc.bracketMatchId === undefined + ? undefined + : stringifyId(doc.bracketMatchId), + code: doc.code === undefined ? undefined : stringifyId(doc.code), gameNumber: - doc.gameNumber === undefined ? undefined : String(doc.gameNumber), + doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber), id: stringifyId(doc._id) ?? '', matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId), riotMatchId: - doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId), - state: doc.state === undefined ? undefined : String(doc.state), + doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId), + state: doc.state, }; } @@ -749,16 +744,19 @@ function readModifiedCount(result: unknown): number { } function hasField(doc: Record, key: string): boolean { - return Object.prototype.hasOwnProperty.call(doc, key); + return Object.hasOwn(doc, key); } function stringifyKeyPart(value: unknown): string { if (value === null) return ''; if (value === undefined) return ''; - return stringifyId(value) ?? String(value); + return stringifyId(value) ?? ''; } function stringifyId(value: unknown): string | undefined { if (value === undefined || value === null) return undefined; + // MongoDB ObjectId and migration fixture IDs intentionally rely on their + // stable string representation. + // eslint-disable-next-line @typescript-eslint/no-base-to-string return typeof value === 'string' ? value : String(value); } diff --git a/apps/api/src/modules/global/nats/nats.module.ts b/apps/api/src/modules/global/nats/nats.module.ts index 79d5a32b..3e5a0287 100644 --- a/apps/api/src/modules/global/nats/nats.module.ts +++ b/apps/api/src/modules/global/nats/nats.module.ts @@ -1,5 +1,4 @@ import { Module } from '@nestjs/common'; -import fs from 'fs/promises'; import { connect } from 'nats'; import type { NatsConnection } from 'nats'; import { SecretModule } from '../secret/secret.module'; diff --git a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts index 6b878473..1cd92f76 100644 --- a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts +++ b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts @@ -38,27 +38,24 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { const markedSchema = schema as SchemaWithPerformanceMarker; if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return; markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true; - const hookableSchema = schema as any; - hookableSchema.pre(QUERY_OPERATION_REGEX, function () { + schema.pre(QUERY_OPERATION_REGEX, function () { const query = this as QueryWithPerformanceState; query[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); query[QUERY_PERFORMANCE_RECORDED] = false; }); - hookableSchema.post(QUERY_OPERATION_REGEX, function (result: unknown) { - recordQueryPerformance( - this as unknown as QueryWithPerformanceState, - result, - ); + schema.post(QUERY_OPERATION_REGEX, function (result: unknown) { + recordQueryPerformance(this as QueryWithPerformanceState, result); }); - hookableSchema.post( + schema.post( QUERY_OPERATION_REGEX, + { errorHandler: true }, function ( - error: unknown, + error: Error, _result: unknown, - next: (error: unknown) => void, + next: (error?: mongoose.CallbackError) => void, ) { recordQueryPerformance( this as unknown as QueryWithPerformanceState, @@ -69,22 +66,23 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { }, ); - hookableSchema.pre('aggregate', function () { + schema.pre('aggregate', function () { const aggregate = this as AggregateWithPerformanceState; aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); aggregate[QUERY_PERFORMANCE_RECORDED] = false; }); - hookableSchema.post('aggregate', function (result: unknown) { + schema.post('aggregate', function (result: unknown) { recordAggregatePerformance(this as AggregateWithPerformanceState, result); }); - hookableSchema.post( + schema.post( 'aggregate', + { errorHandler: true }, function ( - error: unknown, + error: Error, _result: unknown, - next: (error: unknown) => void, + next: (error?: mongoose.CallbackError) => void, ) { recordAggregatePerformance( this as AggregateWithPerformanceState, diff --git a/apps/api/src/modules/global/redis/distributed-lock.service.ts b/apps/api/src/modules/global/redis/distributed-lock.service.ts index fb2e0023..226963dc 100644 --- a/apps/api/src/modules/global/redis/distributed-lock.service.ts +++ b/apps/api/src/modules/global/redis/distributed-lock.service.ts @@ -56,16 +56,11 @@ export class DistributedLockService { const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID(); const result = await this.redisService .raw() - .sendCommand([ - 'SET', - options.lockKey, - lockOwnershipToken, - 'NX', - 'PX', - String(options.lockExpirationDurationMilliseconds), - ]); + .sendCommand< + string | null + >(['SET', options.lockKey, lockOwnershipToken, 'NX', 'PX', String(options.lockExpirationDurationMilliseconds)]); - if (String(result) !== 'OK') return null; + if (result !== 'OK') return null; return { lockKey: options.lockKey, lockOwnershipToken, @@ -124,7 +119,7 @@ export class DistributedLockService { await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { this.logger.warn( `Failed to release distributed lock ${lockOwnership.lockKey}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); @@ -143,8 +138,7 @@ export class DistributedLockService { const lockOwnership = await this.acquireLockWithRetry(options); if (!lockOwnership) return null; - let lockRenewalTimer: NodeJS.Timeout | undefined; - lockRenewalTimer = setInterval(() => { + const lockRenewalTimer = setInterval(() => { void this.extendLockIfOwned(lockOwnership).then((wasExtended) => { if (wasExtended) return; this.logger.warn( @@ -157,11 +151,11 @@ export class DistributedLockService { try { return await operation(lockOwnership); } finally { - if (lockRenewalTimer) clearInterval(lockRenewalTimer); + clearInterval(lockRenewalTimer); await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { this.logger.warn( `Failed to release distributed lock ${lockOwnership.lockKey}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); diff --git a/apps/api/src/modules/global/redis/redis.module.ts b/apps/api/src/modules/global/redis/redis.module.ts index 50d9d7ca..805985f8 100644 --- a/apps/api/src/modules/global/redis/redis.module.ts +++ b/apps/api/src/modules/global/redis/redis.module.ts @@ -54,8 +54,12 @@ async function readFirstSecret( }), ); - client.on('error', (error) => { - logger.error(`Redis client error: ${error?.message ?? error}`); + client.on('error', (error: unknown) => { + logger.error( + `Redis client error: ${ + error instanceof Error ? error.message : String(error) + }`, + ); }); await client.connect(); diff --git a/apps/api/src/modules/global/redis/redis.service.ts b/apps/api/src/modules/global/redis/redis.service.ts index 666fab98..57b6df05 100644 --- a/apps/api/src/modules/global/redis/redis.service.ts +++ b/apps/api/src/modules/global/redis/redis.service.ts @@ -35,11 +35,14 @@ interface RawStreamReadResult { function normalizeStreamFields(fields: unknown): Record { if (Array.isArray(fields)) { + const values = fields as unknown[]; const normalized: Record = {}; - for (let index = 0; index < fields.length; index += 2) { - const key = fields[index]; + for (let index = 0; index < values.length; index += 2) { + const key = values[index]; if (key === undefined) continue; - normalized[String(key)] = String(fields[index + 1] ?? ''); + normalized[redisValueToString(key)] = redisValueToString( + values[index + 1], + ); } return normalized; } @@ -260,10 +263,10 @@ export class RedisService implements OnModuleDestroy { rawMessage: unknown, ): StreamEntry | null { if (Array.isArray(rawMessage)) { - const [id, fields] = rawMessage; + const [id, fields] = rawMessage as unknown[]; if (id === undefined) return null; return { - id: String(id), + id: redisValueToString(id), message: normalizeStreamFields(fields), }; } @@ -291,3 +294,17 @@ export class RedisService implements OnModuleDestroy { return null; } } + +function redisValueToString(value: unknown): string { + if (typeof value === 'string') return value; + if ( + typeof value === 'number' || + typeof value === 'boolean' || + typeof value === 'bigint' + ) { + return String(value); + } + if (Buffer.isBuffer(value)) return value.toString('utf8'); + if (value === undefined || value === null) return ''; + return JSON.stringify(value) ?? ''; +} diff --git a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts index 4619fa50..8fd8d0e7 100644 --- a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts +++ b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/require-await, @typescript-eslint/unbound-method */ import { readFileSync } from 'node:fs'; import mongoose from 'mongoose'; import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service'; diff --git a/apps/api/src/modules/match/match.controller.spec.ts b/apps/api/src/modules/match/match.controller.spec.ts index 36d85ea7..55e9a76c 100644 --- a/apps/api/src/modules/match/match.controller.spec.ts +++ b/apps/api/src/modules/match/match.controller.spec.ts @@ -34,7 +34,7 @@ describe('MatchController participant access', () => { it('requires an authenticated community member for the self-join route', () => { // Metadata must be read from the unbound prototype method itself. - // eslint-disable-next-line @typescript-eslint/unbound-method + const handler = MatchController.prototype.joinMatch; const roles = Reflect.getMetadata(ROLES_KEY, handler) as | string[] diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts index bbb9a940..b05102dd 100644 --- a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts @@ -73,7 +73,7 @@ export class BackgroundRefreshScheduler .catch((err: unknown) => { this.logger.warn( `Background refresh leader release failed: ${ - err instanceof Error ? err.message : err + err instanceof Error ? err.message : String(err) }`, ); }); diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts index 33b31ee2..d1f8f298 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts @@ -215,7 +215,7 @@ export class RiotJobQueueService { public async promoteDueScheduledJobs(limit = 100): Promise { const client = this.redisService.raw(); - const raw = (await client.sendCommand([ + const entries = await client.sendCommand([ 'ZRANGEBYSCORE', RIOT_JOB_SCHEDULED_ZSET, '-inf', @@ -223,16 +223,15 @@ export class RiotJobQueueService { 'LIMIT', '0', String(limit), - ])) as string[] | null; - const entries = raw ?? []; + ]); let promoted = 0; for (const entry of entries) { - const removed = (await client.sendCommand([ + const removed = await client.sendCommand([ 'ZREM', RIOT_JOB_SCHEDULED_ZSET, entry, - ])) as number; + ]); if (removed !== 1) continue; const job = this.parseScheduledJob(entry); if (!job) continue; diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts index db565d41..b28658a0 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -67,7 +67,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { .catch((error: unknown) => { this.logger.warn( `Failed to release Riot job worker leader lock: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); diff --git a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts index da75a504..beef34bd 100644 --- a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts +++ b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts @@ -31,10 +31,10 @@ export class RiotRefreshGateway { private readonly logger = new Logger(RiotRefreshGateway.name); @SubscribeMessage('subscribe') - public async handleSubscribe( + public handleSubscribe( @ConnectedSocket() socket: Socket, @MessageBody() payload: SubscribePayload, - ) { + ): void { const rooms = this.resolveRooms(payload); if (rooms.length === 0) { socket.emit('error', { message: 'Invalid riot refresh subscription.' }); @@ -47,7 +47,7 @@ export class RiotRefreshGateway { return; } - await Promise.all(rooms.map((room) => socket.join(room))); + void socket.join(rooms); socket.emit('subscribed', { rooms }); } diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts index 7ba6114e..b3e6f76b 100644 --- a/apps/api/src/modules/riot/riot-recent-matches.service.ts +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -100,7 +100,7 @@ export class RiotRecentMatchesService { } catch (error: unknown) { this.logger.warn( `Skipping Riot match ${matchId} while syncing ${params.puuid}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); } diff --git a/apps/api/src/modules/riot/riot-webhook.controller.ts b/apps/api/src/modules/riot/riot-webhook.controller.ts index a64a691e..67cc130b 100644 --- a/apps/api/src/modules/riot/riot-webhook.controller.ts +++ b/apps/api/src/modules/riot/riot-webhook.controller.ts @@ -14,6 +14,7 @@ export class RiotWebhookController { public captureTournamentWebhook(@Req() req: RiotWebhookRequest) { const receivedAt = new Date().toISOString(); const rawBodyText = req.rawBody?.toString('utf8') ?? null; + const body: unknown = req.body; const logPayload = { receivedAt, method: req.method, @@ -25,7 +26,7 @@ export class RiotWebhookController { headers: req.headers, query: req.query, params: req.params, - body: req.body, + body, rawBodyLength: req.rawBody?.length ?? null, rawBodyText, }; diff --git a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts index c903a0d8..c36c07da 100644 --- a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts +++ b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { CompetitionResultSnapshot } from './competition-result.adapter'; import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; diff --git a/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts b/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts index c4c4d816..92aba73e 100644 --- a/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts +++ b/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import { Logger } from '@nestjs/common'; import { CommunityStatsService } from '../community-stats/community-stats.service'; diff --git a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts index 514867d4..e197c50a 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 3884231d..1e714229 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; diff --git a/apps/api/src/scripts/api-performance-report.ts b/apps/api/src/scripts/api-performance-report.ts index 20df9e8c..c63f87d7 100644 --- a/apps/api/src/scripts/api-performance-report.ts +++ b/apps/api/src/scripts/api-performance-report.ts @@ -485,7 +485,9 @@ function newRelicTransactionResultToRow( hydratedDocsReturnedP95Budget: number; }, ): EndpointReportRow | null { - const parsed = parseTransactionName(String(result.facet ?? '')); + const facet = result.facet; + if (typeof facet !== 'string') return null; + const parsed = parseTransactionName(facet); if (!parsed) return null; const row: EndpointReportRow = { diff --git a/apps/api/src/scripts/auction-redis-rehearsal.ts b/apps/api/src/scripts/auction-redis-rehearsal.ts index d36ad8f2..61f2edab 100644 --- a/apps/api/src/scripts/auction-redis-rehearsal.ts +++ b/apps/api/src/scripts/auction-redis-rehearsal.ts @@ -419,15 +419,15 @@ async function main(): Promise { auctionRedisService, ); const dummyTournamentCodeService = { - releaseFromMatch: async () => undefined, - reserveForMatch: async () => undefined, + releaseFromMatch: () => Promise.resolve(undefined), + reserveForMatch: () => Promise.resolve(undefined), }; const dummyTournamentResultService = { - cancelPolling: async () => undefined, - scheduleInitialPoll: async () => undefined, + cancelPolling: () => Promise.resolve(undefined), + scheduleInitialPoll: () => Promise.resolve(undefined), }; const dummySideEffectService = { - mirrorMatchSideEffectStatus: async () => true, + mirrorMatchSideEffectStatus: () => Promise.resolve(true), }; const dummyEventBus = { broadcastMatchSideEffect: () => undefined, @@ -436,13 +436,14 @@ async function main(): Promise { const auctionService = new AuctionService( connectionService, { - enrichRiotAccount: async () => ({ - account: null, - league: 'fresh', - masteries: 'fresh', - recentMatches: 'fresh', - summoner: 'fresh', - }), + enrichRiotAccount: () => + Promise.resolve({ + account: null, + league: 'fresh', + masteries: 'fresh', + recentMatches: 'fresh', + summoner: 'fresh', + }), } as never, dummyTournamentCodeService as never, dummyTournamentResultService as never, diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts index 0d7e7627..4e6a5060 100644 --- a/apps/api/src/seed.ts +++ b/apps/api/src/seed.ts @@ -9,7 +9,6 @@ import { ConnectionService } from './modules/global/database/connection.service' import type { ChampionMasteryEntry, MatchParticipant, - MatchTeam, Position, PositionPreference, RiotLane,