서버: Cloudflare Workers 멀티플레이 백엔드 (Phase 4~6 서버 측)

- 게스트/이메일/Google 계정, 게스트 기록 이전, 닉네임 정책
- GameRoomDO: 커스텀 1:1·FFA, 가비지 중계·배율·장기전, 타겟팅, KO, 재접속 유예, 리매치 투표
- MatchmakerDO + Glicko-2 + TR/18랭크 + 리그 결과 기록
- 리더보드·솔로 기록·시즌/RD 감쇠 Cron
- 단위 테스트 17개 + 종단 테스트 스크립트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 09:27:15 +09:00
parent 845969297e
commit 8fcef8e720
18 changed files with 3558 additions and 0 deletions

99
server/src/auth.js Normal file
View File

@@ -0,0 +1,99 @@
// 세션 토큰(HMAC), 비밀번호(PBKDF2), Google ID 토큰 검증. WebCrypto 만 사용.
import { PBKDF2_ITER, TOKEN_TTL_MS } from "./rules.js";
const enc = new TextEncoder();
export function b64url(bytes) {
let s = "";
for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
export function unb64url(s) {
s = s.replace(/-/g, "+").replace(/_/g, "/");
while (s.length % 4) s += "=";
const bin = atob(s);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
async function hmacKey(secret) {
return crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
}
/** 토큰 = base64url(JSON{uid, exp}) + "." + base64url(HMAC). */
export async function signToken(secret, uid, now = Date.now()) {
const body = b64url(enc.encode(JSON.stringify({ uid, exp: now + TOKEN_TTL_MS })));
const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), enc.encode(body));
return `${body}.${b64url(sig)}`;
}
export async function verifyToken(secret, token, now = Date.now()) {
if (typeof token !== "string") return null;
const [body, sig] = token.split(".");
if (!body || !sig) return null;
let ok = false;
try {
ok = await crypto.subtle.verify("HMAC", await hmacKey(secret), unb64url(sig), enc.encode(body));
} catch {
return null;
}
if (!ok) return null;
try {
const p = JSON.parse(new TextDecoder().decode(unb64url(body)));
if (typeof p.uid !== "string" || typeof p.exp !== "number" || p.exp < now) return null;
return p;
} catch {
return null;
}
}
export async function hashPassword(password, saltB64 = null) {
const salt = saltB64 ? unb64url(saltB64) : crypto.getRandomValues(new Uint8Array(16));
const key = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations: PBKDF2_ITER }, key, 256);
return { hash: b64url(bits), salt: b64url(salt) };
}
export function timingSafeEqual(a, b) {
if (a.length !== b.length) return false;
let d = 0;
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
return d === 0;
}
// ── Google ID 토큰 (RS256) ──
let jwksCache = { at: 0, keys: [] };
async function googleKeys(fetchFn = fetch) {
if (Date.now() - jwksCache.at < 3600_000 && jwksCache.keys.length) return jwksCache.keys;
const res = await fetchFn("https://www.googleapis.com/oauth2/v3/certs");
const { keys } = await res.json();
jwksCache = { at: Date.now(), keys };
return keys;
}
/** 검증되면 payload({sub, email, …}), 아니면 null. audiences = 허용할 OAuth 클라이언트 ID 목록. */
export async function verifyGoogleIdToken(idToken, audiences, fetchFn = fetch) {
if (!idToken || !audiences.length) return null;
const parts = idToken.split(".");
if (parts.length !== 3) return null;
let header, payload;
try {
header = JSON.parse(new TextDecoder().decode(unb64url(parts[0])));
payload = JSON.parse(new TextDecoder().decode(unb64url(parts[1])));
} catch {
return null;
}
if (header.alg !== "RS256") return null;
const jwk = (await googleKeys(fetchFn)).find((k) => k.kid === header.kid);
if (!jwk) return null;
const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
const ok = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, unb64url(parts[2]), enc.encode(`${parts[0]}.${parts[1]}`));
if (!ok) return null;
const now = Date.now() / 1000;
if (!["accounts.google.com", "https://accounts.google.com"].includes(payload.iss)) return null;
if (!audiences.includes(payload.aud)) return null;
if (typeof payload.exp !== "number" || payload.exp < now) return null;
if (!payload.sub) return null;
return payload;
}

162
server/src/db.js Normal file
View File

