3D 리플레이 무기 스킨: 뽑아 둔 스킨이면 3인칭 손의 총 · 1인칭 총을 그 모델로 (없거나 못 받으면 기본 총), 없는 스킨은 POST /site/maps3d/skins/want 로 요청 (기본 스킨 · 실패한 것 제외) · 서버 GET /site/maps3d/skins · want.json (형식 검사 · 중복 제거 · 다른 사이트 요청 막음 · 최대 2000) · 목 서버 · 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-20 22:28:13 +09:00
parent 0da993928e
commit 200dbceece
10 changed files with 294 additions and 18 deletions

View File

@@ -368,7 +368,7 @@ export async function buildServer(
});
// ------------------------------------------------------------------ 발로란트 맵 3D (로그인 필요)
registerMaps3d(app, cfg.dataDir, requireSession);
registerMaps3d(app, cfg.dataDir, requireSession, cfg.publicUrl);
app.get('/healthz', async () => 'ok\n');

View File

@@ -13,6 +13,13 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
*
* GET /site/maps3d → index.json (없으면 {maps:{}})
* GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
*
* 무기 스킨 (본 것만 뽑는다, tools/map-extract/scripts/skins-update.sh 가 몇 분마다 요청을 가져가 뽑아 올린다):
* <dataDir>/maps3d/skins/index.json {skins:{"스킨|단계|색상":{weapon, sig}}, looks:{서명:{w3p, points, w1p, points1p, gunClips}}, failed:{열쇠:이유}}
* <dataDir>/maps3d/skins/skin3p_<서명>.glb.gz · skin1p_<서명>.glb.gz (파일 이름이 모습마다 달라 오래 캐시한다)
* <dataDir>/maps3d/skins/want.json 사이트가 받은 요청 (아직 없는 열쇠, 시간 순 · 최대 MAX_WANT)
* GET /site/maps3d/skins → skins/index.json (없으면 빈 목록)
* POST /site/maps3d/skins/want {keys:[열쇠]} → 없는 것만 want.json 에 더한다
*/
export interface Maps3dIndex {
version: string;
@@ -24,7 +31,40 @@ export interface Maps3dIndex {
/** 보내는 파일 종류: 3D (맵 · 요원 · 무기 · 스킬 모델 · 공용 애니메이션) · 스킬 목록 · 스킬 텍스처 */
const TYPES: Record<string, string> = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' };
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>) {
/** 스킨 요청 열쇠 "스킨|단계|색상" (게임 데이터 에셋 경로, 단계 · 색상은 비어도 된다). 추출기 Skins.ValidKey 와 같다 */
const SKIN_KEY = /^\/Game\/Equippables\/[A-Za-z0-9_/-]+\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?$/;
export const isSkinKey = (k: unknown): k is string => typeof k === 'string' && k.length < 600 && SKIN_KEY.test(k);
const MAX_WANT = 2000;
const MAX_WANT_PER_REQUEST = 100;
/** JSON 파일을 mtime 이 바뀔 때만 다시 읽는다 (없거나 깨졌으면 null) */
function jsonFile<T>(file: string): () => T | null {
let cache: { mtime: number; data: T | null } = { mtime: -1, data: null };
return () => {
let st: fs.Stats;
try {
st = fs.statSync(file);
} catch {
return null;
}
if (st.mtimeMs !== cache.mtime) {
try {
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(file, 'utf8')) as T };
} catch {
cache = { mtime: st.mtimeMs, data: null };
}
}
return cache.data;
};
}
export interface SkinsIndex {
skins: Record<string, { weapon: string; sig: string }>;
looks: Record<string, { w3p?: string; points?: Record<string, number[]>; w1p?: string; points1p?: Record<string, number[]>; gunClips?: string[] }>;
failed?: Record<string, string>;
}
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>, publicUrl?: string) {
const root = path.join(dataDir, 'maps3d');
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
const index = (): Maps3dIndex | null => {
@@ -51,6 +91,39 @@ export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSes
return index() ?? { version: null, dir: null, maps: {} };
});
const skinsDir = path.join(root, 'skins');
const skins = jsonFile<SkinsIndex>(path.join(skinsDir, 'index.json'));
app.get('/site/maps3d/skins', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
reply.header('cache-control', 'private, no-cache');
return skins() ?? { skins: {}, looks: {} };
});
app.post<{ Body: { keys?: unknown } }>('/site/maps3d/skins/want', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
const origin = String(req.headers.origin || '');
if (origin && publicUrl && origin !== publicUrl) return reply.code(403).send({ error: 'bad_origin' });
const keys = Array.isArray(req.body?.keys) ? req.body.keys.slice(0, MAX_WANT_PER_REQUEST).filter(isSkinKey) : [];
const idx = skins();
const file = path.join(skinsDir, 'want.json');
let want: string[] = [];
try {
const w = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
if (Array.isArray(w)) want = w.filter(isSkinKey);
} catch {
/* 처음이거나 깨졌으면 새로 */
}
const have = new Set(want);
const add = [...new Set(keys)].filter((k) => !have.has(k) && !idx?.skins?.[k] && !idx?.failed?.[k]);
if (add.length === 0) return { queued: 0 };
// 다 뽑은 것은 뺀다 (뽑는 쪽은 이 파일을 읽기만 한다)
want = [...want.filter((k) => !idx?.skins?.[k] && !idx?.failed?.[k]), ...add].slice(-MAX_WANT);
fs.mkdirSync(skinsDir, { recursive: true });
fs.writeFileSync(file + '.tmp', JSON.stringify(want));
fs.renameSync(file + '.tmp', file);
req.log.info({ area: 'skins', add: add.length, total: want.length }, '무기 스킨 요청');
return { queued: add.length };
});
app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => {
if (!(await requireSession(req, reply))) return;
const { dir, file } = req.params;

View File

@@ -51,7 +51,7 @@ async function stack() {
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!;
};
return { base, store, login, close: async () => (await app.close(), dc.close()) };
return { base, store, login, dataDir: cfg.dataDir, close: async () => (await app.close(), dc.close()) };
}
test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => {
@@ -91,3 +91,39 @@ test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경
await s.close();
}
});
test('무기 스킨: 목록 · 파일은 로그인한 사람만, 요청은 없는 것만 want.json 에 쌓인다', async () => {
const s = await stack();
try {
const sk = path.join(s.dataDir, 'maps3d', 'skins');
fs.mkdirSync(sk, { recursive: true });
const have = '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset||';
const bad = '/Game/Equippables/Melee/Broken/Melee_Broken_PrimaryAsset||';
fs.writeFileSync(path.join(sk, 'index.json'), JSON.stringify({ skins: { [have]: { weapon: 'Vandal', sig: 'abc' } }, looks: { abc: { w3p: 'skin3p_abc.glb' } }, failed: { [bad]: '메시 없음' } }));
fs.writeFileSync(path.join(sk, 'skin3p_abc.glb.gz'), zlib.gzipSync(Buffer.from('skin')));
assert.equal((await fetch(s.base + '/site/maps3d/skins')).status, 401);
assert.equal((await fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"keys":[]}' })).status, 401);
const cookie = await s.login();
const idx = (await (await fetch(s.base + '/site/maps3d/skins', { headers: { cookie } })).json()) as any;
assert.equal(idx.skins[have].sig, 'abc');
const f = await fetch(s.base + '/site/maps3d/skins/skin3p_abc.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(f.status, 200);
assert.equal(await f.text(), 'skin');
const want = (keys: unknown[], origin?: string) =>
fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { cookie, 'content-type': 'application/json', ...(origin ? { origin } : {}) }, body: JSON.stringify({ keys }) });
const k1 = '/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Carbine_SpecOps_PrimaryAsset|/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Levels/Carbine_SpecOps_Lv2_PrimaryAsset|';
// 이미 있는 것 · 실패한 것 · 형식이 틀린 것은 넣지 않는다
const r = await want([k1, have, bad, '../../etc/passwd||', 7, k1]);
assert.equal(r.status, 200);
assert.deepEqual(await r.json(), { queued: 1 });
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
// 같은 것을 다시 요청하면 그대로
assert.deepEqual(await (await want([k1])).json(), { queued: 0 });
// 다른 사이트에서 온 요청은 막는다
assert.equal((await want([k1.replace('Lv2', 'Lv3')], 'https://evil.example')).status, 403);
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
} finally {
await s.close();
}
});

