worst-card-game / packages /server /test /auth.test.ts
freeguy2006's picture
feat: redesign devlog and tighten game logic
cac73cf
Raw History Blame Contribute Delete
10.5 kB
import { describe, it, expect } from "vitest";
import { RULE_VERSION, CARDS_HASH, createGame, step, type Action, type GameState } from "@wcg/battle-core";
import { buildServer } from "../src/server.js";
import { safeNext } from "../src/authRoutes.js";
import { parseCookies } from "../src/auth.js";
import { isFreshDiscordTimestamp } from "../src/discordInteractions.js";
import { InMemoryGhostRepository } from "../src/repository.js";
import { InMemoryUserRepository } from "../src/userRepository.js";
function makeApp(withUsers = true, admin?: { adminToken?: string; adminEmails?: string[] }) {
const repo = new InMemoryGhostRepository(() => 0);
const userRepo = withUsers ? new InMemoryUserRepository() : undefined;
const app = buildServer({
repo, userRepo,
oauth: { providers: {}, redirectBase: "http://localhost:3001", cookieSecure: false, devLogin: true, adminToken: admin?.adminToken, adminEmails: admin?.adminEmails },
});
return { app, userRepo };
}
function sessionCookie(res: { cookies: { name: string; value: string }[] }): string {
const c = res.cookies.find((x) => x.name === "wcg_session");
return c ? `wcg_session=${c.value}` : "";
}
function deathRun(seed: number): Action[] {
let s: GameState = createGame({ classType: "WARRIOR", seed });
const actions: Action[] = [];
let guard = 0;
while (s.phase === "PLAYER_TURN" && guard++ < 3000) {
const a: Action = { type: "END_TURN" };
actions.push(a);
s = step(s, a).state;
}
return actions;
}
describe("帳號 / 統計路由(dev-login e2e)", () => {
it("dev-login → /api/me → 回報一場 → logout 全流程", async () => {
const { app } = makeApp();
const login = await app.inject({ method: "POST", url: "/api/auth/dev-login", payload: { username: "alice" } });
expect(login.statusCode).toBe(200);
expect(login.json().displayName).toBe("alice");
expect(login.json().stats.plays).toBe(0);
const cookie = sessionCookie(login as never);
expect(cookie).toContain("wcg_session=");
const me = await app.inject({ method: "GET", url: "/api/me", headers: { cookie } });
expect(me.statusCode).toBe(200);
expect(me.json().displayName).toBe("alice");
const run = await app.inject({
method: "POST", url: "/api/me/runs", headers: { cookie },
payload: { seed: 7, actions: deathRun(7), classType: "WARRIOR", campaign: "slime", maxLevel: 11, ruleVersion: RULE_VERSION, cardsHash: CARDS_HASH },
});
expect(run.statusCode).toBe(200);
expect(run.json().stats.plays).toBe(1);
expect(run.json().stats.clears).toBe(0); // 戰敗
expect(run.json().stats.classPlays.WARRIOR).toBe(1);
expect(run.json().stats.totalTurns).toBeGreaterThan(0); // 權威重播算出的整場回合數
const logout = await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie } });
expect(logout.statusCode).toBe(204);
const meAfter = await app.inject({ method: "GET", url: "/api/me", headers: { cookie } });
expect(meAfter.statusCode).toBe(401); // session 已刪
});
it("未登入 → /api/me 與 /api/me/runs 皆 401", async () => {
const { app } = makeApp();
expect((await app.inject({ method: "GET", url: "/api/me" })).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url: "/api/me/runs", payload: {} })).statusCode).toBe(401);
});
it("回報版本不符 → 409", async () => {
const { app } = makeApp();
const cookie = sessionCookie(await app.inject({ method: "POST", url: "/api/auth/dev-login", payload: {} }) as never);
const res = await app.inject({
method: "POST", url: "/api/me/runs", headers: { cookie },
payload: { seed: 7, actions: [{ type: "END_TURN" }], classType: "WARRIOR", campaign: "slime", maxLevel: 11, ruleVersion: "0.0.0", cardsHash: CARDS_HASH },
});
expect(res.statusCode).toBe(409);
});
it("GET /api/auth/providers → 列出已啟用 provider(本測試未設 → 空陣列)", async () => {
const { app } = makeApp();
const res = await app.inject({ method: "GET", url: "/api/auth/providers" });
expect(res.statusCode).toBe(200);
expect(res.json().providers).toEqual([]);
});
it("未知 provider 的登入起始 → 302 導回 /?login=error(整頁跳轉、不吐 JSON)", async () => {
const { app } = makeApp();
const res = await app.inject({ method: "GET", url: "/api/auth/unknown" });
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("/?login=error");
});
// 回歸:OAuth 回呼是整頁導回的,出錯時不可回 JSON(否則整頁變生 JSON)。應 302 導回 SPA 帶 ?login= 旗標。
describe("OAuth 回呼錯誤 → 302 導回 SPA(不吐 JSON)", () => {
const stubProvider = {
name: "google",
authorizeUrl: () => "https://accounts.google.com/o/oauth2/v2/auth",
exchange: async () => ({ providerUserId: "g1", displayName: "李侑霖", email: "g@example.com" }),
};
const appWithGoogle = () => buildServer({
repo: new InMemoryGhostRepository(() => 0),
userRepo: new InMemoryUserRepository(),
oauth: { providers: { google: stubProvider }, redirectBase: "http://localhost:3001", cookieSecure: false, devLogin: true },
});
it("state 遺失/不符(如逗留過久過期)→ 302 /?login=expired,不回 400 JSON", async () => {
const res = await appWithGoogle().inject({ method: "GET", url: "/api/auth/google/callback?code=abc&state=nocookie" });
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("/?login=expired");
});
it("回呼遇未知 provider → 302 /?login=error", async () => {
const res = await appWithGoogle().inject({ method: "GET", url: "/api/auth/nope/callback?code=a&state=b" });
expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("/?login=error");
});
it("登入起始被限流(每 IP/分鐘 10 次)→ 302 /?login=ratelimited,不吐 JSON", async () => {
const app = appWithGoogle();
let last!: Awaited<ReturnType<typeof app.inject>>;
for (let i = 0; i < 11; i++) last = await app.inject({ method: "GET", url: "/api/auth/google" });
expect(last.statusCode).toBe(302);
expect(last.headers.location).toBe("/?login=ratelimited");
});
});
it("未提供 userRepo → 帳號路由完全不註冊(/api/me 404)", async () => {
const { app } = makeApp(false);
expect((await app.inject({ method: "GET", url: "/api/me" })).statusCode).toBe(404);
});
it("safeNext:登入後返回點只放行站內絕對路徑(防開放轉址)", () => {
expect(safeNext("/api/admin")).toBe("/api/admin");
expect(safeNext("/map?x=1")).toBe("/map?x=1");
expect(safeNext("//evil.com")).toBeNull();
expect(safeNext("/\\evil.com")).toBeNull();
expect(safeNext("https://evil.com")).toBeNull();
expect(safeNext("evil")).toBeNull();
expect(safeNext("")).toBeNull();
expect(safeNext(undefined)).toBeNull();
});
it("parseCookies:壞 percent-encoding 不應拋錯或打爆 auth 路由", () => {
expect(() => parseCookies("wcg_session=%; ok=good")).not.toThrow();
expect(parseCookies("wcg_session=%; ok=good")).toEqual({ ok: "good" });
});
it("Discord interaction timestamp:只接受 5 分鐘內的 Unix 秒 timestamp", () => {
const now = 1_700_000_000_000;
expect(isFreshDiscordTimestamp(String(Math.floor(now / 1000)), now)).toBe(true);
expect(isFreshDiscordTimestamp(String(Math.floor((now - 4 * 60 * 1000) / 1000)), now)).toBe(true);
expect(isFreshDiscordTimestamp(String(Math.floor((now - 6 * 60 * 1000) / 1000)), now)).toBe(false);
expect(isFreshDiscordTimestamp("not-a-number", now)).toBe(false);
});
it("未設 ADMIN_TOKEN → /api/admin 與 /api/admin/users 都不註冊(404)", async () => {
const { app } = makeApp(); // 無 adminToken
expect((await app.inject({ method: "GET", url: "/api/admin/users" })).statusCode).toBe(404);
expect((await app.inject({ method: "GET", url: "/api/admin" })).statusCode).toBe(404);
});
it("ADMIN_TOKEN 保護:無/錯 token → 401,正確 token → 列出使用者且不洩 providerUserId", async () => {
const { app } = makeApp(true, { adminToken: "s3cret-admin" });
await app.inject({ method: "POST", url: "/api/auth/dev-login", payload: { username: "alice" } });
await app.inject({ method: "POST", url: "/api/auth/dev-login", payload: { username: "bob" } });
expect((await app.inject({ method: "GET", url: "/api/admin/users" })).statusCode).toBe(401); // 無 token
expect((await app.inject({ method: "GET", url: "/api/admin/users", headers: { authorization: "Bearer wrong" } })).statusCode).toBe(401);
// 檢視頁本身不需 token(只是殼,資料 fetch 才要)
const page = await app.inject({ method: "GET", url: "/api/admin" });
expect(page.statusCode).toBe(200);
expect(page.headers["content-type"]).toContain("text/html");
const ok = await app.inject({ method: "GET", url: "/api/admin/users", headers: { authorization: "Bearer s3cret-admin" } });
expect(ok.statusCode).toBe(200);
expect(ok.json().count).toBe(2);
const names = ok.json().users.map((u: { displayName: string }) => u.displayName).sort();
expect(names).toEqual(["alice", "bob"]);
expect(ok.json().users[0]).not.toHaveProperty("providerUserId"); // 不外洩內部識別
});
it("ADMIN_EMAILS 白名單:登入後 email 在名單 → 200;不在 / 未登入 → 401", async () => {
const { app, userRepo } = makeApp(true, { adminEmails: ["Boss@X.com"] }); // 大小寫不敏感
const admin = userRepo!.upsertByOAuth("google", "g-admin", "Boss", "boss@x.com");
const other = userRepo!.upsertByOAuth("google", "g-other", "Nobody", "nobody@x.com");
userRepo!.putSession("adm-tok", admin.id, 3600, Date.now());
userRepo!.putSession("oth-tok", other.id, 3600, Date.now());
const ok = await app.inject({ method: "GET", url: "/api/admin/users", headers: { cookie: "wcg_session=adm-tok" } });
expect(ok.statusCode).toBe(200);
expect(ok.json().count).toBe(2);
expect((await app.inject({ method: "GET", url: "/api/admin/users", headers: { cookie: "wcg_session=oth-tok" } })).statusCode).toBe(401);
expect((await app.inject({ method: "GET", url: "/api/admin/users" })).statusCode).toBe(401); // 未登入
expect((await app.inject({ method: "GET", url: "/api/admin" })).statusCode).toBe(200); // 頁面在 email 模式也有
});
});