@@ -0,0 +1,162 @@
// D1 접근 헬퍼. Worker 와 DO 가 공유한다.
import { glickoUpdate } from "./glicko.js";
import {
GLICKO, PLACEMENT_GAMES, RANK_VISIBLE_RD, RD_DECAY_IDLE_DAYS, RD_DECAY_PER_DAY, SEASON_LENGTH_DAYS,
rankFor, trFor,
} from "./rules.js";
const DAY = 24 * 3600 * 1000;
export async function getSeason(db, now = Date.now()) {
const row = await db.prepare("SELECT value FROM meta WHERE key = 'season'").first();
if (row) return JSON.parse(row.value);
const s = { n: 1, startedAt: now, endsAt: now + SEASON_LENGTH_DAYS * DAY };
await db.prepare("INSERT OR IGNORE INTO meta(key, value) VALUES ('season', ?)").bind(JSON.stringify(s)).run();
return s;
}
export async function getUser(db, uid) {
return db.prepare("SELECT * FROM users WHERE id = ?").bind(uid).first();
}
export function publicUser(u) {
if (!u) return null;
return {
id: u.id, nickname: u.nickname, guest: !!u.is_guest, email: u.email ?? null,
google: !!u.google_sub, nicknameChangedAt: u.nickname_changed_at ?? null,
};
}
export async function getRating(db, uid) {
const r = await db.prepare("SELECT * FROM ratings WHERE user_id = ?").bind(uid).first();
if (r) return r;
return {
user_id: uid, season: 0, glicko: GLICKO.R, rd: GLICKO.RD, vol: GLICKO.VOL, tr: trFor(GLICKO.R, GLICKO.RD),
games: 0, wins: 0, total_games: 0, last_played: null, _new: true,
};
}
/** 클라이언트 표시용 레이팅 요약 (배치 중이면 TR 비공개, RD<100 일 때만 랭크). */
export function ratingView(r) {
const placed = r.total_games >= PLACEMENT_GAMES;
return {
placed,
placement: Math.min(r.total_games, PLACEMENT_GAMES),
tr: placed ? r.tr : null,
rank: placed && r.rd < RANK_VISIBLE_RD ? rankFor(r.tr) : null,
rd: Math.round(r.rd),
games: r.games,
wins: r.wins,
totalGames: r.total_games,
};
}
async function putRating(db, r) {
await db
.prepare(
`INSERT INTO ratings(user_id, season, glicko, rd, vol, tr, games, wins, total_games, last_played)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
ON CONFLICT(user_id) DO UPDATE SET season=?2, glicko=?3, rd=?4, vol=?5, tr=?6, games=?7, wins=?8,
total_games=?9, last_played=?10`,
)
.bind(r.user_id, r.season, r.glicko, r.rd, r.vol, r.tr, r.games, r.wins, r.total_games, r.last_played)
.run();
}
/** 리그 경기 종료: 양측 Glicko-2 동시 갱신 + 전적 기록. 반환 {[uid]: {trDelta, before, after}} */
export async function applyLeagueResult(db, { matchId, winner, loser, score }, now = Date.now()) {
const season = (await getSeason(db, now)).n;
const [w, l] = await Promise.all([getRating(db, winner), getRating(db, loser)]);
const nw = glickoUpdate({ r: w.glicko, rd: w.rd, vol: w.vol }, [{ r: l.glicko, rd: l.rd, score: 1 }]);
const nl = glickoUpdate({ r: l.glicko, rd: l.rd, vol: l.vol }, [{ r: w.glicko, rd: w.rd, score: 0 }]);
const upd = (old, n, won) => ({
...old, season, glicko: n.r, rd: n.rd, vol: n.vol, tr: trFor(n.r, n.rd),
games: (old.season === season ? old.games : 0) + 1,
wins: (old.season === season ? old.wins : 0) + (won ? 1 : 0),
total_games: old.total_games + 1, last_played: now,
});
const W = upd(w, nw, true);
const L = upd(l, nl, false);
await putRating(db, W);
await putRating(db, L);
const dW = W.tr - w.tr;
const dL = L.tr - l.tr;
await db
.prepare(
`INSERT OR IGNORE INTO matches(id, season, mode, finished_at, room_size, p1, p2, score1, score2, tr_delta1, tr_delta2)
VALUES (?, ?, 'league', ?, 2, ?, ?, ?, ?, ?, ?)`,
)
.bind(matchId, season, now, winner, loser, score[winner] ?? 0, score[loser] ?? 0, dW, dL)
.run();
return {
[winner]: { trDelta: dW, before: ratingView(w), after: ratingView(W), won: true },
[loser]: { trDelta: dL, before: ratingView(l), after: ratingView(L), won: false },
};
}
export async function recordCustom(db, { matchId, standings, size }, now = Date.now()) {
const season = (await getSeason(db, now)).n;
const stmts = standings.map((s) =>
db
.prepare(
`INSERT OR IGNORE INTO matches(id, season, mode, finished_at, room_size, p1, score1, score2)
VALUES (?, ?, 'custom', ?, ?, ?, ?, ?)`,
)
.bind(matchId, season, now, size, s.id, s.rank, s.wins),
);
if (stmts.length) await db.batch(stmts);
}
/** 일일 Cron: RD 감쇠 + 시즌 마감. */
export async function dailyMaintenance(db, now = Date.now()) {
const idleBefore = now - RD_DECAY_IDLE_DAYS * DAY;
await db
.prepare("UPDATE ratings SET rd = MIN(?, rd + ?) WHERE last_played IS NOT NULL AND last_played < ?")
.bind(GLICKO.RD_MAX, RD_DECAY_PER_DAY, idleBefore)
.run();
const s = await getSeason(db, now);
if (now >= s.endsAt) {
const next = { n: s.n + 1, startedAt: s.endsAt, endsAt: s.endsAt + SEASON_LENGTH_DAYS * DAY };
await db.batch([
db.prepare("UPDATE meta SET value = ? WHERE key = 'season'").bind(JSON.stringify(next)),
// 시즌 소프트 리셋: R 유지, 불확실도(RD)를 최소 150 으로 올려 초반 변동폭을 키운다. 시즌 전적은 0부터.
db.prepare("UPDATE ratings SET rd = MAX(rd, 150), games = 0, wins = 0, season = ?").bind(next.n),
]);
// TR 은 R/RD 에서 다시 계산
const { results } = await db.prepare("SELECT user_id, glicko, rd FROM ratings").all();
const stmts = results.map((r) => db.prepare("UPDATE ratings SET tr = ? WHERE user_id = ?").bind(trFor(r.glicko, r.rd), r.user_id));
for (let i = 0; i < stmts.length; i += 50) await db.batch(stmts.slice(i, i + 50));
return { rolled: true, season: next.n };
}
return { rolled: false, season: s.n };
}
export const soloBetter = (mode, a, b) => (mode === "sprint" ? a < b : a > b);
/** 게스트 → 계정 기록 이전 (더 좋은 기록 우선). 게스트 행은 삭제해 닉네임을 반환한다. */
export async function mergeGuestInto(db, guestId, userId) {
if (!guestId || guestId === userId) return;
const g = await getUser(db, guestId);
if (!g || !g.is_guest) return;
const { results } = await db.prepare("SELECT mode, best FROM solo_records WHERE user_id = ?").bind(guestId).all();
for (const rec of results) await submitSolo(db, userId, rec.mode, rec.best);
await db.batch([
db.prepare("UPDATE OR IGNORE matches SET p1 = ? WHERE p1 = ? AND mode = 'custom'").bind(userId, guestId),
db.prepare("DELETE FROM solo_records WHERE user_id = ?").bind(guestId),
db.prepare("DELETE FROM matches WHERE p1 = ? AND mode = 'custom'").bind(guestId),
db.prepare("DELETE FROM users WHERE id = ? AND is_guest = 1").bind(guestId),
]);
}
export async function submitSolo(db, uid, mode, value, now = Date.now()) {
const cur = await db.prepare("SELECT best FROM solo_records WHERE user_id = ? AND mode = ?").bind(uid, mode).first();
if (cur && !soloBetter(mode, value, cur.best)) return { improved: false, best: cur.best };
await db
.prepare(
`INSERT INTO solo_records(user_id, mode, best, updated_at) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(user_id, mode) DO UPDATE SET best = ?3, updated_at = ?4`,
)
.bind(uid, mode, value, now)
.run();
return { improved: true, best: value };
}

76
server/src/glicko.js Normal file
View File

@@ -0,0 +1,76 @@
// Glicko-2 (Glickman 2013, http://www.glicko.net/glicko/glicko2.pdf). 경기 1건 = 레이팅 기간 1개로 처리.
import { GLICKO } from "./rules.js";
const SCALE = 173.7178;
const EPS = 1e-6;
const g = (phi) => 1 / Math.sqrt(1 + (3 * phi * phi) / (Math.PI * Math.PI));
const E = (mu, muj, phij) => 1 / (1 + Math.exp(-g(phij) * (mu - muj)));
/**
* player = {r, rd, vol}, results = [{r, rd, score}] (score 1 승 / 0 패 / 0.5 무).
* 반환: 새 {r, rd, vol}. RD 는 [RD_MIN, RD_MAX] 로 자른다.
*/
export function glickoUpdate(player, results, tau = GLICKO.TAU) {
const mu = (player.r - 1500) / SCALE;
const phi = player.rd / SCALE;
const sigma = player.vol;
if (!results.length) {
const phiStar = Math.sqrt(phi * phi + sigma * sigma);
return clamp({ r: player.r, rd: phiStar * SCALE, vol: sigma });
}
let vInv = 0;
let deltaSum = 0;
for (const o of results) {
const muj = (o.r - 1500) / SCALE;
const phij = o.rd / SCALE;
const e = E(mu, muj, phij);
const gj = g(phij);
vInv += gj * gj * e * (1 - e);
deltaSum += gj * (o.score - e);
}
const v = 1 / vInv;
const delta = v * deltaSum;
// 변동성 σ' — Illinois 알고리즘
const a = Math.log(sigma * sigma);
const f = (x) => {
const ex = Math.exp(x);
return (ex * (delta * delta - phi * phi - v - ex)) / (2 * Math.pow(phi * phi + v + ex, 2)) - (x - a) / (tau * tau);
};
let A = a;
let B;
if (delta * delta > phi * phi + v) {
B = Math.log(delta * delta - phi * phi - v);
} else {
let k = 1;
while (f(a - k * tau) < 0) k++;
B = a - k * tau;
}
let fA = f(A);
let fB = f(B);
for (let i = 0; i < 100 && Math.abs(B - A) > EPS; i++) {
const C = A + ((A - B) * fA) / (fB - fA);
const fC = f(C);
if (fC * fB <= 0) {
A = B;
fA = fB;
} else {
fA /= 2;
}
B = C;
fB = fC;
}
const sigmaNew = Math.exp(A / 2);
const phiStar = Math.sqrt(phi * phi + sigmaNew * sigmaNew);
const phiNew = 1 / Math.sqrt(1 / (phiStar * phiStar) + 1 / v);
const muNew = mu + phiNew * phiNew * deltaSum;
return clamp({ r: muNew * SCALE + 1500, rd: phiNew * SCALE, vol: sigmaNew });
}
function clamp(p) {
return { r: p.r, rd: Math.min(GLICKO.RD_MAX, Math.max(GLICKO.RD_MIN, p.rd)), vol: p.vol };
}

311
server/src/index.js Normal file
View File