View File

@@ -0,0 +1,48 @@
// 사이트 3D 리플레이: 무기 스킨 찾기 (site/web/src/lib/skins.ts · replay.ts skinTracks)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { equipAt, skinTracks, type ReplayFile, type SkinInfo } from '../../web/src/lib/replay.ts';
import { isDefaultSkin, lookOf, missingSkins, skinKey } from '../../web/src/lib/skins.ts';
const hype: SkinInfo = {
skin: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset',
level: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_Lv4_PrimaryAsset',
chroma: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/Chromas/Blue/AssaultRifle_AK_HypeBeast_Blue_PrimaryAsset',
};
const knife: SkinInfo = { skin: '/Game/Equippables/Melee/Standard/Melee_Base_Standard_PrimaryAsset', level: null, chroma: '/Game/Equippables/Melee/Standard/Chromas/Standard/Melee_Base_Standard_Standard_PrimaryAsset' };
const ghost: SkinInfo = { skin: '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset', level: null, chroma: null };
test('스킨: 선수가 그 시각에 든 총의 스킨 (주운 총은 그 총의 스킨, 옛 JSON 은 -1)', () => {
const r = {
players: [{}, {}],
skins: [hype, ghost],
// 선수 0: 1초 밴달(hype) · 5초 칼(스킨 기록 없음) · 9초 주운 고스트. 선수 1: 옛 3열 줄
equips: [[1000, 0, 0, 0], [5000, 0, 1, -1], [9000, 0, 2, 1], [2000, 1, 0]],
} as unknown as ReplayFile;
const tr = skinTracks(r);
assert.equal(equipAt(tr[0], 500), -1);
assert.equal(equipAt(tr[0], 3000), 0);
assert.equal(equipAt(tr[0], 6000), -1);
assert.equal(equipAt(tr[0], 9500), 1);
assert.equal(equipAt(tr[1], 3000), -1);
});
test('스킨: 뽑아 둔 것은 그 모습, 기본 스킨 · 없는 것은 null, 없는 것만 요청 목록에', () => {
assert.equal(isDefaultSkin(knife), true);
assert.equal(isDefaultSkin(hype), false);
assert.equal(isDefaultSkin({ skin: '/Game/Equippables/Guns/Sidearms/Compact/Compact_Standard_PrimaryAsset', level: null, chroma: null }), true);
const idx = {
skins: { [skinKey(hype)]: { weapon: 'Vandal', sig: 's1' } },
looks: { s1: { w3p: 'skin3p_s1.glb', w1p: 'skin1p_s1.glb' } },
failed: {} as Record<string, string>,
};
assert.equal(lookOf(idx, hype)?.w3p, 'skin3p_s1.glb');
assert.equal(lookOf(idx, ghost), null);
assert.equal(lookOf(idx, knife), null);
// 같은 스킨이 여러 번 나와도 한 번, 기본 스킨은 요청하지 않는다
assert.deepEqual(missingSkins(idx, { skins: [hype, ghost, knife, { ...ghost }] }), [skinKey(ghost)]);
// 뽑다 실패한 것은 다시 요청하지 않는다
idx.failed[skinKey(ghost)] = '메시 없음';
assert.deepEqual(missingSkins(idx, { skins: [ghost] }), []);
assert.equal(skinKey(ghost), '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset||');
});