refactor: whitelist public match responses

This commit is contained in:
dahyeon committed 2026-07-12 19:28:04 +00:00
1 parent 874d785381
commit 28e9ac1529
4 files changed
+245 -37

No files matched your search

@@ -0,0 +1,96 @@
import { Types } from 'mongoose';
import { presentPublicMatch } from './match-public.presenter';
describe('presentPublicMatch', () => {
it('whitelists recruiting fields and excludes result/code internals', () => {
const response = presentPublicMatch({
_id: oid('1'),
communityId: oid('2'),
competitionId: oid('3'),
shortCode: '33NW',
title: '내전',
description: '설명',
mapId: 11,
status: 'in-progress',
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
maxParticipants: 20,
gameCount: 3,
gameMode: 'double-elimination',
roundRobinMaxRounds: undefined,
hostUserId: oid('4'),
participants: [
{
userId: oid('5'),
puuid: 'public-roster-snapshot',
gameName: '선수',
tagLine: 'KR1',
profileIconId: 1,
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'SUP', priority: 2 },
],
joinedAt: new Date('2026-07-01T00:00:00.000Z'),
excluded: false,
},
],
teams: [
{
teamIndex: 8,
name: '똥칼라파워',
captainUserId: oid('5'),
members: [{ userId: oid('5'), assignedPosition: 'MID', cost: 42 }],
},
],
prizes: ['상품'],
notices: ['안내'],
schedule: [{ time: '20:00', label: '시작' }],
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
tournamentCodeIds: [oid('6')],
tournamentCodes: [{ code: 'SECRET' }],
result: { winnerTeamIndex: 3, games: [], seriesResults: [] },
doubleElimination: { bracketMatches: [{ winnerTeamIndex: 3 }] },
resultPollState: { state: 'polling' },
legacyImportSource: { triggeringPuuid: 'secret' },
});
expect(response).toMatchObject({
_id: oid('1').toString(),
communityId: oid('2').toString(),
competitionId: oid('3').toString(),
title: '내전',
scheduledAt: '2026-07-12T10:00:00.000Z',
participants: [
expect.objectContaining({
userId: oid('5').toString(),
joinedAt: '2026-07-01T00:00:00.000Z',
}),
],
teams: [
{
teamIndex: 8,
name: '똥칼라파워',
captainUserId: oid('5').toString(),
members: [
{
userId: oid('5').toString(),
assignedPosition: 'MID',
cost: 42,
},
],
},
],
});
expect(response).not.toHaveProperty('tournamentCodeIds');
expect(response).not.toHaveProperty('tournamentCodes');
expect(response).not.toHaveProperty('result');
expect(response).not.toHaveProperty('doubleElimination');
expect(response).not.toHaveProperty('resultPollState');
expect(response).not.toHaveProperty('legacyImportSource');
expect(response.participants[0]).not.toHaveProperty('puuid');
});
});
function oid(suffix: string) {
return new Types.ObjectId(suffix.padStart(24, '0'));
}
@@ -0,0 +1,130 @@
import type {
MatchGameMode,
MatchStatus,
Position,
} from '../global/database/schema';
type IdLike = string | { toString(): string };
interface PublicMatchSource {
_id: IdLike;
communityId: IdLike;
competitionId?: IdLike;
shortCode?: string;
title: string;
description: string;
mapId: number;
status: MatchStatus;
scheduledAt: Date | string;
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
hostUserId?: IdLike;
participants: Array<{
userId: IdLike;
gameName?: string;
tagLine?: string;
profileIconId?: number;
tier?: unknown;
preferredPositions: Array<{ position: Position; priority: number }>;
joinedAt: Date | string;
excluded?: boolean;
[key: string]: unknown;
}>;
teams: Array<{
teamIndex: number;
name: string;
captainUserId?: IdLike;
members: Array<{
userId: IdLike;
assignedPosition: Position;
cost?: number;
[key: string]: unknown;
}>;
[key: string]: unknown;
}>;
prizes: string[];
notices: string[];
schedule: Array<{ time: string; label: string }>;
createdAt: Date | string;
updatedAt: Date | string;
[key: string]: unknown;
}
/** Public Match DTO. Competitive results and Tournament Codes live elsewhere. */
export function presentPublicMatch(
source: PublicMatchSource,
options: { joined?: boolean } = {},
) {
return {
_id: source._id.toString(),
communityId: source.communityId.toString(),
...(source.competitionId
? { competitionId: source.competitionId.toString() }
: {}),
...(source.shortCode ? { shortCode: source.shortCode } : {}),
title: source.title,
description: source.description,
mapId: source.mapId,
status: source.status,
scheduledAt: asIso(source.scheduledAt),
maxParticipants: source.maxParticipants,
gameCount: source.gameCount,
gameMode: source.gameMode,
...(source.roundRobinMaxRounds === undefined
? {}
: { roundRobinMaxRounds: source.roundRobinMaxRounds }),
...(source.hostUserId ? { hostUserId: source.hostUserId.toString() } : {}),
participants: source.participants.map((participant) => ({
userId: participant.userId.toString(),
...(participant.gameName ? { gameName: participant.gameName } : {}),
...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
...(participant.profileIconId === undefined
? {}
: { profileIconId: participant.profileIconId }),
...(participant.tier === undefined
? {}
: { tier: toWireValue(participant.tier) }),
preferredPositions: participant.preferredPositions.map((preference) => ({
position: preference.position,
priority: preference.priority,
})),
joinedAt: asIso(participant.joinedAt),
excluded: participant.excluded ?? false,
})),
teams: source.teams.map((team) => ({
teamIndex: team.teamIndex,
name: team.name,
...(team.captainUserId
? { captainUserId: team.captainUserId.toString() }
: {}),
members: team.members.map((member) => ({
userId: member.userId.toString(),
assignedPosition: member.assignedPosition,
...(member.cost === undefined ? {} : { cost: member.cost }),
})),
})),
prizes: [...source.prizes],
notices: [...source.notices],
schedule: source.schedule.map(({ time, label }) => ({ time, label })),
...(options.joined === undefined ? {} : { joined: options.joined }),
createdAt: asIso(source.createdAt),
updatedAt: asIso(source.updatedAt),
};
}
function asIso(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
function toWireValue(value: unknown): unknown {
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toWireValue);
if (typeof value === 'object' && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, toWireValue(child)]),
);
}
return value;
}
+12 -17
View File
@@ -18,11 +18,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator'; import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard'; import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { import type { MatchStatus, UserDocument } from '../global/database/schema';
MatchDocument,
MatchStatus,
UserDocument,
} from '../global/database/schema';
import { import {
AddParticipantDto, AddParticipantDto,
ApplyDoubleEliminationWalkoverDto, ApplyDoubleEliminationWalkoverDto,
@@ -95,11 +91,19 @@ export class MatchController {
scheduledTo: this.toOptionalDate(scheduledTo), scheduledTo: this.toOptionalDate(scheduledTo),
sort, sort,
}); });
if (!currentUser) return result;
const myId = currentUser._id;
return { return {
...result, ...result,
matches: result.matches.map((m) => this.annotateJoined(m, myId)), matches: result.matches.map((match) =>
this.matchService.serialize(match, {
...(currentUser
? {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
}
: {}),
}),
),
}; };
} }
@@ -344,15 +348,6 @@ export class MatchController {
return new mongoose.Types.ObjectId(bodyUserId); return new mongoose.Types.ObjectId(bodyUserId);
} }
private annotateJoined(
match: MatchDocument,
userId: mongoose.Types.ObjectId,
) {
const obj = match.toObject();
const joined = match.participants.some((p) => p.userId.equals(userId));
return { ...obj, joined };
}
private assertSameCommunity( private assertSameCommunity(
user: UserDocument, user: UserDocument,
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
+7 -20
View File
@@ -27,6 +27,7 @@ import {
} from '../global/database/schema'; } from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service'; import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import { presentPublicMatch } from './match-public.presenter';
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const MATCH_SHORT_CODE_LENGTH = 4; const MATCH_SHORT_CODE_LENGTH = 4;
@@ -218,30 +219,16 @@ export class MatchService {
return match; return match;
} }
public async serialize(match: MatchDocument) { public serialize(match: MatchDocument, options: { joined?: boolean } = {}) {
const obj = match.toObject(); const obj = match.toObject();
if (obj.result?.games) { return presentPublicMatch(
obj.result.games = [...obj.result.games].sort( {
(left, right) => left.gameNumber - right.gameNumber,
);
if (!obj.result.seriesResults?.length) {
obj.result.seriesResults = this.buildSeriesResults(obj.result.games);
}
}
return {
...obj, ...obj,
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
gameMode: match.gameMode ?? 'pair', gameMode: match.gameMode ?? 'pair',
participants: (obj.participants ?? []).map((participant) => ({ } as never,
...participant, options,
excluded: participant.excluded ?? false, );
})),
teams: (obj.teams ?? []).map((team) => ({
...team,
})),
gameSchedule: obj.gameSchedule ?? [],
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
};
} }
public async update(params: UpdateMatchParams): Promise<MatchDocument> { public async update(params: UpdateMatchParams): Promise<MatchDocument> {