@@ -0,0 +1,311 @@
// TETRIG Worker — REST API + WebSocket 라우팅 + Cron.
import { hashPassword, signToken, timingSafeEqual, verifyGoogleIdToken, verifyToken } from "./auth.js";
import {
dailyMaintenance, getRating, getSeason, getUser, mergeGuestInto, publicUser, ratingView, submitSolo,
} from "./db.js";
import {
BRAND, NICK_COOLDOWN_MS, NICK_RE, SOLO_MODES, isRoomCode, looksLikeGuestName, randomGuestName, randomRoomCode,
} from "./rules.js";
export { GameRoomDO } from "./room.js";
export { MatchmakerDO } from "./matchmaker.js";
const CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
const json = (data, status = 200) => Response.json(data, { status, headers: CORS });
const err = (msg, status = 400) => json({ error: msg }, status);
async function body(req) {
try {
return await req.json();
} catch {
return {};
}
}
function secret(env) {
if (!env.TOKEN_SECRET) throw new Error("TOKEN_SECRET 미설정");
return env.TOKEN_SECRET;
}
async function authUser(req, env, url) {
const h = req.headers.get("Authorization") || "";
const token = h.startsWith("Bearer ") ? h.slice(7) : url?.searchParams.get("token");
const p = await verifyToken(secret(env), token);
if (!p) return null;
return getUser(env.DB, p.uid);
}
async function issue(env, user) {
return { token: await signToken(secret(env), user.id), user: publicUser(user) };
}
async function uniqueGuestName(db) {
for (let i = 0; i < 20; i++) {
const n = randomGuestName();
const hit = await db.prepare("SELECT 1 FROM users WHERE nickname = ?").bind(n).first();
if (!hit) return n;
}
return "게스트" + crypto.randomUUID().slice(0, 6);
}
async function nicknameProblem(db, nick, selfId = null) {
if (typeof nick !== "string" || !NICK_RE.test(nick)) return "닉네임은 2~12자의 한글·영문·숫자·_ 만 쓸 수 있습니다";
if (looksLikeGuestName(nick)) return "게스트 이름 형식은 쓸 수 없습니다";
const hit = await db.prepare("SELECT id FROM users WHERE nickname = ? COLLATE NOCASE").bind(nick).first();
if (hit && hit.id !== selfId) return "이미 사용 중인 닉네임입니다";
return null;
}
/** 유저 + 리그 요약 (WS 헤더로 DO 에 넘기는 정보). */
async function playerInfo(env, u) {
const r = await getRating(env.DB, u.id);
const v = ratingView(r);
return { nick: u.nickname, guest: !!u.is_guest, tr: v.tr, rank: v.rank, r: r.glicko, rd: r.rd };
}
async function routeWs(req, env, url, u, ns, name, path = "/ws") {
if (req.headers.get("Upgrade") !== "websocket") return err("websocket only", 426);
const stub = ns.get(ns.idFromName(name));
const headers = new Headers(req.headers);
headers.set("x-uid", u.id);
headers.set("x-info", JSON.stringify(await playerInfo(env, u)));
return stub.fetch(new Request(`https://do${path}`, { headers }));
}
async function handle(req, env) {
const url = new URL(req.url);
const path = url.pathname;
if (req.method === "OPTIONS") return new Response(null, { headers: CORS });
const db = env.DB;
if (path === "/" || path === "/api/health") {
return json({ ok: true, name: BRAND, season: (await getSeason(db)).n });
}
// ── 계정 ──
if (path === "/api/guest" && req.method === "POST") {
const b = await body(req);
const id = crypto.randomUUID();
const nickname = await uniqueGuestName(db);
await db
.prepare("INSERT INTO users(id, nickname, is_guest, device_id, created_at) VALUES (?, ?, 1, ?, ?)")
.bind(id, nickname, typeof b.deviceId === "string" ? b.deviceId.slice(0, 64) : null, Date.now())
.run();
return json(await issue(env, await getUser(db, id)));
}
if (path === "/api/register" && req.method === "POST") {
const b = await body(req);
const email = String(b.email || "").trim().toLowerCase();
const password = String(b.password || "");
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return err("이메일 형식이 올바르지 않습니다");
if (password.length < 8) return err("비밀번호는 8자 이상이어야 합니다");
if (await db.prepare("SELECT 1 FROM users WHERE email = ?").bind(email).first()) return err("이미 가입된 이메일입니다", 409);
const me = await authUser(req, env, url);
let nickname = b.nickname ? String(b.nickname) : null;
if (nickname) {
const p = await nicknameProblem(db, nickname, me?.id);
if (p) return err(p);
}
const { hash, salt } = await hashPassword(password);
const now = Date.now();
if (me && me.is_guest) {
// 지금 쓰는 게스트 계정을 그대로 정식 계정으로 승격 → 기록이 자동으로 따라온다.
await db
.prepare("UPDATE users SET is_guest = 0, email = ?, pw_hash = ?, pw_salt = ?, nickname = COALESCE(?, nickname), nickname_changed_at = ? WHERE id = ?")
.bind(email, hash, salt, nickname, nickname ? now : null, me.id)
.run();
return json(await issue(env, await getUser(db, me.id)));
}
const id = crypto.randomUUID();
await db
.prepare("INSERT INTO users(id, nickname, is_guest, email, pw_hash, pw_salt, created_at, nickname_changed_at) VALUES (?, ?, 0, ?, ?, ?, ?, ?)")
.bind(id, nickname ?? (await uniqueGuestName(db)), email, hash, salt, now, nickname ? now : null)
.run();
return json(await issue(env, await getUser(db, id)));
}
if (path === "/api/login" && req.method === "POST") {
const b = await body(req);
const email = String(b.email || "").trim().toLowerCase();
const u = await db.prepare("SELECT * FROM users WHERE email = ?").bind(email).first();
if (!u || !u.pw_hash) return err("이메일 또는 비밀번호가 맞지 않습니다", 401);
const { hash } = await hashPassword(String(b.password || ""), u.pw_salt);
if (!timingSafeEqual(hash, u.pw_hash)) return err("이메일 또는 비밀번호가 맞지 않습니다", 401);
const me = await authUser(req, env, url);
if (me && me.is_guest) await mergeGuestInto(db, me.id, u.id);
return json(await issue(env, u));
}
if (path === "/api/google" && req.method === "POST") {
const auds = String(env.GOOGLE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean);
if (!auds.length) return err("Google 로그인이 아직 설정되지 않았습니다", 503);
const b = await body(req);
const g = await verifyGoogleIdToken(b.idToken, auds);
if (!g) return err("Google 인증에 실패했습니다", 401);
const me = await authUser(req, env, url);
let u = await db.prepare("SELECT * FROM users WHERE google_sub = ?").bind(g.sub).first();
if (!u && me && me.is_guest) {
await db.prepare("UPDATE users SET is_guest = 0, google_sub = ? WHERE id = ?").bind(g.sub, me.id).run();
u = await getUser(db, me.id);
} else if (!u) {
const id = crypto.randomUUID();
await db
.prepare("INSERT INTO users(id, nickname, is_guest, google_sub, created_at) VALUES (?, ?, 0, ?, ?)")
.bind(id, await uniqueGuestName(db), g.sub, Date.now())
.run();
u = await getUser(db, id);
} else if (me && me.is_guest) {
await mergeGuestInto(db, me.id, u.id);
}
return json(await issue(env, u));
}
if (path === "/api/nickname/check") {
const p = await nicknameProblem(db, url.searchParams.get("n") || "");
return json({ ok: !p, reason: p });
}
// 이하 인증 필요
const needAuth = path.startsWith("/api/me") || path === "/api/nickname" || path === "/api/solo" || path === "/api/rooms" || path.startsWith("/ws/");
const me = needAuth ? await authUser(req, env, url) : null;
if (needAuth && !me) return err("로그인이 필요합니다", 401);
if (path === "/api/me") {
const r = await getRating(db, me.id);
const { results: solo } = await db.prepare("SELECT mode, best FROM solo_records WHERE user_id = ?").bind(me.id).all();
const { results: recent } = await db
.prepare(
`SELECT m.id, m.mode, m.finished_at, m.room_size, m.p1, m.p2, m.score1, m.score2, m.tr_delta1, m.tr_delta2,
u1.nickname AS n1, u2.nickname AS n2
FROM matches m LEFT JOIN users u1 ON u1.id = m.p1 LEFT JOIN users u2 ON u2.id = m.p2
WHERE m.p1 = ?1 OR m.p2 = ?1 ORDER BY m.finished_at DESC LIMIT 20`,
)
.bind(me.id)
.all();
return json({
user: publicUser(me),
league: ratingView(r),
season: await getSeason(db),
solo: Object.fromEntries(solo.map((s) => [s.mode, s.best])),
recent: recent.map((m) => {
const mine = m.p1 === me.id;
if (m.mode === "custom") return { id: m.id, mode: "custom", at: m.finished_at, size: m.room_size, place: m.score1, wins: m.score2 };
return {
id: m.id, mode: "league", at: m.finished_at, won: mine, opponent: mine ? m.n2 : m.n1,
score: mine ? [m.score1, m.score2] : [m.score2, m.score1], trDelta: mine ? m.tr_delta1 : m.tr_delta2,
};
}),
});
}
if (path === "/api/nickname" && req.method === "POST") {
if (me.is_guest) return err("게스트는 닉네임을 바꿀 수 없습니다. 로그인해 주세요", 403);
const b = await body(req);
const now = Date.now();
if (me.nickname_changed_at && now - me.nickname_changed_at < NICK_COOLDOWN_MS) {
const days = Math.ceil((me.nickname_changed_at + NICK_COOLDOWN_MS - now) / 86400000);
return err(`닉네임은 30일에 한 번 바꿀 수 있습니다 (${days}일 남음)`, 429);
}
const p = await nicknameProblem(db, b.nickname, me.id);
if (p) return err(p);
await db.prepare("UPDATE users SET nickname = ?, nickname_changed_at = ? WHERE id = ?").bind(b.nickname, now, me.id).run();
return json({ user: publicUser(await getUser(db, me.id)) });
}
if (path === "/api/solo" && req.method === "POST") {
const b = await body(req);
if (!SOLO_MODES.includes(b.mode) || !Number.isInteger(b.value) || b.value <= 0) return err("잘못된 기록");
// 최소 상식 검증: SPRINT 40줄 10초 미만은 불가능에 가깝다.
if (b.mode === "sprint" && b.value < 10_000) return err("기록이 비정상입니다");
return json(await submitSolo(db, me.id, b.mode, b.value));
}
if (path.startsWith("/api/leaderboard")) {
const board = url.searchParams.get("board") || "league";
if (board === "league") {
const { results } = await db
.prepare(
`SELECT u.id, u.nickname, r.tr, r.rd, r.games, r.wins, r.total_games FROM ratings r JOIN users u ON u.id = r.user_id
WHERE u.is_guest = 0 AND r.total_games >= 10 ORDER BY r.tr DESC LIMIT 100`,
)
.all();
return json({
board,
rows: results.map((r, i) => ({ pos: i + 1, id: r.id, nickname: r.nickname, ...ratingView({ ...r }) })),
});
}
if (!SOLO_MODES.includes(board)) return err("unknown board");
const order = board === "sprint" ? "ASC" : "DESC";
const { results } = await db
.prepare(
`SELECT u.id, u.nickname, s.best FROM solo_records s JOIN users u ON u.id = s.user_id
WHERE s.mode = ? AND u.is_guest = 0 ORDER BY s.best ${order} LIMIT 100`,
)
.bind(board)
.all();
return json({ board, rows: results.map((r, i) => ({ pos: i + 1, id: r.id, nickname: r.nickname, best: r.best })) });
}
if (path === "/api/season") return json(await getSeason(db));
// ── 커스텀 방 ──
if (path === "/api/rooms" && req.method === "POST") {
const b = await body(req);
for (let i = 0; i < 8; i++) {
const code = randomRoomCode();
const stub = env.ROOMS.get(env.ROOMS.idFromName(`custom:${code}`));
const res = await stub.fetch("https://do/init", {
method: "POST",
body: JSON.stringify({ id: code, code, kind: "custom", rules: b.rules ?? {} }),
});
if (res.ok) return json({ code });
}
return err("방 코드를 만들지 못했습니다. 다시 시도해 주세요", 503);
}
const roomInfo = /^\/api\/rooms\/([A-Z0-9]{6})$/.exec(path);
if (roomInfo) {
const code = roomInfo[1];
if (!isRoomCode(code)) return json({ exists: false });
const stub = env.ROOMS.get(env.ROOMS.idFromName(`custom:${code}`));
return json(await (await stub.fetch("https://do/info")).json());
}
// ── WebSocket ──
const wsRoom = /^\/ws\/room\/([A-Z0-9]{6})$/.exec(path);
if (wsRoom) {
if (!isRoomCode(wsRoom[1])) return err("잘못된 코드", 404);
const stub = env.ROOMS.get(env.ROOMS.idFromName(`custom:${wsRoom[1]}`));
const info = await (await stub.fetch("https://do/info")).json();
if (!info.exists) return err("없는 방입니다", 404);
return routeWs(req, env, url, me, env.ROOMS, `custom:${wsRoom[1]}`);
}
const wsLeague = /^\/ws\/league\/([0-9a-f-]{36})$/.exec(path);
if (wsLeague) return routeWs(req, env, url, me, env.ROOMS, `league:${wsLeague[1]}`);
if (path === "/ws/queue") {
if (me.is_guest) return err("리그전은 로그인 후 참가할 수 있습니다", 403);
return routeWs(req, env, url, me, env.MATCHMAKER, "global", "/");
}
return err("not found", 404);
}
export default {
async fetch(req, env) {
try {
return await handle(req, env);
} catch (e) {
console.error(e);
return err("서버 오류", 500);
}
},
async scheduled(_event, env) {
await dailyMaintenance(env.DB);
},
};

