From 8fcef8e72063ea5a686479ceca94f1a01063d91c Mon Sep 17 00:00:00 2001 From: tkrmagid Date: Wed, 4 Nov 2026 09:27:15 +0900 Subject: [PATCH] =?UTF-8?q?=EC=84=9C=EB=B2=84:=20Cloudflare=20Workers=20?= =?UTF-8?q?=EB=A9=80=ED=8B=B0=ED=94=8C=EB=A0=88=EC=9D=B4=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20(Phase=204~6=20=EC=84=9C=EB=B2=84=20?= =?UTF-8?q?=EC=B8=A1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 게스트/이메일/Google 계정, 게스트 기록 이전, 닉네임 정책 - GameRoomDO: 커스텀 1:1·FFA, 가비지 중계·배율·장기전, 타겟팅, KO, 재접속 유예, 리매치 투표 - MatchmakerDO + Glicko-2 + TR/18랭크 + 리그 결과 기록 - 리더보드·솔로 기록·시즌/RD 감쇠 Cron - 단위 테스트 17개 + 종단 테스트 스크립트 Co-Authored-By: Claude Opus 5.5 --- server/.gitignore | 3 + server/README.md | 49 ++ server/migrations/0001_init.sql | 58 ++ server/package-lock.json | 1454 +++++++++++++++++++++++++++++++ server/package.json | 14 + server/scripts/e2e.mjs | 124 +++ server/src/auth.js | 99 +++ server/src/db.js | 162 ++++ server/src/glicko.js | 76 ++ server/src/index.js | 311 +++++++ server/src/matchmaker.js | 72 ++ server/src/matchmaking.js | 38 + server/src/room-logic.js | 480 ++++++++++ server/src/room.js | 180 ++++ server/src/rules.js | 146 ++++ server/test/room.test.js | 177 ++++ server/test/rules.test.js | 83 ++ server/wrangler.toml | 32 + 18 files changed, 3558 insertions(+) create mode 100644 server/.gitignore create mode 100644 server/README.md create mode 100644 server/migrations/0001_init.sql create mode 100644 server/package-lock.json create mode 100644 server/package.json create mode 100644 server/scripts/e2e.mjs create mode 100644 server/src/auth.js create mode 100644 server/src/db.js create mode 100644 server/src/glicko.js create mode 100644 server/src/index.js create mode 100644 server/src/matchmaker.js create mode 100644 server/src/matchmaking.js create mode 100644 server/src/room-logic.js create mode 100644 server/src/room.js create mode 100644 server/src/rules.js create mode 100644 server/test/room.test.js create mode 100644 server/test/rules.test.js create mode 100644 server/wrangler.toml diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..a933f10 --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.wrangler/ +.dev.vars diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..cdcbe9c --- /dev/null +++ b/server/README.md @@ -0,0 +1,49 @@ +# TETRIG 서버 (Cloudflare Workers) + +배포 주소: https://tetrig.tkrmagid.workers.dev + +- `src/index.js` — REST API + WebSocket 라우팅 + Cron +- `src/room-logic.js` — 경기방 상태 기계 (리그 1:1 · 커스텀 N인 공용, 순수 로직) +- `src/room.js` — GameRoomDO (WebSocket Hibernation, 상태는 DO storage 에 저장) +- `src/matchmaker.js` / `src/matchmaking.js` — 리그 대기열 (R ± 2×RD, 30초마다 ×1.2 확장) +- `src/glicko.js` — Glicko-2, `src/rules.js` — 튜닝 상수 전부 +- `migrations/` — D1 스키마 + +## 개발 + +```bash +npm install +npm test # 단위 테스트 +printf 'TOKEN_SECRET=dev\n' > .dev.vars +npx wrangler d1 migrations apply tetrig --local +npx wrangler dev --local --port 8799 +node scripts/e2e.mjs http://127.0.0.1:8799 # 종단 테스트 (게스트·FFA·계정·리그) +``` + +## 배포 + +```bash +export CLOUDFLARE_API_TOKEN=... CLOUDFLARE_ACCOUNT_ID=... +npx wrangler d1 migrations apply tetrig --remote +npx wrangler deploy +``` + +비밀값 `TOKEN_SECRET` 은 `wrangler secret put` 으로만 넣는다 (재설정하면 기존 로그인 세션이 모두 끊김). +Google 로그인은 `wrangler.toml` 의 `GOOGLE_CLIENT_IDS` 에 OAuth 클라이언트 ID 를 넣으면 켜진다. + +## API 요약 + +| 경로 | 설명 | +|---|---| +| `POST /api/guest` | 게스트 발급 (랜덤 닉) → `{token, user}` | +| `POST /api/register` | 이메일 가입. 게스트 토큰을 같이 보내면 그 계정을 승격(기록 유지) | +| `POST /api/login` | 이메일 로그인. 게스트 토큰을 같이 보내면 기록 병합 | +| `POST /api/google` | Google ID 토큰 로그인 | +| `GET /api/me` | 프로필·리그 요약·솔로 베스트·최근 전적 | +| `POST /api/nickname` · `GET /api/nickname/check?n=` | 닉 변경(30일 쿨다운) · 중복 검사 | +| `POST /api/solo` | 솔로 베스트 제출 `{mode, value}` | +| `GET /api/leaderboard?board=league\|sprint\|time\|endless` | 상위 100 (계정만) | +| `POST /api/rooms` · `GET /api/rooms/:code` | 커스텀 방 생성 · 조회 | +| `WS /ws/room/:code` · `WS /ws/league/:id` · `WS /ws/queue` | 경기방 · 리그 경기 · 리그 대기열 (`?token=`) | + +WebSocket 메시지 형식은 명세서 §14.3 + `src/room-logic.js` 의 `handle()` 참고. diff --git a/server/migrations/0001_init.sql b/server/migrations/0001_init.sql new file mode 100644 index 0000000..0a0e253 --- /dev/null +++ b/server/migrations/0001_init.sql @@ -0,0 +1,58 @@ +-- TETRIG D1 스키마 (명세서 §14.2 기반) +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + nickname TEXT UNIQUE NOT NULL, + is_guest INTEGER NOT NULL DEFAULT 1, + email TEXT UNIQUE, + google_sub TEXT UNIQUE, + pw_hash TEXT, + pw_salt TEXT, + device_id TEXT, + created_at INTEGER, + nickname_changed_at INTEGER +); + +CREATE TABLE IF NOT EXISTS ratings ( + user_id TEXT PRIMARY KEY REFERENCES users(id), + season INTEGER NOT NULL, + glicko REAL NOT NULL, + rd REAL NOT NULL, + vol REAL NOT NULL, + tr INTEGER NOT NULL DEFAULT 0, + games INTEGER NOT NULL DEFAULT 0, -- 이번 시즌 + wins INTEGER NOT NULL DEFAULT 0, -- 이번 시즌 + total_games INTEGER NOT NULL DEFAULT 0, -- 누적 (배치 판정용) + last_played INTEGER +); +CREATE INDEX IF NOT EXISTS ratings_tr ON ratings(tr DESC); + +CREATE TABLE IF NOT EXISTS matches ( + id TEXT NOT NULL, + season INTEGER, + mode TEXT NOT NULL, -- 'league' | 'custom' + finished_at INTEGER, + room_size INTEGER, + p1 TEXT NOT NULL, -- 커스텀 FFA 는 p1 = 본인, score1 = 순위 + p2 TEXT, + score1 INTEGER, + score2 INTEGER, + tr_delta1 INTEGER, + tr_delta2 INTEGER, + PRIMARY KEY (id, p1) +); +CREATE INDEX IF NOT EXISTS matches_p1 ON matches(p1, finished_at DESC); +CREATE INDEX IF NOT EXISTS matches_p2 ON matches(p2, finished_at DESC); + +CREATE TABLE IF NOT EXISTS solo_records ( + user_id TEXT NOT NULL, + mode TEXT NOT NULL, -- 'sprint'(ms, 낮을수록 좋음) | 'time' | 'endless'(점수) + best INTEGER NOT NULL, + updated_at INTEGER, + PRIMARY KEY (user_id, mode) +); +CREATE INDEX IF NOT EXISTS solo_mode_best ON solo_records(mode, best); + +CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 0000000..94f078a --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,1454 @@ +{ + "name": "tetrig-server", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tetrig-server", + "version": "0.1.0", + "devDependencies": { + "wrangler": "^4.40.0" + } + }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==", + "dev": true, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261103.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261103.1.tgz", + "integrity": "sha512-6lWDetzg9mclXUVv/u6/WQWzuJ96cgBqnQ+kEhqckm5TE6FPUkXkCmjMfyIt0qff6aWhhrtYxEfcE2e1X1i4nQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261103.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261103.1.tgz", + "integrity": "sha512-dtsvzndPMoGK9zHCq/pCIekywDsY1RLcBWZnzK2iL7L4jVvJVsBeRe3a+3lMgIRyM4HcelnJup7tT+2s3WYxHw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261103.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261103.1.tgz", + "integrity": "sha512-g++gRXeum4QXseRgX7/X8RHH+A/wzypgslqVnOzttLjpmw3l+XXRo85S+ct1yYfOsQrlh1II+y3HYbdn2Goxvg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261103.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261103.1.tgz", + "integrity": "sha512-zvVXyJ8h68MVBYboxqZaemdmbvjjNPlZTeKDrwlaaVYaDBWTRsiPjRunEwNtlYF/Zq1IXYEEgkNo4xGAEg+qiQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261103.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261103.1.tgz", + "integrity": "sha512-g7zu5yaJyxPsVAn/WChF3vu0PheeIh/7HCJ3WTOGKshWCcwv1jUs/+Y13cR3srOQ1CGvJSDJoJXrAixQ2M4+IA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/miniflare": { + "version": "5.20261103.0-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261103.0-beta.tgz", + "integrity": "sha512-wghSXG3KHzMbAYvcrHFxN6JNI1Or3LSxpBe1qHdnFXFOPIDIlXCNvsRVF2J97rXsfFSJr7EzxRSjoUCmgVDEUA==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.30.1", + "workerd": "1.20261103.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "optional": true + }, + "node_modules/undici": { + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", + "dev": true, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "dependencies": { + "pathe": "^2.0.3" + } + }, + "node_modules/workerd": { + "version": "1.20261103.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261103.1.tgz", + "integrity": "sha512-GgcAnUH94uY8BEDc7CUyX3qsuLVbiidV+SZqJhasxbKi+f2dtR5xrgBC18uLbnaBFarlNFCYfr8JAIL2xJpnZw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261103.1", + "@cloudflare/workerd-darwin-arm64": "1.20261103.1", + "@cloudflare/workerd-linux-64": "1.20261103.1", + "@cloudflare/workerd-linux-arm64": "1.20261103.1", + "@cloudflare/workerd-windows-64": "1.20261103.1" + } + }, + "node_modules/wrangler": { + "version": "4.157.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.157.0.tgz", + "integrity": "sha512-HUft0VZiUbt/oFZXQRDmJAGzPgfDYpdVmJwCGlGBcXrE5IP0yGcTwc1u/H3+bUYhaX2NHoL1sdQqn3zptxyFkA==", + "dev": true, + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.2", + "@cspotcode/source-map-support": "0.8.1", + "blake3-wasm": "2.1.5", + "esbuild": "0.28.2", + "miniflare": "5.20261103.0-beta", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20261103.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20261103.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..03cbe05 --- /dev/null +++ b/server/package.json @@ -0,0 +1,14 @@ +{ + "name": "tetrig-server", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test test/*.test.js", + "dev": "wrangler dev --local", + "deploy": "wrangler deploy" + }, + "devDependencies": { + "wrangler": "^4.40.0" + } +} diff --git a/server/scripts/e2e.mjs b/server/scripts/e2e.mjs new file mode 100644 index 0000000..272d6d3 --- /dev/null +++ b/server/scripts/e2e.mjs @@ -0,0 +1,124 @@ +// 실서버(로컬 wrangler dev 또는 배포본) 대상 종단 테스트. node scripts/e2e.mjs [baseUrl] +const BASE = process.argv[2] || "http://127.0.0.1:8799"; +const WS = BASE.replace(/^http/, "ws"); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let fails = 0; +const check = (cond, label) => { console.log(`${cond ? "✓" : "✗"} ${label}`); if (!cond) fails++; }; + +async function api(path, { method = "GET", token, body } = {}) { + const res = await fetch(BASE + path, { + method, headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }); + return { status: res.status, data: await res.json().catch(() => null) }; +} + +function client(url, name) { + const ws = new WebSocket(url); + const inbox = []; + const waiters = []; + ws.onmessage = (e) => { + const m = JSON.parse(e.data); + inbox.push(m); + for (const w of [...waiters]) if (w.pred(m)) { waiters.splice(waiters.indexOf(w), 1); w.res(m); } + }; + const open = new Promise((res, rej) => { ws.onopen = res; ws.onerror = () => rej(new Error(name + " ws error")); }); + return { + ws, inbox, open, name, + send: (m) => ws.send(JSON.stringify(m)), + wait(pred, ms = 8000) { + const hit = inbox.find(pred); + if (hit) { inbox.splice(inbox.indexOf(hit), 1); return Promise.resolve(hit); } + return new Promise((res, rej) => { + const w = { pred, res: (m) => { clearTimeout(to); inbox.splice(inbox.indexOf(m), 1); res(m); } }; + const to = setTimeout(() => rej(new Error(`${name}: timeout waiting`)), ms); + waiters.push(w); + }); + }, + }; +} + +const guests = []; +for (let i = 0; i < 4; i++) guests.push((await api("/api/guest", { method: "POST", body: { deviceId: "dev" + i } })).data); +check(guests.every((g) => g.token && g.user.guest), "게스트 4명 발급: " + guests.map((g) => g.user.nickname).join(", ")); + +// ── 커스텀 FFA ── +const { data: room } = await api("/api/rooms", { method: "POST", token: guests[0].token, body: { rules: { ft: 1 } } }); +check(/^[A-HJ-NP-Z2-9]{6}$/.test(room.code), "방 코드 발급 " + room.code); +check((await api(`/api/rooms/${room.code}`)).data.exists, "방 조회"); +check(!(await api(`/api/rooms/ZZZZZZ`)).data.exists, "없는 방은 exists=false"); +const cs = guests.map((g, i) => client(`${WS}/ws/room/${room.code}?token=${g.token}`, "p" + i)); +for (const c of cs) { await c.open; await c.wait((m) => m.t === "sync"); } +const lobby = await cs[0].wait((m) => m.t === "lobby" && m.players.length === 4); +check(lobby.host === guests[0].user.id && lobby.rules.ft === 1, "로비 4인, 호스트=p0, FT1"); +cs[0].send({ t: "start" }); +const rs = await Promise.all(cs.map((c) => c.wait((m) => m.t === "round_start"))); +check(rs.every((m) => m.seed > 0 && m.startIn === 3000), "4명 모두 round_start(seed) 수신"); +await sleep(3100); +const ids = guests.map((g) => g.user.id); +cs[0].send({ t: "target", id: ids[2] }); +cs[0].send({ t: "attack", lines: 4, pieces: 2 }); +const g2 = await cs[2].wait((m) => m.t === "garbage"); +check(g2.from === ids[0] && g2.lines === 4, "p0 → p2 가비지 4줄 (수동 타겟)"); +cs[1].send({ t: "board", grid: ".".repeat(190) + "GGGGGGGGG.", lock: true }); +const b = await cs[3].wait((m) => m.t === "board"); +check(b.id === ids[1], "보드 스냅샷 중계"); +cs[2].send({ t: "topout" }); +const ko = await cs[0].wait((m) => m.t === "ko" && m.who === ids[2]); +check(ko.by === ids[0] && ko.place === 4, "KO 피드: p0 → p2 격추 (4위)"); +cs[1].send({ t: "topout" }); cs[3].send({ t: "topout" }); +const me = await cs[0].wait((m) => m.t === "match_end"); +check(me.winner === ids[0] && me.result[0].id === ids[0], "FT1 매치 종료, 우승 p0"); +cs[1].send({ t: "rematch", vote: true }); cs[2].send({ t: "rematch", vote: true }); cs[3].send({ t: "rematch", vote: true }); +check((await cs[0].wait((m) => m.t === "round_start")).n === 1, "리매치 과반 → 새 경기 1라운드"); +for (const c of cs) c.ws.close(); + +// ── 계정 ── +const email = `t${Date.now()}@ex.com`; +const sprint = await api("/api/solo", { method: "POST", token: guests[0].token, body: { mode: "sprint", value: 65000 } }); +check(sprint.data.improved, "게스트 솔로 기록 저장"); +const reg = await api("/api/register", { method: "POST", token: guests[0].token, body: { email, password: "password1", nickname: "테스터" + (Date.now() % 1000) } }); +check(reg.status === 200 && !reg.data.user.guest && reg.data.user.id === ids[0], "게스트 → 이메일 계정 승격(같은 ID)"); +const meRes = await api("/api/me", { token: reg.data.token }); +check(meRes.data.solo.sprint === 65000 && meRes.data.recent.some((m) => m.mode === "custom"), "승격 후 솔로 기록·커스텀 전적 유지"); +check((await api("/api/login", { method: "POST", body: { email, password: "wrong-pass" } })).status === 401, "틀린 비밀번호 401"); +await api("/api/solo", { method: "POST", token: guests[1].token, body: { mode: "sprint", value: 50000 } }); +const login = await api("/api/login", { method: "POST", token: guests[1].token, body: { email, password: "password1" } }); +check(login.status === 200 && login.data.user.id === ids[0], "로그인 성공"); +const me2 = await api("/api/me", { token: login.data.token }); +check(me2.data.solo.sprint === 50000, "로그인 시 게스트 기록 병합 (더 좋은 기록 50.000)"); +check((await api("/api/nickname", { method: "POST", token: login.data.token, body: { nickname: "다른닉" } })).status === 429, "닉 변경 30일 쿨다운"); +check((await api("/api/nickname/check?n=재빠른미노123")).data.ok === false, "게스트명 패턴 예약"); + +// ── 리그 ── +const acct = [login.data]; +const reg2 = await api("/api/register", { method: "POST", body: { email: "b" + email, password: "password2" } }); +acct.push(reg2.data); +const gq = client(`${WS}/ws/queue?token=${guests[2].token}`, "gq"); +const gqErr = await gq.open.then(() => "opened", () => "rejected"); +check(gqErr === "rejected", "게스트는 리그 큐 접속 거부"); +const qa = client(`${WS}/ws/queue?token=${acct[0].token}`, "qa"); +const qb = client(`${WS}/ws/queue?token=${acct[1].token}`, "qb"); +await qa.open; await qb.open; +const [ma, mb] = await Promise.all([qa.wait((m) => m.t === "matched"), qb.wait((m) => m.t === "matched")]); +check(ma.room === mb.room && ma.ft === 3, "매칭 성사 (FT3) " + ma.room.slice(0, 8)); +const la = client(`${WS}/ws/league/${ma.room}?token=${acct[0].token}`, "la"); +const lb = client(`${WS}/ws/league/${ma.room}?token=${acct[1].token}`, "lb"); +await la.open; await lb.open; +for (let r = 1; r <= 3; r++) { + await la.wait((m) => m.t === "round_start", 10000); + await lb.wait((m) => m.t === "round_start", 10000); + await sleep(3100); + lb.send({ t: "topout" }); + await la.wait((m) => m.t === "round_end"); +} +const [ea, eb] = await Promise.all([la.wait((m) => m.t === "match_end"), lb.wait((m) => m.t === "match_end")]); +check(ea.winner === acct[0].user.id && ea.trDelta > 0 && eb.trDelta < 0, `리그 결과 TR 반영 (승 +${ea.trDelta} / 패 ${eb.trDelta})`); +const meL = await api("/api/me", { token: acct[0].token }); +check(meL.data.league.placement === 1 && meL.data.league.tr === null && meL.data.recent[0].mode === "league", "배치 1/10, TR 비공개, 리그 전적 기록"); +la.ws.close(); lb.ws.close(); +const lbSprint = await api("/api/leaderboard?board=sprint"); +check(lbSprint.data.rows.some((r) => r.id === acct[0].user.id) && !lbSprint.data.rows.some((r) => r.id === ids[3]), "SPRINT 리더보드: 계정만 등재"); + +console.log(fails ? `\n실패 ${fails}건` : "\n전부 통과"); +process.exit(fails ? 1 : 0); diff --git a/server/src/auth.js b/server/src/auth.js new file mode 100644 index 0000000..451e796 --- /dev/null +++ b/server/src/auth.js @@ -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; +} diff --git a/server/src/db.js b/server/src/db.js new file mode 100644 index 0000000..4b52b40 --- /dev/null +++ b/server/src/db.js @@ -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 }; +} diff --git a/server/src/glicko.js b/server/src/glicko.js new file mode 100644 index 0000000..7d63ed4 --- /dev/null +++ b/server/src/glicko.js @@ -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 }; +} diff --git a/server/src/index.js b/server/src/index.js new file mode 100644 index 0000000..cc0bc7a --- /dev/null +++ b/server/src/index.js @@ -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); + }, +}; diff --git a/server/src/matchmaker.js b/server/src/matchmaker.js new file mode 100644 index 0000000..2d52e84 --- /dev/null +++ b/server/src/matchmaker.js @@ -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() {} +} diff --git a/server/src/matchmaking.js b/server/src/matchmaking.js new file mode 100644 index 0000000..3484274 --- /dev/null +++ b/server/src/matchmaking.js @@ -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; +} diff --git a/server/src/room-logic.js b/server/src/room-logic.js new file mode 100644 index 0000000..e496510 --- /dev/null +++ b/server/src/room-logic.js @@ -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} 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; +} diff --git a/server/src/room.js b/server/src/room.js new file mode 100644 index 0000000..e745590 --- /dev/null +++ b/server/src/room.js @@ -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(); // 리매치는 새 경기 + } + } +} diff --git a/server/src/rules.js b/server/src/rules.js new file mode 100644 index 0000000..a57615d --- /dev/null +++ b/server/src/rules.js @@ -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"]; diff --git a/server/test/room.test.js b/server/test/room.test.js new file mode 100644 index 0000000..0c0287f --- /dev/null +++ b/server/test/room.test.js @@ -0,0 +1,177 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { RoomLogic } from "../src/room-logic.js"; + +function mkRoom(kind = "custom", extra = {}) { + let t = 1_000_000; + const clock = { now: () => t, adv: (ms) => (t += ms) }; + let seed = 1; + const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + const r = new RoomLogic({ id: "R", kind, code: "ABCDEF", now: clock.now, rand, ...extra }); + return { r, clock }; +} +const msgs = (r, uid, type) => r.drain().out.filter((o) => (o.to === null ? o.except !== uid : o.to === uid) && (!type || o.msg.t === type)).map((o) => o.msg); +const startPlaying = (r, clock) => { r.handle(r.host, { t: "start" }); clock.adv(3001); r.tick(); }; + +test("커스텀 1:1: 호스트 시작 → 가비지 → 톱아웃 → 라운드 승리", () => { + const { r, clock } = mkRoom(); + r.join("a", { nick: "A" }); + r.join("b", { nick: "B" }); + assert.equal(r.host, "a"); + r.drain(); + r.handle("b", { t: "start" }); // 호스트 아님 + assert.equal(r.phase, "lobby"); + r.handle("a", { t: "start" }); + assert.equal(r.phase, "countdown"); + const starts = r.drain().out.filter((o) => o.msg.t === "round_start"); + assert.equal(starts.length, 2); + assert.ok(starts.every((o) => o.msg.seed > 0)); + clock.adv(3001); + r.tick(); + assert.equal(r.phase, "playing"); + r.handle("a", { t: "attack", lines: 4, pieces: 3 }); + const g = msgs(r, "b", "garbage"); + assert.deepEqual(g, [{ t: "garbage", from: "a", lines: 4 }]); + r.handle("b", { t: "topout" }); + const out = r.drain().out.map((o) => o.msg); + assert.ok(out.find((m) => m.t === "ko" && m.who === "b" && m.by === "a")); + const end = out.find((m) => m.t === "round_end"); + assert.equal(end.winner, "a"); + assert.equal(end.score.a, 1); + assert.equal(r.phase, "between"); // FT 무제한 → 다음 라운드 대기 + clock.adv(4001); + r.tick(); + assert.equal(r.phase, "countdown"); + assert.equal(r.round, 2); +}); + +test("가비지 배율 0.5× 는 소수 누적(carry)으로 공정하게", () => { + const { r, clock } = mkRoom(); + r.join("a"); r.join("b"); + r.handle("a", { t: "rules", rules: { garbageMul: 0.5, overtime: false } }); + startPlaying(r, clock); + r.drain(); + r.handle("a", { t: "attack", lines: 1, pieces: 1 }); + assert.equal(msgs(r, "b", "garbage").length, 0); + r.handle("a", { t: "attack", lines: 1, pieces: 2 }); + assert.equal(msgs(r, "b", "garbage")[0].lines, 1); +}); + +test("안티치트: 비정상 공격량·PPS 는 무시", () => { + const { r, clock } = mkRoom(); + r.join("a"); r.join("b"); + startPlaying(r, clock); + r.drain(); + r.handle("a", { t: "attack", lines: 40, pieces: 1 }); + r.handle("a", { t: "attack", lines: 4, pieces: 500 }); + assert.equal(msgs(r, "b", "garbage").length, 0); + assert.equal(r.players.get("a").flagged, 2); +}); + +test("FFA 4인: 타겟 수동 지정, KO 순위, 최후 생존자 승리, FT1 → match_end → 리매치 과반", () => { + const { r, clock } = mkRoom(); + for (const u of ["a", "b", "c", "d"]) r.join(u, { nick: u.toUpperCase() }); + r.handle("a", { t: "rules", rules: { ft: 1 } }); + startPlaying(r, clock); + r.drain(); + r.handle("a", { t: "target", id: "c" }); + r.handle("a", { t: "attack", lines: 2, pieces: 2 }); + assert.equal(msgs(r, "c", "garbage")[0].from, "a"); + r.handle("c", { t: "topout" }); + assert.equal(r.players.get("c").place, 4); + r.handle("a", { t: "attack", lines: 2, pieces: 3 }); // 수동 타겟이 죽었으니 자동 타겟으로 + const atk = r.drain().out.find((o) => o.msg.t === "garbage"); + assert.ok(["b", "d"].includes(atk.to)); + r.handle("d", { t: "topout" }); + r.handle("b", { t: "topout" }); + assert.equal(r.phase, "match_end"); + const { effects } = r.drain(); + assert.equal(effects[0].type, "custom_end"); + assert.equal(effects[0].standings[0].id, "a"); + r.handle("a", { t: "rematch", vote: true }); + r.handle("b", { t: "rematch", vote: true }); + assert.equal(r.phase, "match_end"); // 2/4 는 과반 아님 + r.handle("c", { t: "rematch", vote: true }); + assert.equal(r.phase, "countdown"); + assert.equal(r.players.get("a").wins, 0); +}); + +test("도중 입장은 관전 후 다음 라운드부터 참전", () => { + const { r, clock } = mkRoom(); + r.join("a"); r.join("b"); + startPlaying(r, clock); + r.join("c"); + assert.equal(r.players.get("c").inRound, false); + r.handle("b", { t: "topout" }); + clock.adv(4001); + r.tick(); + assert.equal(r.players.get("c").inRound, true); +}); + +test("호스트 퇴장 시 다음 입장자에게 위임", () => { + const { r } = mkRoom(); + r.join("a"); r.join("b"); r.join("c"); + r.handle("a", { t: "leave" }); + assert.equal(r.host, "b"); +}); + +test("재접속 유예 15초: 그 안에 돌아오면 유지, 넘기면 톱아웃", () => { + const { r, clock } = mkRoom(); + r.join("a"); r.join("b"); r.join("c"); + startPlaying(r, clock); + r.disconnect("b"); + clock.adv(10_000); r.tick(); + assert.equal(r.players.get("b").alive, true); + r.handle("a", { t: "target", id: "b" }); + r.handle("a", { t: "attack", lines: 2, pieces: 2 }); + r.drain(); + r.join("b"); + const back = msgs(r, "b"); + assert.ok(back.find((m) => m.t === "sync")); + assert.ok(back.find((m) => m.t === "garbage" && m.lines === 2)); // 끊긴 동안 받은 가비지 재전달 + r.disconnect("c"); + clock.adv(15_001); r.tick(); + assert.equal(r.players.get("c").alive, false); +}); + +test("리그: 지정된 2명만 입장, 둘 다 오면 자동 시작, FT3, 이탈은 몰수패", () => { + const { r, clock } = mkRoom("league", { allowed: ["a", "b"], ft: 3 }); + assert.equal(r.join("x").ok, false); + r.join("a"); + assert.equal(r.phase, "lobby"); + r.join("b"); + assert.equal(r.phase, "countdown"); + for (let i = 0; i < 2; i++) { + clock.adv(3001); r.tick(); + r.handle("b", { t: "topout" }); + clock.adv(4001); r.tick(); + } + assert.equal(r.players.get("a").wins, 2); + r.drain(); + r.disconnect("a"); + clock.adv(15_001); r.tick(); + assert.equal(r.phase, "match_end"); + const { effects } = r.drain(); + assert.deepEqual({ w: effects[0].winner, l: effects[0].loser }, { w: "b", l: "a" }); + assert.equal(r.finished, true); +}); + +test("직렬화 왕복 (하이버네이션 복원)", () => { + const { r } = mkRoom(); + r.join("a", { nick: "A" }); r.join("b", { nick: "B" }); + const j = JSON.parse(JSON.stringify(r.toJSON())); + const r2 = RoomLogic.fromJSON(j); + assert.equal(r2.players.get("a").nick, "A"); + assert.equal(r2.host, "a"); +}); + +test("보드 스냅샷 검증·중계", () => { + const { r, clock } = mkRoom(); + r.join("a"); r.join("b"); + startPlaying(r, clock); + r.drain(); + r.handle("a", { t: "board", grid: "x".repeat(200) }); + assert.equal(msgs(r, "b", "board").length, 0); + r.handle("a", { t: "board", grid: ".".repeat(190) + "GGGGGGGGG.", lock: true }); + assert.equal(msgs(r, "b", "board").length, 1); +}); diff --git a/server/test/rules.test.js b/server/test/rules.test.js new file mode 100644 index 0000000..9a4b897 --- /dev/null +++ b/server/test/rules.test.js @@ -0,0 +1,83 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { attackFor, overtimeMultiplier, trFor, rankFor, leagueFt, randomRoomCode, isRoomCode, randomGuestName, looksLikeGuestName, sanitizeRules } from "../src/rules.js"; +import { glickoUpdate } from "../src/glicko.js"; +import { findPairs, compatible } from "../src/matchmaking.js"; + +test("가비지 전송 테이블 (§6)", () => { + assert.equal(attackFor({ lines: 1 }), 0); + assert.equal(attackFor({ lines: 2 }), 1); + assert.equal(attackFor({ lines: 3 }), 2); + assert.equal(attackFor({ lines: 4, difficult: true, b2b: 0 }), 4); + assert.equal(attackFor({ lines: 4, difficult: true, b2b: 1 }), 5); // B2B +1 + assert.equal(attackFor({ lines: 1, tspin: "mini" }), 1); + assert.equal(attackFor({ lines: 0, tspin: "mini" }), 0); + assert.equal(attackFor({ lines: 2, tspin: "tspin", difficult: true, b2b: 0 }), 4); + assert.equal(attackFor({ lines: 3, tspin: "tspin", difficult: true, b2b: 0 }), 6); + assert.equal(attackFor({ lines: 1, combo: 1 }), 1); // 콤보 2번째 → +1 + assert.equal(attackFor({ lines: 1, combo: 20 }), 5); // 이후 5 고정 + assert.equal(attackFor({ lines: 4, allClear: true }), 9); +}); + +test("장기전 배율", () => { + assert.equal(overtimeMultiplier(89_999), 1); + assert.equal(overtimeMultiplier(90_000), 1.25); + assert.equal(overtimeMultiplier(120_000), 1.5); + assert.equal(overtimeMultiplier(200_000, false), 1); +}); + +test("TR·랭크·FT", () => { + assert.ok(trFor(1500, 350) < 1000); + assert.ok(trFor(2500, 60) > 24000); + assert.equal(rankFor(0), "D"); + assert.equal(rankFor(7800), "A+"); + assert.equal(rankFor(9199), "A+"); + assert.equal(rankFor(9200), "S-"); + assert.equal(rankFor(25000), "X+"); + assert.equal(leagueFt(7000, 9199), 3); + assert.equal(leagueFt(1000, 9200), 5); +}); + +test("방 코드·게스트명·규칙", () => { + for (let i = 0; i < 200; i++) { + const c = randomRoomCode(); + assert.ok(isRoomCode(c), c); + assert.ok(!/[I1O0]/.test(c)); + } + const n = randomGuestName(); + assert.match(n, /\d{3}$/); + assert.ok(looksLikeGuestName(n)); + assert.ok(!looksLikeGuestName("홍길동")); + assert.deepEqual(sanitizeRules({ garbageMul: 9, ft: 7, sameBag: true }), { garbageMul: 2, ft: 0, sameBag: true, overtime: true }); +}); + +test("Glicko-2: Glickman 논문 예제", () => { + const p = glickoUpdate({ r: 1500, rd: 200, vol: 0.06 }, [ + { r: 1400, rd: 30, score: 1 }, + { r: 1550, rd: 100, score: 0 }, + { r: 1700, rd: 300, score: 0 }, + ]); + assert.ok(Math.abs(p.r - 1464.06) < 0.05, String(p.r)); + assert.ok(Math.abs(p.rd - 151.52) < 0.05, String(p.rd)); + assert.ok(Math.abs(p.vol - 0.05999) < 0.0001, String(p.vol)); +}); + +test("Glicko-2: 승자는 오르고 패자는 내려간다, RD 하한 58", () => { + const w = glickoUpdate({ r: 1500, rd: 350, vol: 0.06 }, [{ r: 1500, rd: 350, score: 1 }]); + const l = glickoUpdate({ r: 1500, rd: 350, vol: 0.06 }, [{ r: 1500, rd: 350, score: 0 }]); + assert.ok(w.r > 1500 && l.r < 1500); + const tight = glickoUpdate({ r: 1500, rd: 58, vol: 0.06 }, [{ r: 1500, rd: 58, score: 1 }]); + assert.ok(tight.rd >= 58); +}); + +test("매치메이킹: R±2RD 겹침, 대기 시간에 따라 확장", () => { + const now = 1_000_000; + const a = { uid: "a", r: 1500, rd: 50, joinedAt: now }; + const b = { uid: "b", r: 1750, rd: 50, joinedAt: now }; + assert.equal(compatible(a, b, now), false); // 250 > 100+100 + assert.equal(compatible({ ...a, joinedAt: now - 60_000 }, { ...b, joinedAt: now - 60_000 }, now), true); // ×1.44 + const c = { uid: "c", r: 1520, rd: 50, joinedAt: now }; + const pairs = findPairs([b, a, c], now); + assert.equal(pairs.length, 1); + assert.deepEqual(pairs[0].map((x) => x.uid).sort(), ["a", "c"]); +}); diff --git a/server/wrangler.toml b/server/wrangler.toml new file mode 100644 index 0000000..f86a8af --- /dev/null +++ b/server/wrangler.toml @@ -0,0 +1,32 @@ +name = "tetrig" +main = "src/index.js" +compatibility_date = "2026-09-01" +workers_dev = true + +[[d1_databases]] +binding = "DB" +database_name = "tetrig" +database_id = "d08b6a47-4f54-43c1-9590-1fe61930216f" +migrations_dir = "migrations" + +[[durable_objects.bindings]] +name = "ROOMS" +class_name = "GameRoomDO" + +[[durable_objects.bindings]] +name = "MATCHMAKER" +class_name = "MatchmakerDO" + +# 무료 플랜은 SQLite 백엔드 DO 만 쓸 수 있다. +[[migrations]] +tag = "v1" +new_sqlite_classes = ["GameRoomDO", "MatchmakerDO"] + +[triggers] +crons = ["0 18 * * *"] # 매일 03:00 KST — RD 감쇠·시즌 마감 + +[vars] +# Google 로그인용 OAuth 클라이언트 ID (쉼표 구분). 비어 있으면 /api/google 은 503. +GOOGLE_CLIENT_IDS = "" + +# 비밀값: npx wrangler secret put TOKEN_SECRET