This commit is contained in:
dahyeon committed 2026-04-25 11:49:21 -07:00
1 parent 5af2c80cd1
commit f7ee34da4f
78 files changed
+9016 -150

No files matched your search

+113 -7
View File
@@ -9,8 +9,19 @@ import {
WebSocketServer,
} from '@nestjs/websockets';
import mongoose from 'mongoose';
import type { JWTPayload } from 'jose';
import { Namespace, Socket } from 'socket.io';
import type { AuctionDocument, Position, TeamSide } from '../global/database/schema';
import { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service';
import { ConnectionService } from '../global/database/connection.service';
import type {
AuctionDocument,
IdentityDocument,
Position,
TeamSide,
UserDocument,
} from '../global/database/schema';
import { AuctionService } from './auction.service';
interface JoinAuctionPayload {
@@ -32,7 +43,7 @@ interface SoldPayload {
cors: {
origin: true,
credentials: true,
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'],
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
},
})
export class AuctionGateway
@@ -44,10 +55,26 @@ export class AuctionGateway
private readonly logger = new Logger(AuctionGateway.name);
private readonly roomTimers = new Map<string, NodeJS.Timeout>();
constructor(private readonly auctionService: AuctionService) {}
constructor(
private readonly auctionService: AuctionService,
private readonly authService: AuthService,
private readonly jwtService: JwtService,
private readonly identityService: IdentityService,
private readonly connectionService: ConnectionService,
) {}
public handleConnection(socket: Socket) {
this.logger.debug(`Auction client connected: ${socket.id}`);
public async handleConnection(socket: Socket) {
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
}`,
);
socket.disconnect(true);
}
}
public handleDisconnect(socket: Socket) {
@@ -70,6 +97,7 @@ export class AuctionGateway
socket.data.matchId = payload.matchId;
try {
await this.resolveSocketUserForMatch(socket, payload.matchId);
const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId),
);
@@ -165,7 +193,9 @@ export class AuctionGateway
}
private getSocketMatchId(socket: Socket): string | undefined {
return typeof socket.data.matchId === 'string' ? socket.data.matchId : undefined;
return typeof socket.data.matchId === 'string'
? socket.data.matchId
: undefined;
}
private resolveBidderUserId(
@@ -173,7 +203,9 @@ export class AuctionGateway
payloadBidderUserId?: string,
): mongoose.Types.ObjectId | undefined {
const candidate =
payloadBidderUserId ?? this.readHandshakeUserId(socket);
payloadBidderUserId ??
(socket.data.user as UserDocument | undefined)?._id.toString() ??
this.readHandshakeUserId(socket);
if (!candidate || !mongoose.isValidObjectId(candidate)) {
return undefined;
}
@@ -188,6 +220,80 @@ export class AuctionGateway
return Array.isArray(header) ? header[0] : header;
}
private async authenticateSocket(socket: Socket): Promise<void> {
const fallback = await this.authService.resolveDevUserById(
this.readHandshakeUserId(socket),
);
if (fallback) {
socket.data.user = fallback.user;
socket.data.identity = fallback.identity;
return;
}
const token = this.readHandshakeToken(socket);
if (!token) {
throw new Error('Missing auction socket token.');
}
const { payload } = await this.jwtService.verify(
token,
'MICROSOFT_ENTRAID',
);
socket.data.identity = await this.identityService.findOrCreateByOid({
entraOid: this.requireStringClaim(payload, 'oid'),
tenantId: this.stringClaim(payload.tid),
email:
this.stringClaim(payload.preferred_username) ??
this.stringClaim(payload.email),
displayName: this.stringClaim(payload.name),
});
}
private readHandshakeToken(socket: Socket): string | undefined {
const authToken = socket.handshake.auth.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;
if (authorization?.startsWith('Bearer ')) {
return authorization.slice('Bearer '.length).trim();
}
return undefined;
}
private async resolveSocketUserForMatch(
socket: Socket,
matchId: string,
): Promise<void> {
if (socket.data.user || !socket.data.identity) return;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({
communityId: 1,
});
if (!match) return;
const UserModel = await this.connectionService.getModel('user');
socket.data.user = await UserModel.findOne({
communityId: match.communityId,
identityId: (socket.data.identity as IdentityDocument)._id,
}).exec();
}
private requireStringClaim(payload: JWTPayload, key: string): string {
const value = payload[key];
if (typeof value !== 'string' || value.length === 0) {
throw new Error(`Token is missing ${key} claim.`);
}
return value;
}
private stringClaim(value: unknown): string | undefined {
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
private broadcastState(matchId: string, auction: AuctionDocument) {
this.server.to(matchId).emit('state', this.serializeAuction(auction));
this.syncRoomTimer(matchId, auction);