72
server/src/matchmaker.js Normal file
View File

@@ -0,0 +1,72 @@
// MatchmakerDO — 리그 대기열 싱글턴. 대기열 상태는 소켓 attachment 에만 둔다 (하이버네이션 안전).
import { DurableObject } from "cloudflare:workers";
import { findPairs } from "./matchmaking.js";
import { MM_HINT_AFTER_MS, leagueFt } from "./rules.js";
const SWEEP_MS = 3_000;
export class MatchmakerDO extends DurableObject {
async fetch(req) {
if (req.headers.get("Upgrade") !== "websocket") return new Response("websocket only", { status: 426 });
const uid = req.headers.get("x-uid");
const info = JSON.parse(req.headers.get("x-info") || "{}");
for (const old of this.ctx.getWebSockets(uid)) {
try {
old.serializeAttachment({ ...old.deserializeAttachment(), gone: true });
old.close(4000, "replaced");
} catch {}
}
const [client, server] = Object.values(new WebSocketPair());
this.ctx.acceptWebSocket(server, [uid]);
server.serializeAttachment({ uid, r: info.r, rd: info.rd, tr: info.tr, nick: info.nick, rank: info.rank, joinedAt: Date.now() });
server.send(JSON.stringify({ t: "queue", state: "waiting", waitMs: 0, hint: false }));
await this.sweep();
return new Response(null, { status: 101, webSocket: client });
}
waiting() {
return this.ctx
.getWebSockets()
.filter((ws) => ws.readyState === 1)
.map((ws) => ({ ws, a: ws.deserializeAttachment() }))
.filter((x) => x.a && !x.a.gone && !x.a.matched);
}
async sweep() {
const now = Date.now();
const list = this.waiting();
const byUid = new Map(list.map((x) => [x.a.uid, x]));
const pairs = findPairs(list.map((x) => x.a), now);
for (const [a, b] of pairs) {
const roomId = crypto.randomUUID();
const ft = leagueFt(a.tr ?? 0, b.tr ?? 0);
const stub = this.env.ROOMS.get(this.env.ROOMS.idFromName(`league:${roomId}`));
const res = await stub.fetch("https://room/init", {
method: "POST",
body: JSON.stringify({ id: roomId, kind: "league", allowed: [a.uid, b.uid], ft }),
});
if (!res.ok) continue;
for (const [me, opp] of [[a, b], [b, a]]) {
const x = byUid.get(me.uid);
x.ws.serializeAttachment({ ...x.a, matched: true });
x.ws.send(JSON.stringify({ t: "matched", room: roomId, ft, opponent: { id: opp.uid, nick: opp.nick, tr: opp.tr, rank: opp.rank } }));
x.ws.close(1000, "matched");
}
}
for (const x of this.waiting()) {
const waitMs = now - x.a.joinedAt;
x.ws.send(JSON.stringify({ t: "queue", state: "waiting", waitMs, hint: waitMs >= MM_HINT_AFTER_MS, size: this.waiting().length }));
}
if (this.waiting().length) await this.ctx.storage.setAlarm(now + SWEEP_MS);
}
async alarm() {
await this.sweep();
}
async webSocketMessage(ws, data) {
if (data === "leave" || String(data).includes('"leave"')) ws.close(1000, "left");
}
async webSocketClose() {}
}

