Files
game_voice_recorder/site/server/test/maps3d.test.ts

130 lines
7.7 KiB
TypeScript

// 맵 3D (/site/maps3d): 로그인한 사람에게만, gzip 그대로 보낸다
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-maps3d-'));
// member1 은 111 서버에만 있다. 222 서버 이름은 "앱 서버"
async function fakeDiscord() {
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at' }));
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null }));
if (u.pathname === '/guilds/111/members/member1') return res.end(JSON.stringify({ nick: '멤버', avatar: null }));
if (u.pathname === '/guilds/222') return res.end(JSON.stringify({ id: '222', name: '앱 서버' }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
};
// 올려 둔 맵 3D (update.sh 가 만드는 모양)
const dir = path.join(cfg.dataDir, 'maps3d', 'V1-1');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'Ascent.glb.gz'), zlib.gzipSync(Buffer.from('glTF-test')));
fs.writeFileSync(path.join(dir, 'abilities.json.gz'), zlib.gzipSync(Buffer.from('{"classes":{}}')));
fs.writeFileSync(path.join(dir, 't_Smoke.png.gz'), zlib.gzipSync(Buffer.from('png-test')));
fs.writeFileSync(path.join(dir, 'secret.txt.gz'), zlib.gzipSync(Buffer.from('no')));
fs.writeFileSync(path.join(cfg.dataDir, 'maps3d', 'index.json'), JSON.stringify({ version: 'V1', dir: 'V1-1', updatedAt: 'x', maps: { '/Game/Maps/Ascent/Ascent': { code: 'Ascent', file: 'Ascent.glb', bytes: 1, triangles: 1 } } }));
const { app, store } = await buildServer(cfg);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const login = async () => {
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
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, dataDir: cfg.dataDir, close: async () => (await app.close(), dc.close()) };
}
test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => {
const s = await stack();
try {
assert.equal((await fetch(s.base + '/site/maps3d')).status, 401);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb')).status, 401);
} finally {
await s.close();
}
});
test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경로는 404', async () => {
const s = await stack();
try {
const cookie = await s.login();
const idx = (await (await fetch(s.base + '/site/maps3d', { headers: { cookie } })).json()) as any;
assert.equal(idx.dir, 'V1-1');
assert.ok(idx.maps['/Game/Maps/Ascent/Ascent']);
const r = await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(r.status, 200);
assert.equal(r.headers.get('content-encoding'), 'gzip');
assert.equal(await r.text(), 'glTF-test'); // fetch 가 gzip 을 풀어 준다
// 스킬 목록 · 텍스처도 같은 폴더에서 (gzip, 종류에 맞는 content-type)
const j = await fetch(s.base + '/site/maps3d/V1-1/abilities.json', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(j.status, 200);
assert.match(j.headers.get('content-type') ?? '', /application\/json/);
assert.deepEqual(await j.json(), { classes: {} });
const t = await fetch(s.base + '/site/maps3d/V1-1/t_Smoke.png', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(t.status, 200);
assert.equal(t.headers.get('content-type'), 'image/png');
// 정해진 종류(glb · json · png · jpg)가 아니면 404
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/secret.txt', { headers: { cookie } })).status, 404);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/..%2Findex.json', { headers: { cookie } })).status, 404);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Nope.glb', { headers: { cookie } })).status, 404);
} finally {
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();
}
});