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

+481
View File
@@ -0,0 +1,481 @@
# Dakao NATS Command API
dakao는 NATS를 통해 외부 시스템으로부터 command를 받아 LOCO 세션에 반영할 수 있다.
현재 구현 기준으로 지원하는 command는 아래 2종이다.
- `chat.send-text`
기존 API. `text`와 `extra`를 그대로 받아 전송한다.
점진적으로 deprecated 예정.
- `chat.send-message`
신규 권장 API. `segments` 기반으로 텍스트, 멘션, 카카오톡 이모티콘을 조합해서 전송한다.
builder를 거치면서 semantic validation까지 수행한다.
## 개요
### 기본 subject
| 용도 | 기본 subject | 비고 |
| ------------------ | ------------------------------------ | --------------- |
| 레거시 텍스트 전송 | `dakao.command.chat.send-text.v1` | deprecated 예정 |
| 신규 메시지 전송 | `dakao.command.chat.send-message.v1` | 권장 |
### 관련 환경변수
| 키 | 의미 |
| ---------------------------------------------- | ------------------------------- |
| `DAKAO_NATS_COMMANDS_ENABLED` | `1`이면 command consumer 활성화 |
| `DAKAO_NATS_COMMAND_CHAT_SEND_TEXT_SUBJECT` | 레거시 subject override |
| `DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT` | 신규 subject override |
### 전송 포맷
- NATS payload는 JSON object여야 한다.
- 내부 구현은 `JSON.stringify(...)`로 publish하고, subscribe 시 `JSON.parse(...)`로 역직렬화한다.
- 응답은 NATS의 transport-level reply가 아니라, command object 내부의 `replySubject` 필드를 사용해 별도 publish된다.
### subject와 `type`의 관계
운영 규약상 아래처럼 맞춰서 보내는 것을 권장한다.
- `dakao.command.chat.send-text.v1` 에는 `type: "chat.send-text"`
- `dakao.command.chat.send-message.v1` 에는 `type: "chat.send-message"`
현재 구현은 두 subject를 모두 구독한 뒤 `type`으로 실제 처리를 분기한다.
즉 subject와 type이 어긋나도 처리될 수 있지만, 운영 혼선을 막기 위해 반드시 맞춰서 보내는 것을 권장한다.
## 공통 Envelope
모든 command는 아래 envelope를 사용한다.
```json
{
"schema": "dakao.command.v1",
"id": "cmd-001",
"type": "chat.send-message",
"source": "my-service",
"correlationId": "trace-001",
"replySubject": "dakao.result.my-service",
"payload": {}
}
```
### 공통 필드
| 필드 | 타입 | 필수 | 설명 |
| --------------- | ------ | ---- | -------------------------------- |
| `schema` | string | Y | 현재는 반드시 `dakao.command.v1` |
| `id` | string | Y | command 고유 ID |
| `type` | string | Y | command 종류 |
| `source` | string | Y | producer 식별자 |
| `correlationId` | string | N | 추적용 상관관계 ID |
| `replySubject` | string | N | 결과를 publish할 subject |
| `payload` | object | Y | command 본문 |
### 공통 검증
- 문자열 필드인 `id`, `type`, `source`, `correlationId`, `replySubject`는 trim 후 빈 문자열이면 거부된다.
- 최상위 object와 payload는 정의되지 않은 필드를 허용하지 않는다.
- `replySubject`가 없으면 처리 결과는 publish되지 않는다.
## Command: `chat.send-text`
### 상태
- 레거시 API
- 기존 producer 호환성을 위해 유지 중
- `text`와 `extra`를 그대로 전달하므로, 멘션/이모티콘 semantic validation은 수행하지 않는다
### 권장 subject
```text
dakao.command.chat.send-text.v1
```
### Payload
```json
{
"chatroomId": "123456789012345678",
"text": "hello",
"attachment": {
"example": true
},
"extra": "{}"
}
```
| 필드 | 타입 | 필수 | 설명 |
| ------------ | ---------------- | ---- | ------------------------------------------------------- |
| `chatroomId` | string | Y | 채팅방 ID. 실운영에서는 decimal string 사용 권장 |
| `text` | string | Y | 보낼 메시지 본문 |
| `attachment` | string or object | N | 첨부 payload. object면 전송 직전에 JSON string으로 변환 |
| `extra` | string | N | LOCO `WRITE.extra` raw 값 |
### 동작
- 내부적으로 `client.sendMessage(chatroomId, text, { attachment, extra })` 로 전송한다.
- `extra`를 생략하면 최종 LOCO 전송 시 기본값 `"{}"` 가 사용된다.
- 이 API는 `extra` 구조를 검증하지 않는다.
### 예시
```json
{
"schema": "dakao.command.v1",
"id": "cmd-text-001",
"type": "chat.send-text",
"source": "admin-panel",
"replySubject": "dakao.result.admin-panel",
"payload": {
"chatroomId": "123456789012345678",
"text": "plain text message",
"extra": "{}"
}
}
```
## Command: `chat.send-message`
### 상태
- 신규 권장 API
- 텍스트, 멘션, 카카오톡 이모티콘을 조합해서 전송할 수 있다
- `buildLocoMessage(...)` 를 통해 최종 `text`와 `extra`를 생성한다
- Joi schema validation 이후 builder semantic validation이 한 번 더 수행된다
### 권장 subject
```text
dakao.command.chat.send-message.v1
```
### Payload
```json
{
"chatroomId": "123456789012345678",
"segments": [
{ "kind": "text", "text": "안녕하세요 " },
{
"kind": "mention",
"userId": "6215844374579825921",
"displayText": "날으는꼴뚜기/95/여/D"
},
{ "kind": "text", "text": " " },
{ "kind": "emoticon", "id": "1200281_004", "altText": "플라워" }
],
"attachment": {
"example": true
},
"type": 1,
"noSeen": false,
"scope": 1,
"silence": false
}
```
| 필드 | 타입 | 필수 | 설명 |
| ------------ | ---------------- | ---- | ------------------------------------------------------- |
| `chatroomId` | string | Y | 채팅방 ID. 실운영에서는 decimal string 사용 권장 |
| `segments` | array | Y | 메시지 세그먼트 배열. 최소 1개 이상 |
| `attachment` | string or object | N | 첨부 payload. object면 전송 직전에 JSON string으로 변환 |
| `type` | integer | N | LOCO `WRITE.type`. 기본값 `1` |
| `noSeen` | boolean | N | LOCO `WRITE.noSeen`. 기본값 `false` |
| `scope` | integer | N | LOCO `WRITE.scope`. 기본값 `1` |
| `silence` | boolean | N | LOCO `WRITE.silence`. 기본값 `false` |
### Segment 종류
#### `text`
```json
{ "kind": "text", "text": "안녕하세요 " }
```
| 필드 | 타입 | 필수 | 설명 |
| ------ | ------ | ---- | -------------------------------------- |
| `kind` | string | Y | 반드시 `text` |
| `text` | string | Y | 일반 텍스트. 빈 문자열은 허용되지 않음 |
#### `mention`
```json
{
"kind": "mention",
"userId": "6215844374579825921",
"displayText": "날으는꼴뚜기/95/여/D"
}
```
| 필드 | 타입 | 필수 | 설명 |
| ------------- | ------ | ---- | --------------------------------------------------------- |
| `kind` | string | Y | 반드시 `mention` |
| `userId` | string | Y | 양의 정수 문자열 권장. int64 손실 방지를 위해 문자열 사용 |
| `displayText` | string | Y | 화면에 표시될 이름. builder가 앞의 `@`를 자동 정리 |
멘션은 최종 메시지에서 아래처럼 렌더링된다.
```text
@{displayText}
```
예를 들어 `displayText: "홍길동"` 이면 `@홍길동` 으로 전송된다.
`displayText`를 `@홍길동`처럼 보내도 builder가 앞의 `@` 하나를 제거한 뒤 다시 렌더링한다.
#### `emoticon`
```json
{
"kind": "emoticon",
"id": "1200281_004",
"altText": "플라워"
}
```
| 필드 | 타입 | 필수 | 설명 |
| --------- | ------ | ---- | --------------------------------------- |
| `kind` | string | Y | 반드시 `emoticon` |
| `id` | string | Y | 카카오톡 이모티콘 item ID |
| `altText` | string | Y | 대체 텍스트. builder가 괄호를 자동 정리 |
이모티콘은 최종 메시지에서 아래처럼 렌더링된다.
```text
({altText})
```
예를 들어 `altText: "플라워"` 이면 `(플라워)` 로 전송된다.
`altText`를 `(플라워)`처럼 보내도 builder가 바깥 괄호를 제거한 뒤 다시 렌더링한다.
### Builder semantic validation
`chat.send-message`는 schema validation 외에 아래 규칙도 검사한다.
#### 공통
- 최종적으로 만들어진 메시지 전체 텍스트는 비어 있으면 안 된다
- `segments`가 모두 비어 있거나 렌더링 결과가 빈 문자열이면 거부된다
#### mention 규칙
- `userId`는 양의 정수여야 한다
- producer에서는 숫자 대신 문자열 사용을 권장한다
- `displayText`는 비어 있으면 안 된다
- 같은 `userId`를 여러 번 멘션하면 `extra.mentions[].at` 배열로 합쳐진다
- 같은 `userId`를 서로 다른 길이의 `displayText`로 섞어 보내면 거부된다
#### emoticon 규칙
- `id`는 trim 후 비어 있으면 안 된다
- `altText`는 trim 후 비어 있으면 안 된다
- `altText` 내부에는 `@`, `(`, `)` 문자가 들어가면 안 된다
- 같은 `(id, 렌더링 길이)` 조합의 이모티콘은 `extra.emojis.items[].at` 배열로 합쳐진다
#### `extra` 생성 규칙
producer가 `extra`를 직접 만들지 않는다.
builder가 최종 텍스트를 기준으로 아래 구조를 자동 생성한다.
```json
{
"mentions": [
{
"user_id": 6215844374579825921,
"at": [1],
"len": 13
}
],
"emojis": {
"total_item": 1,
"total_len": 5,
"items": [
{
"id": "1200281_004",
"len": 5,
"at": [1]
}
]
}
}
```
주의:
- `mentions[].at` 는 메시지 안의 `@` anchor 순번이다
- `emojis.items[].at` 는 메시지 안의 `(` anchor 순번이다
- `len` 은 렌더링된 문자열 길이 기준이다
- `total_item` 은 이모티콘 총 출현 횟수다
- `total_len` 은 각 이모티콘 렌더링 길이의 합이다
### 예시: 추천 전송
```json
{
"schema": "dakao.command.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"source": "admin-panel",
"correlationId": "trace-20260417-001",
"replySubject": "dakao.result.admin-panel",
"payload": {
"chatroomId": "123456789012345678",
"segments": [
{ "kind": "text", "text": "😄 " },
{
"kind": "mention",
"userId": "6215844374579825921",
"displayText": "날으는꼴뚜기/95/여/D"
},
{ "kind": "text", "text": " " },
{ "kind": "emoticon", "id": "1200281_004", "altText": "플라워" },
{ "kind": "emoticon", "id": "1200281_003", "altText": "네잎클로버" }
],
"type": 1,
"noSeen": false,
"scope": 1,
"silence": false
}
}
```
위 payload는 내부적으로 대략 아래 LOCO 메시지로 변환된다.
```json
{
"text": "😄 @날으는꼴뚜기/95/여/D (플라워)(네잎클로버)",
"extra": "{\"mentions\":[{\"user_id\":6215844374579825921,\"at\":[1],\"len\":13}],\"emojis\":{\"total_item\":2,\"total_len\":12,\"items\":[{\"id\":\"1200281_004\",\"len\":5,\"at\":[1]},{\"id\":\"1200281_003\",\"len\":7,\"at\":[2]}]}}"
}
```
## Result API
응답이 필요한 경우 producer는 command에 `replySubject`를 포함해야 한다.
consumer는 처리 후 `replySubject`로 결과 object를 publish한다.
### 공통 Result envelope
```json
{
"schema": "dakao.result.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"status": "succeeded",
"handledAt": "2026-04-17T12:34:56.789Z",
"correlationId": "trace-20260417-001",
"result": {}
}
```
### 공통 필드
| 필드 | 타입 | 설명 |
| --------------- | ------ | --------------------------------------- |
| `schema` | string | 현재는 반드시 `dakao.result.v1` |
| `id` | string | 원본 command ID |
| `type` | string | 원본 command type |
| `status` | string | `succeeded` 또는 `failed` |
| `handledAt` | string | ISO-8601 timestamp |
| `correlationId` | string | 원본 correlationId가 있으면 그대로 전달 |
| `result` | object | 성공 시 포함 |
| `error` | object | 실패 시 포함 |
### Success result
`chat.send-text`와 `chat.send-message`의 성공 응답 구조는 동일하다.
```json
{
"schema": "dakao.result.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"status": "succeeded",
"handledAt": "2026-04-17T12:34:56.789Z",
"correlationId": "trace-20260417-001",
"result": {
"chatroomId": "123456789012345678",
"messageLength": 31,
"hasAttachment": true
}
}
```
| 필드 | 타입 | 설명 |
| --------------- | ------- | ---------------------------- |
| `chatroomId` | string | 대상 채팅방 ID |
| `messageLength` | number | 실제 전송된 최종 메시지 길이 |
| `hasAttachment` | boolean | attachment가 있으면 포함 |
### Failure result
```json
{
"schema": "dakao.result.v1",
"id": "cmd-msg-001",
"type": "chat.send-message",
"status": "failed",
"handledAt": "2026-04-17T12:34:56.789Z",
"correlationId": "trace-20260417-001",
"error": {
"code": "invalid_command",
"message": "emoticon.altText must not contain '@', '(' or ')': \"(bad@text)\"",
"retryable": false
}
}
```
| 필드 | 타입 | 설명 |
| ----------- | ------- | ------------------------------- |
| `code` | string | 오류 코드 |
| `message` | string | 사람이 읽을 수 있는 오류 메시지 |
| `retryable` | boolean | 재시도 권장 여부 |
### 현재 사용되는 오류 코드
| 코드 | retryable | 의미 |
| -------------------------- | --------- | ----------------------------------------------- |
| `invalid_command` | `false` | envelope/payload/schema/builder validation 실패 |
| `command_execution_failed` | `true` | LOCO 전송 등 실행 단계 실패 |
## 응답 publish 조건
아래 조건이 모두 충족될 때만 실패 응답을 publish할 수 있다.
- `replySubject` 존재
- `id` 존재
- `type` 존재
따라서 malformed payload를 보내더라도 `replySubject`가 없으면 실패 응답은 발행되지 않는다.
producer가 처리 결과를 반드시 받아야 한다면 `replySubject`를 항상 넣는 것을 권장한다.
## 운영 권장사항
### 새 producer는 `chat.send-message`만 사용
권장 이유:
- 멘션과 이모티콘을 구조적으로 표현할 수 있다
- `extra`를 producer가 직접 조립하지 않아도 된다
- semantic validation이 추가로 수행된다
- 향후 레거시 `chat.send-text` 제거 시 마이그레이션 부담이 적다
### `chatroomId`와 `userId`는 문자열 사용
- `userId`는 int64 범위일 수 있으므로 JSON number 대신 string 사용을 권장한다
- `chatroomId`도 실운영에서는 decimal string으로 통일하는 것이 안전하다
### `replySubject`는 항상 지정
- 성공/실패를 추적하려면 `replySubject`를 항상 넣는 것이 좋다
- `correlationId`도 함께 넣어두면 producer 로그와 결과 로그를 쉽게 연결할 수 있다
### `send-text` 사용 시 주의
- `extra` 구조를 잘못 만들면 consumer 단계에서는 걸러지지 않는다
- 멘션, 유니코드 이모지, 카카오톡 이모티콘 혼합 메시지는 `send-message` 사용을 권장한다
## 요약
- 레거시: `dakao.command.chat.send-text.v1` + `type: "chat.send-text"`
- 권장: `dakao.command.chat.send-message.v1` + `type: "chat.send-message"`
- 결과 스키마는 공통으로 `dakao.result.v1`
- 신규 API는 `segments`를 받아 builder 기반으로 `text`와 `extra`를 안전하게 생성한다
+586
View File
@@ -0,0 +1,586 @@
# Riot 캐싱 Phase 2 플랜
> **대상**: codex가 이어서 진행 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-25
> **선행 작업**: dakao NATS 통합, RiotAccountEnrichmentService(force=true 동기 호출, summoner/league/mastery v4) 1차 구현 완료
---
## 1. Context
dakao 카카오톡 명령(`!내전 신청 ...`) 이 들어오면 라이엇 ID를 검증·등록하고, 동시에 summoner v4 / league v4 / champion-mastery v4 데이터를 가져와 `User.riotAccounts[*]` 임베딩에 캐싱하는 1차 구현이 끝난 상태입니다.
이 플랜은 그 위에 다음을 더합니다.
1. **community별 default platform 지정** + region/by-puuid 기반 자동 보정
2. **champion-mastery top 10** 으로 좁히고 스키마를 Riot DTO 그대로
3. **league 변동 시 tierHistory 자동 누적**
4. **사용자 수동 갱신 엔드포인트 + 한가한 시간대 스케줄러**
5. **신선도 표시(API 응답에 `*FetchedAt` 노출)**
6. **무거운 필드(`championRecords`, `tiers`)는 list/find 쿼리에서 projection 으로 잘라내기**
7. **동일 puuid 동시 enrichment dedup**
8. **v4 서비스 응답 파서 단위 테스트**
비목표:
- Rate limit 글로벌 throttle (token bucket / Redis) — Phase 3
- OpenSearch / Slack 운영 알림 — Phase 3
- 백오피스 UI — 별도 트랙
---
## 2. 결정된 설계 사항
### 2.1 Riot Schema 우선 (Data Dragon 호환)
기존 `ChampionMasteryEntry`, `TierInfo`, `TierHistoryEntry` 를 Riot v4 응답 그대로 매칭하도록 재정의합니다.
**현재 (수정 전)**
```ts
export interface ChampionMasteryEntry {
championId: string; // ← Riot 은 number
championName?: string; // ← Riot 응답에 없음
level: number; // ← championLevel
points: number; // ← championPoints
}
export interface TierInfo {
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: Date;
}
```
**목표 (수정 후)**
```ts
// Riot Champion-Mastery-V4 DTO 그대로
export interface ChampionMasteryEntry {
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
lastPlayTime?: number;
championPointsSinceLastLevel?: number;
championPointsUntilNextLevel?: number;
markRequiredForNextLevel?: number;
tokensEarned?: number;
championSeasonMilestone?: number;
milestoneGrades?: string[];
nextSeasonMilestone?: Record<string, unknown>;
}
// Riot League-V4 entries DTO + 우리 측 fetchedAt
export interface TierInfo {
leagueId: string;
queueType: string;
tier: string;
rank: string;
puuid: string;
leaguePoints: number;
wins: number;
losses: number;
veteran?: boolean;
inactive?: boolean;
freshBlood?: boolean;
hotStreak?: boolean;
miniSeries?: Record<string, unknown>;
fetchedAt: Date;
}
// 시점별 tier 스냅샷
export interface TierHistoryEntry {
queueType: string;
tier: string;
rank?: string;
leaguePoints?: number;
wins?: number;
losses?: number;
recordedAt: Date;
// 시즌 단위 통계 / peak (옵션)
season?: string;
peakTier?: string;
peakRank?: string;
}
```
`championRecords` 는 챔피언별 *집계 데이터(향후 매치 분석)* 용으로 유지하되, **mastery 원본은 더 이상 `championRecords` 에 중복 저장하지 않습니다.** mastery 자체가 이제 Riot DTO 형태이기 때문입니다.
기존 schema 의 `RiotAccount.championRecords` 와 `RiotAccount.championRecordsFetchedAt` 는 그대로 둡니다 (다른 용도).
### 2.2 community 별 default platform
```ts
export interface Community extends MongooseTimestamps {
// ...
riotPlatform?: RiotPlatformRoute; // default 'kr'
riotRegion?: RiotRegionalRoute; // default 'asia'
}
```
- platform 기본 `kr`, region 기본 `asia` 는 코드 상 fallback. 명시 지정 시 community 설정값 우선.
- enrichment / lookup 시 community 의 platform 을 사용.
- 추가로 puuid 만 있는 상황(예: 다른 community 매치 import)에서는 region/by-puuid 로 platform 보정.
### 2.3 region/by-puuid 자동 보정
> `GET https://{regional}.api.riotgames.com/riot/account/v1/region/by-game/lol/by-puuid/{puuid}` → `{ puuid, game, region }`
- 응답의 `region` 이 platform 코드 (`kr`, `na1`, …)
- 사용 시점: community 의 platform 과 puuid 의 실제 platform 이 다른지 의심될 때 (예: 처음 등록 시, summoner v4 404 발생 시)
- 새 서비스: `RiotAccountService.getRegionByPuuid(puuid, options)`
- enrichment fallback 정책: summoner v4 가 404 면 region/by-puuid 호출해서 platform 보정 후 한 번 더 시도, 그래도 실패면 failed 처리
### 2.4 mastery top 10
- 엔드포인트 변경: `/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top?count=10`
- 저장 상한 10. `MASTERY_LIMIT = 10`.
- `RiotChampionMasteryService.getTopByPuuid(puuid, { platform, count })` 신규 메서드. 기존 `getByPuuid` 는 leftover/내부용으로 유지하거나 삭제 (사용처 확인 후 결정).
### 2.5 tierHistory 누적 규칙
- enrichment 가 league entries 를 갱신할 때, **queueType 별로 가장 최근 history entry 와 비교**하여 다음 중 하나라도 다르면 history 에 push:
- `tier`, `rank`
- `leaguePoints` 변화 (옵션 — 너무 잦으면 noise. 1차에선 tier/rank 변화만 추적)
- 1차 결정: **tier 또는 rank 가 변하면 push**. lp 변화는 history 에 안 남김.
- 신규 등록 시(history 비어있음)는 첫 league fetch 결과를 그대로 history 에 1건 push.
- `recordedAt = new Date()`.
- queueType 외 다른 분류는 도입하지 않음. season 추적은 별도 작업.
### 2.6 신선도 노출 (`*FetchedAt`)
API 응답(`GET /users/:id`, `/me`, `/communities/:id/matches/:id` 등)에 RiotAccount 가 포함될 때 다음 필드를 함께 노출:
- `tiers[*].fetchedAt`
- `championMasteriesFetchedAt`
- `revisionDate` (summoner)
- `championRecordsFetchedAt`
스키마 상 이미 존재하므로 변경 불필요. 단, **list 쿼리에서는 무거운 raw 필드(`championRecords`, `championMasteries[*].milestoneGrades` 등) 는 projection 으로 제외**. (2.8 참조)
### 2.7 수동 갱신 + 스케줄러
**HTTP 엔드포인트**
```
POST /users/me/riot-accounts/:puuid/refresh
Body: { force?: boolean, platform?: RiotPlatformRoute }
Auth: 본인 또는 admin
Response: EnrichResult
```
- 본인 또는 community admin 이상만 허용.
- `force = true` 면 TTL 무시.
- platform 지정 시 community default 무시.
**스케줄러**
- NestJS `@nestjs/schedule` (cron) 도입.
- 작업명: `RiotAccountRefreshScheduler`
- 실행 주기: 매일 KST 04:00 ~ 06:00 사이에 chunked 실행
- 대상 선정:
- `tiers[*].fetchedAt` 가 24h 초과 또는 비어있는 RiotAccount
- 한 batch 당 최대 200건, batch 간 5초 간격
- enrichment 호출 시 `force = false` (TTL 기반)
- per-batch try/catch + 실패 카운터 로그
- `@Cron('0 4 * * *')` 단일 트리거로 시작 → 추후 batch 분산은 Phase 3 에서 보강
### 2.8 list/find projection 정책
`apps/api/src/modules/global/database/projection.ts` 신설하여 공통 projection 상수를 모음.
```ts
// 매치 리스트, /me 등에서 RiotAccount 의 무거운 필드를 잘라낸다
export const RIOT_ACCOUNT_LIGHT_PROJECTION = {
'riotAccounts.championRecords': 0,
'riotAccounts.championRecordsFetchedAt': 0,
// championMasteries 자체는 살리되 milestoneGrades 등 무거운 nested 는 protected list 에서만 fetch
} as const;
```
- 적용 대상: `MatchService.list`, `UserController.list`, `MatchController.listMatches` 등
- 단건 조회(`getById`, `/me`) 는 풀 데이터 포함
### 2.9 동일 puuid 동시 enrichment dedup
**채택 방식**: in-memory `Map<puuid, Promise<EnrichResult>>` (단일 인스턴스 dedup)
```ts
private inFlight = new Map<string, Promise<EnrichResult>>();
public enrichRiotAccount(params): Promise<EnrichResult> {
const key = params.puuid;
const existing = this.inFlight.get(key);
if (existing) return existing;
const promise = this.doEnrich(params).finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
}
```
이유:
- 카카오 신청 빈도가 낮아 분산 락까지 필요 없음.
- 동일 인스턴스 내 race(동시 신청)만 막아도 90%의 중복 호출 절감.
- 멀티 인스턴스 환경 dedup 은 Phase 3 (Redis SET NX) 에서.
**대안 비교 (참고)**
| 방식 | 장점 | 단점 |
| --- | --- | --- |
| in-memory Map | 의존성 없음, 빠름 | 멀티 인스턴스 미지원 |
| Mongo `findOneAndUpdate` 락 | 의존성 없음, 분산 가능 | 실패 시 락 만료 처리 복잡, 추가 필드 필요 |
| Redis SET NX EX | 분산 / TTL 자연스러움 | Redis 인프라 필요 |
### 2.10 v4 파서 단위 테스트
- `riot-summoner.service.spec.ts`
- `riot-league.service.spec.ts`
- `riot-champion-mastery.service.spec.ts`
각각 정상 응답 / 누락 필드 거부 / 빈 배열 / 타입 불일치 거부 케이스.
---
## 3. 실행 단계 (codex 진행 순서)
작업 단위는 PR 단위로 쪼갤 수 있도록 분리되어 있습니다. 단계 간 의존성이 있는 부분은 명시.
### Step 1. 스키마 재정의 (TierInfo / ChampionMasteryEntry / TierHistoryEntry)
**파일**: `apps/api/src/modules/global/database/schema.ts`
1. `TierInfo`, `TierHistoryEntry`, `ChampionMasteryEntry` 인터페이스 위 2.1 정의로 교체.
2. `TierInfoSubSchema`, `TierHistoryEntrySubSchema`, `ChampionMasteryEntrySubSchema` 도 동일하게 갱신.
- `championId`: `Number` 로 변경
- `championLevel`, `championPoints`: 새 필드명
- `milestoneGrades`: `[String]` (default `undefined`)
- `nextSeasonMilestone`: `Schema.Types.Mixed`
- `TierInfo` 에 `leagueId`, `puuid`, `veteran`, `inactive`, `freshBlood`, `hotStreak`, `miniSeries(Mixed)` 추가
- `TierHistoryEntry` 에 `recordedAt: { type: Date, required: true }`, `leaguePoints/wins/losses` optional
3. `Community` 에 `riotPlatform`, `riotRegion` 추가:
```ts
riotPlatform: { type: String },
riotRegion: { type: String },
```
4. `MatchParticipantSubSchema.tier` 는 새 `TierInfo` 모양을 자동으로 따라감 — 추가 변경 없음.
**Risk**: 기존 데이터가 있다면 마이그레이션 필요. 현재 dev 환경 seed 만 사용한다면 seed 재실행으로 충분. `apps/api/src/seed.ts` 도 새 필드명에 맞춰 갱신.
**테스트**: 타입체크 통과 확인.
### Step 2. RiotChampionMasteryService → top 엔드포인트로 변경
**파일**: `apps/api/src/modules/riot/riot-champion-mastery.service.ts`
1. 메서드 시그니처 변경 또는 신규:
```ts
public async getTopByPuuid(
puuid: string,
options: { platform?: RiotPlatformRoute; count?: number; signal?: AbortSignal } = {},
): Promise<RiotChampionMasteryDto[]>
```
엔드포인트: `/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}/top`
query: `count` (default 10, max 10)
2. 기존 `getByPuuid` 사용처 grep 후 모두 `getTopByPuuid` 로 교체.
3. `riot-account-enrichment.service.ts` 에서 `MASTERY_LIMIT = 10` 으로 변경.
### Step 3. region/by-puuid 서비스 + 자동 보정
**파일**: `apps/api/src/modules/riot/riot-account.service.ts`
```ts
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<{ puuid: string; game: string; region: RiotPlatformRoute }> {
return this.riotClientService.get(
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
{ region: options.region ?? 'asia', signal: options.signal },
parseRegionByPuuid,
);
}
```
`riot.types.ts` 에 응답 타입 추가:
```ts
export interface RiotAccountRegionDto {
puuid: string;
game: 'lol' | string;
region: RiotPlatformRoute;
}
```
**enrichment 보정 로직**:
`RiotAccountEnrichmentService.fetchSummonerSafe` 에서 `RiotApiError && status === 404` 발생 시:
1. `getRegionByPuuid` 호출
2. 받은 platform 으로 다시 summoner 호출
3. 그래도 실패면 `failed` 처리
4. 새 platform 이 community default 와 다르면 로그(`logger.warn`) — 향후 schema 에 puuid 별 platform 저장 여부는 별도 결정
### Step 4. enrichment dedup + force/TTL 흐름 정리
**파일**: `apps/api/src/modules/riot/riot-account-enrichment.service.ts`
1. 클래스에 `private inFlight = new Map<string, Promise<EnrichResult>>()` 추가.
2. `enrichRiotAccount` 진입부에서 dedup 체크. key 는 `${userId}:${puuid}` (user 다른데 puuid 같은 케이스도 있으니 user 포함이 안전).
3. `applyMasteries` 에서 `championRecords` 채우는 코드 제거 (2.1 결정).
4. `applyLeagueEntries` 호출 직전 `tierHistory` 갱신 헬퍼 호출:
```ts
private appendTierHistoryIfChanged(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
): void {
const now = new Date();
for (const e of entries) {
const last = [...account.tierHistory]
.reverse()
.find((h) => h.queueType === e.queueType);
const changed =
!last ||
last.tier !== e.tier ||
(last.rank ?? '') !== (e.rank ?? '');
if (changed) {
account.tierHistory.push({
queueType: e.queueType,
tier: e.tier,
rank: e.rank,
leaguePoints: e.leaguePoints,
wins: e.wins,
losses: e.losses,
recordedAt: now,
});
}
}
}
```
5. 위 헬퍼는 `applyLeagueEntries` 가 처음 호출되더라도 빈 history → 첫 entry push 가 자연스럽게 일어남.
### Step 5. community.platform 사용 + DakaoUserService 연결
**파일**:
- `apps/api/src/modules/dakao/dakao-user.service.ts`
- `apps/api/src/modules/dakao/handlers/match-join.handler.ts` (필요 시)
1. `resolveRiotAccount` 가 community 를 한 번 조회해서 `riotPlatform`, `riotRegion` 을 옵션으로 enrichment / Riot lookup 에 전달.
2. `RiotAccountService.getByRiotId` 에 `region` 옵션 전달 (community.riotRegion 우선, fallback `asia`).
3. enrichment 호출에도 `platform: community.riotPlatform ?? 'kr'`.
```ts
const community = await CommunityModel.findById(context.communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
const platform = (community?.riotPlatform as RiotPlatformRoute) ?? 'kr';
const region = (community?.riotRegion as RiotRegionalRoute) ?? 'asia';
```
### Step 6. 수동 갱신 엔드포인트
**신규 파일**: `apps/api/src/modules/user/user.controller.ts` (이미 존재) 에 라우트 추가, 또는 `riot-account.controller.ts` 신설.
- 기존 `user.module.ts` / `user.controller.ts` 구조 확인 (현재 `user/user.controller.ts`, `user/user.module.ts` 존재).
- 라우트:
```ts
@Post('me/riot-accounts/:puuid/refresh')
async refreshMyRiotAccount(
@CurrentUser() me: UserDocument,
@Param('puuid') puuid: string,
@Body() body: { force?: boolean; platform?: RiotPlatformRoute },
): Promise<EnrichResult> {
if (!me) throw new UnauthorizedException();
const owns = me.riotAccounts.some((a) => a.puuid === puuid);
if (!owns) throw new ForbiddenException();
return this.enrichmentService.enrichRiotAccount({
userId: me._id,
puuid,
options: { force: body.force === true, platform: body.platform },
});
}
```
- `UserModule.imports` 에 `RiotModule` 추가 (이미 RiotModule 이 `RiotAccountEnrichmentService` export 함).
- DTO: `class-validator` 기반 `RefreshRiotAccountDto`.
### Step 7. 스케줄러
**의존성**: `pnpm --filter api add @nestjs/schedule`
**신규 파일**: `apps/api/src/modules/riot/riot-account-refresh.scheduler.ts`
```ts
@Injectable()
export class RiotAccountRefreshScheduler {
private readonly logger = new Logger(RiotAccountRefreshScheduler.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichment: RiotAccountEnrichmentService,
) {}
@Cron('0 4 * * *', { timeZone: 'Asia/Seoul' })
async refreshStaleAccounts() {
const UserModel = await this.connectionService.getModel('user');
const cursor = UserModel.find({
'riotAccounts.0': { $exists: true },
})
.select({ _id: 1, riotAccounts: 1, communityId: 1 })
.cursor();
let processed = 0;
for await (const user of cursor) {
for (const acc of user.riotAccounts) {
try {
await this.enrichment.enrichRiotAccount({
userId: user._id,
puuid: acc.puuid,
options: { force: false },
});
processed += 1;
if (processed % 50 === 0) {
await sleep(5000);
}
} catch (err) {
this.logger.warn(`refresh failed: ${(err as Error)?.message ?? err}`);
}
}
}
this.logger.log(`Scheduler done: processed=${processed}`);
}
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
```
`RiotModule.providers` 에 추가, `app.module.ts` 에 `ScheduleModule.forRoot()` 추가.
### Step 8. projection 적용
**신규 파일**: `apps/api/src/modules/global/database/projections.ts`
```ts
export const USER_LIGHT_PROJECTION = {
'riotAccounts.championRecords': 0,
'riotAccounts.championRecordsFetchedAt': 0,
} as const;
```
**적용 지점**:
- `MatchService.list` — 매치 자체에는 RiotAccount 가 없지만 향후 populate 시 사용
- 신규 `UserService.list` 또는 `findByCommunity` 류 — projection 적용
- `/me` 핸들러 — full 데이터 유지
- `/users/:id` 단건 조회 — full 데이터 유지
대부분의 `riotAccounts.*` 가 무거워지는 시점이 mastery top 10 + tierHistory 누적이므로, 우선 list 쿼리에만 적용.
### Step 9. v4 파서 단위 테스트
**신규 파일**:
- `apps/api/src/modules/riot/riot-summoner.service.spec.ts`
- `apps/api/src/modules/riot/riot-league.service.spec.ts`
- `apps/api/src/modules/riot/riot-champion-mastery.service.spec.ts`
각 서비스에 RiotClientService mock 주입, 정상/누락 필드/배열 비정상 케이스 검증. enrichment 의 적용 단계는 기존 `riot-account-enrichment.service.spec.ts` 에서 이미 커버 중이므로, **Step 1 변경에 따라 기존 spec 의 응답 fixture 도 새 필드명으로 갱신** 필요.
### Step 10. 회귀 테스트 / 정리
1. `npx tsc --noEmit` 통과
2. `npx jest` 전체 PASS
3. seed 재실행으로 새 스키마 정상 작동 확인
4. dakao 시나리오 수동 검증:
- 신규 카카오 사용자가 `!내전 신청 ...` 으로 등록될 때 summoner v4 가 한 번 호출되고, 응답 후 user 문서에 `tiers`, `championMasteries`(10건), `tierHistory`(1건) 가 채워지는지 확인
- 같은 사용자가 즉시 재신청하면 enrichment 가 dedup 으로 단일 호출에 합쳐지는지 로그로 확인
- 한 시즌 후 tier 가 변경된 상태에서 enrichment 가 호출되면 `tierHistory` 에 새 entry 가 push 되는지 단위 테스트
---
## 4. 변경/추가 파일 목록
### 신규
- `apps/api/src/modules/global/database/projections.ts`
- `apps/api/src/modules/riot/riot-account-refresh.scheduler.ts`
- `apps/api/src/modules/riot/riot-summoner.service.spec.ts`
- `apps/api/src/modules/riot/riot-league.service.spec.ts`
- `apps/api/src/modules/riot/riot-champion-mastery.service.spec.ts`
- (옵션) `apps/api/src/modules/user/dto/refresh-riot-account.dto.ts`
### 수정
- `apps/api/src/modules/global/database/schema.ts` — TierInfo / TierHistoryEntry / ChampionMasteryEntry / Community 재정의
- `apps/api/src/modules/riot/riot.types.ts` — DTO 타입, RiotAccountRegionDto 추가
- `apps/api/src/modules/riot/riot-account.service.ts` — `getRegionByPuuid` 추가
- `apps/api/src/modules/riot/riot-champion-mastery.service.ts` — `getTopByPuuid` 로 교체
- `apps/api/src/modules/riot/riot-account-enrichment.service.ts` — 새 스키마 적용, dedup, tierHistory 누적, 404 보정
- `apps/api/src/modules/riot/riot.module.ts` — Scheduler / region service provider 등록
- `apps/api/src/modules/dakao/dakao-user.service.ts` — community platform/region 사용
- `apps/api/src/modules/user/user.controller.ts` (또는 신설) — `/me/riot-accounts/:puuid/refresh`
- `apps/api/src/modules/user/user.module.ts` — RiotModule import
- `apps/api/src/modules/match/match.service.ts` — list 쿼리 projection
- `apps/api/src/app.module.ts` — `ScheduleModule.forRoot()`
- `apps/api/src/seed.ts` — 새 mastery / tier 필드명에 맞춰 seed 데이터 수정
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` — fixture 갱신
### 의존성
- `pnpm --filter api add @nestjs/schedule`
---
## 5. 검증 체크리스트
- [ ] `pnpm --filter api exec tsc --noEmit` 통과
- [ ] `pnpm --filter api exec jest` 전체 PASS
- [ ] seed 재실행 후 user 문서 정상 (`db.user.findOne()` 으로 새 필드 확인)
- [ ] dakao `!내전 신청 <id> <기존_등록_riot_id> 미드,탑` → enrichment 캐시 hit, Riot API 호출 0회
- [ ] dakao `!내전 신청 <id> <신규_riot_id> 미드,탑` → summoner v4 1회, league v4 1회, mastery top v4 1회 호출, user 문서에 tiers/masteries/tierHistory 채워짐
- [ ] `POST /users/me/riot-accounts/:puuid/refresh { force: true }` → enrichment 수동 강제 갱신 동작
- [ ] cron 시뮬레이션 (`@Cron` 수동 트리거 또는 `node -e` 로 메서드 직접 호출) → 200건 이상 처리되어도 OOM/timeout 없이 완료
- [ ] match list API 응답 사이즈 → projection 적용으로 기존 대비 30%+ 감소 (실측)
- [ ] 동시 동일 puuid enrichment 두 번 호출 → in-flight Map 으로 1회로 합쳐짐 (단위 테스트)
---
## 6. Phase 3 으로 미루는 것 (참고)
- **분산 dedup** (Redis SET NX EX 또는 mongo 락)
- **Token bucket / Riot API rate limit** 글로벌 throttle
- **OpenSearch 인덱싱** (RiotAccount, Match 변화 로그)
- **Slack 알림** (enrichment 실패 임계 초과, scheduler 실패)
- **puuid 별 last-known platform 캐싱** (Step 3 의 보정 결과를 RiotAccount 에 영구 저장)
- **시즌 종료 시 tierHistory 의 `season` 필드 자동 채움** + peakTier 계산
- **백오피스 UI** — community.riotPlatform 설정 / 수동 갱신 트리거 / 신선도 리포트
- **NATS 기반 enrichment 분산** (현재 dakao 외 트리거가 없으므로 보류)
---
## 7. 운영 노트
- Riot personal API key 는 **개당 100req / 2분 / IP** 한도. mastery + summoner + league 가 1 user attach 당 3회. dakao 첫 신청이 폭주해도 분당 ~30명 미만이면 무탈.
- 스케줄러는 5초 간격 batch 50건 → 10분에 6000건. 대부분의 community 규모에서 충분.
- region/by-puuid 보정은 community 의 platform 이 잘못 설정된 케이스에서 운영자가 즉시 알 수 있도록 `logger.warn` 만 남김. Phase 3 에서 알림 채널로 승격.
- `championRecords` 와 `championRecordsFetchedAt` 은 비워두는 채로 schema 만 유지. mastery 와는 다른 용도(향후 매치 분석 집계)이므로 충돌 없음.
+1
View File
@@ -33,6 +33,7 @@
"@nestjs/websockets": "^11.1.19", "@nestjs/websockets": "^11.1.19",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.15.1", "class-validator": "^0.15.1",
"jose": "^6.2.2",
"mongoose": "^9.4.1", "mongoose": "^9.4.1",
"nats": "^2.29.3", "nats": "^2.29.3",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
+2
View File
@@ -1,4 +1,5 @@
import { Controller, Get } from '@nestjs/common'; import { Controller, Get } from '@nestjs/common';
import { AllowPublicAccess } from './modules/auth/allow-public-access.decorator';
import { AppService } from './app.service'; import { AppService } from './app.service';
@Controller() @Controller()
@@ -6,6 +7,7 @@ export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@Get() @Get()
@AllowPublicAccess()
getHello(): string { getHello(): string {
return this.appService.getHello(); return this.appService.getHello();
} }
+2
View File
@@ -5,6 +5,7 @@ import { AppService } from './app.service';
import { AuctionModule } from './modules/auction/auction.module'; import { AuctionModule } from './modules/auction/auction.module';
import { AuthModule } from './modules/auth/auth.module'; import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module'; import { CommunityModule } from './modules/community/community.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module'; import { GlobalModule } from './modules/global/global.module';
import { MatchModule } from './modules/match/match.module'; import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module'; import { RiotModule } from './modules/riot/riot.module';
@@ -23,6 +24,7 @@ import { UserModule } from './modules/user/user.module';
MatchModule, MatchModule,
AuctionModule, AuctionModule,
UserModule, UserModule,
DakaoModule,
], ],
controllers: [AppController], controllers: [AppController],
providers: [AppService], providers: [AppService],
+1 -1
View File
@@ -15,7 +15,7 @@ async function bootstrap() {
app.enableCors({ app.enableCors({
origin: isDev ? true : webOrigins, origin: isDev ? true : webOrigins,
credentials: true, credentials: true,
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'], allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
}); });
app.useGlobalPipes( app.useGlobalPipes(
new ValidationPipe({ new ValidationPipe({
@@ -9,17 +9,21 @@ import {
Param, Param,
Post, Post,
UseGuards, UseGuards,
UseInterceptors,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator'; 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 { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema'; import type { UserDocument } from '../global/database/schema';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto'; import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
@Controller('communities/:communityId/matches/:matchId/auction') @Controller('communities/:communityId/matches/:matchId/auction')
@UseInterceptors(UserResolverInterceptor)
export class AuctionController { export class AuctionController {
constructor(private readonly auctionService: AuctionService) {} constructor(private readonly auctionService: AuctionService) {}
@@ -47,6 +51,7 @@ export class AuctionController {
} }
@Get() @Get()
@AllowPublicAccess()
public async getAuction( public async getAuction(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) { ) {
@@ -55,6 +60,7 @@ export class AuctionController {
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전). // 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
@Post('open-bidding') @Post('open-bidding')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
public async openBidding( public async openBidding(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@@ -63,6 +69,7 @@ export class AuctionController {
} }
@Post('bids') @Post('bids')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
public async placeBid( public async placeBid(
@CurrentUser() currentUser: UserDocument | undefined, @CurrentUser() currentUser: UserDocument | undefined,
@@ -78,6 +85,7 @@ export class AuctionController {
} }
@Post('sold') @Post('sold')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
public async markSold( public async markSold(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@@ -90,6 +98,7 @@ export class AuctionController {
} }
@Post('next') @Post('next')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
public async next( public async next(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
+113 -7
View File
@@ -9,8 +9,19 @@ import {
WebSocketServer, WebSocketServer,
} from '@nestjs/websockets'; } from '@nestjs/websockets';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { JWTPayload } from 'jose';
import { Namespace, Socket } from 'socket.io'; 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'; import { AuctionService } from './auction.service';
interface JoinAuctionPayload { interface JoinAuctionPayload {
@@ -32,7 +43,7 @@ interface SoldPayload {
cors: { cors: {
origin: true, origin: true,
credentials: true, credentials: true,
allowedHeaders: ['Content-Type', 'X-Auth-User-Id'], allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
}, },
}) })
export class AuctionGateway export class AuctionGateway
@@ -44,10 +55,26 @@ export class AuctionGateway
private readonly logger = new Logger(AuctionGateway.name); private readonly logger = new Logger(AuctionGateway.name);
private readonly roomTimers = new Map<string, NodeJS.Timeout>(); 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) { public async handleConnection(socket: Socket) {
this.logger.debug(`Auction client connected: ${socket.id}`); 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) { public handleDisconnect(socket: Socket) {
@@ -70,6 +97,7 @@ export class AuctionGateway
socket.data.matchId = payload.matchId; socket.data.matchId = payload.matchId;
try { try {
await this.resolveSocketUserForMatch(socket, payload.matchId);
const auction = await this.auctionService.getByMatchId( const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId), new mongoose.Types.ObjectId(payload.matchId),
); );
@@ -165,7 +193,9 @@ export class AuctionGateway
} }
private getSocketMatchId(socket: Socket): string | undefined { 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( private resolveBidderUserId(
@@ -173,7 +203,9 @@ export class AuctionGateway
payloadBidderUserId?: string, payloadBidderUserId?: string,
): mongoose.Types.ObjectId | undefined { ): mongoose.Types.ObjectId | undefined {
const candidate = const candidate =
payloadBidderUserId ?? this.readHandshakeUserId(socket); payloadBidderUserId ??
(socket.data.user as UserDocument | undefined)?._id.toString() ??
this.readHandshakeUserId(socket);
if (!candidate || !mongoose.isValidObjectId(candidate)) { if (!candidate || !mongoose.isValidObjectId(candidate)) {
return undefined; return undefined;
} }
@@ -188,6 +220,80 @@ export class AuctionGateway
return Array.isArray(header) ? header[0] : header; 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) { private broadcastState(matchId: string, auction: AuctionDocument) {
this.server.to(matchId).emit('state', this.serializeAuction(auction)); this.server.to(matchId).emit('state', this.serializeAuction(auction));
this.syncRoomTimer(matchId, auction); this.syncRoomTimer(matchId, auction);
@@ -0,0 +1,7 @@
import { SetMetadata } from '@nestjs/common';
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED =
'lolympus:allow_public_access';
export const AllowPublicAccess = () =>
SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
+16
View File
@@ -0,0 +1,16 @@
import type { JWTHeaderParameters, JWTPayload } from 'jose';
import type {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import type { IdentityProviderName } from './jwt.service';
declare module 'express' {
interface Request {
tokenPayload?: JWTPayload;
tokenHeader?: JWTHeaderParameters;
identityProvider?: IdentityProviderName;
identity?: IdentityDocument;
user?: UserDocument;
}
}
+6 -9
View File
@@ -1,21 +1,18 @@
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Injectable, NestMiddleware } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express'; import type { NextFunction, Request, Response } from 'express';
import { UserDocument } from '../global/database/schema';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import './auth-request';
declare module 'express' {
interface Request {
user?: UserDocument;
}
}
@Injectable() @Injectable()
export class AuthMiddleware implements NestMiddleware { export class AuthMiddleware implements NestMiddleware {
constructor(private readonly authService: AuthService) {} constructor(private readonly authService: AuthService) {}
public async use(req: Request, _res: Response, next: NextFunction) { public async use(req: Request, _res: Response, next: NextFunction) {
const user = await this.authService.resolveUserFromRequest(req); const fallback = await this.authService.resolveDevFallbackFromRequest(req);
if (user) req.user = user; if (fallback) {
req.user = fallback.user;
req.identity = fallback.identity;
}
next(); next();
} }
} }
+26 -9
View File
@@ -1,15 +1,32 @@
import { Global, MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { AuthMiddleware } from './auth.middleware'; import { APP_GUARD } from '@nestjs/core';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
import { IdentityResolverGuard } from './identity-resolver.guard';
import { IdentityService } from './identity.service';
import { JwtAuthGuard } from './jwt.guard';
import { JwtService } from './jwt.service';
import { RolesGuard } from './roles.guard'; import { RolesGuard } from './roles.guard';
import { UserResolverInterceptor } from './user-resolver.interceptor';
@Global() @Global()
@Module({ @Module({
providers: [AuthService, RolesGuard], providers: [
exports: [AuthService, RolesGuard], AuthService,
JwtService,
IdentityService,
JwtAuthGuard,
IdentityResolverGuard,
RolesGuard,
UserResolverInterceptor,
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
],
exports: [
AuthService,
JwtService,
IdentityService,
RolesGuard,
UserResolverInterceptor,
],
}) })
export class AuthModule implements NestModule { export class AuthModule {}
public configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes('*');
}
}
+47 -8
View File
@@ -2,22 +2,61 @@ import { Injectable } from '@nestjs/common';
import type { Request } from 'express'; import type { Request } from 'express';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { UserDocument } from '../global/database/schema'; import {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { SecretService } from '../global/secret/secret.service';
import './auth-request';
interface DevFallbackResult {
user: UserDocument;
identity?: IdentityDocument;
}
@Injectable() @Injectable()
export class AuthService { export class AuthService {
constructor(private readonly connectionService: ConnectionService) {} constructor(
private readonly connectionService: ConnectionService,
private readonly secretService: SecretService,
) {}
// 로그인/세션 구현 전까지는 `X-Auth-User-Id` 헤더로 유저를 식별. public async resolveDevFallbackFromRequest(
// OAuth 도입 시 이 메서드만 교체하면 됨.
public async resolveUserFromRequest(
req: Request, req: Request,
): Promise<UserDocument | null> { ): Promise<DevFallbackResult | null> {
if (!(await this.isDevHeaderEnabled())) return null;
const header = req.headers['x-auth-user-id']; const header = req.headers['x-auth-user-id'];
const userId = Array.isArray(header) ? header[0] : header; const userId = Array.isArray(header) ? header[0] : header;
if (!userId || !mongoose.isValidObjectId(userId)) return null; return this.resolveDevUserById(userId);
}
public async resolveDevUserById(
userId: unknown,
): Promise<DevFallbackResult | null> {
if (!(await this.isDevHeaderEnabled())) return null;
if (typeof userId !== 'string' || !mongoose.isValidObjectId(userId)) {
return null;
}
const UserModel = await this.connectionService.getModel('user'); const UserModel = await this.connectionService.getModel('user');
return UserModel.findById(userId).exec(); const user = await UserModel.findById(userId).exec();
if (!user) return null;
const result: DevFallbackResult = { user };
if (user.identityId) {
const IdentityModel = await this.connectionService.getModel('identity');
const identity = await IdentityModel.findById(user.identityId).exec();
if (identity) result.identity = identity;
}
return result;
}
private async isDevHeaderEnabled(): Promise<boolean> {
if (process.env.NODE_ENV === 'prod') return false;
const value = await this.secretService.get<string>(
'AUTH_DEV_HEADER_ENABLED',
process.env.AUTH_DEV_HEADER_ENABLED ?? 'false',
);
return value === 'true';
} }
} }
@@ -0,0 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { Request } from 'express';
import { IdentityDocument } from '../global/database/schema';
import './auth-request';
export const CurrentIdentity = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): IdentityDocument | undefined => {
const req = ctx.switchToHttp().getRequest<Request>();
return req.identity;
},
);
@@ -1,9 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common'; import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { Request } from 'express';
import { UserDocument } from '../global/database/schema'; import { UserDocument } from '../global/database/schema';
import './auth-request';
export const CurrentUser = createParamDecorator( export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): UserDocument | undefined => { (_data: unknown, ctx: ExecutionContext): UserDocument | undefined => {
const req = ctx.switchToHttp().getRequest<{ user?: UserDocument }>(); const req = ctx.switchToHttp().getRequest<Request>();
return req.user; return req.user;
}, },
); );
@@ -0,0 +1,38 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import type { Request } from 'express';
import { IdentityService } from './identity.service';
import './auth-request';
@Injectable()
export class IdentityResolverGuard implements CanActivate {
constructor(private readonly identityService: IdentityService) {}
public async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
if (request.identity || !request.tokenPayload) return true;
const entraOid = stringClaim(request.tokenPayload.oid);
if (!entraOid) {
throw new UnauthorizedException('Token is missing oid claim.');
}
request.identity = await this.identityService.findOrCreateByOid({
entraOid,
tenantId: stringClaim(request.tokenPayload.tid),
email:
stringClaim(request.tokenPayload.preferred_username) ??
stringClaim(request.tokenPayload.email),
displayName: stringClaim(request.tokenPayload.name),
});
return true;
}
}
function stringClaim(value: unknown): string | undefined {
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
@@ -0,0 +1,39 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ConnectionService } from '../global/database/connection.service';
import { IdentityDocument } from '../global/database/schema';
interface IdentityInput {
entraOid: string;
tenantId?: string;
email?: string;
displayName?: string;
}
@Injectable()
export class IdentityService {
constructor(private readonly connectionService: ConnectionService) {}
public async findOrCreateByOid(
input: IdentityInput,
): Promise<IdentityDocument> {
const IdentityModel = await this.connectionService.getModel('identity');
const identity = await IdentityModel.findOneAndUpdate(
{ entraOid: input.entraOid },
{
$set: {
tenantId: input.tenantId,
email: input.email,
displayName: input.displayName,
lastSignInAt: new Date(),
},
$setOnInsert: { entraOid: input.entraOid },
},
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
if (!identity) {
throw new InternalServerErrorException('Failed to resolve identity.');
}
return identity;
}
}
+91
View File
@@ -0,0 +1,91 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { decodeJwt } from 'jose';
import type { Request } from 'express';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
import { AuthService } from './auth.service';
import { IdentityProviderName, JwtService } from './jwt.service';
import './auth-request';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly jwtService: JwtService,
private readonly authService: AuthService,
) {}
public async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()],
);
const authz = request.headers?.authorization;
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
if (!authzHeader) {
const fallback =
await this.authService.resolveDevFallbackFromRequest(request);
if (fallback) {
request.user = fallback.user;
request.identity = fallback.identity;
return true;
}
if (isPublicAccessAllowed) return true;
throw new UnauthorizedException(
'Missing or invalid Authorization header',
);
}
if (!authzHeader.startsWith('Bearer ')) {
throw new UnauthorizedException(
'Missing or invalid Authorization header',
);
}
const token = authzHeader.slice('Bearer '.length).trim();
if (!token) {
throw new UnauthorizedException('Empty bearer token');
}
const identityProvider = this.pickIdPFromToken(token);
try {
const verifyResult = await this.jwtService.verify(
token,
identityProvider,
);
request.tokenPayload = verifyResult.payload;
request.tokenHeader = verifyResult.protectedHeader;
request.identityProvider = identityProvider;
return true;
} catch (err) {
const message =
err instanceof Error ? err.message : 'JWT verification failed';
throw new UnauthorizedException(message);
}
}
private pickIdPFromToken(token: string): IdentityProviderName {
try {
const { iss } = decodeJwt(token) as { iss?: string };
if (!iss) {
throw new Error('Token has no issuer (iss) claim');
}
const lower = iss.toLowerCase();
if (lower.includes('login.microsoftonline.com')) {
return 'MICROSOFT_ENTRAID';
}
throw new Error(`Unknown issuer: ${iss}`);
} catch (err) {
const message = err instanceof Error ? err.message : 'Unable to decode token';
throw new UnauthorizedException(message);
}
}
}
+100
View File
@@ -0,0 +1,100 @@
import { Injectable } from '@nestjs/common';
import {
createRemoteJWKSet,
jwtVerify,
JWTPayload,
JWTVerifyGetKey,
JWTVerifyResult,
} from 'jose';
import { SecretService } from '../global/secret/secret.service';
export type IdentityProviderName = 'MICROSOFT_ENTRAID';
interface EntraConfig {
tenantId: string;
audience: string;
issuer: string;
allowedAlgs: string[];
jwks: JWTVerifyGetKey;
}
@Injectable()
export class JwtService {
private entraConfig?: EntraConfig;
private readonly clockTolerance = Number(
process.env.JWT_CLOCK_TOLERANCE || 5,
);
constructor(private readonly secretService: SecretService) {}
public async verify(
token: string,
identityProvider: IdentityProviderName,
): Promise<JWTVerifyResult<JWTPayload>> {
if (!token) {
throw new Error('Empty token');
}
if (identityProvider !== 'MICROSOFT_ENTRAID') {
throw new Error(`Identity provider not configured: ${identityProvider}`);
}
const provider = await this.getEntraConfig();
const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience,
algorithms: provider.allowedAlgs,
clockTolerance: this.clockTolerance,
});
const { payload, protectedHeader } = result;
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
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.tid && payload.tid !== provider.tenantId) {
throw new Error(`Unexpected tenant: ${payload.tid}`);
}
return result;
}
private async getEntraConfig(): Promise<EntraConfig> {
if (this.entraConfig) return this.entraConfig;
await this.secretService.ready();
const [audience, tenantId, allowedAlgsRaw] = await Promise.all([
this.secretService.get<string>('JWT_CLAIM_AUDIENCE'),
this.secretService.get<string>('MICROSOFT_ENTRAID_TENANT_ID'),
this.secretService.get<string>('MICROSOFT_ENTRAID_ALLOWED_ALGS', 'RS256'),
]);
const allowedAlgs = allowedAlgsRaw
.split(',')
.map((alg) => alg.trim())
.filter(Boolean);
if (allowedAlgs.length === 0) {
allowedAlgs.push('RS256');
}
const issuer = `https://login.microsoftonline.com/${tenantId}/v2.0`;
const jwks = createRemoteJWKSet(
new URL('https://login.microsoftonline.com/common/discovery/v2.0/keys'),
{
cooldownDuration: 30_000,
timeoutDuration: 10_000,
},
);
this.entraConfig = {
tenantId,
audience,
issuer,
allowedAlgs,
jwks,
};
return this.entraConfig;
}
}
+4
View File
@@ -9,6 +9,7 @@ import { Reflector } from '@nestjs/core';
import type { Request } from 'express'; import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema'; import { CommunityRole, UserDocument } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator'; import { ROLES_KEY } from './roles.decorator';
import './auth-request';
@Injectable() @Injectable()
export class RolesGuard implements CanActivate { export class RolesGuard implements CanActivate {
@@ -23,6 +24,9 @@ export class RolesGuard implements CanActivate {
const req = context.switchToHttp().getRequest<Request>(); const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined; const user = req.user as UserDocument | undefined;
if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.');
}
if (!user) throw new UnauthorizedException('Authentication required.'); if (!user) throw new UnauthorizedException('Authentication required.');
if (!requiredRoles.includes(user.role)) { if (!requiredRoles.includes(user.role)) {
throw new ForbiddenException('Insufficient role.'); throw new ForbiddenException('Insufficient role.');
@@ -0,0 +1,40 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { Observable } from 'rxjs';
import { ConnectionService } from '../global/database/connection.service';
import './auth-request';
@Injectable()
export class UserResolverInterceptor implements NestInterceptor {
constructor(private readonly connectionService: ConnectionService) {}
public async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<unknown>> {
const request = context.switchToHttp().getRequest<Request>();
const communityId = request.params?.communityId;
if (
!request.user &&
request.identity &&
typeof communityId === 'string' &&
mongoose.isValidObjectId(communityId)
) {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOne({
communityId: new mongoose.Types.ObjectId(communityId),
identityId: request.identity._id,
}).exec();
if (user) request.user = user;
}
return next.handle();
}
}
@@ -1,33 +1,54 @@
import { import {
Body, Body,
Controller, Controller,
BadRequestException,
ForbiddenException, ForbiddenException,
Get, Get,
Param, Param,
Patch, Patch,
Post, Post,
Req,
UseGuards, UseGuards,
UseInterceptors,
} from '@nestjs/common'; } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator'; 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 { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema'; import type { UserDocument } from '../global/database/schema';
import '../auth/auth-request';
import { CommunityService } from './community.service'; import { CommunityService } from './community.service';
import { CreateCommunityDto } from './dto/create-community.dto'; import { CreateCommunityDto } from './dto/create-community.dto';
import { TransferOwnershipDto } from './dto/transfer-ownership.dto'; import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
@Controller('communities') @Controller('communities')
@UseInterceptors(UserResolverInterceptor)
export class CommunityController { export class CommunityController {
constructor(private readonly communityService: CommunityService) {} constructor(private readonly communityService: CommunityService) {}
@Post() @Post()
public async createCommunity(@Body() body: CreateCommunityDto) { @AllowPublicAccess()
return this.communityService.createCommunityWithOwner(body); public async createCommunity(
@Body() body: CreateCommunityDto,
@Req() req: Request,
) {
if (!req.identity && !body.owner) {
throw new BadRequestException(
'owner is required when not authenticated.',
);
}
return this.communityService.createCommunityWithOwner({
...body,
identityId: req.identity?._id,
});
} }
@Get(':communityId') @Get(':communityId')
@AllowPublicAccess()
public async getCommunity( public async getCommunity(
@Param('communityId', ParseObjectIdPipe) @Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
@@ -14,7 +14,8 @@ import {
export interface CreateCommunityInput { export interface CreateCommunityInput {
name: string; name: string;
description?: string; description?: string;
owner: { identityId?: mongoose.Types.ObjectId;
owner?: {
kakaoTalkId?: string; kakaoTalkId?: string;
kakaoTalkNickname?: string; kakaoTalkNickname?: string;
discordId?: string; discordId?: string;
@@ -70,11 +71,12 @@ export class CommunityService {
{ {
_id: ownerUserId, _id: ownerUserId,
communityId, communityId,
identityId: input.identityId,
role: 'owner', role: 'owner',
kakaoTalkId: input.owner.kakaoTalkId, kakaoTalkId: input.owner?.kakaoTalkId,
kakaoTalkNickname: input.owner.kakaoTalkNickname, kakaoTalkNickname: input.owner?.kakaoTalkNickname,
discordId: input.owner.discordId, discordId: input.owner?.discordId,
discordNickname: input.owner.discordNickname, discordNickname: input.owner?.discordNickname,
}, },
], ],
{ session }, { session },
@@ -40,7 +40,8 @@ export class CreateCommunityDto {
@MaxLength(1024) @MaxLength(1024)
description?: string; description?: string;
@IsOptional()
@ValidateNested() @ValidateNested()
@Type(() => CreateCommunityOwnerDto) @Type(() => CreateCommunityOwnerDto)
owner!: CreateCommunityOwnerDto; owner?: CreateCommunityOwnerDto;
} }
@@ -0,0 +1,347 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose, { isValidObjectId } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { RiotAccount, UserDocument } from '../global/database/schema';
import { RiotApiError } from '../riot/riot.client.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotAccountService } from '../riot/riot-account.service';
import {
RIOT_PLATFORM_ROUTES,
RIOT_REGIONAL_ROUTES,
RiotPlatformRoute,
RiotRegionalRoute,
} from '../riot/riot.types';
import { formatCodePoints, normalizeRiotIdPart } from './riot-id.util';
export class DakaoUserError extends Error {
constructor(
public readonly code:
| 'invalid_project_id'
| 'community_not_found'
| 'riot_account_not_found'
| 'riot_account_conflict'
| 'riot_account_lookup_failed',
public readonly detail?: string,
) {
super(`Dakao user error: ${code}${detail ? ` (${detail})` : ''}`);
}
}
interface ResolveContext {
communityId: mongoose.Types.ObjectId;
kakaoTalkId: string;
kakaoTalkNickname: string;
gameName: string;
tagLine: string;
}
interface ResolveResult {
user: UserDocument;
riotAccount: RiotAccount;
}
interface RiotRouting {
platform: RiotPlatformRoute;
region: RiotRegionalRoute;
}
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
@Injectable()
export class DakaoUserService {
private readonly logger = new Logger(DakaoUserService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly riotAccountService: RiotAccountService,
private readonly enrichmentService: RiotAccountEnrichmentService,
) {}
public async resolveCommunityIdByDakaoProjectId(
dakaoProjectId: string,
): Promise<mongoose.Types.ObjectId> {
if (!isValidObjectId(dakaoProjectId)) {
throw new DakaoUserError('invalid_project_id', dakaoProjectId);
}
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findOne({
dakaoProjectId: dakaoProjectId,
})
.select({ _id: 1 })
.lean()
.exec();
if (!community) {
throw new DakaoUserError('community_not_found', dakaoProjectId);
}
return community._id as mongoose.Types.ObjectId;
}
public async upsertUser(params: {
communityId: mongoose.Types.ObjectId;
kakaoTalkId: string;
kakaoTalkNickname: string;
}): Promise<UserDocument> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOneAndUpdate(
{ communityId: params.communityId, kakaoTalkId: params.kakaoTalkId },
{
$set: { kakaoTalkNickname: params.kakaoTalkNickname },
$setOnInsert: {
communityId: params.communityId,
kakaoTalkId: params.kakaoTalkId,
role: 'member',
isActivated: true,
},
},
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
if (!user) {
// upsert + returnDocument='after' 이면 항상 반환되지만 타입 안전을 위해 가드.
throw new DakaoUserError('community_not_found');
}
return user;
}
public async resolveRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
const user = await this.upsertUser(context);
const routing = await this.resolveRiotRouting(context.communityId);
const requestedGameName = normalizeRiotIdPart(context.gameName);
const requestedTagLine = normalizeRiotIdPart(context.tagLine);
this.logRiotIdNormalization(context, requestedGameName, requestedTagLine);
const existing = user.riotAccounts.find(
(a) =>
a.gameName.toLowerCase() === requestedGameName.toLowerCase() &&
a.tagLine.toLowerCase() === requestedTagLine.toLowerCase(),
);
if (existing) {
this.logger.log(
`Found existing Riot account ${requestedGameName}#${requestedTagLine}: puuid=${existing.puuid}`,
);
}
let dto: { puuid: string; gameName: string | null; tagLine: string | null };
try {
dto = await this.riotAccountService.getByRiotId(
requestedGameName,
requestedTagLine,
{ region: routing.region },
);
this.logger.log(
`Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`,
);
} catch (err) {
if (err instanceof RiotApiError && err.status === 404) {
throw new DakaoUserError(
'riot_account_not_found',
`${requestedGameName}#${requestedTagLine}`,
);
}
this.logger.error(
`Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${
(err as Error)?.message ?? err
}`,
);
throw new DakaoUserError(
'riot_account_lookup_failed',
(err as Error)?.message,
);
}
if (existing) {
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
if (existing.puuid !== dto.puuid) {
this.logger.warn(
`Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`,
);
existing.puuid = dto.puuid;
existing.gameName = nextGameName;
existing.tagLine = nextTagLine;
this.clearRiotCache(existing);
await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine);
return this.enrichAttachedAccount({
user,
riotAccount: existing,
platform: routing.platform,
region: routing.region,
});
}
if (
existing.gameName !== nextGameName ||
existing.tagLine !== nextTagLine
) {
existing.gameName = nextGameName;
existing.tagLine = nextTagLine;
await user.save();
}
return { user, riotAccount: existing };
}
return this.attachRiotAccount({
user,
puuid: dto.puuid,
gameName: dto.gameName ?? requestedGameName,
tagLine: dto.tagLine ?? requestedTagLine,
platform: routing.platform,
region: routing.region,
});
}
private logRiotIdNormalization(
context: ResolveContext,
normalizedGameName: string,
normalizedTagLine: string,
): void {
if (
context.gameName === normalizedGameName &&
context.tagLine === normalizedTagLine
) {
return;
}
this.logger.warn(
`Normalized Riot ID input ${context.gameName}#${context.tagLine} -> ${normalizedGameName}#${normalizedTagLine} ` +
`(gameNameCodePoints=${formatCodePoints(context.gameName)}, tagLineCodePoints=${formatCodePoints(context.tagLine)})`,
);
}
private async resolveRiotRouting(
communityId: mongoose.Types.ObjectId,
): Promise<RiotRouting> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
return {
platform: this.toRiotPlatform(community?.riotPlatform),
region: this.toRiotRegion(community?.riotRegion),
};
}
private async attachRiotAccount(params: {
user: UserDocument;
puuid: string;
gameName: string;
tagLine: string;
platform: RiotPlatformRoute;
region: RiotRegionalRoute;
}): Promise<ResolveResult> {
const { user } = params;
const isFirst = user.riotAccounts.length === 0;
user.riotAccounts.push({
puuid: params.puuid,
gameName: params.gameName,
tagLine: params.tagLine,
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
isPrimary: isFirst,
tiers: [],
tierHistory: [],
matchIds: [],
championMasteries: [],
championRecords: {},
} as unknown as RiotAccount);
await this.saveUserHandlingDuplicate(user, params.gameName, params.tagLine);
const attached = user.riotAccounts.find((a) => a.puuid === params.puuid);
if (!attached) {
throw new DakaoUserError('riot_account_lookup_failed', 'attach failed');
}
return this.enrichAttachedAccount({
user,
riotAccount: attached,
platform: params.platform,
region: params.region,
});
}
private async enrichAttachedAccount(params: {
user: UserDocument;
riotAccount: RiotAccount;
platform: RiotPlatformRoute;
region: RiotRegionalRoute;
}): Promise<ResolveResult> {
// 외부 API 실패는 등록 자체를 막지 않음.
try {
const enrichResult = await this.enrichmentService.enrichRiotAccount({
userId: params.user._id,
puuid: params.riotAccount.puuid,
options: {
force: true,
platform: params.platform,
region: params.region,
},
});
if (enrichResult.account) {
return { user: params.user, riotAccount: enrichResult.account };
}
} catch (err) {
this.logger.warn(
`Riot enrichment failed (continuing with empty data): ${
(err as Error)?.message ?? err
}`,
);
}
return { user: params.user, riotAccount: params.riotAccount };
}
private async saveUserHandlingDuplicate(
user: UserDocument,
gameName: string,
tagLine: string,
): Promise<void> {
try {
await user.save();
} catch (err) {
// 같은 communityId + puuid 중복은 다른 유저가 이미 등록한 케이스.
if ((err as { code?: number })?.code === 11000) {
throw new DakaoUserError(
'riot_account_conflict',
`${gameName}#${tagLine}`,
);
}
throw err;
}
}
private clearRiotCache(account: RiotAccount): void {
account.profileIconId = 0;
account.revisionDate = 0;
account.summonerLevel = 0;
account.tiers = [];
account.tierHistory = [];
account.matchIds = [];
account.matchIdsFetchedAt = undefined;
account.recentStatsSummary = undefined;
account.recentStatsFetchedAt = undefined;
account.championMasteries = [];
account.championMasteriesFetchedAt = undefined;
account.championRecords = {};
account.championRecordsFetchedAt = undefined;
}
private toRiotPlatform(value: unknown): RiotPlatformRoute {
return typeof value === 'string' &&
RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
? (value as RiotPlatformRoute)
: DEFAULT_RIOT_PLATFORM;
}
private toRiotRegion(value: unknown): RiotRegionalRoute {
return typeof value === 'string' &&
RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute)
? (value as RiotRegionalRoute)
: DEFAULT_RIOT_REGION;
}
}
@@ -0,0 +1,31 @@
import { Module } from '@nestjs/common';
import { MatchModule } from '../match/match.module';
import { RiotModule } from '../riot/riot.module';
import {
DAKAO_OPTIONS,
createDefaultDakaoOptions,
} from './dakao.options';
import { DakaoPublisher } from './dakao.publisher';
import { DakaoSubscriber } from './dakao.subscriber';
import { DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler';
@Module({
imports: [RiotModule, MatchModule],
providers: [
{
provide: DAKAO_OPTIONS,
useFactory: createDefaultDakaoOptions,
},
DakaoPublisher,
DakaoSubscriber,
DakaoUserService,
IdempotencyCache,
MatchListHandler,
MatchJoinHandler,
],
exports: [DakaoPublisher],
})
export class DakaoModule {}
@@ -0,0 +1,13 @@
import { randomUUID } from 'crypto';
export const DAKAO_OPTIONS = Symbol('DAKAO_OPTIONS');
export interface DakaoOptions {
instanceId: string;
}
export function createDefaultDakaoOptions(): DakaoOptions {
return {
instanceId: process.env.DAKAO_INSTANCE_ID || randomUUID(),
};
}
@@ -0,0 +1,97 @@
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import { SecretService } from '../global/secret/secret.service';
import { NatsService } from '../global/nats/nats.service';
import {
DakaoCommandEnvelope,
DakaoResultEnvelope,
DakaoSegment,
DakaoSendMessagePayload,
} from './dakao.types';
import type { DakaoOptions } from './dakao.options';
import { DAKAO_OPTIONS } from './dakao.options';
const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1';
const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support';
@Injectable()
export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(DakaoPublisher.name);
private replySubject = '';
private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT;
private source = COMMAND_SOURCE_DEFAULT;
constructor(
private readonly natsService: NatsService,
private readonly secretService: SecretService,
@Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions,
) {}
async onModuleInit() {
const replyOverride = await this.secretService
.get<string>('DAKAO_REPLY_SUBJECT_PREFIX')
.catch(() => undefined);
const sendOverride = await this.secretService
.get<string>('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT')
.catch(() => undefined);
const sourceOverride = await this.secretService
.get<string>('DAKAO_COMMAND_SOURCE')
.catch(() => undefined);
const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`;
this.replySubject = `${replyPrefix}.${this.options.instanceId}`;
this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT;
this.source = sourceOverride || COMMAND_SOURCE_DEFAULT;
this.natsService.subscribe<DakaoResultEnvelope>(
this.replySubject,
(data) => this.handleReply(data),
);
this.logger.log(
`Dakao reply subscriber ready on subject="${this.replySubject}"`,
);
}
async onModuleDestroy() {
// NatsService 가 subscription 정리한다.
}
public async sendMessage(params: {
chatroomId: string;
segments: DakaoSegment[];
correlationId?: string;
}): Promise<void> {
const payload: DakaoSendMessagePayload = {
chatroomId: params.chatroomId,
segments: params.segments,
};
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
schema: 'dakao.command.v1',
id: randomUUID(),
type: 'chat.send-message',
source: this.source,
correlationId: params.correlationId,
replySubject: this.replySubject,
payload,
};
await this.natsService.publish(this.sendMessageSubject, envelope);
}
private handleReply(reply: DakaoResultEnvelope): void {
if (reply.status === 'succeeded') {
this.logger.log(
`Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`,
);
return;
}
this.logger.warn(
`Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`,
);
}
}
@@ -0,0 +1,186 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { NatsService } from '../global/nats/nats.service';
import { SecretService } from '../global/secret/secret.service';
import { CommandParseError, parseCommand } from './parsers/command.parser';
import { DakaoInboundEvent, DakaoSegment } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher';
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler';
const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command';
@Injectable()
export class DakaoSubscriber implements OnModuleInit {
private readonly logger = new Logger(DakaoSubscriber.name);
private inboundSubject = INBOUND_SUBJECT_DEFAULT;
private botUserId: string | undefined;
constructor(
private readonly natsService: NatsService,
private readonly secretService: SecretService,
private readonly dakaoUserService: DakaoUserService,
private readonly publisher: DakaoPublisher,
private readonly idempotency: IdempotencyCache,
private readonly matchListHandler: MatchListHandler,
private readonly matchJoinHandler: MatchJoinHandler,
) {}
async onModuleInit() {
const subjectOverride = await this.secretService
.get<string>('DAKAO_INBOUND_SUBJECT')
.catch(() => undefined);
this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT;
this.botUserId = await this.secretService
.get<string>('DAKAO_BOT_USER_ID')
.catch(() => undefined);
this.natsService.subscribe<DakaoInboundEvent>(
this.inboundSubject,
(event) => this.handleEvent(event),
);
this.logger.log(
`Dakao inbound subscriber ready on subject="${this.inboundSubject}"`,
);
}
private async handleEvent(event: DakaoInboundEvent): Promise<void> {
if (!this.validate(event)) return;
if (this.botUserId && event.userId === this.botUserId) {
return;
}
const logIdKey = this.deriveLogIdKey(event);
if (logIdKey && this.idempotency.has(logIdKey)) {
return;
}
if (logIdKey) this.idempotency.remember(logIdKey);
let communityId: mongoose.Types.ObjectId;
try {
communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId(
event.projectId,
);
} catch (err) {
if (err instanceof DakaoUserError) {
if (err.code === 'invalid_project_id') {
this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`);
return;
}
if (err.code === 'community_not_found') {
// 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만.
this.logger.warn(`Unknown dakao projectId: ${event.projectId}`);
return;
}
}
throw err;
}
let segments: DakaoSegment[];
try {
const command = parseCommand(event.origin.chatLog.message);
const correlationId = String(event.origin.chatLog.logId ?? '');
switch (command.kind) {
case 'match-list':
segments = await this.matchListHandler.handle({
communityId,
senderUserId: event.userId,
senderNickname: event.nickname,
});
break;
case 'match-join':
segments = await this.matchJoinHandler.handle({
communityId,
matchId: command.matchId,
senderUserId: event.userId,
senderNickname: event.nickname,
gameName: command.gameName,
tagLine: command.tagLine,
positions: command.positions.positions,
});
break;
}
await this.publisher.sendMessage({
chatroomId: event.chatroomId,
segments,
correlationId,
});
} catch (err) {
if (err instanceof CommandParseError) {
// not_a_command 는 명령이 아닌 일반 메시지 → 무시.
if (err.code === 'not_a_command') return;
await this.publisher.sendMessage({
chatroomId: event.chatroomId,
segments: this.parseErrorReply(event, err),
correlationId: String(event.origin.chatLog.logId ?? ''),
});
return;
}
this.logger.error(
`Unhandled dakao event error: ${(err as Error)?.stack ?? err}`,
);
}
}
private validate(event: unknown): event is DakaoInboundEvent {
if (!event || typeof event !== 'object') return false;
const e = event as Partial<DakaoInboundEvent>;
if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false;
if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0)
return false;
if (typeof e.nickname !== 'string') return false;
if (typeof e.userId !== 'string' || e.userId.length === 0) return false;
if (!e.origin || typeof e.origin !== 'object') return false;
const chatLog = (e.origin as { chatLog?: unknown }).chatLog;
if (!chatLog || typeof chatLog !== 'object') return false;
if (typeof (chatLog as { message?: unknown }).message !== 'string')
return false;
return true;
}
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
const logId = event.origin.chatLog.logId;
if (typeof logId === 'string') return `${event.projectId}:${logId}`;
if (logId && typeof logId === 'object') {
const { high, low, unsigned } = logId;
return `${event.projectId}:${high ?? ''}|${low ?? ''}|${unsigned ?? ''}`;
}
return null;
}
private parseErrorReply(
event: DakaoInboundEvent,
err: CommandParseError,
): DakaoSegment[] {
const head: DakaoSegment[] = [
{
kind: 'mention',
userId: event.userId,
displayText: event.nickname,
},
];
const text = ((): string => {
switch (err.code) {
case 'unknown_command':
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록 또는 !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
case 'usage':
return ` 사용법: !내전 목록 또는 !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
case 'invalid_match_id':
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
case 'invalid_riot_id':
return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`;
case 'invalid_position':
return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿) 사용.`;
default:
return ` 명령을 처리할 수 없습니다.`;
}
})();
return [...head, { kind: 'text', text }];
}
}
+102
View File
@@ -0,0 +1,102 @@
// dakao NATS contracts
// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트
// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령
// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과
// ===== Inbound =====
export interface DakaoLong {
high?: number;
low?: number;
unsigned?: boolean;
}
export interface DakaoOriginChatLog {
logId: DakaoLong | string;
chatId: DakaoLong | string;
authorId: DakaoLong | string;
type: number;
sendAt: number;
message: string;
prevId?: DakaoLong | string;
msgId?: number;
revision?: number;
scope?: number;
}
export interface DakaoOrigin {
chatId: DakaoLong | string;
logId: DakaoLong | string;
authorNickname?: string;
chatLog: DakaoOriginChatLog;
noSeen?: boolean;
notiRead?: boolean;
li?: number;
status?: number;
}
export interface DakaoInboundEvent {
projectId: string;
chatroomId: string;
nickname: string;
userId: string;
origin: DakaoOrigin;
}
// ===== Outbound: chat.send-message =====
export interface DakaoTextSegment {
kind: 'text';
text: string;
}
export interface DakaoMentionSegment {
kind: 'mention';
userId: string;
displayText: string;
}
export interface DakaoEmoticonSegment {
kind: 'emoticon';
id: string;
altText: string;
}
export type DakaoSegment =
| DakaoTextSegment
| DakaoMentionSegment
| DakaoEmoticonSegment;
export interface DakaoSendMessagePayload {
chatroomId: string;
segments: DakaoSegment[];
attachment?: string | Record<string, unknown>;
type?: number;
noSeen?: boolean;
scope?: number;
silence?: boolean;
}
export interface DakaoCommandEnvelope<TPayload> {
schema: 'dakao.command.v1';
id: string;
type: string;
source: string;
correlationId?: string;
replySubject?: string;
payload: TPayload;
}
// ===== Reply =====
export interface DakaoResultEnvelope {
schema: 'dakao.result.v1';
id: string;
type: string;
status: 'succeeded' | 'failed';
handledAt: string;
correlationId?: string;
result?: Record<string, unknown>;
error?: {
code: string;
message: string;
retryable: boolean;
};
}
@@ -0,0 +1,138 @@
import { BadRequestException } from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
import { MatchJoinHandler } from './match-join.handler';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeHandler(overrides?: {
matchService?: Partial<MatchService>;
dakaoUserService?: Partial<DakaoUserService>;
}): MatchJoinHandler {
const matchService = {
join: jest.fn(),
...overrides?.matchService,
} as unknown as MatchService;
const dakaoUserService = {
resolveRiotAccount: jest.fn(),
...overrides?.dakaoUserService,
} as unknown as DakaoUserService;
return new MatchJoinHandler(matchService, dakaoUserService);
}
const baseParams = {
communityId: objectId('111111111111111111111111'),
matchId: '69b63bc96da18dfdb218ee8c',
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
positions: ['MID', 'TOP'] as const,
};
describe('MatchJoinHandler', () => {
it('rejects invalid match id without touching services', async () => {
const handler = makeHandler();
const segments = await handler.handle({
...baseParams,
matchId: 'not-an-id',
positions: [...baseParams.positions],
});
expect(segments).toEqual([
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
expect.objectContaining({
kind: 'text',
text: expect.stringContaining('유효하지 않은 매치 ID'),
}),
]);
});
it('replies with success and uses input position priority', async () => {
const join = jest.fn().mockResolvedValue({
title: '저녁 내전',
participants: [{}, {}, {}],
maxParticipants: 10,
});
const resolveRiotAccount = jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
});
const handler = makeHandler({
matchService: { join } as Partial<MatchService>,
dakaoUserService: {
resolveRiotAccount,
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
positions: [...baseParams.positions],
});
expect(resolveRiotAccount).toHaveBeenCalledWith({
communityId: baseParams.communityId,
kakaoTalkId: 'kakao-user-1',
kakaoTalkNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
});
expect(join).toHaveBeenCalledWith({
matchId: expect.any(mongoose.Types.ObjectId),
userId: expect.any(mongoose.Types.ObjectId),
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'TOP', priority: 2 },
],
riotPuuid: 'puuid-1',
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('신청 완료 (3/10)'),
});
});
it('translates riot_account_not_found errors', async () => {
const handler = makeHandler({
dakaoUserService: {
resolveRiotAccount: jest
.fn()
.mockRejectedValue(
new DakaoUserError('riot_account_not_found', '프리리#KR1'),
),
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
positions: [...baseParams.positions],
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('라이엇 계정을 찾을 수 없습니다'),
});
});
it('translates match BadRequest into korean', async () => {
const handler = makeHandler({
matchService: {
join: jest
.fn()
.mockRejectedValue(new BadRequestException('Match is full.')),
} as Partial<MatchService>,
dakaoUserService: {
resolveRiotAccount: jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { puuid: 'p', gameName: 'g', tagLine: 't' },
}),
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
positions: [...baseParams.positions],
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('정원이 가득'),
});
});
});
@@ -0,0 +1,122 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import { Position, PositionPreference } from '../../global/database/schema';
import { DakaoSegment } from '../dakao.types';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
interface JoinHandlerParams {
communityId: mongoose.Types.ObjectId;
matchId: string;
senderUserId: string; // kakaoTalkId
senderNickname: string; // kakaoTalkNickname
gameName: string;
tagLine: string;
positions: Position[];
}
@Injectable()
export class MatchJoinHandler {
constructor(
private readonly matchService: MatchService,
private readonly dakaoUserService: DakaoUserService,
) {}
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
if (!mongoose.isValidObjectId(params.matchId)) {
return this.errorReply(params, '유효하지 않은 매치 ID 입니다.');
}
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
let resolved;
try {
resolved = await this.dakaoUserService.resolveRiotAccount({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname,
gameName: params.gameName,
tagLine: params.tagLine,
});
} catch (err) {
if (err instanceof DakaoUserError) {
return this.errorReply(params, this.translateUserError(err));
}
throw err;
}
const preferredPositions: PositionPreference[] = params.positions.map(
(position, index) => ({ position, priority: index + 1 }),
);
try {
const match = await this.matchService.join({
matchId: matchObjectId,
userId: resolved.user._id,
preferredPositions,
riotPuuid: resolved.riotAccount.puuid,
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text:
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
`\n매치: ${match.title}` +
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
`\n포지션: ${params.positions.join(', ')}`,
},
];
} catch (err) {
if (err instanceof NotFoundException) {
return this.errorReply(params, '매치를 찾을 수 없습니다.');
}
if (err instanceof BadRequestException) {
return this.errorReply(params, this.translateBadRequest(err.message));
}
throw err;
}
}
private errorReply(
params: JoinHandlerParams,
message: string,
): DakaoSegment[] {
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ` ${message}` },
];
}
private translateUserError(err: DakaoUserError): string {
switch (err.code) {
case 'invalid_project_id':
return '커뮤니티 식별자가 올바르지 않습니다.';
case 'community_not_found':
return '연결된 커뮤니티를 찾을 수 없습니다.';
case 'riot_account_not_found':
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
case 'riot_account_conflict':
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
case 'riot_account_lookup_failed':
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
}
}
private translateBadRequest(raw: string): string {
if (raw.includes('different communities'))
return '이 매치는 현재 채팅방의 커뮤니티 소속이 아닙니다.';
if (raw.includes('not recruiting')) return '모집 중인 매치가 아닙니다.';
if (raw.includes('full')) return '정원이 가득 찼습니다.';
if (raw.includes('already joined')) return '이미 신청한 매치입니다.';
return raw;
}
}
@@ -0,0 +1,63 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import { DakaoSegment } from '../dakao.types';
@Injectable()
export class MatchListHandler {
constructor(private readonly matchService: MatchService) {}
public async handle(params: {
communityId: mongoose.Types.ObjectId;
senderUserId: string;
senderNickname: string;
}): Promise<DakaoSegment[]> {
const matches = await this.matchService.list({
communityId: params.communityId,
status: 'recruiting',
limit: 10,
});
if (matches.length === 0) {
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ' 모집 중인 내전이 없습니다.' },
];
}
const lines = matches.map((m, i) => {
const id = (m._id as mongoose.Types.ObjectId).toString();
const filled = m.participants.length;
const cap = m.maxParticipants;
const time = formatScheduledAt(m.scheduledAt);
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`;
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n신청: !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`,
},
];
}
}
function formatScheduledAt(date: Date): string {
// YYYY-MM-DD HH:mm (KST 표기)
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
const yyyy = kst.getUTCFullYear();
const mm = String(kst.getUTCMonth() + 1).padStart(2, '0');
const dd = String(kst.getUTCDate()).padStart(2, '0');
const hh = String(kst.getUTCHours()).padStart(2, '0');
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
}
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
const TTL_MS = 5 * 60 * 1000;
const MAX_ENTRIES = 5000;
@Injectable()
export class IdempotencyCache {
private readonly entries = new Map<string, number>();
public has(key: string): boolean {
const expiresAt = this.entries.get(key);
if (expiresAt === undefined) return false;
if (expiresAt < Date.now()) {
this.entries.delete(key);
return false;
}
return true;
}
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);
}
this.entries.set(key, Date.now() + TTL_MS);
}
private evictExpired(): void {
const now = Date.now();
for (const [key, expiresAt] of this.entries) {
if (expiresAt < now) this.entries.delete(key);
}
}
}
@@ -0,0 +1,76 @@
import { CommandParseError, parseCommand } from './command.parser';
describe('parseCommand', () => {
it('parses match-list command (목록)', () => {
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
});
it('parses match-list command (리스트)', () => {
expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' });
});
it('parses match-join command with simple riot id', () => {
const result = parseCommand(
'!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑',
);
expect(result).toMatchObject({
kind: 'match-join',
matchId: '69b63bc96da18dfdb218ee8c',
gameName: '프리리',
tagLine: 'KR1',
});
if (result.kind === 'match-join') {
expect(result.positions.positions).toEqual(['MID', 'TOP']);
}
});
it('handles riot game name with spaces', () => {
const result = parseCommand(
'!내전 신청 69b63bc96da18dfdb218ee8c hello world#KR1 미드,서폿',
);
expect(result).toMatchObject({
kind: 'match-join',
gameName: 'hello world',
tagLine: 'KR1',
});
});
it('normalizes hidden unicode differences in riot id', () => {
const decomposedGameName = '프리리'.normalize('NFD');
const result = parseCommand(
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
);
expect(result).toMatchObject({
kind: 'match-join',
gameName: '프리리',
tagLine: 'KR1',
});
});
it('throws not_a_command for non-prefix messages', () => {
expect(() => parseCommand('안녕하세요')).toThrow(/not_a_command/);
});
it('throws unknown_command for unrecognized subcommands', () => {
expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/);
});
it('throws invalid_match_id for non-objectid match', () => {
expect(() =>
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'),
).toThrow(/invalid_match_id/);
});
it('throws invalid_riot_id when # missing', () => {
expect(() =>
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
).toThrow(/invalid_riot_id/);
});
it('throws invalid_position for too few positions', () => {
expect(() => {
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드');
}).toThrow(CommandParseError);
});
});
@@ -0,0 +1,117 @@
import { ParsedPositions, parsePositionList } from './position.parser';
import { normalizeRiotIdPart } from '../riot-id.util';
export type DakaoCommand =
| { kind: 'match-list' }
| {
kind: 'match-join';
matchId: string;
gameName: string;
tagLine: string;
positions: ParsedPositions;
};
export class CommandParseError extends Error {
constructor(
public readonly code:
| 'not_a_command'
| 'unknown_command'
| 'usage'
| 'invalid_riot_id'
| 'invalid_position'
| 'invalid_match_id',
public readonly detail?: string,
) {
super(`Command parse error: ${code}${detail ? ` (${detail})` : ''}`);
}
}
const COMMAND_PREFIX = '!내전';
export function parseCommand(rawMessage: string): DakaoCommand {
const message = rawMessage.trim();
if (!message.startsWith(COMMAND_PREFIX)) {
throw new CommandParseError('not_a_command');
}
const rest = message.slice(COMMAND_PREFIX.length).trim();
if (rest.length === 0) {
throw new CommandParseError('usage');
}
const firstSpace = rest.search(/\s/);
const subCommand = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
const args = firstSpace === -1 ? '' : rest.slice(firstSpace + 1).trim();
switch (subCommand) {
case '목록':
case '리스트':
return { kind: 'match-list' };
case '신청':
return parseJoinArgs(args);
default:
throw new CommandParseError('unknown_command', subCommand);
}
}
function parseJoinArgs(args: string): DakaoCommand {
if (args.length === 0) {
throw new CommandParseError('usage');
}
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId.
// 형식: <matchId> <gameName...>#<tagLine> <pos1>,<pos2>...
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
const lastSpace = args.lastIndexOf(' ');
if (lastSpace === -1) {
throw new CommandParseError('usage');
}
const positionPart = args.slice(lastSpace + 1).trim();
const head = args.slice(0, lastSpace).trim();
if (positionPart.length === 0 || head.length === 0) {
throw new CommandParseError('usage');
}
const headSpace = head.indexOf(' ');
if (headSpace === -1) {
throw new CommandParseError('usage');
}
const matchId = head.slice(0, headSpace).trim();
const riotId = head.slice(headSpace + 1).trim();
if (!isObjectIdHex(matchId)) {
throw new CommandParseError('invalid_match_id', matchId);
}
const hashIndex = riotId.lastIndexOf('#');
if (hashIndex <= 0 || hashIndex === riotId.length - 1) {
throw new CommandParseError('invalid_riot_id', riotId);
}
const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex));
const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1));
if (gameName.length === 0 || tagLine.length === 0) {
throw new CommandParseError('invalid_riot_id', riotId);
}
let positions: ParsedPositions;
try {
positions = parsePositionList(positionPart);
} catch (err) {
throw new CommandParseError(
'invalid_position',
(err as Error)?.message ?? positionPart,
);
}
return {
kind: 'match-join',
matchId,
gameName,
tagLine,
positions,
};
}
function isObjectIdHex(value: string): boolean {
return /^[a-f0-9]{24}$/i.test(value);
}
@@ -0,0 +1,41 @@
import { parsePositionList, PositionParseError } from './position.parser';
describe('parsePositionList', () => {
it('parses two korean positions in priority order', () => {
const result = parsePositionList('미드,탑');
expect(result.positions).toEqual(['MID', 'TOP']);
});
it('parses english aliases case-insensitively', () => {
const result = parsePositionList('JGL, sup');
expect(result.positions).toEqual(['JGL', 'SUP']);
});
it('accepts up to 5 distinct positions', () => {
const result = parsePositionList('탑,정글,미드,원딜,서폿');
expect(result.positions).toEqual(['TOP', 'JGL', 'MID', 'ADC', 'SUP']);
});
it('rejects when fewer than 2 positions', () => {
expect(() => parsePositionList('미드')).toThrow(PositionParseError);
expect(() => parsePositionList('미드')).toThrow(/too_few/);
});
it('rejects when more than 5 positions', () => {
expect(() => parsePositionList('탑,정글,미드,원딜,서폿,바텀')).toThrow(
/too_many/,
);
});
it('rejects duplicates after alias normalization', () => {
expect(() => parsePositionList('미드,mid')).toThrow(/duplicate/);
});
it('rejects unknown tokens', () => {
expect(() => parsePositionList('미드,캐리')).toThrow(/unknown/);
});
it('rejects empty input', () => {
expect(() => parsePositionList('')).toThrow(/empty/);
});
});
@@ -0,0 +1,87 @@
import { Position } from '../../global/database/schema';
const POSITION_ALIASES: Record<string, Position> = {
// TOP
top: 'TOP',
탑: 'TOP',
top레인: 'TOP',
// JUNGLE
jgl: 'JGL',
jungle: 'JGL',
jng: 'JGL',
jg: 'JGL',
정글: 'JGL',
정글러: 'JGL',
// MID
mid: 'MID',
middle: 'MID',
미드: 'MID',
// ADC (BOTTOM)
adc: 'ADC',
ad: 'ADC',
bot: 'ADC',
bottom: 'ADC',
원딜: 'ADC',
바텀: 'ADC',
// SUP
sup: 'SUP',
supp: 'SUP',
support: 'SUP',
서폿: 'SUP',
서포터: 'SUP',
};
export interface ParsedPositions {
positions: Position[];
}
export class PositionParseError extends Error {
constructor(
public readonly reason:
| 'too_few'
| 'too_many'
| 'duplicate'
| 'unknown'
| 'empty',
public readonly token?: string,
) {
super(`Position parse error: ${reason}${token ? ` (${token})` : ''}`);
}
}
export function parsePositionList(input: string): ParsedPositions {
const trimmed = input.trim();
if (trimmed.length === 0) {
throw new PositionParseError('empty');
}
const tokens = trimmed
.split(',')
.map((t) => t.trim())
.filter((t) => t.length > 0);
if (tokens.length < 2) {
throw new PositionParseError('too_few');
}
if (tokens.length > 5) {
throw new PositionParseError('too_many');
}
const positions: Position[] = [];
const seen = new Set<Position>();
for (const token of tokens) {
const key = token.toLowerCase().replace(/\s+/g, '');
const mapped = POSITION_ALIASES[key];
if (!mapped) {
throw new PositionParseError('unknown', token);
}
if (seen.has(mapped)) {
throw new PositionParseError('duplicate', token);
}
seen.add(mapped);
positions.push(mapped);
}
return { positions };
}
@@ -0,0 +1,14 @@
const ZERO_WIDTH_CHARACTERS = /[\u200B-\u200D\uFEFF]/g;
export function normalizeRiotIdPart(value: string): string {
return value.replace(ZERO_WIDTH_CHARACTERS, '').trim().normalize('NFC');
}
export function formatCodePoints(value: string): string {
return Array.from(value)
.map((char) => {
const codePoint = char.codePointAt(0);
return `U+${codePoint?.toString(16).toUpperCase().padStart(4, '0')}`;
})
.join(' ');
}
@@ -0,0 +1,14 @@
import { resolveMongoDbName } from './connection.service';
describe('resolveMongoDbName', () => {
it('uses production database only for prod', () => {
expect(resolveMongoDbName('prod')).toBe('lolympus');
});
it('uses isolated databases for non-production environments', () => {
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
expect(resolveMongoDbName('test')).toBe('lolympus-test');
expect(resolveMongoDbName('')).toBe('lolympus-dev');
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
});
});
@@ -3,6 +3,12 @@ import mongoose from 'mongoose';
import { SecretService } from '../secret/secret.service'; import { SecretService } from '../secret/secret.service';
import { tournamentModelDefinitions, TournamentModelTypes } from './schema'; import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus';
if (nodeEnv === 'test') return 'lolympus-test';
return 'lolympus-dev';
}
@Injectable({ scope: Scope.DEFAULT }) @Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit { export class ConnectionService implements OnModuleInit {
private connection: mongoose.Connection | null = null; private connection: mongoose.Connection | null = null;
@@ -18,15 +24,16 @@ export class ConnectionService implements OnModuleInit {
const connectionString = await this.secretService.get( const connectionString = await this.secretService.get(
'MONGODB_CONNECTION_STRING', 'MONGODB_CONNECTION_STRING',
); );
const dbName = resolveMongoDbName();
const defaultConnection = await mongoose const defaultConnection = await mongoose
.createConnection(connectionString, { .createConnection(connectionString, {
dbName: 'lolympus', dbName,
minPoolSize: 10, minPoolSize: 10,
maxPoolSize: 20, maxPoolSize: 20,
}) })
.asPromise(); .asPromise();
this.connection = defaultConnection; this.connection = defaultConnection;
console.log('Default Connection이 새로 생성됨.'); console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`);
return this.connection; return this.connection;
} }
+98 -12
View File
@@ -1,4 +1,8 @@
import mongoose, { Schema, HydratedDocument } from 'mongoose'; import mongoose, { Schema, HydratedDocument } from 'mongoose';
import type {
RiotPlatformRoute,
RiotRegionalRoute,
} from '../../riot/riot.types';
import { ModelDefinition } from './types'; import { ModelDefinition } from './types';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
@@ -46,25 +50,44 @@ export interface MongooseTimestamps {
updatedAt: Date; updatedAt: Date;
} }
// ===== Identity =====
export interface Identity extends MongooseTimestamps {
entraOid: string;
tenantId?: string;
email?: string;
displayName?: string;
lastSignInAt?: Date;
}
// ===== Tier ===== // ===== Tier =====
export interface TierInfo { export interface TierInfo {
leagueId?: string;
queueType: string; // RANKED_SOLO_5x5, RANKED_FLEX_SR 등 queueType: string; // RANKED_SOLO_5x5, RANKED_FLEX_SR 등
tier: string; // IRON, BRONZE, ..., CHALLENGER tier: string; // IRON, BRONZE, ..., CHALLENGER
rank: string; // I | II | III | IV rank: string; // I | II | III | IV
puuid?: string;
leaguePoints: number; leaguePoints: number;
wins: number; wins: number;
losses: number; losses: number;
veteran?: boolean;
inactive?: boolean;
freshBlood?: boolean;
hotStreak?: boolean;
miniSeries?: Record<string, unknown>;
fetchedAt: Date; // Riot API로부터 조회된 시각 fetchedAt: Date; // Riot API로부터 조회된 시각
} }
export interface TierHistoryEntry { export interface TierHistoryEntry {
season: string; // e.g., 'S13', 'S14'
queueType: string; queueType: string;
tier: string; tier: string;
rank?: string; rank?: string;
leaguePoints?: number;
wins?: number;
losses?: number;
recordedAt: Date;
season?: string; // e.g., 'S13', 'S14'
peakTier?: string; peakTier?: string;
peakRank?: string; peakRank?: string;
fetchedAt: Date;
} }
// ===== RiotAccount (User 하위에 임베딩) ===== // ===== RiotAccount (User 하위에 임베딩) =====
@@ -75,10 +98,18 @@ export interface TierHistoryEntry {
export type ChampionRecordMap = Record<string, Record<string, unknown>>; export type ChampionRecordMap = Record<string, Record<string, unknown>>;
export interface ChampionMasteryEntry { export interface ChampionMasteryEntry {
championId: string; puuid: string;
championName?: string; championId: number;
level: number; championLevel: number;
points: number; championPoints: number;
lastPlayTime?: number;
championPointsSinceLastLevel?: number;
championPointsUntilNextLevel?: number;
markRequiredForNextLevel?: number;
tokensEarned?: number;
championSeasonMilestone?: number;
milestoneGrades?: string[];
nextSeasonMilestone?: Record<string, unknown>;
} }
export interface RiotRecentStatsSummary { export interface RiotRecentStatsSummary {
@@ -128,6 +159,7 @@ export interface RiotAccount extends MongooseTimestamps {
// ===== User ===== // ===== User =====
export interface User extends MongooseTimestamps { export interface User extends MongooseTimestamps {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
identityId?: mongoose.Types.ObjectId;
role: CommunityRole; role: CommunityRole;
kakaoTalkId?: string; kakaoTalkId?: string;
kakaoTalkNickname?: string; kakaoTalkNickname?: string;
@@ -142,9 +174,13 @@ export interface Community extends MongooseTimestamps {
name: string; name: string;
description: string; description: string;
ownerUserId: mongoose.Types.ObjectId; ownerUserId: mongoose.Types.ObjectId;
dakaoProjectId?: mongoose.Types.ObjectId;
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
} }
export type CommunityDocument = HydratedDocument<Community>; export type CommunityDocument = HydratedDocument<Community>;
export type IdentityDocument = HydratedDocument<Identity>;
export type UserDocument = HydratedDocument<User>; export type UserDocument = HydratedDocument<User>;
// ===== RiotMatch (Riot 원본 매치 아카이브) ===== // ===== RiotMatch (Riot 원본 매치 아카이브) =====
@@ -282,12 +318,19 @@ const PositionPreferenceSubSchema = new Schema<PositionPreference>(
const TierInfoSubSchema = new Schema<TierInfo>( const TierInfoSubSchema = new Schema<TierInfo>(
{ {
leagueId: { type: String },
queueType: { type: String, required: true }, queueType: { type: String, required: true },
tier: { type: String, required: true }, tier: { type: String, required: true },
rank: { type: String, required: true, default: '' }, rank: { type: String, required: true, default: '' },
puuid: { type: String },
leaguePoints: { type: Number, required: true, default: 0 }, leaguePoints: { type: Number, required: true, default: 0 },
wins: { type: Number, required: true, default: 0 }, wins: { type: Number, required: true, default: 0 },
losses: { type: Number, required: true, default: 0 }, losses: { type: Number, required: true, default: 0 },
veteran: { type: Boolean },
inactive: { type: Boolean },
freshBlood: { type: Boolean },
hotStreak: { type: Boolean },
miniSeries: { type: Schema.Types.Mixed },
fetchedAt: { type: Date, required: true, default: Date.now }, fetchedAt: { type: Date, required: true, default: Date.now },
}, },
{ _id: false }, { _id: false },
@@ -295,23 +338,34 @@ const TierInfoSubSchema = new Schema<TierInfo>(
const TierHistoryEntrySubSchema = new Schema<TierHistoryEntry>( const TierHistoryEntrySubSchema = new Schema<TierHistoryEntry>(
{ {
season: { type: String, required: true },
queueType: { type: String, required: true }, queueType: { type: String, required: true },
tier: { type: String, required: true }, tier: { type: String, required: true },
rank: { type: String }, rank: { type: String },
leaguePoints: { type: Number },
wins: { type: Number },
losses: { type: Number },
recordedAt: { type: Date, required: true },
season: { type: String },
peakTier: { type: String }, peakTier: { type: String },
peakRank: { type: String }, peakRank: { type: String },
fetchedAt: { type: Date, required: true, default: Date.now },
}, },
{ _id: false }, { _id: false },
); );
const ChampionMasteryEntrySubSchema = new Schema<ChampionMasteryEntry>( const ChampionMasteryEntrySubSchema = new Schema<ChampionMasteryEntry>(
{ {
championId: { type: String, required: true }, puuid: { type: String, required: true },
championName: { type: String }, championId: { type: Number, required: true },
level: { type: Number, required: true, default: 0 }, championLevel: { type: Number, required: true, default: 0 },
points: { type: Number, required: true, default: 0 }, championPoints: { type: Number, required: true, default: 0 },
lastPlayTime: { type: Number },
championPointsSinceLastLevel: { type: Number },
championPointsUntilNextLevel: { type: Number },
markRequiredForNextLevel: { type: Number },
tokensEarned: { type: Number },
championSeasonMilestone: { type: Number },
milestoneGrades: { type: [String] },
nextSeasonMilestone: { type: Schema.Types.Mixed },
}, },
{ _id: false }, { _id: false },
); );
@@ -374,11 +428,31 @@ const RiotAccountSubSchema = new Schema<RiotAccount>(
}, },
); );
export const IdentitySchema = new Schema<Identity>(
{
entraOid: { type: String, required: true },
tenantId: { type: String },
email: { type: String },
displayName: { type: String },
lastSignInAt: { type: Date },
},
{
timestamps: true,
collection: 'identity',
},
);
IdentitySchema.index({ entraOid: 1 }, { unique: true });
IdentitySchema.index({ email: 1 });
export const CommunitySchema = new Schema<Community>( export const CommunitySchema = new Schema<Community>(
{ {
name: { type: String, required: true }, name: { type: String, required: true },
description: { type: String, required: true, default: '' }, description: { type: String, required: true, default: '' },
ownerUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, ownerUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
dakaoProjectId: { type: Schema.Types.ObjectId },
riotPlatform: { type: String },
riotRegion: { type: String },
}, },
{ {
timestamps: true, timestamps: true,
@@ -388,6 +462,7 @@ export const CommunitySchema = new Schema<Community>(
CommunitySchema.index({ name: 1 }, { unique: true }); CommunitySchema.index({ name: 1 }, { unique: true });
CommunitySchema.index({ ownerUserId: 1 }); CommunitySchema.index({ ownerUserId: 1 });
CommunitySchema.index({ dakaoProjectId: 1 }, { unique: true, sparse: true });
export const UserSchema = new Schema<User>( export const UserSchema = new Schema<User>(
{ {
@@ -396,6 +471,7 @@ export const UserSchema = new Schema<User>(
ref: 'community', ref: 'community',
required: true, required: true,
}, },
identityId: { type: Schema.Types.ObjectId, ref: 'identity' },
role: { role: {
type: String, type: String,
enum: COMMUNITY_ROLES, enum: COMMUNITY_ROLES,
@@ -444,6 +520,14 @@ export const UserSchema = new Schema<User>(
UserSchema.index({ communityId: 1 }); UserSchema.index({ communityId: 1 });
UserSchema.index({ communityId: 1, role: 1 }); UserSchema.index({ communityId: 1, role: 1 });
UserSchema.index(
{ communityId: 1, identityId: 1 },
{
unique: true,
partialFilterExpression: { identityId: { $exists: true } },
},
);
UserSchema.index({ identityId: 1 }, { sparse: true });
UserSchema.index( UserSchema.index(
{ communityId: 1, kakaoTalkId: 1 }, { communityId: 1, kakaoTalkId: 1 },
{ unique: true, sparse: true }, { unique: true, sparse: true },
@@ -676,6 +760,7 @@ export const AuctionSchema = new Schema<Auction>(
); );
export const tournamentModelDefinitions: ModelDefinition[] = [ export const tournamentModelDefinitions: ModelDefinition[] = [
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
{ name: 'user', schema: UserSchema, schemaName: 'user' }, { name: 'user', schema: UserSchema, schemaName: 'user' },
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' }, { name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
@@ -684,6 +769,7 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
]; ];
export interface TournamentModelTypes { export interface TournamentModelTypes {
identity: Identity;
community: Community; community: Community;
user: User; user: User;
riotMatch: RiotMatch; riotMatch: RiotMatch;
@@ -1,28 +1,49 @@
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common'; import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
} from '@nestjs/common';
import { StringCodec } from 'nats'; import { StringCodec } from 'nats';
import type { NatsConnection } from 'nats'; import type { Msg, NatsConnection, Subscription } from 'nats';
import { NATS_CLIENT } from './nats.constants'; import { NATS_CLIENT } from './nats.constants';
export type NatsMessageHandler<T = unknown> = (
data: T,
msg: Msg,
) => Promise<void> | void;
@Injectable() @Injectable()
export class NatsService implements OnModuleDestroy { export class NatsService implements OnModuleDestroy {
private readonly logger = new Logger(NatsService.name);
private readonly stringCodec = StringCodec(); private readonly stringCodec = StringCodec();
private readonly subscriptions = new Set<Subscription>();
constructor( constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection, @Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {} ) {}
async onModuleDestroy() { async onModuleDestroy() {
for (const sub of this.subscriptions) {
try {
sub.unsubscribe();
} catch {
// ignore
}
}
this.subscriptions.clear();
try { try {
// 안전 종료: drain -> closed 대기
const closed = this.natsClient.closed(); const closed = this.natsClient.closed();
await this.natsClient.drain(); await this.natsClient.drain();
const err = await closed; const err = await closed;
if (err) console.error('NATS closed with error:', err); if (err) this.logger.error(`NATS closed with error: ${err}`);
} catch (e) { } catch {
// drain 실패 시 강제 close
try { try {
await this.natsClient.close(); await this.natsClient.close();
} catch {} } catch {
// ignore
}
} }
} }
@@ -33,4 +54,64 @@ export class NatsService implements OnModuleDestroy {
); );
await this.natsClient.flush(); await this.natsClient.flush();
} }
public subscribe<T = unknown>(
subject: string,
handler: NatsMessageHandler<T>,
options?: { queue?: string },
): Subscription {
const sub = this.natsClient.subscribe(subject, {
queue: options?.queue,
});
this.subscriptions.add(sub);
void this.consumeSubscription(sub, handler);
return sub;
}
private async consumeSubscription<T>(
sub: Subscription,
handler: NatsMessageHandler<T>,
): Promise<void> {
try {
for await (const msg of sub) {
await this.dispatch(msg, handler);
}
} catch (err) {
this.logger.error(
`NATS subscription on subject="${sub.getSubject()}" terminated: ${
(err as Error)?.message ?? err
}`,
);
} finally {
this.subscriptions.delete(sub);
}
}
private async dispatch<T>(
msg: Msg,
handler: NatsMessageHandler<T>,
): Promise<void> {
let data: T;
try {
const decoded = this.stringCodec.decode(msg.data);
data = JSON.parse(decoded) as T;
} catch (err) {
this.logger.warn(
`Failed to decode NATS message on subject="${msg.subject}": ${
(err as Error)?.message ?? err
}`,
);
return;
}
try {
await handler(data, msg);
} catch (err) {
this.logger.error(
`Handler error on subject="${msg.subject}": ${
(err as Error)?.stack ?? err
}`,
);
}
}
} }
@@ -23,6 +23,16 @@ export class SecretService {
'NATS_ENDPOINT', 'NATS_ENDPOINT',
'NATS_TOKEN', 'NATS_TOKEN',
'NATS_URL', 'NATS_URL',
'DAKAO_INBOUND_SUBJECT',
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
'DAKAO_REPLY_SUBJECT_PREFIX',
'DAKAO_COMMAND_SOURCE',
'DAKAO_BOT_USER_ID',
'DAKAO_INSTANCE_ID',
'JWT_CLAIM_AUDIENCE',
'MICROSOFT_ENTRAID_TENANT_ID',
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
'AUTH_DEV_HEADER_ENABLED',
// 필요시 추가 // 필요시 추가
] as const; ] as const;
@@ -11,11 +11,14 @@ import {
Post, Post,
Query, Query,
UseGuards, UseGuards,
UseInterceptors,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator'; 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 { UserResolverInterceptor } from '../auth/user-resolver.interceptor';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { import type {
MatchDocument, MatchDocument,
@@ -30,6 +33,7 @@ import {
import { MatchService } from './match.service'; import { MatchService } from './match.service';
@Controller('communities/:communityId/matches') @Controller('communities/:communityId/matches')
@UseInterceptors(UserResolverInterceptor)
export class MatchController { export class MatchController {
constructor(private readonly matchService: MatchService) {} constructor(private readonly matchService: MatchService) {}
@@ -61,6 +65,7 @@ export class MatchController {
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@Get() @Get()
@AllowPublicAccess()
public async listMatches( public async listMatches(
@CurrentUser() currentUser: UserDocument | undefined, @CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe) @Param('communityId', ParseObjectIdPipe)
@@ -81,6 +86,7 @@ export class MatchController {
} }
@Get(':matchId') @Get(':matchId')
@AllowPublicAccess()
public async getMatch( public async getMatch(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) { ) {
@@ -117,6 +123,7 @@ export class MatchController {
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용). // 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
@Post(':matchId/participants') @Post(':matchId/participants')
@AllowPublicAccess()
public async joinMatch( public async joinMatch(
@CurrentUser() currentUser: UserDocument | undefined, @CurrentUser() currentUser: UserDocument | undefined,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
+19 -10
View File
@@ -35,6 +35,8 @@ interface JoinMatchParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
preferredPositions: PositionPreference[]; preferredPositions: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
riotPuuid?: string;
} }
@Injectable() @Injectable()
@@ -119,22 +121,22 @@ export class MatchService {
if (match.participants.length >= match.maxParticipants) { if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.'); throw new BadRequestException('Match is full.');
} }
const alreadyIn = match.participants.some((p) => const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
p.userId.equals(user._id),
);
if (alreadyIn) { if (alreadyIn) {
throw new BadRequestException('User already joined this match.'); throw new BadRequestException('User already joined this match.');
} }
const primaryRiot = user.riotAccounts.find((a) => a.isPrimary); const selectedRiot = params.riotPuuid
const primaryTier = this.selectParticipantTier(primaryRiot?.tiers ?? []); ? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
: user.riotAccounts.find((a) => a.isPrimary);
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
match.participants.push({ match.participants.push({
userId: user._id, userId: user._id,
puuid: primaryRiot?.puuid, puuid: selectedRiot?.puuid,
gameName: primaryRiot?.gameName, gameName: selectedRiot?.gameName,
tagLine: primaryRiot?.tagLine, tagLine: selectedRiot?.tagLine,
profileIconId: primaryRiot?.profileIconId, profileIconId: selectedRiot?.profileIconId,
tier: primaryTier, tier: selectedTier,
preferredPositions: params.preferredPositions, preferredPositions: params.preferredPositions,
joinedAt: new Date(), joinedAt: new Date(),
}); });
@@ -148,12 +150,19 @@ export class MatchService {
if (!tier) return undefined; if (!tier) return undefined;
return { return {
leagueId: tier.leagueId,
queueType: tier.queueType, queueType: tier.queueType,
tier: tier.tier, tier: tier.tier,
rank: tier.rank, rank: tier.rank,
puuid: tier.puuid,
leaguePoints: tier.leaguePoints, leaguePoints: tier.leaguePoints,
wins: tier.wins, wins: tier.wins,
losses: tier.losses, losses: tier.losses,
veteran: tier.veteran,
inactive: tier.inactive,
freshBlood: tier.freshBlood,
hotStreak: tier.hotStreak,
miniSeries: tier.miniSeries,
fetchedAt: tier.fetchedAt, fetchedAt: tier.fetchedAt,
}; };
} }
@@ -0,0 +1,391 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
import { RiotAccountService } from './riot-account.service';
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
import { RiotApiError } from './riot.client.service';
import { RiotLeagueService } from './riot-league.service';
import { RiotSummonerService } from './riot-summoner.service';
interface FakeAccount {
puuid: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
tiers: Array<{
leagueId: string;
queueType: string;
tier: string;
rank: string;
puuid: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: Date;
}>;
tierHistory: Array<{
queueType: string;
tier: string;
rank?: string;
leaguePoints?: number;
wins?: number;
losses?: number;
recordedAt: Date;
}>;
championMasteries: Array<{
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
}>;
championMasteriesFetchedAt?: Date;
championRecords: Record<string, unknown>;
championRecordsFetchedAt?: Date;
}
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
return {
puuid: 'puuid-1',
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
tiers: [],
tierHistory: [],
championMasteries: [],
championRecords: {},
...overrides,
};
}
function makeUser(account: FakeAccount) {
const _id = new mongoose.Types.ObjectId();
const save = jest.fn().mockResolvedValue(undefined);
return {
_id,
riotAccounts: [account],
save,
};
}
function makeService(overrides?: {
user?: any;
account?: Partial<RiotAccountService>;
summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>;
mastery?: Partial<RiotChampionMasteryService>;
}) {
const user = overrides?.user;
const findById = jest.fn().mockReturnValue({
exec: () => Promise.resolve(user ?? null),
});
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findById }),
} as unknown as ConnectionService;
const summonerService = {
getByPuuid: jest.fn(),
...overrides?.summoner,
} as unknown as RiotSummonerService;
const accountService = {
getRegionByPuuid: jest.fn(),
...overrides?.account,
} as unknown as RiotAccountService;
const leagueService = {
getEntriesByPuuid: jest.fn(),
...overrides?.league,
} as unknown as RiotLeagueService;
const masteryService = {
getTopByPuuid: jest.fn(),
...overrides?.mastery,
} as unknown as RiotChampionMasteryService;
const service = new RiotAccountEnrichmentService(
connectionService,
accountService,
summonerService,
leagueService,
masteryService,
);
return {
service,
user,
accountService,
summonerService,
leagueService,
masteryService,
};
}
describe('RiotAccountEnrichmentService', () => {
it('returns failed for unknown user', async () => {
const { service } = makeService();
const result = await service.enrichRiotAccount({
userId: new mongoose.Types.ObjectId(),
puuid: 'puuid-1',
});
expect(result.summoner).toBe('failed');
expect(result.account).toBeNull();
});
it('fills summoner / league / mastery on first attach (force)', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, summonerService, leagueService, masteryService } =
makeService({
user,
summoner: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
profileIconId: 588,
revisionDate: 1776977597000,
summonerLevel: 529,
}),
} as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
wins: 160,
losses: 148,
},
]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]),
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
expect(result.summoner).toBe('updated');
expect(result.league).toBe('updated');
expect(result.masteries).toBe('updated');
expect(account.profileIconId).toBe(588);
expect(account.summonerLevel).toBe(529);
expect(account.tiers).toHaveLength(1);
expect(account.tiers[0]).toMatchObject({
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
});
expect(account.tierHistory).toHaveLength(1);
expect(account.tierHistory[0]).toMatchObject({
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
leaguePoints: 75,
wins: 160,
losses: 148,
});
expect(account.championMasteries).toEqual([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]);
expect(account.championRecords).toEqual({});
expect(user.save).toHaveBeenCalledTimes(1);
expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
});
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
});
expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
count: 10,
});
});
it('skips fresh data when within TTL and not forced', async () => {
const recent = new Date(Date.now() - 60_000);
const account = makeAccount({
profileIconId: 1,
revisionDate: Date.now() - 60_000,
summonerLevel: 100,
tiers: [
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'II',
puuid: 'puuid-1',
leaguePoints: 1,
wins: 1,
losses: 1,
fetchedAt: recent,
},
],
championMasteriesFetchedAt: recent,
});
const user = makeUser(account);
const summoner = jest.fn();
const league = jest.fn();
const mastery = jest.fn();
const { service } = makeService({
user,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: league,
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: mastery,
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
});
expect(result.summoner).toBe('fresh');
expect(result.league).toBe('fresh');
expect(result.masteries).toBe('fresh');
expect(summoner).not.toHaveBeenCalled();
expect(league).not.toHaveBeenCalled();
expect(mastery).not.toHaveBeenCalled();
expect(user.save).not.toHaveBeenCalled();
});
it('records failed for individual failing fetches but updates the rest', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
summoner: {
getByPuuid: jest.fn().mockRejectedValue(new Error('boom')),
} as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
expect(result.summoner).toBe('failed');
expect(result.league).toBe('updated');
expect(result.masteries).toBe('updated');
expect(user.save).toHaveBeenCalled();
});
it('retries summoner lookup with region/by-puuid platform on 404', async () => {
const account = makeAccount();
const user = makeUser(account);
const summoner = jest
.fn()
.mockRejectedValueOnce(new RiotApiError('not found', 404, 'url'))
.mockResolvedValueOnce({
puuid: 'puuid-1',
profileIconId: 100,
revisionDate: 1776977597000,
summonerLevel: 30,
});
const region = jest.fn().mockResolvedValue({
puuid: 'puuid-1',
game: 'lol',
region: 'jp1',
});
const league = jest.fn().mockResolvedValue([]);
const mastery = jest.fn().mockResolvedValue([]);
const { service } = makeService({
user,
account: { getRegionByPuuid: region } as Partial<RiotAccountService>,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: league,
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: mastery,
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true, platform: 'kr' },
});
expect(result.summoner).toBe('updated');
expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' });
expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', {
platform: 'kr',
});
expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', {
platform: 'jp1',
});
expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' });
expect(mastery).toHaveBeenCalledWith('puuid-1', {
platform: 'jp1',
count: 10,
});
});
it('deduplicates concurrent enrichment for the same user and puuid', async () => {
const account = makeAccount();
const user = makeUser(account);
let resolveSummoner: (value: unknown) => void;
const summonerPromise = new Promise((resolve) => {
resolveSummoner = resolve;
});
const summoner = jest.fn().mockReturnValue(summonerPromise);
const { service } = makeService({
user,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotChampionMasteryService>,
});
const first = service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
const second = service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
resolveSummoner!({
puuid: 'puuid-1',
profileIconId: 100,
revisionDate: 1776977597000,
summonerLevel: 30,
});
await Promise.all([first, second]);
expect(summoner).toHaveBeenCalledTimes(1);
expect(user.save).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,329 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
ChampionMasteryEntry,
RiotAccount,
TierInfo,
UserDocument,
} from '../global/database/schema';
import { RiotAccountService } from './riot-account.service';
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
import { RiotApiError } from './riot.client.service';
import { RiotLeagueService } from './riot-league.service';
import { RiotSummonerService } from './riot-summoner.service';
import {
RiotChampionMasteryDto,
RiotLeagueEntryDto,
RiotPlatformRoute,
RiotRegionalRoute,
RiotSummonerDto,
} from './riot.types';
const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr';
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
const MASTERY_LIMIT = 10;
const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h
const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h
const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h
export interface EnrichOptions {
platform?: RiotPlatformRoute;
region?: RiotRegionalRoute;
force?: boolean;
summonerTtlMs?: number;
leagueTtlMs?: number;
masteryTtlMs?: number;
}
export interface EnrichResult {
summoner: 'updated' | 'fresh' | 'failed';
league: 'updated' | 'fresh' | 'failed';
masteries: 'updated' | 'fresh' | 'failed';
account: RiotAccount | null;
}
@Injectable()
export class RiotAccountEnrichmentService {
private readonly logger = new Logger(RiotAccountEnrichmentService.name);
private readonly inFlight = new Map<string, Promise<EnrichResult>>();
constructor(
private readonly connectionService: ConnectionService,
private readonly accountService: RiotAccountService,
private readonly summonerService: RiotSummonerService,
private readonly leagueService: RiotLeagueService,
private readonly masteryService: RiotChampionMasteryService,
) {}
public async enrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
options?: EnrichOptions;
}): Promise<EnrichResult> {
const key = `${params.userId.toString()}:${params.puuid}`;
const existing = this.inFlight.get(key);
if (existing) return existing;
const promise = this.doEnrichRiotAccount(params).finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
}
private async doEnrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
options?: EnrichOptions;
}): Promise<EnrichResult> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId).exec();
if (!user) {
return {
summoner: 'failed',
league: 'failed',
masteries: 'failed',
account: null,
};
}
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
if (!account) {
return {
summoner: 'failed',
league: 'failed',
masteries: 'failed',
account: null,
};
}
const opts = params.options ?? {};
const platform = opts.platform ?? DEFAULT_PLATFORM;
const region = opts.region ?? DEFAULT_REGION;
const now = Date.now();
const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS;
const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS;
const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS;
const force = opts.force === true;
const summonerStale =
force ||
account.revisionDate === 0 ||
now - account.revisionDate > summonerTtl;
const leagueStale =
force ||
account.tiers.length === 0 ||
this.tiersOldestAt(account.tiers) < now - leagueTtl;
const masteryStale =
force ||
!account.championMasteriesFetchedAt ||
now - account.championMasteriesFetchedAt.getTime() > masteryTtl;
const summonerOutcome = summonerStale
? await this.fetchSummonerSafe(params.puuid, platform, region)
: { status: 'fresh' as const, dto: null, platform };
const effectivePlatform = summonerOutcome.platform ?? platform;
const [leagueOutcome, masteryOutcome] = await Promise.all([
leagueStale
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
: Promise.resolve({ status: 'fresh' as const, dto: null }),
masteryStale
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
: Promise.resolve({ status: 'fresh' as const, dto: null }),
]);
if (summonerOutcome.status === 'updated' && summonerOutcome.dto) {
this.applySummoner(account, summonerOutcome.dto);
}
if (leagueOutcome.status === 'updated' && leagueOutcome.dto) {
this.applyLeagueEntries(account, leagueOutcome.dto);
}
if (masteryOutcome.status === 'updated' && masteryOutcome.dto) {
this.applyMasteries(account, masteryOutcome.dto);
}
if (
summonerOutcome.status === 'updated' ||
leagueOutcome.status === 'updated' ||
masteryOutcome.status === 'updated'
) {
await user.save();
}
return {
summoner: summonerOutcome.status,
league: leagueOutcome.status,
masteries: masteryOutcome.status,
account,
};
}
private async fetchSummonerSafe(
puuid: string,
platform: RiotPlatformRoute,
region: RiotRegionalRoute,
): Promise<
| { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute }
| { status: 'failed'; dto: null; platform: RiotPlatformRoute }
> {
try {
const dto = await this.summonerService.getByPuuid(puuid, { platform });
return { status: 'updated', dto, platform };
} catch (err) {
if (err instanceof RiotApiError && err.status === 404) {
try {
const regionDto = await this.accountService.getRegionByPuuid(puuid, {
region,
});
if (regionDto.region !== platform) {
this.logger.warn(
`Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`,
);
}
const dto = await this.summonerService.getByPuuid(puuid, {
platform: regionDto.region,
});
return { status: 'updated', dto, platform: regionDto.region };
} catch (fallbackErr) {
this.logger.warn(
`Summoner fallback fetch failed for ${puuid}: ${
(fallbackErr as Error)?.message ?? fallbackErr
}`,
);
return { status: 'failed', dto: null, platform };
}
}
this.logger.warn(
`Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`,
);
return { status: 'failed', dto: null, platform };
}
}
private async fetchLeagueSafe(
puuid: string,
platform: RiotPlatformRoute,
): Promise<
| { status: 'updated'; dto: RiotLeagueEntryDto[] }
| { status: 'failed'; dto: null }
> {
try {
const dto = await this.leagueService.getEntriesByPuuid(puuid, {
platform,
});
return { status: 'updated', dto };
} catch (err) {
this.logger.warn(
`League entries fetch failed for ${puuid}: ${
(err as Error)?.message ?? err
}`,
);
return { status: 'failed', dto: null };
}
}
private async fetchMasteriesSafe(
puuid: string,
platform: RiotPlatformRoute,
): Promise<
| { status: 'updated'; dto: RiotChampionMasteryDto[] }
| { status: 'failed'; dto: null }
> {
try {
const dto = await this.masteryService.getTopByPuuid(puuid, {
platform,
count: MASTERY_LIMIT,
});
return { status: 'updated', dto };
} catch (err) {
this.logger.warn(
`Champion masteries fetch failed for ${puuid}: ${
(err as Error)?.message ?? err
}`,
);
return { status: 'failed', dto: null };
}
}
private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void {
account.profileIconId = dto.profileIconId;
account.revisionDate = dto.revisionDate;
account.summonerLevel = dto.summonerLevel;
}
private applyLeagueEntries(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
): void {
const fetchedAt = new Date();
this.appendTierHistoryIfChanged(account, entries, fetchedAt);
const next: TierInfo[] = entries.map((e) => ({
leagueId: e.leagueId,
queueType: e.queueType,
tier: e.tier,
rank: e.rank,
puuid: e.puuid,
leaguePoints: e.leaguePoints,
wins: e.wins,
losses: e.losses,
veteran: e.veteran,
inactive: e.inactive,
freshBlood: e.freshBlood,
hotStreak: e.hotStreak,
miniSeries: e.miniSeries,
fetchedAt,
}));
account.tiers = next;
}
private appendTierHistoryIfChanged(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
recordedAt: Date,
): void {
for (const entry of entries) {
const last = [...account.tierHistory]
.reverse()
.find((history) => history.queueType === entry.queueType);
const changed =
!last ||
last.tier !== entry.tier ||
(last.rank ?? '') !== (entry.rank ?? '');
if (!changed) continue;
account.tierHistory.push({
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
leaguePoints: entry.leaguePoints,
wins: entry.wins,
losses: entry.losses,
recordedAt,
});
}
}
private applyMasteries(
account: RiotAccount,
masteries: RiotChampionMasteryDto[],
): void {
const summary: ChampionMasteryEntry[] = masteries
.slice(0, MASTERY_LIMIT)
.map((m) => ({ ...m }));
account.championMasteries = summary;
account.championMasteriesFetchedAt = new Date();
}
private tiersOldestAt(tiers: TierInfo[]): number {
if (tiers.length === 0) return 0;
let oldest = Infinity;
for (const t of tiers) {
const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0;
if (at < oldest) oldest = at;
}
return oldest === Infinity ? 0 : oldest;
}
}
@@ -1,8 +1,10 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service'; import { RiotClientService } from './riot.client.service';
import { import {
RIOT_PLATFORM_ROUTES,
RiotAccountDto, RiotAccountDto,
RiotAccountLookupOptions, RiotAccountLookupOptions,
RiotAccountRegionDto,
} from './riot.types'; } from './riot.types';
@Injectable() @Injectable()
@@ -37,6 +39,20 @@ export class RiotAccountService {
parseRiotAccountDto, parseRiotAccountDto,
); );
} }
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<RiotAccountRegionDto> {
return this.riotClientService.get<RiotAccountRegionDto>(
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
{
region: options.region ?? 'asia',
signal: options.signal,
},
parseRiotAccountRegionDto,
);
}
} }
function parseRiotAccountDto(value: unknown): RiotAccountDto { function parseRiotAccountDto(value: unknown): RiotAccountDto {
@@ -67,6 +83,38 @@ function parseRiotAccountDto(value: unknown): RiotAccountDto {
}; };
} }
function parseRiotAccountRegionDto(value: unknown): RiotAccountRegionDto {
if (!isRecord(value)) {
throw new TypeError('Riot account region response must be an object.');
}
const puuid = value.puuid;
const game = value.game;
const region = value.region;
if (!isNonEmptyString(puuid)) {
throw new TypeError(
'Riot account region response is missing a valid puuid.',
);
}
if (!isNonEmptyString(game)) {
throw new TypeError(
'Riot account region response is missing a valid game.',
);
}
const platformRegion = region as (typeof RIOT_PLATFORM_ROUTES)[number];
if (
!isNonEmptyString(region) ||
!RIOT_PLATFORM_ROUTES.includes(platformRegion)
) {
throw new TypeError(
'Riot account region response is missing a valid region.',
);
}
return { puuid, game, region: platformRegion };
}
function isRecord(value: unknown): value is Record<string, unknown> { function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null; return typeof value === 'object' && value !== null;
} }
@@ -0,0 +1,129 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotChampionMasteryDto,
RiotPlatformLookupOptions,
} from './riot.types';
interface MasteriesByPuuidOptions extends RiotPlatformLookupOptions {
count?: number;
}
const DEFAULT_TOP_MASTERY_COUNT = 10;
const MAX_TOP_MASTERY_COUNT = 10;
@Injectable()
export class RiotChampionMasteryService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotChampionMasteryDto[]> {
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseMasteries,
);
}
public async getTopByPuuid(
puuid: string,
options: MasteriesByPuuidOptions = {},
): Promise<RiotChampionMasteryDto[]> {
const count = options.count ?? DEFAULT_TOP_MASTERY_COUNT;
if (
!Number.isInteger(count) ||
count <= 0 ||
count > MAX_TOP_MASTERY_COUNT
) {
throw new RangeError('count must be an integer between 1 and 10.');
}
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
query: { count },
},
parseMasteries,
);
}
}
function parseMasteries(value: unknown): RiotChampionMasteryDto[] {
if (!Array.isArray(value)) {
throw new TypeError('Champion masteries response must be an array.');
}
return value.map((entry, index) => parseEntry(entry, index));
}
function parseEntry(value: unknown, index: number): RiotChampionMasteryDto {
if (!isRecord(value)) {
throw new TypeError(`championMasteries[${index}] must be an object.`);
}
const puuid = value.puuid;
const championId = value.championId;
const championLevel = value.championLevel;
const championPoints = value.championPoints;
if (typeof puuid !== 'string') {
throw new TypeError(`championMasteries[${index}].puuid must be a string.`);
}
if (typeof championId !== 'number' || !Number.isFinite(championId)) {
throw new TypeError(
`championMasteries[${index}].championId must be a number.`,
);
}
if (typeof championLevel !== 'number' || !Number.isFinite(championLevel)) {
throw new TypeError(
`championMasteries[${index}].championLevel must be a number.`,
);
}
if (typeof championPoints !== 'number' || !Number.isFinite(championPoints)) {
throw new TypeError(
`championMasteries[${index}].championPoints must be a number.`,
);
}
return {
...value,
puuid,
championId,
championLevel,
championPoints,
lastPlayTime:
typeof value.lastPlayTime === 'number' ? value.lastPlayTime : undefined,
championPointsSinceLastLevel:
typeof value.championPointsSinceLastLevel === 'number'
? value.championPointsSinceLastLevel
: undefined,
championPointsUntilNextLevel:
typeof value.championPointsUntilNextLevel === 'number'
? value.championPointsUntilNextLevel
: undefined,
markRequiredForNextLevel:
typeof value.markRequiredForNextLevel === 'number'
? value.markRequiredForNextLevel
: undefined,
tokensEarned:
typeof value.tokensEarned === 'number' ? value.tokensEarned : undefined,
championSeasonMilestone:
typeof value.championSeasonMilestone === 'number'
? value.championSeasonMilestone
: undefined,
milestoneGrades: Array.isArray(value.milestoneGrades)
? (value.milestoneGrades as unknown[]).filter(
(v): v is string => typeof v === 'string',
)
: undefined,
nextSeasonMilestone: isRecord(value.nextSeasonMilestone)
? value.nextSeasonMilestone
: undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,79 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotLeagueEntryDto,
RiotPlatformLookupOptions,
} from './riot.types';
@Injectable()
export class RiotLeagueService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getEntriesByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotLeagueEntryDto[]> {
return this.riotClientService.get<RiotLeagueEntryDto[]>(
`/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseLeagueEntries,
);
}
}
function parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] {
if (!Array.isArray(value)) {
throw new TypeError('League entries response must be an array.');
}
return value.map((entry, index) => parseEntry(entry, index));
}
function parseEntry(value: unknown, index: number): RiotLeagueEntryDto {
if (!isRecord(value)) {
throw new TypeError(`leagueEntries[${index}] must be an object.`);
}
return {
leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`),
queueType: requireString(
value.queueType,
`leagueEntries[${index}].queueType`,
),
tier: requireString(value.tier, `leagueEntries[${index}].tier`),
rank: requireString(value.rank, `leagueEntries[${index}].rank`),
puuid: requireString(value.puuid, `leagueEntries[${index}].puuid`),
leaguePoints: requireNumber(
value.leaguePoints,
`leagueEntries[${index}].leaguePoints`,
),
wins: requireNumber(value.wins, `leagueEntries[${index}].wins`),
losses: requireNumber(value.losses, `leagueEntries[${index}].losses`),
veteran: typeof value.veteran === 'boolean' ? value.veteran : undefined,
inactive: typeof value.inactive === 'boolean' ? value.inactive : undefined,
freshBlood:
typeof value.freshBlood === 'boolean' ? value.freshBlood : undefined,
hotStreak:
typeof value.hotStreak === 'boolean' ? value.hotStreak : undefined,
miniSeries: isRecord(value.miniSeries) ? value.miniSeries : undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function requireString(value: unknown, path: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new TypeError(`${path} must be a non-empty string.`);
}
return value;
}
function requireNumber(value: unknown, path: string): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new TypeError(`${path} must be a finite number.`);
}
return value;
}
@@ -0,0 +1,60 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotPlatformLookupOptions,
RiotSummonerDto,
} from './riot.types';
@Injectable()
export class RiotSummonerService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotSummonerDto> {
return this.riotClientService.get<RiotSummonerDto>(
`/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseSummoner,
);
}
}
function parseSummoner(value: unknown): RiotSummonerDto {
if (!isRecord(value)) {
throw new TypeError('Riot summoner response must be an object.');
}
const puuid = value.puuid;
const profileIconId = value.profileIconId;
const revisionDate = value.revisionDate;
const summonerLevel = value.summonerLevel;
if (typeof puuid !== 'string' || puuid.length === 0) {
throw new TypeError('Summoner.puuid must be a non-empty string.');
}
if (typeof profileIconId !== 'number') {
throw new TypeError('Summoner.profileIconId must be a number.');
}
if (typeof revisionDate !== 'number') {
throw new TypeError('Summoner.revisionDate must be a number.');
}
if (typeof summonerLevel !== 'number') {
throw new TypeError('Summoner.summonerLevel must be a number.');
}
return {
puuid,
profileIconId,
revisionDate,
summonerLevel,
id: typeof value.id === 'string' ? value.id : undefined,
accountId:
typeof value.accountId === 'string' ? value.accountId : undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -6,6 +6,7 @@ import {
Req, Req,
} from '@nestjs/common'; } from '@nestjs/common';
import type { Request } from 'express'; import type { Request } from 'express';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
type RiotWebhookRequest = Request & { type RiotWebhookRequest = Request & {
rawBody?: Buffer; rawBody?: Buffer;
@@ -14,6 +15,7 @@ type RiotWebhookRequest = Request & {
@Controller('riot') @Controller('riot')
export class RiotWebhookController { export class RiotWebhookController {
@All('webhooks/tournament') @All('webhooks/tournament')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
public captureTournamentWebhook(@Req() req: RiotWebhookRequest) { public captureTournamentWebhook(@Req() req: RiotWebhookRequest) {
const receivedAt = new Date().toISOString(); const receivedAt = new Date().toISOString();
@@ -2,18 +2,39 @@ import { Injectable, Logger } from '@nestjs/common';
import { SecretService } from '../global/secret/secret.service'; import { SecretService } from '../global/secret/secret.service';
import { import {
RiotApiErrorBody, RiotApiErrorBody,
RiotPlatformRoute,
RiotRegionalRoute, RiotRegionalRoute,
RiotRequestOptions, RiotRequestOptions,
RiotResponseParser, RiotResponseParser,
} from './riot.types'; } from './riot.types';
const RIOT_BASE_URLS: Record<RiotRegionalRoute, string> = { const RIOT_REGION_BASE_URLS: Record<RiotRegionalRoute, string> = {
americas: 'https://americas.api.riotgames.com', americas: 'https://americas.api.riotgames.com',
asia: 'https://asia.api.riotgames.com', asia: 'https://asia.api.riotgames.com',
europe: 'https://europe.api.riotgames.com', europe: 'https://europe.api.riotgames.com',
sea: 'https://sea.api.riotgames.com', sea: 'https://sea.api.riotgames.com',
}; };
const RIOT_PLATFORM_BASE_URLS: Record<RiotPlatformRoute, string> = {
br1: 'https://br1.api.riotgames.com',
eun1: 'https://eun1.api.riotgames.com',
euw1: 'https://euw1.api.riotgames.com',
jp1: 'https://jp1.api.riotgames.com',
kr: 'https://kr.api.riotgames.com',
la1: 'https://la1.api.riotgames.com',
la2: 'https://la2.api.riotgames.com',
me1: 'https://me1.api.riotgames.com',
na1: 'https://na1.api.riotgames.com',
oc1: 'https://oc1.api.riotgames.com',
ph2: 'https://ph2.api.riotgames.com',
ru: 'https://ru.api.riotgames.com',
sg2: 'https://sg2.api.riotgames.com',
th2: 'https://th2.api.riotgames.com',
tr1: 'https://tr1.api.riotgames.com',
tw2: 'https://tw2.api.riotgames.com',
vn2: 'https://vn2.api.riotgames.com',
};
export class RiotApiError extends Error { export class RiotApiError extends Error {
constructor( constructor(
message: string, message: string,
@@ -67,8 +88,9 @@ export class RiotClientService {
} }
private buildUrl(path: string, options: RiotRequestOptions): string { private buildUrl(path: string, options: RiotRequestOptions): string {
const region = options.region ?? 'asia'; const baseUrl = options.platform
const baseUrl = RIOT_BASE_URLS[region]; ? RIOT_PLATFORM_BASE_URLS[options.platform]
: RIOT_REGION_BASE_URLS[options.region ?? 'asia'];
const normalizedPath = path.startsWith('/') ? path : `/${path}`; const normalizedPath = path.startsWith('/') ? path : `/${path}`;
const url = new URL(`${baseUrl}${normalizedPath}`); const url = new URL(`${baseUrl}${normalizedPath}`);
+22 -2
View File
@@ -1,14 +1,34 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { SecretModule } from '../global/secret/secret.module'; import { SecretModule } from '../global/secret/secret.module';
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
import { RiotAccountService } from './riot-account.service'; import { RiotAccountService } from './riot-account.service';
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
import { RiotClientService } from './riot.client.service'; import { RiotClientService } from './riot.client.service';
import { RiotLeagueService } from './riot-league.service';
import { RiotMatchService } from './riot-match.service'; import { RiotMatchService } from './riot-match.service';
import { RiotSummonerService } from './riot-summoner.service';
import { RiotWebhookController } from './riot-webhook.controller'; import { RiotWebhookController } from './riot-webhook.controller';
@Module({ @Module({
imports: [SecretModule], imports: [SecretModule],
controllers: [RiotWebhookController], controllers: [RiotWebhookController],
providers: [RiotClientService, RiotAccountService, RiotMatchService], providers: [
exports: [RiotClientService, RiotAccountService, RiotMatchService], RiotClientService,
RiotAccountService,
RiotMatchService,
RiotSummonerService,
RiotLeagueService,
RiotChampionMasteryService,
RiotAccountEnrichmentService,
],
exports: [
RiotClientService,
RiotAccountService,
RiotMatchService,
RiotSummonerService,
RiotLeagueService,
RiotChampionMasteryService,
RiotAccountEnrichmentService,
],
}) })
export class RiotModule {} export class RiotModule {}
+83 -1
View File
@@ -1,6 +1,39 @@
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea'; export const RIOT_REGIONAL_ROUTES = [
'americas',
'asia',
'europe',
'sea',
] as const;
export type RiotRegionalRoute = (typeof RIOT_REGIONAL_ROUTES)[number];
export const RIOT_PLATFORM_ROUTES = [
'br1',
'eun1',
'euw1',
'jp1',
'kr',
'la1',
'la2',
'me1',
'na1',
'oc1',
'ph2',
'ru',
'sg2',
'th2',
'tr1',
'tw2',
'vn2',
] as const;
export type RiotPlatformRoute = (typeof RIOT_PLATFORM_ROUTES)[number];
export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial'; export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial';
export interface RiotAccountRegionDto {
puuid: string;
game: string;
region: RiotPlatformRoute;
}
export interface RiotAccountApiResponse { export interface RiotAccountApiResponse {
puuid: string; puuid: string;
gameName?: string; gameName?: string;
@@ -15,6 +48,7 @@ export interface RiotAccountDto {
export interface RiotRequestOptions { export interface RiotRequestOptions {
region?: RiotRegionalRoute; region?: RiotRegionalRoute;
platform?: RiotPlatformRoute;
query?: Record<string, string | number | boolean | undefined>; query?: Record<string, string | number | boolean | undefined>;
signal?: AbortSignal; signal?: AbortSignal;
} }
@@ -38,6 +72,54 @@ export interface RiotMatchLookupOptions {
signal?: AbortSignal; signal?: AbortSignal;
} }
export interface RiotPlatformLookupOptions {
platform?: RiotPlatformRoute;
signal?: AbortSignal;
}
// Summoner-V4 by-puuid 응답 (간소화 — 실제 응답에 id 가 빠질 수 있어 optional 처리)
export interface RiotSummonerDto {
puuid: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
id?: string;
accountId?: string;
}
// League-V4 entries by-puuid 응답
export interface RiotLeagueEntryDto {
leagueId: string;
queueType: string;
tier: string;
rank: string;
puuid: string;
leaguePoints: number;
wins: number;
losses: number;
veteran?: boolean;
inactive?: boolean;
freshBlood?: boolean;
hotStreak?: boolean;
miniSeries?: Record<string, unknown>;
}
// Champion-Mastery-V4 by-puuid 응답
export interface RiotChampionMasteryDto extends Record<string, unknown> {
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
lastPlayTime?: number;
championPointsSinceLastLevel?: number;
championPointsUntilNextLevel?: number;
markRequiredForNextLevel?: number;
tokensEarned?: number;
championSeasonMilestone?: number;
milestoneGrades?: string[];
nextSeasonMilestone?: Record<string, unknown>;
}
export interface RiotMatchIdsLookupOptions extends RiotMatchLookupOptions { export interface RiotMatchIdsLookupOptions extends RiotMatchLookupOptions {
start?: number; start?: number;
count?: number; count?: number;
@@ -0,0 +1,22 @@
import type {
CommunityDocument,
UserDocument,
} from '../../global/database/schema';
export interface MeIdentityDto {
id: string;
entraOid: string;
tenantId?: string;
email?: string;
displayName?: string;
}
export interface MeMembershipDto {
user: UserDocument;
community: CommunityDocument | null;
}
export interface MeResponseDto {
identity: MeIdentityDto | null;
memberships: MeMembershipDto[];
}
@@ -0,0 +1,13 @@
import { IsBoolean, IsIn, IsOptional } from 'class-validator';
import { RIOT_PLATFORM_ROUTES } from '../../riot/riot.types';
import type { RiotPlatformRoute } from '../../riot/riot.types';
export class RefreshRiotAccountDto {
@IsOptional()
@IsBoolean()
force?: boolean;
@IsOptional()
@IsIn(RIOT_PLATFORM_ROUTES)
platform?: RiotPlatformRoute;
}
+113 -4
View File
@@ -1,11 +1,120 @@
import { Controller, Get } from '@nestjs/common'; import {
Body,
Controller,
ForbiddenException,
Get,
Param,
Post,
Req,
UnauthorizedException,
} from '@nestjs/common';
import type { Request } from 'express';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import '../auth/auth-request';
import { CurrentUser } from '../auth/current-user.decorator'; import { CurrentUser } from '../auth/current-user.decorator';
import type { UserDocument } from '../global/database/schema'; import { ConnectionService } from '../global/database/connection.service';
import type {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import type { MeResponseDto } from './dto/me-response.dto';
import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto';
@Controller('me') @Controller('me')
export class UserController { export class UserController {
constructor(
private readonly enrichment: RiotAccountEnrichmentService,
private readonly connectionService: ConnectionService,
) {}
@Get() @Get()
public me(@CurrentUser() user: UserDocument | undefined) { @AllowPublicAccess()
return { user: user ?? null }; public async me(@Req() req: Request): Promise<MeResponseDto> {
if (req.identity) {
return this.resolveMeByIdentity(req.identity);
}
if (req.user) {
return {
identity: null,
memberships: [
{
user: req.user,
community: await this.findCommunity(req.user),
},
],
};
}
return { identity: null, memberships: [] };
}
@Post('riot-accounts/:puuid/refresh')
public async refreshRiotAccount(
@CurrentUser() user: UserDocument | undefined,
@Req() req: Request,
@Param('puuid') puuid: string,
@Body() body: RefreshRiotAccountDto,
) {
const resolvedUser =
user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null);
if (!resolvedUser) {
throw new UnauthorizedException('Authentication required.');
}
if (!resolvedUser.riotAccounts.some((account) => account.puuid === puuid)) {
throw new ForbiddenException('Riot account does not belong to user.');
}
return this.enrichment.enrichRiotAccount({
userId: resolvedUser._id,
puuid,
options: {
force: body.force === true,
platform: body.platform,
},
});
}
private async resolveMeByIdentity(
identity: IdentityDocument,
): Promise<MeResponseDto> {
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const users = await UserModel.find({ identityId: identity._id }).exec();
const communities = await CommunityModel.find({
_id: { $in: users.map((user) => user.communityId) },
}).exec();
const communityById = new Map(
communities.map((community) => [community._id.toString(), community]),
);
return {
identity: {
id: identity._id.toString(),
entraOid: identity.entraOid,
tenantId: identity.tenantId,
email: identity.email,
displayName: identity.displayName,
},
memberships: users.map((user) => ({
user,
community: communityById.get(user.communityId.toString()) ?? null,
})),
};
}
private async findCommunity(user: UserDocument) {
const CommunityModel = await this.connectionService.getModel('community');
return CommunityModel.findById(user.communityId).exec();
}
private async findUserByIdentityAndPuuid(
identity: IdentityDocument,
puuid: string,
): Promise<UserDocument | null> {
const UserModel = await this.connectionService.getModel('user');
return UserModel.findOne({
identityId: identity._id,
'riotAccounts.puuid': puuid,
}).exec();
} }
} }
+2
View File
@@ -1,7 +1,9 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { UserController } from './user.controller'; import { UserController } from './user.controller';
@Module({ @Module({
imports: [RiotModule],
controllers: [UserController], controllers: [UserController],
}) })
export class UserModule {} export class UserModule {}
+138 -20
View File
@@ -81,16 +81,54 @@ type SeedPlayer = {
wins: number; wins: number;
losses: number; losses: number;
}; };
masteries: ChampionMasteryEntry[]; masteries: SeedChampionMastery[];
recentStatsSummary: RiotRecentStatsSummary; recentStatsSummary: RiotRecentStatsSummary;
}; };
type SeedChampionMastery = {
championId: string;
championName?: string;
level: number;
points: number;
};
const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community'; const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community';
const DEV_COMMUNITY_DESCRIPTION = const DEV_COMMUNITY_DESCRIPTION =
'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.'; 'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.';
const NOW = new Date(); const NOW = new Date();
const CHAMPION_IDS: Record<string, number> = {
Ahri: 103,
Ashe: 22,
Camille: 164,
Ezreal: 81,
Gwen: 887,
Hwei: 910,
JarvanIV: 59,
Jax: 24,
Jinx: 222,
KaiSa: 145,
LeeSin: 64,
Nami: 267,
Nasus: 75,
Nautilus: 111,
Nidalee: 76,
Orianna: 61,
Rakan: 497,
Rengar: 107,
Sona: 37,
Syndra: 134,
Taliyah: 163,
Thresh: 412,
Viego: 234,
Viktor: 112,
Xayah: 498,
Yorick: 83,
Yuumi: 350,
Zeri: 221,
};
const PLAYER_SEEDS: SeedPlayer[] = [ const PLAYER_SEEDS: SeedPlayer[] = [
{ {
key: 'priri', key: 'priri',
@@ -115,9 +153,19 @@ const PLAYER_SEEDS: SeedPlayer[] = [
losses: 22, losses: 22,
}, },
masteries: [ masteries: [
{ championId: 'Syndra', championName: '신드라', level: 7, points: 124300 }, {
championId: 'Syndra',
championName: '신드라',
level: 7,
points: 124300,
},
{ championId: 'Ahri', championName: '아리', level: 7, points: 98200 }, { championId: 'Ahri', championName: '아리', level: 7, points: 98200 },
{ championId: 'Orianna', championName: '오리아나', level: 6, points: 63400 }, {
championId: 'Orianna',
championName: '오리아나',
level: 6,
points: 63400,
},
], ],
recentStatsSummary: { recentStatsSummary: {
games: 24, games: 24,
@@ -155,7 +203,12 @@ const PLAYER_SEEDS: SeedPlayer[] = [
masteries: [ masteries: [
{ championId: 'Viego', championName: '비에고', level: 7, points: 138200 }, { championId: 'Viego', championName: '비에고', level: 7, points: 138200 },
{ championId: 'LeeSin', championName: '리신', level: 6, points: 88700 }, { championId: 'LeeSin', championName: '리신', level: 6, points: 88700 },
{ championId: 'Nidalee', championName: '니달리', level: 6, points: 64100 }, {
championId: 'Nidalee',
championName: '니달리',
level: 6,
points: 64100,
},
], ],
recentStatsSummary: { recentStatsSummary: {
games: 28, games: 28,
@@ -229,8 +282,18 @@ const PLAYER_SEEDS: SeedPlayer[] = [
losses: 11, losses: 11,
}, },
masteries: [ masteries: [
{ championId: 'Thresh', championName: '쓰레쉬', level: 7, points: 187300 }, {
{ championId: 'Nautilus', championName: '노틸러스', level: 7, points: 144800 }, championId: 'Thresh',
championName: '쓰레쉬',
level: 7,
points: 187300,
},
{
championId: 'Nautilus',
championName: '노틸러스',
level: 7,
points: 144800,
},
{ championId: 'Rakan', championName: '라칸', level: 6, points: 65300 }, { championId: 'Rakan', championName: '라칸', level: 6, points: 65300 },
], ],
recentStatsSummary: { recentStatsSummary: {
@@ -269,7 +332,12 @@ const PLAYER_SEEDS: SeedPlayer[] = [
masteries: [ masteries: [
{ championId: 'Jinx', championName: '징크스', level: 7, points: 166100 }, { championId: 'Jinx', championName: '징크스', level: 7, points: 166100 },
{ championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 }, { championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 },
{ championId: 'Ezreal', championName: '이즈리얼', level: 6, points: 90100 }, {
championId: 'Ezreal',
championName: '이즈리얼',
level: 6,
points: 90100,
},
], ],
recentStatsSummary: { recentStatsSummary: {
games: 29, games: 29,
@@ -305,9 +373,19 @@ const PLAYER_SEEDS: SeedPlayer[] = [
losses: 8, losses: 8,
}, },
masteries: [ masteries: [
{ championId: 'Viktor', championName: '빅토르', level: 7, points: 172900 }, {
championId: 'Viktor',
championName: '빅토르',
level: 7,
points: 172900,
},
{ championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 }, { championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 },
{ championId: 'Taliyah', championName: '탈리야', level: 6, points: 55300 }, {
championId: 'Taliyah',
championName: '탈리야',
level: 6,
points: 55300,
},
], ],
recentStatsSummary: { recentStatsSummary: {
games: 25, games: 25,
@@ -474,7 +552,10 @@ const PLAYER_SEEDS: SeedPlayer[] = [
}, },
]; ];
function createPreferences(main: Position, sub: Position): PositionPreference[] { function createPreferences(
main: Position,
sub: Position,
): PositionPreference[] {
const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter( const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter(
(position) => position !== main && position !== sub, (position) => position !== main && position !== sub,
); );
@@ -490,6 +571,7 @@ function createPreferences(main: Position, sub: Position): PositionPreference[]
} }
function createTier( function createTier(
puuid: string,
queueType: string, queueType: string,
tier: string, tier: string,
rank: string, rank: string,
@@ -498,9 +580,11 @@ function createTier(
losses: number, losses: number,
): TierInfo { ): TierInfo {
return { return {
leagueId: `dev-${puuid}-${queueType}`,
queueType, queueType,
tier, tier,
rank: rank || 'I', rank: rank || 'I',
puuid,
leaguePoints, leaguePoints,
wins, wins,
losses, losses,
@@ -513,8 +597,10 @@ function selectPrimaryTier(tiers: TierInfo[]) {
} }
function createRiotAccount(player: SeedPlayer) { function createRiotAccount(player: SeedPlayer) {
const puuid = `dev-seed-${player.key}-puuid`;
const tiers = [ const tiers = [
createTier( createTier(
puuid,
'RANKED_SOLO_5x5', 'RANKED_SOLO_5x5',
player.tier.tier, player.tier.tier,
player.tier.rank, player.tier.rank,
@@ -527,6 +613,7 @@ function createRiotAccount(player: SeedPlayer) {
if (player.flex) { if (player.flex) {
tiers.push( tiers.push(
createTier( createTier(
puuid,
'RANKED_FLEX_SR', 'RANKED_FLEX_SR',
player.flex.tier, player.flex.tier,
player.flex.rank, player.flex.rank,
@@ -538,7 +625,7 @@ function createRiotAccount(player: SeedPlayer) {
} }
return { return {
puuid: `dev-seed-${player.key}-puuid`, puuid,
gameName: player.gameName, gameName: player.gameName,
tagLine: player.tagLine, tagLine: player.tagLine,
profileIconId: player.profileIconId, profileIconId: player.profileIconId,
@@ -550,7 +637,7 @@ function createRiotAccount(player: SeedPlayer) {
matchIds: [], matchIds: [],
recentStatsSummary: player.recentStatsSummary, recentStatsSummary: player.recentStatsSummary,
recentStatsFetchedAt: NOW, recentStatsFetchedAt: NOW,
championMasteries: player.masteries, championMasteries: createChampionMasteries(puuid, player.masteries),
championMasteriesFetchedAt: NOW, championMasteriesFetchedAt: NOW,
championRecords: {}, championRecords: {},
championRecordsFetchedAt: NOW, championRecordsFetchedAt: NOW,
@@ -559,16 +646,21 @@ function createRiotAccount(player: SeedPlayer) {
}; };
} }
function createStaffRiotAccount(key: string, gameName: string, tagLine: string) { function createStaffRiotAccount(
key: string,
gameName: string,
tagLine: string,
) {
const puuid = `dev-seed-${key}-puuid`;
return { return {
puuid: `dev-seed-${key}-puuid`, puuid,
gameName, gameName,
tagLine, tagLine,
profileIconId: 29, profileIconId: 29,
revisionDate: Date.now(), revisionDate: Date.now(),
summonerLevel: 120, summonerLevel: 120,
isPrimary: true, isPrimary: true,
tiers: [createTier('RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)], tiers: [createTier(puuid, 'RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)],
tierHistory: [], tierHistory: [],
matchIds: [], matchIds: [],
recentStatsSummary: { recentStatsSummary: {
@@ -582,10 +674,20 @@ function createStaffRiotAccount(key: string, gameName: string, tagLine: string)
mostPlayedChampionIds: ['Orianna', 'JarvanIV'], mostPlayedChampionIds: ['Orianna', 'JarvanIV'],
}, },
recentStatsFetchedAt: NOW, recentStatsFetchedAt: NOW,
championMasteries: [ championMasteries: createChampionMasteries(puuid, [
{ championId: 'Orianna', championName: '오리아나', level: 5, points: 18300 }, {
{ championId: 'JarvanIV', championName: '자르반 4세', level: 5, points: 12600 }, championId: 'Orianna',
], championName: '오리아나',
level: 5,
points: 18300,
},
{
championId: 'JarvanIV',
championName: '자르반 4세',
level: 5,
points: 12600,
},
]),
championMasteriesFetchedAt: NOW, championMasteriesFetchedAt: NOW,
championRecords: {}, championRecords: {},
championRecordsFetchedAt: NOW, championRecordsFetchedAt: NOW,
@@ -594,6 +696,18 @@ function createStaffRiotAccount(key: string, gameName: string, tagLine: string)
}; };
} }
function createChampionMasteries(
puuid: string,
masteries: SeedChampionMastery[],
): ChampionMasteryEntry[] {
return masteries.map((mastery) => ({
puuid,
championId: CHAMPION_IDS[mastery.championId] ?? 0,
championLevel: mastery.level,
championPoints: mastery.points,
}));
}
function toMatchParticipant(user: { function toMatchParticipant(user: {
_id: mongoose.Types.ObjectId; _id: mongoose.Types.ObjectId;
riotAccounts: Array<{ riotAccounts: Array<{
@@ -650,7 +764,9 @@ async function main() {
await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec(); await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec();
} }
await MatchModel.deleteMany({ communityId: existingCommunity._id }).exec(); await MatchModel.deleteMany({
communityId: existingCommunity._id,
}).exec();
await UserModel.deleteMany({ communityId: existingCommunity._id }).exec(); await UserModel.deleteMany({ communityId: existingCommunity._id }).exec();
await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec(); await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec();
} }
@@ -664,6 +780,8 @@ async function main() {
name: DEV_COMMUNITY_NAME, name: DEV_COMMUNITY_NAME,
description: DEV_COMMUNITY_DESCRIPTION, description: DEV_COMMUNITY_DESCRIPTION,
ownerUserId, ownerUserId,
riotPlatform: 'kr',
riotRegion: 'asia',
}); });
const owner = { const owner = {
+5 -1
View File
@@ -1,2 +1,6 @@
VITE_API_BASE_URL=http://126.dahyeon.us:3000 VITE_API_BASE_URL=http://localhost:3000
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
+6
View File
@@ -0,0 +1,6 @@
VITE_API_BASE_URL=http://localhost:3000
VITE_DEFAULT_COMMUNITY_ID=
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/<tenant-id>
VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
+2
View File
@@ -10,6 +10,8 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@azure/msal-browser": "^5.8.0",
"@azure/msal-react": "^5.3.1",
"@tanstack/react-query": "^5.100.1", "@tanstack/react-query": "^5.100.1",
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4", "react-dom": "^19.2.4",
+41 -9
View File
@@ -1,11 +1,38 @@
import { BrowserRouter, Link, Route, Routes } from 'react-router'; import { BrowserRouter, Link, Route, Routes } from 'react-router';
import { useMsal } from '@azure/msal-react';
import DevAuthSwitcher from './components/DevAuthSwitcher'; import DevAuthSwitcher from './components/DevAuthSwitcher';
import { DEFAULT_COMMUNITY_ID } from './config'; import { DEFAULT_COMMUNITY_ID } from './config';
import { useCommunity } from './api/hooks'; import { useCommunity } from './api/hooks';
import { isMsalConfigured } from './lib/auth/msal.config';
import AuthCallbackPage from './pages/AuthCallback';
import HomePage from './pages/HomePage'; import HomePage from './pages/HomePage';
import LoginPage from './pages/Login';
import MatchDetailPage from './pages/MatchDetailPage'; import MatchDetailPage from './pages/MatchDetailPage';
import AuctionPage from './pages/AuctionPage'; import AuctionPage from './pages/AuctionPage';
function MsalHeaderActions() {
const { accounts, instance } = useMsal();
const account = instance.getActiveAccount() ?? accounts[0];
if (!account) {
return (
<Link className="btn btn-primary btn-xs px-3" to="/login">
로그인
</Link>
);
}
return (
<button
type="button"
className="btn btn-ghost btn-xs px-3"
onClick={() => void instance.logoutRedirect()}
>
{account.name ?? account.username} 로그아웃
</button>
);
}
function App() { function App() {
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS'; const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS';
@@ -21,20 +48,25 @@ function App() {
> >
{communityLabel} {communityLabel}
</Link> </Link>
{DEFAULT_COMMUNITY_ID ? ( <div className="flex items-center gap-3">
<span className="text-[10px] uppercase tracking-wider text-base-content/25"> {DEFAULT_COMMUNITY_ID ? (
API Live <span className="text-[10px] uppercase tracking-wider text-base-content/25">
</span> API Live
) : ( </span>
<span className="text-[10px] uppercase tracking-wider text-amber-500/70"> ) : (
Set `VITE_DEFAULT_COMMUNITY_ID` <span className="text-[10px] uppercase tracking-wider text-amber-500/70">
</span> Set `VITE_DEFAULT_COMMUNITY_ID`
)} </span>
)}
{isMsalConfigured && <MsalHeaderActions />}
</div>
</div> </div>
</nav> </nav>
<Routes> <Routes>
<Route path="/" element={<HomePage />} /> <Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} /> <Route path="/match/:id" element={<MatchDetailPage />} />
<Route path="/match/:id/auction" element={<AuctionPage />} /> <Route path="/match/:id/auction" element={<AuctionPage />} />
</Routes> </Routes>
+16 -1
View File
@@ -68,6 +68,7 @@ export interface ApiRiotAccount {
export interface ApiUser { export interface ApiUser {
_id: string; _id: string;
communityId: string; communityId: string;
identityId?: string;
role: CommunityRole; role: CommunityRole;
kakaoTalkId?: string; kakaoTalkId?: string;
kakaoTalkNickname?: string; kakaoTalkNickname?: string;
@@ -198,8 +199,22 @@ export interface ApiAuction {
updatedAt: string; updatedAt: string;
} }
export interface ApiIdentity {
id: string;
entraOid: string;
tenantId?: string;
email?: string;
displayName?: string;
}
export interface ApiMembership {
user: ApiUser;
community: ApiCommunity | null;
}
export interface MeResponse { export interface MeResponse {
user: ApiUser | null; identity: ApiIdentity | null;
memberships: ApiMembership[];
} }
export interface MatchesResponse { export interface MatchesResponse {
+40 -23
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client'; import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config'; import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider';
import type { ApiAuction, Position, TeamSide } from './types'; import type { ApiAuction, Position, TeamSide } from './types';
type ConnectionStatus = type ConnectionStatus =
@@ -31,37 +32,53 @@ export function useAuctionSocket(matchId: string | undefined) {
return; return;
} }
const socket = io(`${API_BASE_URL}/auction`, { let disposed = false;
transports: ['websocket'],
auth: authUserId ? { 'x-auth-user-id': authUserId } : {},
});
socketRef.current = socket;
setConnectionStatus('connecting'); setConnectionStatus('connecting');
setError(null); setError(null);
socket.on('connect', () => { void (async () => {
setConnectionStatus('connected'); const accessToken = await acquireAccessToken().catch((error) => {
socket.emit('join', { matchId }); console.warn('Failed to acquire socket access token:', error);
}); return null;
});
if (disposed) return;
socket.on('disconnect', () => { const socket = io(`${API_BASE_URL}/auction`, {
setConnectionStatus('disconnected'); transports: ['websocket'],
}); auth: accessToken
? { token: accessToken }
: authUserId
? { 'x-auth-user-id': authUserId }
: {},
});
socket.on('state', (nextAuction: ApiAuction) => { socketRef.current = socket;
setAuction(nextAuction);
setError(null);
});
socket.on('error', (payload: { message?: string }) => { socket.on('connect', () => {
setConnectionStatus('error'); setConnectionStatus('connected');
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); socket.emit('join', { matchId });
}); });
socket.on('disconnect', () => {
setConnectionStatus('disconnected');
});
socket.on('state', (nextAuction: ApiAuction) => {
setAuction(nextAuction);
setError(null);
});
socket.on('error', (payload: { message?: string }) => {
setConnectionStatus('error');
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
});
})();
return () => { return () => {
socket.removeAllListeners(); disposed = true;
socket.disconnect(); const socket = socketRef.current;
socket?.removeAllListeners();
socket?.disconnect();
socketRef.current = null; socketRef.current = null;
setConnectionStatus('idle'); setConnectionStatus('idle');
}; };
+2
View File
@@ -36,12 +36,14 @@ function subscribeToWindowChanges(eventName: string, callback: () => void) {
} }
export function getAuthUserId(): string | null { export function getAuthUserId(): string | null {
if (!import.meta.env.DEV) return null;
if (typeof window === 'undefined') return null; if (typeof window === 'undefined') return null;
const value = window.localStorage.getItem(AUTH_USER_ID_STORAGE_KEY)?.trim(); const value = window.localStorage.getItem(AUTH_USER_ID_STORAGE_KEY)?.trim();
return value ? value : null; return value ? value : null;
} }
export function setAuthUserId(userId: string | null) { export function setAuthUserId(userId: string | null) {
if (!import.meta.env.DEV) return;
if (typeof window === 'undefined') return; if (typeof window === 'undefined') return;
if (!userId?.trim()) { if (!userId?.trim()) {
+6 -3
View File
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './index.css'; import './index.css';
import App from './App.tsx'; import App from './App.tsx';
import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx';
const queryClient = new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { defaultOptions: {
@@ -16,8 +17,10 @@ const queryClient = new QueryClient({
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <MsalAppProvider>
<App /> <QueryClientProvider client={queryClient}>
</QueryClientProvider> <App />
</QueryClientProvider>
</MsalAppProvider>
</StrictMode>, </StrictMode>,
); );
+11 -3
View File
@@ -8,7 +8,11 @@ import {
type AuctionStateView, type AuctionStateView,
} from '../api/mappers'; } from '../api/mappers';
import { useAuctionSocket } from '../api/useAuctionSocket'; import { useAuctionSocket } from '../api/useAuctionSocket';
import { DEFAULT_COMMUNITY_ID, setDevCaptainSide, useDevCaptainSide } from '../config'; import {
DEFAULT_COMMUNITY_ID,
setDevCaptainSide,
useDevCaptainSide,
} from '../config';
import { ApiError } from '../lib/api'; import { ApiError } from '../lib/api';
import { positionIcon, positionLabel } from '../lib/league'; import { positionIcon, positionLabel } from '../lib/league';
import type { Position } from '../api/types'; import type { Position } from '../api/types';
@@ -395,6 +399,10 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
export default function AuctionPage() { export default function AuctionPage() {
const { id } = useParams(); const { id } = useParams();
const meQuery = useMe(); const meQuery = useMe();
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null;
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const socket = useAuctionSocket(id); const socket = useAuctionSocket(id);
@@ -460,8 +468,8 @@ export default function AuctionPage() {
const canManageAuction = const canManageAuction =
import.meta.env.DEV || import.meta.env.DEV ||
meQuery.data?.user?.role === 'owner' || currentUser?.role === 'owner' ||
meQuery.data?.user?.role === 'admin'; currentUser?.role === 'admin';
const phaseLabel: Record<AuctionStateView['phase'], string> = { const phaseLabel: Record<AuctionStateView['phase'], string> = {
waiting: '경매 준비 중...', waiting: '경매 준비 중...',
presenting: '다음 선수 등장', presenting: '다음 선수 등장',
+17
View File
@@ -0,0 +1,17 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router';
export default function AuthCallbackPage() {
const navigate = useNavigate();
useEffect(() => {
const timer = window.setTimeout(() => navigate('/', { replace: true }), 300);
return () => window.clearTimeout(timer);
}, [navigate]);
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20 text-center">
<span className="text-sm text-base-content/45">로그인 처리 중...</span>
</main>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { useMsal } from '@azure/msal-react';
import {
isMsalConfigured,
MSAL_API_SCOPE,
msalInstance,
} from '../lib/auth/msal.config';
function LoginButton() {
const { instance } = useMsal();
return (
<button
type="button"
className="btn btn-primary btn-sm px-5"
onClick={() => void instance.loginRedirect({ scopes: [MSAL_API_SCOPE] })}
>
Microsoft로 로그인
</button>
);
}
export default function LoginPage() {
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-20">
<div className="max-w-md border border-base-content/10 bg-base-100 p-6 shadow-sm">
<h1 className="text-xl font-bold tracking-tight">로그인</h1>
<p className="mt-2 text-sm text-base-content/50">
Microsoft Entra ID 계정으로 로그인하면 LOLYMPUS 멤버십을 불러옵니다.
</p>
<div className="mt-5">
{isMsalConfigured && msalInstance ? (
<LoginButton />
) : (
<div className="text-sm text-amber-600">
MSAL 환경변수 설정이 필요합니다.
</div>
)}
</div>
</div>
</main>
);
}
+11 -6
View File
@@ -281,6 +281,11 @@ export default function MatchDetailPage() {
const authUserId = useAuthUserId(); const authUserId = useAuthUserId();
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const meQuery = useMe(); const meQuery = useMe();
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null;
const canUseMemberActions = Boolean(currentUser || authUserId);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const [blueCaptainUserId, setBlueCaptainUserId] = useState(''); const [blueCaptainUserId, setBlueCaptainUserId] = useState('');
const [redCaptainUserId, setRedCaptainUserId] = useState(''); const [redCaptainUserId, setRedCaptainUserId] = useState('');
@@ -291,8 +296,8 @@ export default function MatchDetailPage() {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
preferredPositions: preferredPositions:
meQuery.data?.user?.preferredPositions.length currentUser?.preferredPositions.length
? meQuery.data.user.preferredPositions.slice(0, 5) ? currentUser.preferredPositions.slice(0, 5)
: buildDefaultPreferredPositions(), : buildDefaultPreferredPositions(),
}), }),
}), }),
@@ -376,7 +381,7 @@ export default function MatchDetailPage() {
const match = mapApiMatchToMatchDetail(matchQuery.data); const match = mapApiMatchToMatchDetail(matchQuery.data);
const si = statusBadge(match.status); const si = statusBadge(match.status);
const canManageAuction = const canManageAuction =
meQuery.data?.user?.role === 'owner' || meQuery.data?.user?.role === 'admin'; currentUser?.role === 'owner' || currentUser?.role === 'admin';
const auctionNotStarted = const auctionNotStarted =
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
const showAuctionLink = Boolean(auctionQuery.data); const showAuctionLink = Boolean(auctionQuery.data);
@@ -490,7 +495,7 @@ export default function MatchDetailPage() {
participants={match.participants} participants={match.participants}
maxParticipants={match.maxParticipants} maxParticipants={match.maxParticipants}
joined={match.joined} joined={match.joined}
canJoin={Boolean(authUserId)} canJoin={canUseMemberActions}
onJoin={() => joinMatchMutation.mutate()} onJoin={() => joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending} isJoining={joinMatchMutation.isPending}
/> />
@@ -551,9 +556,9 @@ export default function MatchDetailPage() {
> >
{startAuctionMutation.isPending ? '시작 중...' : '경매 시작'} {startAuctionMutation.isPending ? '시작 중...' : '경매 시작'}
</button> </button>
{!authUserId && ( {!canUseMemberActions && (
<span className="text-xs text-amber-600"> <span className="text-xs text-amber-600">
Dev Auth에 owner/admin User ID를 먼저 입력해주세요. 로그인 또는 Dev Auth에 owner/admin User ID를 먼저 입력해주세요.
</span> </span>
)} )}
</div> </div>
File diff suppressed because it is too large. Load diff
+598
View File
@@ -0,0 +1,598 @@
# Microsoft Entra ID OIDC 로그인 도입 플랜
> **대상**: codex 가 이어서 진행 가능한 수준의 실행 플랜
> **레포**: `/Users/dahyeon/source/lolympus-tournament-support` (pnpm workspace)
> **작성 기준**: 2026-04-25
> **선행 상태**: dakao NATS 통합, RiotAccount enrichment(force=true 동기 호출, summoner/league/mastery v4) 1차 구현 완료. 인증은 여전히 `X-Auth-User-Id` 헤더 기반.
---
## 1. Context
현재 인증은 `apps/api/src/modules/auth/auth.middleware.ts` 가 `X-Auth-User-Id` 헤더 (Mongo ObjectId) 를 읽어 User 를 `req.user` 에 붙이는 임시 방식입니다. 프로덕션으로 가려면 진짜 OIDC 로그인이 필요합니다.
다른 프로젝트에서 검증된 `apps/api/src/modules/auth/jwt.guard.ts`, `jwt.service.ts` 를 이식해 **Microsoft Entra ID 단일 IdP** OIDC 인증으로 교체합니다. 결정:
- **Identity 모델**: Top-level `Identity` 컬렉션 신설. User 는 community 별로 유지하되 `identityId` 로 Identity 를 가리킴. 한 Entra 사용자가 여러 community 에 멤버가 되는 모델을 자연스럽게 표현.
- **첫 로그인**: `/me` 가 빈 `memberships` 반환. 자동 멤버십 생성 없음. 프론트가 "커뮤니티 만들기/초대 받기" 분기.
- **프론트엔드 통합**: `@azure/msal-browser` + `@azure/msal-react` 로 같은 변경 묶음에 포함.
- **Dev fallback**: `AUTH_DEV_HEADER_ENABLED=true` + `NODE_ENV !== 'prod'` 일 때만 `X-Auth-User-Id` 헤더 허용.
dakao NATS 경로(카카오 명령) 는 HTTP 미들웨어/가드를 거치지 않으므로 그대로 보존됩니다.
---
## 2. 결정된 설계
### 2.1 `Identity` 컬렉션 (신규)
```ts
// apps/api/src/modules/global/database/schema.ts
export interface Identity extends MongooseTimestamps {
entraOid: string; // Entra 'oid' claim (tenant 내 유일)
tenantId?: string; // 'tid' claim — 다중 테넌트 대비
email?: string; // preferred_username
displayName?: string; // name
lastSignInAt?: Date;
}
export const IdentitySchema = new Schema<Identity>({
entraOid: { type: String, required: true },
tenantId: { type: String },
email: { type: String },
displayName: { type: String },
lastSignInAt: { type: Date },
}, { timestamps: true, collection: 'identity' });
IdentitySchema.index({ entraOid: 1 }, { unique: true });
IdentitySchema.index({ email: 1 });
```
`tournamentModelDefinitions` 에 `{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }` 추가, `TournamentModelTypes` 에 `identity: Identity` 추가.
### 2.2 `User` 변경
```ts
export interface User {
// 기존 필드 유지
identityId?: mongoose.Types.ObjectId;
}
```
스키마/인덱스:
```ts
identityId: { type: Schema.Types.ObjectId, ref: 'identity' },
// ...
UserSchema.index(
{ communityId: 1, identityId: 1 },
{ unique: true, sparse: true },
);
UserSchema.index({ identityId: 1 }, { sparse: true });
```
같은 사람이 한 community 에 두 번 등록되지 못하게 `{ communityId, identityId }` unique sparse. 글로벌 `{ identityId }` 로 한 사람의 모든 멤버십 빠른 조회.
기존 `kakaoTalkId`, `discordId` 인덱스/필드는 유지. dakao 사용자가 추후 Entra 로 로그인하면 같은 community 에서 별도 User 가 생기지 않도록 후속 "계정 연결" 플로우는 별도 작업(이번 범위 외).
### 2.3 인증 파이프라인
```
HTTP Request
└ JwtAuthGuard (verify JWT, req.tokenPayload 채움)
└ IdentityResolverGuard (oid → Identity 조회/upsert, req.identity)
└ (라우트별) UserResolverInterceptor (path :communityId + identityId → req.user)
└ RolesGuard (req.user.role 검증)
```
- `JwtAuthGuard`, `IdentityResolverGuard` 는 `APP_GUARD` 로 글로벌 등록.
- `UserResolverInterceptor` 는 `:communityId` path 파라미터를 가진 community 라우트에 `@UseInterceptors` 로 명시 적용.
- `@AllowPublicAccess()` 메타데이터가 붙은 라우트는 두 글로벌 가드를 통과(JWT 없어도 됨). 토큰이 있으면 `req.identity` 까지는 채워줌(soft auth).
### 2.4 `request` 필드 명세
| 필드 | 타입 | 의미 | 누가 채우나 |
| --- | --- | --- | --- |
| `request.tokenPayload` | `JWTPayload \| undefined` | 검증된 JWT claims | `JwtAuthGuard` |
| `request.identityProvider` | `IdentityProviderName` | 발행자 | `JwtAuthGuard` |
| `request.identity` | `IdentityDocument \| undefined` | DB Identity | `IdentityResolverGuard` |
| `request.user` | `UserDocument \| undefined` | community 멤버십 User | `UserResolverInterceptor` 또는 dev fallback |
기존 `request.user` 시맨틱(UserDocument)을 유지해 `RolesGuard` / `@CurrentUser()` 호환성 보존.
### 2.5 Dev fallback
`JwtAuthGuard` 또는 별도 `AuthDevFallbackMiddleware` 안에서:
```ts
if (
!authzHeader &&
process.env.NODE_ENV !== 'prod' &&
process.env.AUTH_DEV_HEADER_ENABLED === 'true'
) {
const userId = request.headers['x-auth-user-id'];
if (userId && isValidObjectId(userId)) {
const user = await UserModel.findById(userId).exec();
if (user) {
request.user = user;
if (user.identityId) {
request.identity = await IdentityModel.findById(user.identityId).exec();
}
return true;
}
}
}
```
`prod` 에서는 환경변수 무시.
### 2.6 `@AllowPublicAccess()` 적용 라우트
| 라우트 | 이유 |
| --- | --- |
| `RiotWebhookController.captureTournamentWebhook` | 외부 webhook |
| `CommunityController.createCommunity` | 가입 (MVP 호환을 위해 공개 유지하되 토큰이 있으면 token identity 우선) |
| `CommunityController.getCommunity` | 공개 정보 |
| `MatchController.listMatches`, `getMatch` | 공개 읽기 |
| `UserController.getMe` | 토큰 있으면 채워주고 없으면 빈 응답 |
### 2.7 엔드포인트 동작 변경
#### `GET /me`
**Before**: `{ user: UserDocument | null }`
**After**:
```jsonc
{
"identity": {
"id": "...",
"entraOid": "f0e47b9f-00cd-...",
"email": "park@dahyeon.us",
"displayName": "박 다현"
} /* | null */,
"memberships": [
{
"user": { /* UserDocument */ },
"community": { "id": "...", "name": "..." }
}
]
}
```
- 토큰 없이 호출하면 `{ identity: null, memberships: [] }`.
- `memberships` 가 빈 배열이면 프론트는 "community 만들기 / 초대 받기" UI 분기.
#### `POST /communities`
owner 정보를 body 에서 받지 않고 `req.identity` + 새 community 에 owner User 자동 생성. 기존 `CreateCommunityDto.owner` 는 deprecated. dev fallback 시에는 body 도 backward compat 으로 허용.
#### `PATCH /communities/:communityId/...`, `POST /communities/:communityId/matches/...`
`UserResolverInterceptor` 가 path 의 `communityId` + `req.identity._id` 로 User 를 찾아 `req.user` 에 주입. 못 찾으면 `RolesGuard` 가 `ForbiddenException('No membership in this community.')`.
### 2.8 WebSocket (auction gateway)
- 클라이언트: `io('/auction', { auth: { token: <bearer> } })`
- 서버: `handleConnection` 에서 `socket.handshake.auth.token` 을 `JwtService.verify()` 로 검증, identity → user 조회, `socket.data.user` 에 저장.
- dev fallback: `socket.handshake.auth['x-auth-user-id']` 도 dev 환경에서 허용.
- 인증 실패 시 `socket.disconnect(true)`.
### 2.9 프론트엔드 (apps/web)
#### 의존성
```bash
pnpm --filter web add @azure/msal-browser @azure/msal-react
```
#### 환경변수 (`apps/web/.env`, `.env.example`)
- `VITE_MSAL_CLIENT_ID` — Azure App 등록의 Application (client) ID
- `VITE_MSAL_AUTHORITY` — `https://login.microsoftonline.com/<tenantId>`
- `VITE_MSAL_API_SCOPE` — 예: `api://lolympus-api/access_as_user`
- `VITE_MSAL_REDIRECT_URI` — 예: `http://localhost:5173/auth/callback`
#### 신규 파일
- `apps/web/src/lib/auth/msal.config.ts` — `PublicClientApplication` 인스턴스
- `apps/web/src/lib/auth/MsalAppProvider.tsx` — `MsalProvider` 래핑 + redirect 처리
- `apps/web/src/lib/auth/use-access-token.ts` — `acquireTokenSilent → acquireTokenPopup/Redirect` fallback
- `apps/web/src/pages/Login.tsx` — 로그인 진입
- `apps/web/src/pages/AuthCallback.tsx` — redirect 콜백
- `apps/web/src/components/CommunitySwitcher.tsx` — memberships > 1 일 때 active community 선택
#### 수정 파일
- `apps/web/src/main.tsx` — `MsalAppProvider` 로 앱 감싸기
- `apps/web/src/lib/api.ts` — `apiFetch` 가 `acquireTokenSilent` 후 `Authorization: Bearer ...` 첨부, 401 시 재로그인 트리거
- `apps/web/src/lib/socket.ts` (또는 socket 초기화 파일) — `io({ auth: { token } })`
- `apps/web/src/config.ts` — `getAuthUserId/setAuthUserId/useAuthUserId` 는 `import.meta.env.DEV` 분기로 격리
- `apps/web/src/components/DevAuthSwitcher.tsx` — `import.meta.env.DEV` 빌드에서만 렌더
#### `/me` consumer
- `useMe()` 훅 결과 모양 변경 (`{ identity, memberships }`)
- header 의 사용자 표시: `identity.displayName ?? identity.email`
- admin 가시성: `memberships.find(m => m.community.id === activeCommunityId)?.user.role`
### 2.10 Azure App Registration 체크리스트
운영자 작업 (코드 외):
1. App Registration 생성 (single-tenant 권장)
2. Authentication 플랫폼 추가:
- SPA: redirect URI = `http://localhost:5173/auth/callback`, 프로덕션 URL 추가
3. Expose an API:
- Application ID URI = `api://lolympus-api`
- Scope 추가 = `access_as_user`
- Authorized client applications (자기 자신 추가)
4. Token configuration: optional claim `email`, `preferred_username` 활성화
Infisical 시크릿 추가:
- `MICROSOFT_ENTRAID_TENANT_ID`
- `MICROSOFT_ENTRAID_ALLOWED_ALGS=RS256`
- `JWT_CLAIM_AUDIENCE` = Application ID URI
- `AUTH_DEV_HEADER_ENABLED=true` (dev/staging 환경만)
`SecretService.PROCESS_ENVS` 에 `JWT_CLAIM_AUDIENCE`, `MICROSOFT_ENTRAID_TENANT_ID`, `MICROSOFT_ENTRAID_ALLOWED_ALGS`, `AUTH_DEV_HEADER_ENABLED` 추가.
---
## 3. 실행 단계 (codex 진행 순서)
작업 단위는 PR 단위로 쪼갤 수 있도록 분리되어 있습니다.
### Step 1. 스키마 변경
**파일**: `apps/api/src/modules/global/database/schema.ts`
- `Identity` 인터페이스/스키마/인덱스 추가
- `tournamentModelDefinitions` 에 등록, `TournamentModelTypes` 확장
- `User.identityId` optional 필드 + 인덱스 추가
- `UserDocument` / `IdentityDocument` 타입 export
### Step 2. `AllowPublicAccess` 데코레이터
**신규**: `apps/api/src/modules/auth/allow-public-access.decorator.ts`
```ts
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED = 'allow_public_access';
export const AllowPublicAccess = () =>
SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
```
### Step 3. JwtService / JwtAuthGuard 이식
**신규**: `apps/api/src/modules/auth/jwt.service.ts`, `apps/api/src/modules/auth/jwt.guard.ts`
- 다른 프로젝트의 참고 코드를 그대로 이식하되 `import` 경로는 `../global/secret/secret.service` 로 수정
- `jose` 의존성 추가: `pnpm --filter api add jose`
- `JwtAuthGuard` 의 동작 변경: `request.tokenPayload = payload` (기존 `request.user` 가 아닌)
- public access 시 토큰이 있으면 검증 시도, 없으면 그냥 통과 (soft auth)
### Step 4. IdentityService + IdentityResolverGuard
**신규**: `apps/api/src/modules/auth/identity.service.ts`
```ts
@Injectable()
export class IdentityService {
constructor(private readonly connectionService: ConnectionService) {}
async findOrCreateByOid(payload: {
entraOid: string;
tenantId?: string;
email?: string;
displayName?: string;
}): Promise<IdentityDocument> {
const IdentityModel = await this.connectionService.getModel('identity');
return IdentityModel.findOneAndUpdate(
{ entraOid: payload.entraOid },
{
$set: {
email: payload.email,
displayName: payload.displayName,
tenantId: payload.tenantId,
lastSignInAt: new Date(),
},
$setOnInsert: { entraOid: payload.entraOid },
},
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
}
}
```
**신규**: `apps/api/src/modules/auth/identity-resolver.guard.ts`
`request.tokenPayload` 가 있으면 `IdentityService.findOrCreateByOid` 호출해 `request.identity` 채움. public 라우트에서도 토큰 있으면 채워줌.
### Step 5. UserResolverInterceptor
**신규**: `apps/api/src/modules/auth/user-resolver.interceptor.ts`
```ts
@Injectable()
export class UserResolverInterceptor implements NestInterceptor {
constructor(private readonly connectionService: ConnectionService) {}
async intercept(ctx: ExecutionContext, next: CallHandler) {
const req = ctx.switchToHttp().getRequest();
const communityId = req.params?.communityId;
if (req.identity && communityId && isValidObjectId(communityId)) {
const UserModel = await this.connectionService.getModel('user');
req.user = await UserModel.findOne({
communityId: new mongoose.Types.ObjectId(communityId),
identityId: req.identity._id,
}).exec();
}
return next.handle();
}
}
```
community 라우트 controller 들 (Match, Auction, Community 의 `:communityId` 라우트) 에 `@UseInterceptors(UserResolverInterceptor)` 적용.
### Step 6. AuthModule 재구성
**파일**: `apps/api/src/modules/auth/auth.module.ts`
```ts
@Global()
@Module({
imports: [SecretModule],
providers: [
JwtService,
JwtAuthGuard,
IdentityService,
IdentityResolverGuard,
UserResolverInterceptor,
AuthService, // dev fallback 전용으로 축소
RolesGuard,
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
],
exports: [JwtService, IdentityService, RolesGuard, UserResolverInterceptor],
})
export class AuthModule {}
```
### Step 7. AuthMiddleware → AuthService dev fallback 으로 축소
**파일**: `apps/api/src/modules/auth/auth.middleware.ts`, `auth.service.ts`
- `AuthModule.configure` 에서 글로벌 미들웨어 등록 제거
- `auth.service.ts` 는 dev fallback 메서드만 노출. `JwtAuthGuard` 내부에서 호출하거나 별도 미들웨어로 dev only 등록
### Step 8. RolesGuard 호환 보강
**파일**: `apps/api/src/modules/auth/roles.guard.ts`
- 동작 그대로. `req.user` 가 `UserDocument` 면 OK
- `request.identity` 만 있고 `request.user` 가 없을 때 메시지: `ForbiddenException('No membership in this community.')`
### Step 9. `/me` 엔드포인트 변경
**파일**: `apps/api/src/modules/user/user.controller.ts`, `apps/api/src/modules/user/dto/me-response.dto.ts` (신규)
```ts
@Get('me')
@AllowPublicAccess()
async getMe(@Req() req): Promise<MeResponse> {
if (!req.identity) return { identity: null, memberships: [] };
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const users = await UserModel.find({ identityId: req.identity._id }).exec();
const communities = await CommunityModel.find({
_id: { $in: users.map((u) => u.communityId) },
}).exec();
return {
identity: serializeIdentity(req.identity),
memberships: users.map((u) => ({
user: u,
community: communities.find((c) => c._id.equals(u.communityId)),
})),
};
}
```
`@CurrentIdentity()` 데코레이터 추가 시 `req.identity` 직접 주입 가능.
### Step 10. Community 생성 흐름
**파일**: `apps/api/src/modules/community/community.controller.ts`, `community.service.ts`, `dto/create-community.dto.ts`
- `createCommunity` 가 `req.identity` 가 있으면 owner User 의 `identityId` 자동 설정
- body 의 `owner` 필드는 dev fallback / backward compat 으로만 사용
### Step 11. Public access 라우트 표시
위 §2.6 표의 라우트들에 `@AllowPublicAccess()` 추가.
### Step 12. WebSocket 인증
**파일**: `apps/api/src/modules/auction/auction.gateway.ts`
- `handleConnection` 에서 token → identity → user 조회
- 실패 시 `client.disconnect(true)`
- dev fallback: `socket.handshake.auth['x-auth-user-id']` 도 dev 환경에서 허용
### Step 13. SecretService 확장
**파일**: `apps/api/src/modules/global/secret/secret.service.ts`
`PROCESS_ENVS` 에 추가:
- `JWT_CLAIM_AUDIENCE`
- `MICROSOFT_ENTRAID_TENANT_ID`
- `MICROSOFT_ENTRAID_ALLOWED_ALGS`
- `AUTH_DEV_HEADER_ENABLED`
### Step 14. 백엔드 단위 테스트
**신규 spec**:
- `auth/jwt.service.spec.ts` — issuer/audience/tenant/alg 검증, 잘못된 토큰 거부
- `auth/jwt.guard.spec.ts` — public access 통과, missing/invalid bearer 거부
- `auth/identity.service.spec.ts` — findOrCreateByOid upsert 동작
- `auth/identity-resolver.guard.spec.ts` — tokenPayload → identity 매핑
- `auth/user-resolver.interceptor.spec.ts` — path communityId + identityId 매칭
- `auth/dev-fallback.spec.ts` — 환경변수 OFF 시 차단, ON 시 동작
### Step 15. 프론트엔드 MSAL 통합
위 §2.9 의 신규/수정 파일들. `apiFetch` 의 token 첨부 흐름:
```ts
const token = await acquireAccessToken(); // silent → popup/redirect fallback
return fetch(url, {
...init,
headers: {
...init?.headers,
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
```
401 응답 시 토큰 캐시 invalidate 후 1회 재시도, 그래도 실패면 `/login` redirect.
WebSocket 초기화:
```ts
const socket = io('/auction', {
auth: { token: await acquireAccessToken() },
});
```
### Step 16. 회귀 / 통합 검증
- `pnpm --filter api exec tsc --noEmit` 통과
- `pnpm --filter api exec jest` 전체 PASS
- 로컬에서 Entra 로그인 → JWT 생성 → API 호출 → `/me` 가 identity 반환
- dakao `!내전 신청 ...` 시나리오 → 여전히 동작 (HTTP 인증과 무관)
- dev fallback: `AUTH_DEV_HEADER_ENABLED=true` + `X-Auth-User-Id` 헤더 → 200 OK / `=false` → 401
- Azure App 등록 후 `JWT_CLAIM_AUDIENCE` 시크릿 일치 확인
- `pnpm --filter web build` 통과, `/login` → 콜백 → memberships 분기
---
## 4. 변경/추가 파일 목록
### 신규 (백엔드)
- `apps/api/src/modules/auth/allow-public-access.decorator.ts`
- `apps/api/src/modules/auth/jwt.service.ts`
- `apps/api/src/modules/auth/jwt.guard.ts`
- `apps/api/src/modules/auth/identity.service.ts`
- `apps/api/src/modules/auth/identity-resolver.guard.ts`
- `apps/api/src/modules/auth/user-resolver.interceptor.ts`
- `apps/api/src/modules/auth/current-identity.decorator.ts`
- `apps/api/src/modules/auth/jwt.service.spec.ts`
- `apps/api/src/modules/auth/jwt.guard.spec.ts`
- `apps/api/src/modules/auth/identity.service.spec.ts`
- `apps/api/src/modules/auth/identity-resolver.guard.spec.ts`
- `apps/api/src/modules/auth/user-resolver.interceptor.spec.ts`
- `apps/api/src/modules/auth/dev-fallback.spec.ts`
- `apps/api/src/modules/user/dto/me-response.dto.ts`
### 수정 (백엔드)
- `apps/api/src/modules/global/database/schema.ts` — Identity 추가, User.identityId
- `apps/api/src/modules/auth/auth.module.ts` — APP_GUARD 등록, providers 재구성
- `apps/api/src/modules/auth/auth.service.ts` — dev fallback 전용 축소
- `apps/api/src/modules/auth/auth.middleware.ts` — 제거 또는 dev only 축소
- `apps/api/src/modules/auth/roles.guard.ts` — 에러 메시지 보강
- `apps/api/src/modules/auth/current-user.decorator.ts` — 그대로 (호환 유지)
- `apps/api/src/modules/user/user.controller.ts` — `/me` 응답 모양 변경
- `apps/api/src/modules/community/community.controller.ts` — `@AllowPublicAccess`, owner 자동 연결
- `apps/api/src/modules/community/community.service.ts` — owner 생성 시 identityId 연결
- `apps/api/src/modules/community/dto/create-community.dto.ts` — owner 필드 deprecated
- `apps/api/src/modules/match/match.controller.ts` — `@AllowPublicAccess` (read), `@UseInterceptors(UserResolverInterceptor)` (write)
- `apps/api/src/modules/auction/auction.controller.ts` — interceptor 적용
- `apps/api/src/modules/auction/auction.gateway.ts` — JWT handshake 검증
- `apps/api/src/modules/riot/riot-webhook.controller.ts` — `@AllowPublicAccess`
- `apps/api/src/modules/global/secret/secret.service.ts` — PROCESS_ENVS 확장
### 의존성 (백엔드)
- `pnpm --filter api add jose`
### 신규 (프론트엔드)
- `apps/web/src/lib/auth/msal.config.ts`
- `apps/web/src/lib/auth/MsalAppProvider.tsx`
- `apps/web/src/lib/auth/use-access-token.ts`
- `apps/web/src/pages/Login.tsx`
- `apps/web/src/pages/AuthCallback.tsx`
- `apps/web/src/components/CommunitySwitcher.tsx`
### 수정 (프론트엔드)
- `apps/web/src/main.tsx`
- `apps/web/src/lib/api.ts`
- `apps/web/src/lib/socket.ts` (또는 해당 socket 초기화 파일)
- `apps/web/src/config.ts`
- `apps/web/src/components/DevAuthSwitcher.tsx`
- `apps/web/.env.example`
### 의존성 (프론트엔드)
- `pnpm --filter web add @azure/msal-browser @azure/msal-react`
### 인프라 / 시크릿
- Azure App Registration (SPA platform, expose API, scope `access_as_user`)
- Infisical: `MICROSOFT_ENTRAID_TENANT_ID`, `MICROSOFT_ENTRAID_ALLOWED_ALGS`, `JWT_CLAIM_AUDIENCE`, `AUTH_DEV_HEADER_ENABLED`(dev 만)
- Frontend env: `VITE_MSAL_CLIENT_ID`, `VITE_MSAL_AUTHORITY`, `VITE_MSAL_API_SCOPE`, `VITE_MSAL_REDIRECT_URI`
---
## 5. 기존 파일 / 함수 재사용 매핑
| 신규 작업 | 재사용 대상 | 경로 |
| --- | --- | --- |
| JwtService / JwtGuard 본체 | 다른 프로젝트 참고 파일 | `apps/api/src/modules/auth/jwt.service.ts`, `jwt.guard.ts` |
| 시크릿 로딩 | `SecretService.get` / `ready` | `apps/api/src/modules/global/secret/secret.service.ts` |
| Mongo 모델 액세스 | `ConnectionService.getModel` | `apps/api/src/modules/global/database/connection.service.ts` |
| 현재 user 데코레이터 | `CurrentUser` (그대로 호환) | `apps/api/src/modules/auth/current-user.decorator.ts` |
| 권한 매핑 | `permissions.ts`, `roles.guard.ts`, `roles.decorator.ts` | `apps/api/src/modules/auth/` |
| ObjectId 검증 | `ParseObjectIdPipe`, `mongoose.isValidObjectId` | `apps/api/src/modules/common/parse-object-id.pipe.ts` |
---
## 6. 검증 (end-to-end)
### 백엔드
1. `pnpm --filter api exec tsc --noEmit`
2. `pnpm --filter api exec jest`
3. dev 환경 부팅 후:
- `curl -H "X-Auth-User-Id: <id>" http://localhost:3000/me` → `AUTH_DEV_HEADER_ENABLED=true` 일 때 200, `=false` 일 때 401
- 실제 Entra access token 으로 `Authorization: Bearer ...` 호출 → 200, identity 채워짐
- `Authorization` 누락 + dev fallback 비활성 + 보호 라우트 → 401
- `Authorization` 정상 + community path 의 멤버 아님 → 403 `No membership in this community.`
4. dakao 시나리오: `!내전 신청 ...` 메시지 publish → 변동 없이 동작 확인
### 프론트엔드
1. `pnpm --filter web build` 통과
2. `pnpm --filter web dev` 후:
- `/login` → Entra 로그인 → 콜백 → `/me` 호출 성공
- memberships 빈 배열 → "커뮤니티 만들기/초대 받기" 분기 표시
- 보호된 페이지(매치 관리) 진입 시 토큰 자동 첨부
- 토큰 만료 시 silent refresh → 실패 시 재로그인 redirect
- WebSocket(/auction) 연결 시 핸드셰이크에 토큰 포함, 인증 실패면 disconnect
---
## 7. 범위 외 (다음 작업으로 미룸)
- dakao 사용자 ↔ Entra identity 자동/수동 연결 플로우
- `createCommunity` 강제 인증 + invitation token 기반 멤버 가입
- 다중 테넌트 지원 (`tid` 동적 분기)
- Cognito 등 추가 IdP
- Refresh token 백엔드 처리 (현재 stateless)
- Audit log (로그인/identity 변경 이벤트 기록)
+2
View File
@@ -5,6 +5,8 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start:api:dev": "pnpm --filter api start:dev", "start:api:dev": "pnpm --filter api start:dev",
"start:api:test": "pnpm --filter api start:test",
"start:api:prod": "pnpm --filter api start:prod",
"start:api": "pnpm --filter api start:prod", "start:api": "pnpm --filter api start:prod",
"build:api": "pnpm --filter api build", "build:api": "pnpm --filter api build",
"dev:web": "pnpm --filter web dev", "dev:web": "pnpm --filter web dev",
+40
View File
@@ -41,6 +41,9 @@ importers:
class-validator: class-validator:
specifier: ^0.15.1 specifier: ^0.15.1
version: 0.15.1 version: 0.15.1
jose:
specifier: ^6.2.2
version: 6.2.2
mongoose: mongoose:
specifier: ^9.4.1 specifier: ^9.4.1
version: 9.4.1(@aws-sdk/credential-providers@3.993.0) version: 9.4.1(@aws-sdk/credential-providers@3.993.0)
@@ -132,6 +135,12 @@ importers:
apps/web: apps/web:
dependencies: dependencies:
'@azure/msal-browser':
specifier: ^5.8.0
version: 5.8.0
'@azure/msal-react':
specifier: ^5.3.1
version: 5.3.1(@azure/msal-browser@5.8.0)(react@19.2.5)
'@tanstack/react-query': '@tanstack/react-query':
specifier: ^5.100.1 specifier: ^5.100.1
version: 5.100.1(react@19.2.5) version: 5.100.1(react@19.2.5)
@@ -356,6 +365,21 @@ packages:
resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==} resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==}
engines: {node: '>=18.0.0'} engines: {node: '>=18.0.0'}
'@azure/msal-browser@5.8.0':
resolution: {integrity: sha512-X7IZV77bN56l7sbLjkcbQJX1t3U4tgxqztDr/XFbUcUfKk+z2FavcLgKP+OYUNj0wl/pEEtV9lldW9siY8BuHQ==}
engines: {node: '>=0.8.0'}
'@azure/msal-common@16.5.1':
resolution: {integrity: sha512-WS9w9SfI8SEYO7mTnxGeZ3UwQfhAVYCWglYF2/7GNx3ioHiAs2gPkl9eSwVs8cPrmiGh+zi9ai/OOKoq4cyzDw==}
engines: {node: '>=0.8.0'}
'@azure/msal-react@5.3.1':
resolution: {integrity: sha512-yR6BFVPyufFDg9qmtCxqpqMH3axxz/9hBL5ZO7zqMH9X9dZvjhcuAO5BL6zhS33VVPpNEZhJflU0LW1NHI2lIw==}
engines: {node: '>=20'}
peerDependencies:
'@azure/msal-browser': ^5.8.0
react: ^16.8.0 || ^17 || ^18 || ^19.2.1
'@babel/code-frame@7.29.0': '@babel/code-frame@7.29.0':
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
engines: {node: '>=6.9.0'} engines: {node: '>=6.9.0'}
@@ -2861,6 +2885,9 @@ packages:
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true hasBin: true
jose@6.2.2:
resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==}
js-tokens@4.0.0: js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -4538,6 +4565,17 @@ snapshots:
'@aws/lambda-invoke-store@0.2.4': {} '@aws/lambda-invoke-store@0.2.4': {}
'@azure/msal-browser@5.8.0':
dependencies:
'@azure/msal-common': 16.5.1
'@azure/msal-common@16.5.1': {}
'@azure/msal-react@5.3.1(@azure/msal-browser@5.8.0)(react@19.2.5)':
dependencies:
'@azure/msal-browser': 5.8.0
react: 19.2.5
'@babel/code-frame@7.29.0': '@babel/code-frame@7.29.0':
dependencies: dependencies:
'@babel/helper-validator-identifier': 7.28.5 '@babel/helper-validator-identifier': 7.28.5
@@ -7574,6 +7612,8 @@ snapshots:
jiti@2.6.1: {} jiti@2.6.1: {}
jose@6.2.2: {}
js-tokens@4.0.0: {} js-tokens@4.0.0: {}
js-yaml@3.14.2: js-yaml@3.14.2:
+6
View File
@@ -0,0 +1,6 @@
{
"puuid": "IuAfAe5If2LWCBULfotm1Zyq0XGD5vw5ERIMK743eHYZ1tMAKbhQCRQHYQ0h3J74VpIt-PNeAyKetQ",
"profileIconId": 588,
"revisionDate": 1776977597000,
"summonerLevel": 529
}