38
server/src/matchmaking.js Normal file
View File

@@ -0,0 +1,38 @@
// 리그 매치메이킹 순수 로직 (§8.3). MatchmakerDO 가 대기열 스냅샷을 넘겨 짝을 받는다.
import { MM_EXPAND_EVERY_MS, MM_EXPAND_FACTOR, MM_WINDOW_RD } from "./rules.js";
/** 대기 시간에 따라 넓어지는 탐색 반경 (R 기준 반폭). */
export function windowFor(entry, now) {
const steps = Math.floor(Math.max(0, now - entry.joinedAt) / MM_EXPAND_EVERY_MS);
return MM_WINDOW_RD * entry.rd * Math.pow(MM_EXPAND_FACTOR, steps);
}
/** 두 사람의 구간 [R-w, R+w] 가 겹치면 성사. */
export function compatible(a, b, now) {
return Math.abs(a.r - b.r) <= windowFor(a, now) + windowFor(b, now);
}
/**
* queue: [{uid, r, rd, joinedAt}] — 오래 기다린 순서로 우선 매칭, 그 안에서는 R 차이가 가장 작은 상대.
* 반환: [[a, b], …]
*/
export function findPairs(queue, now) {
const waiting = [...queue].sort((x, y) => x.joinedAt - y.joinedAt);
const used = new Set();
const pairs = [];
for (const a of waiting) {
if (used.has(a.uid)) continue;
let best = null;
for (const b of waiting) {
if (b.uid === a.uid || used.has(b.uid)) continue;
if (!compatible(a, b, now)) continue;
if (!best || Math.abs(a.r - b.r) < Math.abs(a.r - best.r)) best = b;
}
if (best) {
used.add(a.uid);
used.add(best.uid);
pairs.push([a, best]);
}
}
return pairs;
}

480
server/src/room-logic.js Normal file
View File

