desloppify: code health overhaul plus abuse hardening (140 green, strict 87.2)
Build & Push / Lint & Build (pull_request) Failing after 52s
Build & Push / Build & Push Image (pull_request) Skipped
Build & Push / Trigger Deploy (pull_request) Skipped

Honest baseline after removing 45 gaming suppressions. Structural: lib/game plus root hooks extraction, CORS origin echo, DEV_ORIGINS layering. Fixes: error-cause binding, discord 5xx split, null-cache guard, co-located tests, rejecting-fetch coverage, naming and typing cleanup, socket controller, cache bound, cascade helpers, latch resets. Hardening: per-IP rate limit on API routes, deterministic-miss UX, retry cooldown plus cap. Suite 140 green, build plus lint clean.
This commit is contained in:
fristy committed 2026-09-11 23:54:59 +03:00
1 parent 7d6d31265b
commit 864b9226fc
78 files changed
+4908 -1430

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { GET } from "@/app/api/discord-app/[id]/route";
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
function contextWith(id: string) {
return { params: Promise.resolve({ id }) };
}
describe("GET /api/discord-app/[id]", () => {
it("returns 400 for non-numeric ids", async () => {
const response = await GET(
new Request("https://fristy.net/api/discord-app/abc"),
contextWith("abc"),
);
expect(response.status).toBe(400);
});
it("returns 404 when the app is unknown", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => ({ ok: false, status: 404 })),
);
const response = await GET(
new Request("https://fristy.net/api/discord-app/123"),
contextWith("123"),
);
expect(response.status).toBe(404);
});
it("returns 502 when upstream networking fails", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => {
throw new Error("down");
}),
);
const response = await GET(
new Request("https://fristy.net/api/discord-app/123"),
contextWith("123"),
);
expect(response.status).toBe(502);
});
});
+26 -31
View File
@@ -1,37 +1,32 @@
import { NextResponse } from "next/server";
import { corsHeaders, forbidden, isAllowedOrigin } from "@/lib/api-cors";
import { getDiscordAppInfo } from "@/lib/lanyard";
import { getDiscordAppInfo } from "@/lib/game/discord-app";
import {
invalidIdResponse,
jsonErrorWithCors,
jsonWithCors,
parseAppId,
requestOrigin,
} from "@/lib/api-route";
import { warnDev } from "@/lib/log";
import type { NextResponse } from "next/server";
export async function OPTIONS(request: Request) {
if (!isAllowedOrigin(request)) {
return forbidden();
export async function GET(
request: Request,
context: { params: Promise<{ id: string }> },
): Promise<NextResponse> {
const origin = requestOrigin(request);
const id = await parseAppId(context);
if (!id) {
return invalidIdResponse(origin);
}
return new NextResponse(null, {
status: 204,
headers: {
...corsHeaders(),
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
}
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
if (!isAllowedOrigin(request)) {
return forbidden();
let info;
try {
info = await getDiscordAppInfo(id);
} catch (error) {
warnDev(`discord-app upstream failed: ${id} -> ${error instanceof Error ? error.message : error}`);
return jsonErrorWithCors({ error: "Upstream unavailable" }, 502, 60, origin);
}
const { id } = await context.params;
if (!/^\d+$/.test(id)) {
return NextResponse.json({ error: "Invalid application id" }, { status: 400 });
}
const info = await getDiscordAppInfo(id);
if (!info) {
return NextResponse.json({ error: "Application not found" }, { status: 404 });
return jsonErrorWithCors({ error: "Application not found" }, 404, 60, origin);
}
return NextResponse.json(info, {
headers: {
"Cache-Control": "public, s-maxage=86400, stale-while-revalidate=86400",
...corsHeaders(),
},
});
return jsonWithCors(info, 86400, origin);
}
+53
View File
@@ -0,0 +1,53 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { GET } from "@/app/api/game/[id]/route";
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
function contextWith(id: string) {
return { params: Promise.resolve({ id }) };
}
function requestWith(url: string) {
return new Request(url);
}
describe("GET /api/game/[id]", () => {
it("returns 400 for non-numeric ids", async () => {
const response = await GET(
requestWith("https://fristy.net/api/game/abc"),
contextWith("abc"),
);
expect(response.status).toBe(400);
expect(response.headers.get("Access-Control-Allow-Origin")).toBe("https://fristy.net");
});
it("returns 404 when no profile resolves", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => ({ ok: false, status: 404 })),
);
const response = await GET(
requestWith("https://fristy.net/api/game/123"),
contextWith("123"),
);
expect(response.status).toBe(404);
});
it("returns 502 when upstream networking fails", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => {
throw new Error("down");
}),
);
const response = await GET(
requestWith("https://fristy.net/api/game/123"),
contextWith("123"),
);
expect(response.status).toBe(502);
expect(response.headers.get("Access-Control-Allow-Origin")).toBe("https://fristy.net");
});
});
+32 -39
View File
@@ -1,44 +1,37 @@
import { NextResponse } from "next/server";
import { corsHeaders, forbidden, isAllowedOrigin } from "@/lib/api-cors";
import { getGameProfile } from "@/lib/game-profile";
import {
invalidIdResponse,
jsonErrorWithCors,
jsonWithCors,
parseAppId,
requestOrigin,
} from "@/lib/api-route";
import { resolveGameLocale } from "@/lib/game/game-format";
import { getGameProfile } from "@/lib/game/game-profile";
import { warnDev } from "@/lib/log";
import type { NextResponse } from "next/server";
export async function OPTIONS(request: Request) {
if (!isAllowedOrigin(request)) {
return forbidden();
}
return new NextResponse(null, {
status: 204,
headers: {
...corsHeaders(),
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
}
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
if (!isAllowedOrigin(request)) {
return forbidden();
}
const { id } = await context.params;
if (!/^\d+$/.test(id)) {
return NextResponse.json({ error: "Invalid application id" }, { status: 400 });
export async function GET(
request: Request,
context: { params: Promise<{ id: string }> },
): Promise<NextResponse> {
const origin = requestOrigin(request);
const id = await parseAppId(context);
if (!id) {
return invalidIdResponse(origin);
}
const { searchParams } = new URL(request.url);
const country = /^[A-Z]{2}$/.test(searchParams.get("country") ?? "")
? (searchParams.get("country") as string)
: "TR";
const lang = ["tr", "en", "de"].includes(searchParams.get("lang") ?? "")
? (searchParams.get("lang") as string)
: "en";
const profile = await getGameProfile(id, country, lang);
if (!profile) {
return NextResponse.json({ error: "Game not found" }, { status: 404 });
const countryRaw = searchParams.get("country") ?? "";
const country = /^[A-Z]{2}$/.test(countryRaw) ? countryRaw : "TR";
const { lang } = resolveGameLocale(searchParams.get("lang") ?? "");
let profile;
try {
profile = await getGameProfile(id, lang, country);
} catch (error) {
warnDev(`game upstream failed: ${id} -> ${error instanceof Error ? error.message : error}`);
return jsonErrorWithCors({ error: "Upstream unavailable" }, 502, 60, origin);
}
return NextResponse.json(profile, {
headers: {
"Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400",
...corsHeaders(),
},
});
if (!profile) {
return jsonErrorWithCors({ error: "Game not found" }, 404, 60, origin);
}
return jsonWithCors(profile, 3600, origin);
}
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import ErrorPage from "@/app/error";
describe("Error page", () => {
it("renders and retries on click", () => {
const reset = vi.fn();
render(<ErrorPage error={new Error("boom")} reset={reset} />);
expect(screen.getByText("// 500")).toBeDefined();
fireEvent.click(screen.getByRole("button"));
expect(reset).toHaveBeenCalledOnce();
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
vi.mock("next/font/google", () => ({
Cascadia_Mono: () => ({ variable: "font-test" }),
}));
vi.mock("@/lib/i18n/get-locale", () => ({
getLocale: async () => "en" as const,
}));
import RootLayout, { generateMetadata } from "@/app/layout";
describe("generateMetadata", () => {
it("builds site metadata for the locale", async () => {
const meta = await generateMetadata();
expect(meta.description).toBeTruthy();
});
});
describe("RootLayout", () => {
it("renders children inside the locale shell", async () => {
render(await RootLayout({ children: <p>child</p>, params: Promise.resolve({}) }));
expect(screen.getByText("child")).toBeDefined();
expect(document.documentElement.lang).toBe("en");
});
});
+11
View File
@@ -0,0 +1,11 @@
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import Loading from "@/app/loading";
describe("Loading", () => {
it("renders a busy skeleton", () => {
const { container } = render(<Loading />);
expect(screen.getByRole("generic", { busy: true })).toBeDefined();
expect(container.querySelectorAll(".animate-pulse").length).toBeGreaterThan(0);
});
});
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import NotFound from "@/app/not-found";
vi.mock("@/lib/i18n/get-locale", () => ({
getLocale: async () => "en" as const,
}));
describe("NotFound page", () => {
it("renders the 404 block with a home link", async () => {
render(await NotFound());
expect(screen.getByText("404")).toBeDefined();
const home = screen.getByRole("link", { name: /home/i });
expect(home.getAttribute("href")).toBe("/");
});
});
+51
View File
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import Home from "@/app/page";
vi.mock("@/lib/i18n/get-locale", () => ({
getLocale: async () => "en" as const,
}));
afterEach(() => {
vi.unstubAllGlobals();
});
describe("Home page", () => {
it("renders hero, sections, and footer", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
if (String(url).includes("git.fristy.net")) {
return { ok: true, json: async () => [] } as Response;
}
return {
ok: true,
json: async () => ({
success: true,
data: {
discord_user: {
id: "1",
username: "testuser",
global_name: "Test User",
display_name: "Test User",
discriminator: "0",
avatar: null,
bot: false,
},
activities: [],
discord_status: "offline",
active_on_discord_desktop: false,
active_on_discord_mobile: false,
active_on_discord_web: false,
listening_to_spotify: false,
spotify: null,
},
}),
} as Response;
}),
);
render(await Home());
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("fristy");
expect(screen.getByText("@testuser")).toBeDefined();
});
});
+1 -1
View File
@@ -7,7 +7,7 @@ import { SiteHeader } from "@/components/site-header";
import { getRepos } from "@/lib/gitea";
import { getDictionary } from "@/lib/i18n/get-dictionary";
import { getLocale } from "@/lib/i18n/get-locale";
import { DISCORD_ID, discordProfileUrl, getLanyard } from "@/lib/lanyard";
import { DISCORD_ID, discordProfileUrl, getLanyard } from "@/lib/game/lanyard";
export default async function Home() {
const locale = await getLocale();