@@ -0,0 +1,480 @@
// 경기방 상태 기계 (리그 1:1 & 커스텀 N인 공용). 전송·저장과 분리된 순수 로직이라 node 로 테스트한다.
// GameRoomDO(room.js)가 소켓 메시지를 handle() 로 넘기고, outbox/effects 를 비워 실제로 보낸다.
import {
AUTO_TARGET_MS, DEFAULT_RULES, MAX_ATTACK_PER_PIECE, MAX_PPS, RECONNECT_GRACE_MS,
ROUND_COUNTDOWN_MS, ROUND_GAP_MS, overtimeMultiplier, sanitizeRules,
} from "./rules.js";
const BOARD_W = 10;
const BOARD_ROWS = 20;
const BOARD_RE = /^[.IOTSZJLG]+$/;
export class RoomLogic {
/**
* opts: { id, kind: "custom"|"league", code?, allowed?: [uid, uid], ft?, now?, rand? }
*/
constructor(opts) {
this.id = opts.id;
this.kind = opts.kind;
this.code = opts.code ?? null;
this.allowed = opts.allowed ?? null;
this.rules = { ...DEFAULT_RULES, ...(opts.kind === "league" ? { ft: opts.ft ?? 3 } : {}) };
this.now = opts.now ?? (() => Date.now());
this.rand = opts.rand ?? Math.random;
/** @type {Map<string, any>} uid -> player */
this.players = new Map();
this.order = [];
this.host = null;
this.phase = "lobby"; // lobby | countdown | playing | between | match_end
this.round = 0;
this.roundStartAt = 0;
this.nextRoundAt = 0;
this.matchId = null;
this.finished = false; // 리그 경기 종료 후 방 폐기 표시
this.outbox = []; // {to: uid|null, except?: uid, msg}
this.effects = []; // {type, ...}
}
// ── 출력 ──
send(to, msg) {
this.outbox.push({ to, msg });
}
broadcast(msg, except = null) {
this.outbox.push({ to: null, except, msg });
}
drain() {
const o = this.outbox;
const e = this.effects;
this.outbox = [];
this.effects = [];
return { out: o, effects: e };
}
// ── 직렬화 (DO 하이버네이션 대비) ──
toJSON() {
return {
id: this.id, kind: this.kind, code: this.code, allowed: this.allowed, rules: this.rules,
players: [...this.players.values()], order: this.order, host: this.host, phase: this.phase,
round: this.round, roundStartAt: this.roundStartAt, nextRoundAt: this.nextRoundAt,
matchId: this.matchId, finished: this.finished,
};
}
static fromJSON(j, deps = {}) {
const r = new RoomLogic({ id: j.id, kind: j.kind, code: j.code, allowed: j.allowed, ...deps });
Object.assign(r, {
rules: j.rules, order: j.order, host: j.host, phase: j.phase, round: j.round,
roundStartAt: j.roundStartAt, nextRoundAt: j.nextRoundAt, matchId: j.matchId, finished: j.finished,
});
for (const p of j.players) r.players.set(p.uid, p);
return r;
}
// ── 조회 ──
get connected() {
return [...this.players.values()].filter((p) => p.connected);
}
get alive() {
return [...this.players.values()].filter((p) => p.inRound && p.alive);
}
ftTarget() {
return this.rules.ft;
}
lobbyMsg() {
return {
t: "lobby",
room: this.id,
code: this.code,
kind: this.kind,
host: this.host,
rules: this.rules,
phase: this.phase,
round: this.round,
players: this.order.map((uid) => {
const p = this.players.get(uid);
return {
id: p.uid, nick: p.nick, guest: p.guest, wins: p.wins, alive: p.alive, inRound: p.inRound,
connected: p.connected, rematch: p.rematch, tr: p.tr ?? null, rank: p.rank ?? null,
};
}),
};
}
// ── 입장/퇴장 ──
/** 반환: {ok:true} | {ok:false, reason} */
join(uid, info = {}) {
if (this.finished) return { ok: false, reason: "이미 끝난 경기입니다" };
if (this.allowed && !this.allowed.includes(uid)) return { ok: false, reason: "이 경기의 참가자가 아닙니다" };
const existing = this.players.get(uid);
if (existing) {
existing.connected = true;
existing.disconnectedAt = 0;
Object.assign(existing, pickInfo(info));
this.send(uid, this.syncMsg(uid));
if (existing.pendingGarbage?.length) {
for (const g of existing.pendingGarbage) this.send(uid, g);
existing.pendingGarbage = [];
}
this.broadcast(this.lobbyMsg());
return { ok: true, rejoined: true };
}
const p = {
uid, nick: info.nick ?? "?", guest: !!info.guest, tr: info.tr ?? null, rank: info.rank ?? null,
connected: true, disconnectedAt: 0,
wins: 0, inRound: false, alive: false, place: 0,
target: null, autoTarget: null, autoTargetAt: 0, lastAttacker: null,
carry: 0, pieces: 0, lastBoardAt: 0, grid: null, rematch: false, pendingGarbage: [], flagged: 0,
};
this.players.set(uid, p);
this.order.push(uid);
if (!this.host) this.host = uid;
this.send(uid, this.syncMsg(uid));
this.broadcast(this.lobbyMsg());
if (this.kind === "league" && this.phase === "lobby" && this.allowed.every((u) => this.players.get(u)?.connected)) {
this.startRound();
}
return { ok: true };
}
syncMsg(uid) {
const p = this.players.get(uid);
return {
...this.lobbyMsg(), t: "sync", you: uid,
inRound: p.inRound, alive: p.alive,
boards: Object.fromEntries([...this.players.values()].filter((o) => o.grid && o.uid !== uid).map((o) => [o.uid, o.grid])),
};
}
/** 소켓 종료. 리그·라운드 중이면 15초 유예 후 톱아웃 처리. */
disconnect(uid) {
const p = this.players.get(uid);
if (!p) return;
p.connected = false;
p.disconnectedAt = this.now();
this.broadcast(this.lobbyMsg());
}
leave(uid) {
const p = this.players.get(uid);
if (!p) return;
if (this.kind === "league" && !this.finished) {
this.forfeit(uid);
return;
}
if (p.inRound && p.alive) this.topout(uid);
this.players.delete(uid);
this.order = this.order.filter((u) => u !== uid);
if (this.host === uid) this.host = this.order.find((u) => this.players.get(u).connected) ?? this.order[0] ?? null;
if (this.phase !== "lobby" && this.phase !== "match_end" && this.participants().length < 2 && this.alive.length <= 1) {
// 남은 인원으로 라운드를 이어갈 수 없으면 로비로
if (this.phase === "between" || this.phase === "countdown") this.toLobby();
}
this.broadcast(this.lobbyMsg());
}
participants() {
return this.connected;
}
// ── 라운드 ──
startRound() {
const ready = this.connected;
if (ready.length < 2) return false;
this.round += 1;
this.phase = "countdown";
const now = this.now();
this.roundStartAt = now + ROUND_COUNTDOWN_MS;
this.nextRoundAt = 0;
const shared = this.randomSeed();
for (const p of this.players.values()) {
const inRound = p.connected;
Object.assign(p, {
inRound, alive: inRound, place: 0, target: null, autoTarget: null, autoTargetAt: 0,
lastAttacker: null, carry: 0, pieces: 0, grid: null, rematch: false, pendingGarbage: [],
});
}
for (const p of this.players.values()) {
if (!p.inRound) continue;
const seed = this.rules.sameBag ? shared : this.randomSeed();
this.send(p.uid, { t: "round_start", n: this.round, startIn: ROUND_COUNTDOWN_MS, seed, rules: this.rules });
}
// 관전자에게도 라운드 시작 알림 (seed 없음)
for (const p of this.players.values()) {
if (!p.inRound) this.send(p.uid, { t: "round_start", n: this.round, startIn: ROUND_COUNTDOWN_MS, seed: null, rules: this.rules });
}
this.broadcast(this.lobbyMsg());
return true;
}
randomSeed() {
return 1 + Math.floor(this.rand() * 0x7ffffffe);
}
elapsed() {
return Math.max(0, this.now() - this.roundStartAt);
}
/** 시간 경과 처리. DO 알람에서 호출. */
tick() {
const now = this.now();
if (this.phase === "countdown" && now >= this.roundStartAt) this.phase = "playing";
if (this.phase === "between" && this.nextRoundAt && now >= this.nextRoundAt) {
if (!this.startRound()) this.toLobby();
}
for (const p of [...this.players.values()]) {
if (!p.connected && p.disconnectedAt && now - p.disconnectedAt >= RECONNECT_GRACE_MS) {
if (this.kind === "league" && !this.finished) {
this.forfeit(p.uid);
} else if (p.inRound && p.alive) {
this.topout(p.uid);
p.disconnectedAt = 0;
} else if (this.phase === "lobby" || this.phase === "match_end") {
this.leave(p.uid);
} else {
p.disconnectedAt = 0;
}
}
}
}
/** 다음에 tick() 이 필요한 시각 (없으면 null). */
nextWake() {
const t = [];
if (this.phase === "countdown") t.push(this.roundStartAt);
if (this.phase === "between" && this.nextRoundAt) t.push(this.nextRoundAt);
for (const p of this.players.values()) if (!p.connected && p.disconnectedAt) t.push(p.disconnectedAt + RECONNECT_GRACE_MS);
return t.length ? Math.min(...t) : null;
}
ensurePlaying() {
if (this.phase === "countdown" && this.now() >= this.roundStartAt) this.phase = "playing";
return this.phase === "playing";
}
// ── 메시지 처리 ──
handle(uid, m) {
const p = this.players.get(uid);
if (!p || !m || typeof m.t !== "string") return;
switch (m.t) {
case "start":
if (this.kind === "custom" && uid === this.host && (this.phase === "lobby" || this.phase === "match_end")) {
if (this.phase === "match_end") this.resetWins();
if (!this.startRound()) this.send(uid, { t: "error", msg: "2명 이상 있어야 시작할 수 있습니다" });
}
break;
case "rules":
if (this.kind === "custom" && uid === this.host && this.phase === "lobby") {
this.rules = sanitizeRules(m.rules, this.rules);
this.broadcast(this.lobbyMsg());
}
break;
case "stop":
if (this.kind === "custom" && uid === this.host) this.toLobby();
break;
case "attack":
this.onAttack(p, m);
break;
case "board":
this.onBoard(p, m);
break;
case "topout":
if (p.inRound && p.alive && (this.phase === "playing" || this.ensurePlaying())) this.topout(uid);
break;
case "target":
if (typeof m.id === "string" && m.id !== uid && this.players.has(m.id)) {
p.target = m.id;
this.send(uid, { t: "targeting", id: m.id, manual: true });
} else if (m.id === null) {
p.target = null;
}
break;
case "rematch":
this.onRematch(p, !!m.vote);
break;
case "leave":
this.leave(uid);
break;
case "ping":
this.send(uid, { t: "pong", ts: m.ts ?? null });
break;
}
}
onAttack(p, m) {
if (!p.inRound || !p.alive || !this.ensurePlaying()) return;
const lines = m.lines;
const pieces = m.pieces;
if (!Number.isInteger(lines) || lines < 0 || lines > MAX_ATTACK_PER_PIECE) {
p.flagged++;
return;
}
if (Number.isInteger(pieces)) {
const sec = this.elapsed() / 1000;
if (pieces > MAX_PPS * sec + 3) {
p.flagged++;
return;
}
p.pieces = pieces;
}
if (lines === 0) return;
const mul = this.rules.garbageMul * overtimeMultiplier(this.elapsed(), this.rules.overtime);
p.carry += lines * mul;
const send = Math.floor(p.carry + 1e-9);
p.carry -= send;
if (send <= 0) return;
const target = this.pickTarget(p);
if (!target) return;
target.lastAttacker = p.uid;
const msg = { t: "garbage", from: p.uid, lines: send };
if (target.connected) this.send(target.uid, msg);
else target.pendingGarbage.push(msg);
this.broadcast({ t: "attack", from: p.uid, to: target.uid, lines: send }, target.uid);
}
pickTarget(p) {
const others = this.alive.filter((o) => o.uid !== p.uid);
if (!others.length) return null;
if (others.length === 1) return others[0];
if (p.target) {
const t = this.players.get(p.target);
if (t && t.inRound && t.alive) return t;
p.target = null;
}
const now = this.now();
let t = p.autoTarget && this.players.get(p.autoTarget);
if (!t || !t.alive || !t.inRound || now - p.autoTargetAt >= AUTO_TARGET_MS) {
t = others[Math.floor(this.rand() * others.length)];
p.autoTarget = t.uid;
p.autoTargetAt = now;
this.send(p.uid, { t: "targeting", id: t.uid, manual: false });
}
return t;
}
onBoard(p, m) {
if (!p.inRound) return;
const grid = m.grid;
if (typeof grid !== "string" || grid.length !== BOARD_W * BOARD_ROWS || !BOARD_RE.test(grid)) return;
p.grid = grid;
const now = this.now();
// 인원이 많을수록 브로드캐스트 주기를 늘린다 (§14.1).
const minGap = 150 * Math.max(1, Math.ceil(this.connected.length / 6));
if (now - p.lastBoardAt < minGap && !m.lock) return;
p.lastBoardAt = now;
this.broadcast({ t: "board", id: p.uid, grid, pending: m.pending ?? 0 }, p.uid);
}
topout(uid) {
const p = this.players.get(uid);
if (!p || !p.alive) return;
const aliveBefore = this.alive.length;
p.alive = false;
p.place = aliveBefore;
this.broadcast({ t: "ko", who: uid, by: p.lastAttacker, place: p.place });
const left = this.alive;
if (left.length <= 1) this.endRound(left[0] ?? null);
}
endRound(winner) {
if (winner) {
winner.wins += 1;
winner.place = 1;
}
const score = Object.fromEntries(this.order.map((u) => [u, this.players.get(u).wins]));
this.broadcast({ t: "round_end", n: this.round, winner: winner?.uid ?? null, score });
const ft = this.ftTarget();
if (ft > 0 && winner && winner.wins >= ft) {
this.endMatch(winner.uid);
return;
}
this.phase = "between";
this.nextRoundAt = this.now() + ROUND_GAP_MS;
this.broadcast(this.lobbyMsg());
}
standings() {
return [...this.players.values()]
.filter((p) => p.wins > 0 || p.inRound)
.sort((a, b) => b.wins - a.wins)
.map((p, i) => ({ id: p.uid, nick: p.nick, wins: p.wins, rank: i + 1 }));
}
endMatch(winnerUid) {
this.phase = "match_end";
this.nextRoundAt = 0;
const standings = this.standings();
if (this.kind === "league") {
this.finished = true;
const [a, b] = this.allowed;
const loser = winnerUid === a ? b : a;
this.effects.push({
type: "league_end", winner: winnerUid, loser,
score: { [a]: this.players.get(a)?.wins ?? 0, [b]: this.players.get(b)?.wins ?? 0 },
});
// match_end 메시지는 레이팅 반영 후 래퍼가 trDelta 를 붙여 보낸다.
} else {
this.effects.push({ type: "custom_end", standings, size: this.order.length });
this.broadcast({ t: "match_end", result: standings, winner: winnerUid });
this.broadcastRematch();
}
this.broadcast(this.lobbyMsg());
}
forfeit(uid) {
if (this.finished) return;
const other = this.allowed.find((u) => u !== uid);
const o = this.players.get(other);
if (o) o.wins = Math.max(o.wins, this.rules.ft);
const me = this.players.get(uid);
if (me) me.alive = false;
this.broadcast({ t: "ko", who: uid, by: null, place: 2, forfeit: true });
this.endMatch(other);
}
resetWins() {
for (const p of this.players.values()) {
p.wins = 0;
p.rematch = false;
}
this.round = 0;
}
toLobby() {
this.phase = "lobby";
this.nextRoundAt = 0;
for (const p of this.players.values()) {
p.inRound = false;
p.alive = false;
}
this.broadcast(this.lobbyMsg());
}
onRematch(p, vote) {
if (this.kind !== "custom" || this.phase !== "match_end") return;
p.rematch = vote;
this.broadcastRematch();
const conn = this.connected;
const votes = conn.filter((x) => x.rematch).length;
if (votes * 2 > conn.length && conn.length >= 2) {
this.resetWins();
this.startRound();
}
}
broadcastRematch() {
const conn = this.connected;
this.broadcast({
t: "rematch_state",
votes: conn.filter((x) => x.rematch).map((x) => x.uid),
needed: Math.floor(conn.length / 2) + 1,
});
}
}
function pickInfo(info) {
const o = {};
for (const k of ["nick", "guest", "tr", "rank"]) if (k in info) o[k] = info[k];
return o;
}

180
server/src/room.js Normal file
View File

@@ -0,0 +1,180 @@
// GameRoomDO — 경기당 1개 (리그 1:1 & 커스텀 N인 공용). WebSocket Hibernation 사용.
import { DurableObject } from "cloudflare:workers";
import { RoomLogic } from "./room-logic.js";
import { DEFAULT_RULES, sanitizeRules } from "./rules.js";
import { applyLeagueResult, recordCustom } from "./db.js";
const QUIET = new Set(["board", "attack", "ping"]);
export class GameRoomDO extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
this.logic = null;
}
async load() {
if (this.logic) return this.logic;
const j = await this.ctx.storage.get("room");
if (j) this.logic = RoomLogic.fromJSON(j);
return this.logic;
}
async save() {
if (this.logic) await this.ctx.storage.put("room", this.logic.toJSON());
}
async fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/init") {
const body = await req.json();
const cur = await this.load();
if (cur && cur.players.size > 0) return Response.json({ ok: false, reason: "exists" }, { status: 409 });
this.logic = new RoomLogic({
id: body.id, kind: body.kind, code: body.code ?? null, allowed: body.allowed ?? null, ft: body.ft,
});
if (body.kind === "custom") this.logic.rules = sanitizeRules(body.rules ?? {}, DEFAULT_RULES);
this.logic.matchId = crypto.randomUUID();
this.logic.createdAt = Date.now();
await this.save();
// 아무도 안 들어오면 10분 뒤 정리
await this.ctx.storage.setAlarm(Date.now() + 10 * 60_000);
return Response.json({ ok: true });
}
if (url.pathname === "/info") {
const l = await this.load();
if (!l || l.finished) return Response.json({ exists: false });
return Response.json({ exists: true, kind: l.kind, players: l.players.size, phase: l.phase, rules: l.rules });
}
if (url.pathname === "/ws") {
if (req.headers.get("Upgrade") !== "websocket") return new Response("websocket only", { status: 426 });
const l = await this.load();
if (!l) return new Response("no such room", { status: 404 });
const uid = req.headers.get("x-uid");
const info = JSON.parse(req.headers.get("x-info") || "{}");
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
// 같은 유저의 이전 소켓은 정리 (재접속)
for (const old of this.ctx.getWebSockets(uid)) {
try {
old.serializeAttachment({ uid, replaced: true });
old.close(4000, "replaced");
} catch {}
}
this.ctx.acceptWebSocket(server, [uid]);
server.serializeAttachment({ uid });
const res = l.join(uid, info);
if (!res.ok) {
server.send(JSON.stringify({ t: "error", msg: res.reason, fatal: true }));
server.close(4001, "rejected");
}
await this.flush();
return new Response(null, { status: 101, webSocket: client });
}
return new Response("not found", { status: 404 });
}
async webSocketMessage(ws, data) {
const l = await this.load();
const att = ws.deserializeAttachment();
if (!l || !att || att.replaced) return;
let m;
try {
m = JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data));
} catch {
return;
}
l.handle(att.uid, m);
await this.flush(!QUIET.has(m.t));
}
async webSocketClose(ws) {
await this.onGone(ws);
}
async webSocketError(ws) {
await this.onGone(ws);
}
async onGone(ws) {
const l = await this.load();
const att = ws.deserializeAttachment();
if (!l || !att || att.replaced) return;
const others = this.ctx.getWebSockets(att.uid).filter((s) => s !== ws && s.readyState === 1);
if (!others.length) l.disconnect(att.uid);
await this.flush();
}
async alarm() {
const l = await this.load();
if (!l) return;
if (l.players.size === 0) {
await this.ctx.storage.deleteAll();
this.logic = null;
return;
}
l.tick();
await this.flush();
}
/** outbox 전송 + effects 처리 + 저장 + 다음 알람. */
async flush(persist = true) {
const l = this.logic;
if (!l) return;
// 효과를 먼저 처리해야 match_end(trDelta 포함)가 순서대로 나간다.
for (let guard = 0; guard < 4; guard++) {
const { out, effects } = l.drain();
this.deliver(out);
if (!effects.length) break;
for (const e of effects) await this.applyEffect(l, e);
}
if (persist) await this.save();
const wake = l.nextWake();
if (l.players.size === 0) {
await this.ctx.storage.setAlarm(Date.now() + 60_000);
} else if (wake) {
await this.ctx.storage.setAlarm(wake);
}
}
deliver(out) {
if (!out.length) return;
const sockets = this.ctx.getWebSockets();
for (const o of out) {
const payload = JSON.stringify(o.msg);
for (const ws of sockets) {
const att = ws.deserializeAttachment();
if (!att || att.replaced) continue;
if (o.to !== null && att.uid !== o.to) continue;
if (o.except && att.uid === o.except) continue;
try {
ws.send(payload);
} catch {}
}
}
}
async applyEffect(l, e) {
const db = this.env.DB;
if (e.type === "league_end") {
let result = null;
try {
result = await applyLeagueResult(db, { matchId: l.matchId, winner: e.winner, loser: e.loser, score: e.score });
} catch (err) {
console.error("league_end failed", err);
}
for (const uid of [e.winner, e.loser]) {
l.send(uid, {
t: "match_end", winner: e.winner, score: e.score,
trDelta: result?.[uid]?.trDelta ?? null, before: result?.[uid]?.before ?? null, after: result?.[uid]?.after ?? null,
});
}
} else if (e.type === "custom_end") {
try {
await recordCustom(db, { matchId: l.matchId, standings: e.standings, size: e.size });
} catch (err) {
console.error("custom_end failed", err);
}
l.matchId = crypto.randomUUID(); // 리매치는 새 경기
}
}
}

146
server/src/rules.js Normal file
View File

@@ -0,0 +1,146 @@
// TETRIG 서버 공용 규칙·튜닝 상수 (명세서 §6~§9).
// 튜닝 대상 수치는 전부 여기 모아 둔다. 클라이언트(Kotlin)의 Versus.kt 와 값이 같아야 한다.
export const BRAND = "TETRIG";
export const BRAND_KO = "테트리그";
// ── 대전 (§6) ────────────────────────────────────────────────────
export const ATTACK = {
lines: [0, 0, 1, 2, 4], // Single/Double/Triple/Quad
tspinMini: [0, 1], // Mini(0줄) / Mini Single
tspin: [0, 2, 4, 6], // T-spin 0/Single/Double/Triple
b2bBonus: 1,
allClear: 5,
combo: [1, 1, 2, 2, 3, 3, 4, 4, 4, 5], // 콤보 2부터(combo 인덱스 1부터), 이후 5 고정
};
export const GARBAGE_MAX_PER_INSERT = 8;
export const GARBAGE_SAME_HOLE_CHANCE = 0.7;
export const OVERTIME_START_MS = 90_000;
export const OVERTIME_STEP_MS = 30_000;
export const OVERTIME_STEP = 0.25;
export const AUTO_TARGET_MS = 8_000;
export const RECONNECT_GRACE_MS = 15_000;
export const ROUND_COUNTDOWN_MS = 3_000;
export const ROUND_GAP_MS = 4_000;
// 최소 안티치트 (§14.1)
export const MAX_PPS = 5.0;
// 한 피스로 낼 수 있는 이론상 최대치: T-spin Triple 6 + B2B 1 + AC 5 + 콤보 5 = 17
export const MAX_ATTACK_PER_PIECE = 17;
/**
* 한 번의 락 결과로 보낼 줄 수 (상쇄 전).
* combo: 연속 클리어 인덱스 (0 = 첫 클리어, 1 = 콤보 2번째 …). b2b: 연속 어려운 클리어 인덱스.
*/
export function attackFor({ lines, tspin = "none", allClear = false, combo = -1, b2b = -1, difficult = false }) {
if (lines <= 0) return 0;
let n;
if (tspin === "tspin") n = ATTACK.tspin[Math.min(lines, 3)];
else if (tspin === "mini") n = ATTACK.tspinMini[Math.min(lines, 1)];
else n = ATTACK.lines[Math.min(lines, 4)];
if (difficult && b2b >= 1) n += ATTACK.b2bBonus;
if (combo >= 1) n += ATTACK.combo[Math.min(combo - 1, ATTACK.combo.length - 1)];
if (allClear) n += ATTACK.allClear;
return n;
}
/** 장기전 배율: 90초 후 30초마다 +25%. */
export function overtimeMultiplier(elapsedMs, enabled = true) {
if (!enabled || elapsedMs < OVERTIME_START_MS) return 1;
return 1 + OVERTIME_STEP * (1 + Math.floor((elapsedMs - OVERTIME_START_MS) / OVERTIME_STEP_MS));
}
// ── 커스텀 룸 (§7) ───────────────────────────────────────────────
export const ROOM_CODE_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // I/1/O/0 제외
export const ROOM_CODE_LEN = 6;
export const DEFAULT_RULES = Object.freeze({
garbageMul: 1.0, // 0.5 ~ 2.0
ft: 0, // 0 = 무제한, 1/3/5
sameBag: false, // true = 동일 bag 공정전
overtime: true,
});
export function sanitizeRules(input = {}, base = DEFAULT_RULES) {
const r = { ...base };
if (typeof input.garbageMul === "number") r.garbageMul = Math.min(2, Math.max(0.5, Math.round(input.garbageMul * 4) / 4));
if ([0, 1, 3, 5].includes(input.ft)) r.ft = input.ft;
if (typeof input.sameBag === "boolean") r.sameBag = input.sameBag;
if (typeof input.overtime === "boolean") r.overtime = input.overtime;
return r;
}
export function randomRoomCode(rand = Math.random) {
let s = "";
for (let i = 0; i < ROOM_CODE_LEN; i++) s += ROOM_CODE_CHARS[Math.floor(rand() * ROOM_CODE_CHARS.length)];
return s;
}
export function isRoomCode(s) {
return typeof s === "string" && s.length === ROOM_CODE_LEN && [...s].every((c) => ROOM_CODE_CHARS.includes(c));
}
// ── 리그 (§8) ────────────────────────────────────────────────────
export const GLICKO = { R: 1500, RD: 350, VOL: 0.06, TAU: 0.5, RD_MIN: 58, RD_MAX: 350 };
export const TR_MID = 1600;
export const TR_SCALE = 300;
export const PLACEMENT_GAMES = 10;
export const RANK_VISIBLE_RD = 100;
export const RD_DECAY_IDLE_DAYS = 7;
export const RD_DECAY_PER_DAY = 1;
export const SEASON_LENGTH_DAYS = 61; // 약 2개월 (§17 기본 제안값)
export const RANKS = [
["D", 0], ["D+", 800], ["C-", 1400], ["C", 2000], ["C+", 2600], ["B-", 3300], ["B", 4000], ["B+", 4800],
["A-", 5700], ["A", 6700], ["A+", 7800], ["S-", 9200], ["S", 10800], ["S+", 12400], ["SS", 14200],
["U", 16500], ["X", 19500], ["X+", 22500],
];
export function trFor(R, RD) {
return Math.round(25000 / (1 + Math.pow(10, (TR_MID - (R - RD)) / TR_SCALE)));
}
export function rankFor(tr) {
let r = RANKS[0][0];
for (const [name, cut] of RANKS) if (tr >= cut) r = name;
return r;
}
/** 경기 형식: 높은 쪽 랭크가 S- 이상이면 FT5, 아니면 FT3. */
export function leagueFt(trA, trB) {
const sMinus = RANKS.find(([n]) => n === "S-")[1];
return Math.max(trA, trB) >= sMinus ? 5 : 3;
}
// 매치메이킹 (§8.3)
export const MM_WINDOW_RD = 2;
export const MM_EXPAND_EVERY_MS = 30_000;
export const MM_EXPAND_FACTOR = 1.2;
export const MM_HINT_AFTER_MS = 120_000;
// ── 계정 (§9) ────────────────────────────────────────────────────
export const GUEST_ADJ = [
"재빠른", "용감한", "조용한", "빛나는", "날쌘", "느긋한", "단단한", "엉뚱한", "반짝이는", "졸린",
"배고픈", "씩씩한", "수상한", "깜찍한", "똑똑한", "푸른", "붉은", "하얀", "검은", "노란",
];
export const GUEST_NOUN = [
"미노", "블록", "벽돌", "큐브", "타일", "조각", "기둥", "탑", "망치", "번개",
"여우", "고양이", "펭귄", "수달", "다람쥐", "부엉이", "판다", "고래", "참새", "두더지",
];
export function randomGuestName(rand = Math.random) {
const a = GUEST_ADJ[Math.floor(rand() * GUEST_ADJ.length)];
const n = GUEST_NOUN[Math.floor(rand() * GUEST_NOUN.length)];
const d = String(Math.floor(rand() * 1000)).padStart(3, "0");
return a + n + d;
}
/** 게스트명 패턴은 시스템 예약 — 로그인 유저가 이 모양의 닉으로 바꿀 수 없다. */
export function looksLikeGuestName(s) {
const m = /^(.+?)(\d{3})$/.exec(s);
if (!m) return false;
return GUEST_ADJ.some((a) => m[1].startsWith(a) && GUEST_NOUN.includes(m[1].slice(a.length)));
}
export const NICK_RE = /^[가-힣A-Za-z0-9_]{2,12}$/;
export const NICK_COOLDOWN_MS = 30 * 24 * 3600 * 1000;
export const TOKEN_TTL_MS = 30 * 24 * 3600 * 1000;
export const PBKDF2_ITER = 100_000;
export const SOLO_MODES = ["sprint", "time", "endless"];