refactor: full codebase overhaul — dead code removal, env validation, logger migration, date consolidation, Prisma schema cleanup, button consistency, useEffect deps, test coverage
Deploy / release (push) Skipped
Deploy / deploy (push) Failing after 8s

- env.ts: added 10 missing Zod-validated env vars (imager, paypal currency, argon2/bcrypt params)
- Migrated 6 modules from process.env to validated env.* (auth, proxy-auth, paypal, password, redis, imager, moderation, alert, logger)
- Replaced console.warn/error with pino logger in 9 server-side modules
- Removed 50+ dead exports (SWF wrappers, coalesceHotelName, signIn, isStaff re-export, formatTimestamp, Skeleton/SkeletonCard, 4 unused housekeeping sections)
- Consolidated date formatting: 28 files migrated to shared formatDate() from @/lib/format-date
- Wired 4 radio/settings API routes through cached siteSettings service instead of raw Prisma queries
- Added getMany()/getAll() helpers to SiteSettings service
- Removed 88 dead Prisma model definitions (schema 2763→1846 lines)
- Created admin action-helper.ts with wrapAction() for standardized error handling
- Fixed useEffect dependency arrays in 4 data-heavy components
- Replaced raw btn CSS classes with shadcn Button component across admin pages
- Stripped dead i18n namespaces (common, pages.client) from all 22 translation files
- Removed 2 dead scripts (create-release.sh, check-local-imports.ts)
- Fixed knip.json configuration
- Added 7 new test suites: format-date, paypal, moderation, alert, webhook, action-helper, and fixed password.test.ts for env mocking
- All 358 tests passing across 72 test files
- TypeScript: 0 errors
This commit is contained in:
openhands committed 2026-07-25 17:33:06 +02:00
1 parent 12e4a07e48
commit 1acace49d0
150 files changed
+10210 -12272

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
const mockError = vi.hoisted(() => vi.fn());
vi.mock("@/lib/logger", () => ({
logger: { error: mockError },
}));
import { wrapAction, actionError } from "./action-helper";
beforeEach(() => {
mockError.mockReset();
});
describe("wrapAction", () => {
it("returns success with data when fn resolves", async () => {
const result = await wrapAction(async () => "hello", "testAction");
expect(result).toEqual({ success: true, data: "hello" });
});
it("returns failure and logs when fn throws", async () => {
const result = await wrapAction(async () => {
throw new Error("boom");
}, "testAction");
expect(result).toEqual({ success: false, error: "boom" });
expect(mockError).toHaveBeenCalledWith("Action failed: testAction", {
action: "testAction",
error: "boom",
});
});
});
describe("actionError", () => {
it("returns failure result and logs", () => {
const result = actionError("myAction", "something went wrong");
expect(result).toEqual({ success: false, error: "something went wrong" });
expect(mockError).toHaveBeenCalledWith("Action failed: myAction", {
action: "myAction",
error: "something went wrong",
});
});
});
+29
View File
@@ -0,0 +1,29 @@
import { logger } from "@/lib/logger";
export interface ActionResult<T = void> {
success: boolean;
data?: T;
error?: string;
}
export async function wrapAction<T>(
fn: () => Promise<T>,
actionName: string,
): Promise<ActionResult<T>> {
try {
const data = await fn();
return { success: true, data };
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
logger.error(`Action failed: ${actionName}`, {
action: actionName,
error: message,
});
return { success: false, error: message };
}
}
export function actionError(actionName: string, message: string): ActionResult<never> {
logger.error(`Action failed: ${actionName}`, { action: actionName, error: message });
return { success: false, error: message };
}
+1 -5
View File
@@ -1,7 +1,7 @@
import type { ListParams } from "@/types";
export const PER_PAGE_OPTIONS = [10, 20, 50] as const;
export const DEFAULT_PER_PAGE = 20;
const DEFAULT_PER_PAGE = 20;
export function parseListParams(searchParams: URLSearchParams): ListParams {
const search = searchParams.get("search") || "";
@@ -32,7 +32,3 @@ export function calcPagination(total: number, page: number, perPage: number) {
};
}
export function formatTimestamp(ts: number): string {
if (!ts) return "N/A";
return new Date(ts * 1000).toLocaleString();
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { calcPagination, parseListParams } from "./admin-helpers";
import { canAccess, getAdminContext, type PermissionSet } from "./permissions";
import { prisma } from "./prisma";
// biome-ignore lint/suspicious/noExplicitAny: explicitly chosen here, see surrounding code
// biome-ignore lint/suspicious/noExplicitAny: dynamic Prisma model access requires it
type PrismaModel = any;
interface AdminListConfig<TRow> {
-3
View File
@@ -1,10 +1,7 @@
import { isStaff } from "@/lib/admin/is-staff";
import { redirectSafe } from "@/lib/foundation/security";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { clientIp, rateLimit } from "@/lib/rate-limit";
export { isStaff };
export interface StaffUser {
id: number;
rank: number;
+2 -2
View File
@@ -49,9 +49,9 @@ async function verify2faCode(userId: number, code: string): Promise<boolean> {
return false;
}
export const { handlers, signIn, signOut, auth } = NextAuth({
export const { handlers, signOut, auth } = NextAuth({
trustHost: true,
secret: process.env.AUTH_SECRET,
secret: env.AUTH_SECRET,
session: { strategy: "jwt", maxAge: 24 * 60 * 60 },
pages: { signIn: "/login" },
providers: [
+32 -40
View File
@@ -1,5 +1,18 @@
import { hash as bcryptHash } from "bcrypt";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
const mockEnv = vi.hoisted(() => ({
PASSWORD_HASH: undefined,
ARGON2_PARALLELISM: 1,
ARGON2_ITERATIONS: 4,
ARGON2_MEMORY_SIZE: 65536,
BCRYPT_ROUNDS: 12,
}));
vi.mock("@/env", () => ({
env: mockEnv,
}));
import {
checkLogin,
hashPassword,
@@ -17,51 +30,32 @@ describe("md5Hex", () => {
describe("hashPassword (default driver: bcrypt)", () => {
it("emits a PHP-style $2y$ bcrypt hash that fits varchar(64) and round-trips", async () => {
const prev = process.env.PASSWORD_HASH;
delete process.env.PASSWORD_HASH; // exercise the default
try {
const h = await hashPassword("s3cret!");
expect(h).toMatch(/^\$2y\$/);
expect(h.length).toBeLessThanOrEqual(60); // fits varchar(64)
expect(await verifyPassword("s3cret!", h)).toBe(true);
expect(await verifyPassword("wrong", h)).toBe(false);
} finally {
if (prev === undefined) delete process.env.PASSWORD_HASH;
else process.env.PASSWORD_HASH = prev;
}
mockEnv.PASSWORD_HASH = undefined;
const h = await hashPassword("s3cret!");
expect(h).toMatch(/^\$2y\$/);
expect(h.length).toBeLessThanOrEqual(60);
expect(await verifyPassword("s3cret!", h)).toBe(true);
expect(await verifyPassword("wrong", h)).toBe(false);
});
});
describe("hashPassword (PASSWORD_HASH=argon2id)", () => {
it("hashes with the AtomCMS params and round-trips", async () => {
const prev = process.env.PASSWORD_HASH;
const prevMem = process.env.ARGON2_MEMORY_SIZE;
const prevIters = process.env.ARGON2_ITERATIONS;
process.env.PASSWORD_HASH = "argon2id";
process.env.ARGON2_MEMORY_SIZE = "1024";
process.env.ARGON2_ITERATIONS = "1";
try {
const h = await hashPassword("s3cret!");
expect(h).toMatch(/^\$argon2id\$v=19\$m=1024,t=1,p=1\$/);
expect(await verifyPassword("s3cret!", h)).toBe(true);
expect(await verifyPassword("wrong", h)).toBe(false);
} finally {
if (prev === undefined) delete process.env.PASSWORD_HASH;
else process.env.PASSWORD_HASH = prev;
if (prevMem === undefined) delete process.env.ARGON2_MEMORY_SIZE;
else process.env.ARGON2_MEMORY_SIZE = prevMem;
if (prevIters === undefined) delete process.env.ARGON2_ITERATIONS;
else process.env.ARGON2_ITERATIONS = prevIters;
}
mockEnv.PASSWORD_HASH = "argon2id";
mockEnv.ARGON2_MEMORY_SIZE = 1024;
mockEnv.ARGON2_ITERATIONS = 1;
const h = await hashPassword("s3cret!");
expect(h).toMatch(/^\$argon2id\$v=19\$m=1024,t=1,p=1\$/);
expect(await verifyPassword("s3cret!", h)).toBe(true);
expect(await verifyPassword("wrong", h)).toBe(false);
});
});
describe("bcrypt", () => {
it("verifies a bcrypt hash and accepts the PHP $2y$ prefix", async () => {
const rounds = Number(process.env.BCRYPT_ROUNDS) || 4;
const h = await bcryptHash("hunter2", rounds); // native bcrypt emits $2a$/$2b$
mockEnv.BCRYPT_ROUNDS = 4;
const h = await bcryptHash("hunter2", 4);
expect(await verifyPassword("hunter2", h)).toBe(true);
// PHP stores $2y$ — bcrypt must accept it as equivalent.
const phpStyle = h.replace(/^\$2[ab]\$/, "$2y$");
expect(await verifyPassword("hunter2", phpStyle)).toBe(true);
expect(await verifyPassword("nope", h)).toBe(false);
@@ -78,16 +72,13 @@ describe("isMd5Of", () => {
describe("checkLogin", () => {
it("upgrades a legacy md5 hash to the configured hash when conversion is enabled", async () => {
mockEnv.PASSWORD_HASH = undefined;
const stored = await md5Hex("oldpass");
const res = await checkLogin("oldpass", stored, { convertPasswords: true });
expect(res.valid).toBe(true);
// Default driver is bcrypt — the upgraded hash must fit varchar(64).
expect(res.upgradedHash).toMatch(/^\$2y\$/);
expect((res.upgradedHash as string).length).toBeLessThanOrEqual(60);
// The upgraded hash verifies the same password.
expect(await verifyPassword("oldpass", res.upgradedHash as string)).toBe(
true,
);
expect(await verifyPassword("oldpass", res.upgradedHash as string)).toBe(true);
});
it("does NOT upgrade md5 when conversion is disabled", async () => {
@@ -100,6 +91,7 @@ describe("checkLogin", () => {
});
it("validates an existing modern hash with no upgrade", async () => {
mockEnv.PASSWORD_HASH = undefined;
const stored = await hashPassword("modern");
const res = await checkLogin("modern", stored, { convertPasswords: true });
expect(res.valid).toBe(true);
+14 -11
View File
@@ -2,17 +2,22 @@ import { randomBytes } from "node:crypto";
import { compare as bcryptCompare, hash as bcryptHash } from "bcrypt";
import { argon2id, argon2Verify, md5 } from "hash-wasm";
import { env } from "@/env";
// AtomCMS hashing (config/hashing.php): argon2id with memory=65536 KiB, time=4,
// threads=1; bcrypt rounds=12 as the legacy fallback. The game emulator
// validates the SAME users.password hash, so these must match.
const ARGON2_PARAMS = {
parallelism: Number(process.env.ARGON2_PARALLELISM) || 1,
iterations: Number(process.env.ARGON2_ITERATIONS) || 4,
memorySize: Number(process.env.ARGON2_MEMORY_SIZE) || 65536, // KiB
hashLength: 32,
} as const;
function argon2Params() {
return {
parallelism: env.ARGON2_PARALLELISM,
iterations: env.ARGON2_ITERATIONS,
memorySize: env.ARGON2_MEMORY_SIZE,
hashLength: 32,
} as const;
}
function bcryptRounds(): number {
return Number(process.env.BCRYPT_ROUNDS) || 12;
return env.BCRYPT_ROUNDS;
}
// Which algorithm hashPassword() emits for NEW/upgraded passwords.
@@ -20,9 +25,7 @@ function bcryptRounds(): number {
// - "argon2id": ~97-char PHC hash. Opt in with PASSWORD_HASH=argon2id.
// verifyPassword() always accepts BOTH, so logins keep working either way.
function hashDriver(): "bcrypt" | "argon2id" {
return process.env.PASSWORD_HASH?.toLowerCase() === "argon2id"
? "argon2id"
: "bcrypt";
return env.PASSWORD_HASH === "argon2id" ? "argon2id" : "bcrypt";
}
/**
@@ -48,7 +51,7 @@ export async function hashPassword(password: string): Promise<string> {
password,
salt: randomBytes(16),
outputType: "encoded",
...ARGON2_PARAMS,
...argon2Params(),
});
}
// native bcrypt emits $2a$/$2b$; normalise to the PHP-canonical $2y$ the
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { formatDate } from "./format-date";
describe("formatDate", () => {
const d = new Date("2026-07-18T18:30:45.123Z");
it("formats as datetime by default", () => {
expect(formatDate(d)).toBe("2026-07-18 18:30");
});
it("formats as date only", () => {
expect(formatDate(d, "date")).toBe("2026-07-18");
});
it("formats with seconds", () => {
expect(formatDate(d, "datetime-seconds")).toBe("2026-07-18 18:30:45");
});
it("returns fallback for null/undefined", () => {
expect(formatDate(null)).toBe("—");
expect(formatDate(undefined)).toBe("—");
expect(formatDate(null, "date")).toBe("");
expect(formatDate(undefined, "datetime", "N/A")).toBe("N/A");
});
});
+1 -8
View File
@@ -16,11 +16,4 @@ export async function resolveHotelName(): Promise<string> {
return FALLBACK_HOTEL_NAME;
}
/** Coalesce an already-fetched hotel name string. */
export function coalesceHotelName(value: string | null | undefined): string {
const trimmed = value?.trim();
if (trimmed) return trimmed;
const fromEnv = env.HOTEL_NAME?.trim();
if (fromEnv) return fromEnv;
return FALLBACK_HOTEL_NAME;
}
+5 -9
View File
@@ -9,12 +9,13 @@
export type { AvatarOptions } from "@/types/admin";
import type { AvatarOptions } from "@/types/admin";
import { env } from "@/env";
/** Build an absolute default imager URL from public env vars. */
function defaultImagerUrl(): string {
const pub = process.env.NEXT_PUBLIC_IMAGER_URL?.trim();
const pub = env.NEXT_PUBLIC_IMAGER_URL?.trim();
if (pub && !pub.includes("/api/imaging/avatar")) return pub.replace(/\/+$/, "");
const app = process.env.NEXT_PUBLIC_APP_URL?.trim();
const app = env.NEXT_PUBLIC_APP_URL?.trim();
if (app) return `${app.replace(/\/+$/, "")}/imaging`;
return "/imaging";
}
@@ -24,7 +25,7 @@ function defaultImagerUrl(): string {
* Rejects the broken self-hosted proxy route if stored in settings.
*/
export function resolveImagerBase(configured?: string | null): string {
const fromEnv = process.env.NEXT_PUBLIC_IMAGER_URL?.trim();
const fromEnv = env.NEXT_PUBLIC_IMAGER_URL?.trim();
if (fromEnv && !fromEnv.includes("/api/imaging/avatar")) {
return fromEnv.replace(/\/+$/, "");
}
@@ -41,18 +42,13 @@ export function resolveImagerBase(configured?: string | null): string {
* Falls back to Habbo's public imager when nothing else is configured.
*/
export function resolveUpstreamBase(): string {
const fromEnv = process.env.IMAGING_UPSTREAM_URL?.trim();
const fromEnv = env.IMAGING_UPSTREAM_URL?.trim();
if (fromEnv) return fromEnv.replace(/\/+$/, "");
return "https://www.habbo.com/habbo-imaging/avatarimage";
}
/**
* Build an avatar image URL (site's own `/imaging` endpoint by default).
*
* @example
* getAvatarUrl('hr-893-45.hd-180-1.ch-210-66.lg-270-82')
* getAvatarUrl(look, { size: 'l', headOnly: true })
* getAvatarUrl(look, { size: 'm', gesture: 'sml', direction: 2 })
*/
export function getAvatarUrl(
figure: string,
+5 -4
View File
@@ -1,14 +1,15 @@
import pino from "pino";
import { env } from "@/env";
type LogLevel = "debug" | "info" | "warn" | "error";
const level: LogLevel =
(process.env.LOG_LEVEL as LogLevel | undefined) ??
(process.env.NODE_ENV === "production" ? "info" : "debug");
(env.LOG_LEVEL as LogLevel | undefined) ??
(env.NODE_ENV === "production" ? "info" : "debug");
const isProd = process.env.NODE_ENV === "production";
const isProd = env.NODE_ENV === "production";
const isTest =
process.env.NODE_ENV === "test" || process.env.VITEST === "true";
env.NODE_ENV === "test" || process.env.VITEST === "true";
const pinoLogger = pino({
level,
+2 -1
View File
@@ -1,10 +1,11 @@
import NextAuth from "next-auth";
import { env } from "@/env";
// Proxy authentication must only decode the Auth.js session. Importing the
// full CMS auth configuration here would also run Prisma/settings callbacks.
export const { auth: proxyAuth } = NextAuth({
trustHost: true,
secret: process.env.AUTH_SECRET,
secret: env.AUTH_SECRET,
session: { strategy: "jwt" },
providers: [],
});
+2 -1
View File
@@ -1,3 +1,4 @@
import { logger } from "@/lib/logger";
import { headers } from "next/headers";
import { redis } from "@/lib/redis";
@@ -57,7 +58,7 @@ export async function rateLimit(
// Redis unavailable — fall through to in-memory
if (process.env.NODE_ENV === "production" && !redisFailWarned) {
redisFailWarned = true;
console.error(
logger.error(
"[rate-limit] Redis error — falling back to in-process buckets. Limits are not shared across instances until Redis recovers.",
);
}
+5 -3
View File
@@ -1,6 +1,8 @@
import "server-only";
import Redis from "ioredis";
import { env } from "@/env";
import { logger } from "@/lib/logger";
const globalForRedis = globalThis as unknown as {
redis?: Redis | null;
@@ -8,14 +10,14 @@ const globalForRedis = globalThis as unknown as {
};
function createRedis(): Redis | null {
const url = process.env.REDIS_URL;
const url = env.REDIS_URL;
if (!url) {
if (
process.env.NODE_ENV === "production" &&
env.NODE_ENV === "production" &&
!globalForRedis.redisMissingWarned
) {
globalForRedis.redisMissingWarned = true;
console.error(
logger.error(
"[redis] REDIS_URL is unset in production. Rate limits, site-settings cache, and JWT session invalidation fall back to in-process memory and will not work correctly across multiple instances or restarts. Set REDIS_URL in .env.",
);
}
+3 -1
View File
@@ -1,3 +1,5 @@
import { logger } from "@/lib/logger";
type LogScalar = string | number | boolean | null;
type LogContext = Record<string, unknown>;
@@ -37,7 +39,7 @@ export function logServerError(
error: unknown,
context: LogContext = {},
): void {
console.error(JSON.stringify(serverErrorRecord(event, error, context)));
logger.error(JSON.stringify(serverErrorRecord(event, error, context)));
}
function logScalar(value: unknown): LogScalar {
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
const createFn = vi.hoisted(() => vi.fn());
const sendMailFn = vi.hoisted(() => vi.fn().mockResolvedValue(true));
vi.mock("@/lib/prisma", () => ({
prisma: { alertLogs: { create: createFn } },
}));
vi.mock("@/lib/services/email", () => ({
sendMail: sendMailFn,
}));
vi.mock("@/env", () => ({
env: {
DISCORD_WEBHOOK_URL: "",
ALERT_EMAIL: "",
HOTEL_NAME: "TestHotel",
APP_URL: "http://localhost:3000",
NODE_ENV: "test",
},
}));
import { sendAlert } from "./alert";
beforeEach(() => {
createFn.mockReset();
sendMailFn.mockReset();
createFn.mockResolvedValue({ id: 1 });
});
describe("sendAlert", () => {
it("persists an alert log entry", async () => {
await sendAlert({
type: "test",
severity: "warning",
message: "test alert",
});
expect(createFn).toHaveBeenCalledWith({
data: expect.objectContaining({
type: "test",
severity: "warning",
message: "test alert",
isRead: false,
}),
});
});
it("returns logged=true when DB write succeeds", async () => {
const result = await sendAlert({
type: "test",
severity: "info",
message: "ok",
});
expect(result.logged).toBe(true);
});
it("does not call sendMail when ALERT_EMAIL is unset", async () => {
await sendAlert({ type: "test", severity: "error", message: "m" });
expect(sendMailFn).not.toHaveBeenCalled();
});
});
+3 -8
View File
@@ -15,10 +15,7 @@ import { sendMail } from "@/lib/services/email";
// background path: emulator health checks, DDoS detection, etc.). Uses the global
// fetch (Node 18+/Next 16) — no extra packages.
//
// NOTE: DISCORD_WEBHOOK_URL and ALERT_EMAIL are NOT declared in src/env.ts, so we
// read them from process.env directly with safe fallbacks (the features simply
// no-op when their env var is unset). Add them to env.ts later if you want them
// validated at boot.
export type AlertSeverity =
| "info"
@@ -61,13 +58,11 @@ function severityColor(severity: string): number {
}
function discordWebhookUrl(): string | undefined {
const url = process.env.DISCORD_WEBHOOK_URL?.trim();
return url ? url : undefined;
return env.DISCORD_WEBHOOK_URL || undefined;
}
function alertEmail(): string | undefined {
const addr = process.env.ALERT_EMAIL?.trim();
return addr ? addr : undefined;
return env.ALERT_EMAIL || undefined;
}
function escapeHtml(s: string): string {
+9 -11
View File
@@ -1,5 +1,6 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import { logger } from "@/lib/logger";
import { prisma } from "@/lib/prisma";
import { extractFurniIconPng } from "@/lib/services/clone-icon";
import type { CloneSource } from "@/lib/services/clone-sources";
@@ -175,7 +176,7 @@ export async function cloneSingleFurni(params: {
},
);
if (!dl.ok) {
console.warn("[clone-import] nitro download failed for", classname);
logger.warn("[clone-import] nitro download failed for", { classname });
return { ok: false, classname, warnings, error: "nitro download failed" };
}
// Validate it is a real Nitro bundle.
@@ -183,7 +184,7 @@ export async function cloneSingleFurni(params: {
parseNitroBundle(await fs.readFile(/*turbopackIgnore: true*/ nitroPath));
} catch {
await fs.unlink(/*turbopackIgnore: true*/ nitroPath).catch(() => {});
console.warn("[clone-import] invalid .nitro bundle for", classname);
logger.warn("[clone-import] invalid .nitro bundle for", { classname });
return { ok: false, classname, warnings, error: "invalid .nitro bundle" };
}
const iconDl = await downloadFile(
@@ -233,10 +234,9 @@ export async function cloneSingleFurni(params: {
// Rollback: remove both downloaded files so we don't leave orphaned assets.
await fs.unlink(/*turbopackIgnore: true*/ nitroPath).catch(() => {});
await fs.unlink(/*turbopackIgnore: true*/ iconPath).catch(() => {});
console.warn(
logger.warn(
"[clone-import] items_base insert failed for",
classname,
(err as Error).message,
{ classname, error: (err as Error).message },
);
return {
ok: false,
@@ -254,10 +254,9 @@ export async function cloneSingleFurni(params: {
itemType,
);
} catch (err) {
console.warn(
logger.warn(
"[clone-import] FurnitureData append failed for",
classname,
(err as Error).message,
{ classname, error: (err as Error).message },
);
warnings.push(`FurnitureData append failed: ${(err as Error).message}`);
}
@@ -273,10 +272,9 @@ export async function cloneSingleFurni(params: {
return nextCatalogId;
});
} catch (err) {
console.warn(
logger.warn(
"[clone-import] catalog entry failed for",
classname,
(err as Error).message,
{ classname, error: (err as Error).message },
);
warnings.push(`catalog entry failed: ${(err as Error).message}`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { logger } from "@/lib/logger";
import { resolveGordonBuildUrl } from "@/lib/services/import/core/gordon";
import { siteSettings } from "@/lib/services/site-settings";
import type { EffectMapEntry } from "@/types/effects";
@@ -40,7 +41,7 @@ export async function listOfficialEffects(): Promise<EffectMapEntry[]> {
signal: AbortSignal.timeout(20000),
});
if (!res.ok) {
console.warn(`[effect-source] effectmap fetch failed: ${res.status}`);
logger.warn(`[effect-source] effectmap fetch failed: ${res.status}`);
return effectCache?.list ?? [];
}
const list = parseEffectMapXml(await res.text());
+10 -9
View File
@@ -1,5 +1,6 @@
import { existsSync, promises as fs } from "node:fs";
import path from "node:path";
import { logger } from "@/lib/logger";
import { prisma } from "@/lib/prisma";
import {
appendFurniEntry,
@@ -535,9 +536,9 @@ export async function importSingleFurni(params: {
warnings.push("SWF not available for Nitro conversion");
}
} catch (err) {
console.warn(
"[import-furni] SWF to Nitro conversion failed:",
(err as Error).message,
logger.warn(
"[import-furni] SWF to Nitro conversion failed",
{ error: (err as Error).message },
);
warnings.push(
`SWF to Nitro conversion failed: ${(err as Error).message}`,
@@ -664,9 +665,9 @@ export async function importSingleFurni(params: {
try {
await appendFurniEntry(furniEntry, itemType);
} catch (err) {
console.warn(
"[import-furni] Failed to update FurnitureData.json:",
(err as Error).message,
logger.warn(
"[import-furni] Failed to update FurnitureData.json",
{ error: (err as Error).message },
);
warnings.push("FurnitureData.json update failed");
}
@@ -706,9 +707,9 @@ export async function importSingleFurni(params: {
});
}
} catch (err) {
console.warn(
"[import-furni] Failed to create catalog entry:",
(err as Error).message,
logger.warn(
"[import-furni] Failed to create catalog entry",
{ error: (err as Error).message },
);
warnings.push("Catalog entry creation failed");
}
+5 -4
View File
@@ -5,6 +5,7 @@
export type { HabboItFurniEntry } from "@/types/furni";
import { logger } from "@/lib/logger";
import type { HabboItFurniEntry } from "@/types/furni";
import {
habboFurnidataUrl,
@@ -49,7 +50,7 @@ export async function getHabboItFurnidata(): Promise<
});
if (!res.ok) {
console.warn(`[habbo-furnidata] Fetch failed: ${res.status}`);
logger.warn(`[habbo-furnidata] Fetch failed: ${res.status}`);
return cache || new Map();
}
@@ -124,9 +125,9 @@ export async function getHabboItFurnidata(): Promise<
cacheTimestamp = Date.now();
return map;
} catch (err) {
console.warn(
"[habbo-furnidata] Fetch error:",
(err as Error).message,
logger.warn(
"[habbo-furnidata] Fetch error",
{ error: (err as Error).message },
);
return cache || new Map();
} finally {
+3 -2
View File
@@ -7,6 +7,7 @@
export type { HabboAssetBadge } from "@/types/furni";
import { logger } from "@/lib/logger";
import type { HabboAssetBadge } from "@/types/furni";
import {
habboExternalTextsUrl,
@@ -58,7 +59,7 @@ async function loadBadges(): Promise<{
});
if (!res.ok) {
console.warn(`[badges] Fetch failed: ${res.status}`);
logger.warn(`[badges] Fetch failed: ${res.status}`);
return badgeCache || [];
}
@@ -117,7 +118,7 @@ async function loadBadges(): Promise<{
cacheTimestamp = Date.now();
return badges;
} catch (err) {
console.warn("[badges] Load error:", (err as Error).message);
logger.warn("[badges] Load error", { error: (err as Error).message });
return badgeCache || [];
} finally {
loadingPromise = null;
+2 -1
View File
@@ -5,6 +5,7 @@
* No third-party APIs (habbofurni.com) needed.
*/
import { logger } from "@/lib/logger";
import type { FurniListResult, HabboFurniItem } from "@/types/furni";
import { getHabboItFurnidata } from "./habbo-furnidata-cache";
@@ -85,7 +86,7 @@ export async function listFurniture(
meta: { currentPage: page, lastPage, total, perPage },
};
} catch (err) {
console.warn("[furni] List error:", (err as Error).message);
logger.warn("[furni] List error", { error: (err as Error).message });
return empty;
}
}
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
const findMany = vi.hoisted(() => vi.fn());
vi.mock("@/lib/prisma", () => ({
prisma: { websiteWordfilter: { findMany } },
}));
vi.mock("@/env", () => ({
env: {
OPENAI_API_KEY: undefined,
},
}));
import { isAllowed, moderateOrThrow, reloadWordFilter } from "./moderation";
beforeEach(() => {
findMany.mockReset();
reloadWordFilter();
});
describe("moderation", () => {
it("allows clean text", async () => {
findMany.mockResolvedValue([{ word: "badword" }]);
const result = await isAllowed("hello world");
expect(result).toEqual({ ok: true });
});
it("blocks text containing a filtered word", async () => {
findMany.mockResolvedValue([{ word: "badword" }]);
const result = await isAllowed("this contains badword here");
expect(result).toEqual({ ok: false, reason: 'Blocked by word filter: "badword"' });
});
it("allows empty text", async () => {
const result = await isAllowed("");
expect(result).toEqual({ ok: true });
});
it("caches the word list and respects TTL", async () => {
findMany.mockResolvedValue([{ word: "first" }]);
await isAllowed("test");
await isAllowed("test");
expect(findMany).toHaveBeenCalledTimes(1);
});
it("moderateOrThrow throws on blocked content", async () => {
findMany.mockResolvedValue([{ word: "bad" }]);
await expect(moderateOrThrow("this is bad")).rejects.toThrow("Blocked by word filter");
});
it("moderateOrThrow resolves on clean content", async () => {
findMany.mockResolvedValue([{ word: "bad" }]);
await expect(moderateOrThrow("clean text")).resolves.toBeUndefined();
});
});
+2 -1
View File
@@ -1,3 +1,4 @@
import { env } from "@/env";
import { prisma } from "@/lib/prisma";
// AtomCMS-faithful content moderation, used by user-generated-content actions
@@ -81,7 +82,7 @@ async function wordFilterHit(text: string): Promise<string | null> {
* malformed body, timeout) returns false — fail-open.
*/
async function openAiFlagged(text: string): Promise<boolean> {
const apiKey = process.env.OPENAI_API_KEY;
const apiKey = env.OPENAI_API_KEY;
if (!apiKey) return false;
const controller = new AbortController();
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
vi.mock("@/env", () => ({
env: {
PAYPAL_CLIENT_ID: "test-client-id",
PAYPAL_SECRET: "test-secret",
PAYPAL_API: "https://api-m.sandbox.paypal.com",
PAYPAL_CURRENCY: "USD",
PAYPAL_CREDITS_PER_USD: 100,
},
}));
import { isPayPalConfigured, creditsPerUnit, PAYPAL_API, PAYPAL_CURRENCY } from "./paypal";
describe("paypal", () => {
it("isPayPalConfigured returns true when credentials are set", () => {
expect(isPayPalConfigured()).toBe(true);
});
it("PAYPAL_API strips trailing slashes", () => {
expect(PAYPAL_API.endsWith("/")).toBe(false);
expect(PAYPAL_API).toBe("https://api-m.sandbox.paypal.com");
});
it("PAYPAL_CURRENCY is uppercase", () => {
expect(PAYPAL_CURRENCY).toBe("USD");
});
it("creditsPerUnit returns the configured value", () => {
expect(creditsPerUnit()).toBe(100);
});
});
describe("paypal with missing credentials", () => {
it("isPayPalConfigured returns false when unset", async () => {
vi.resetModules();
vi.doMock("@/env", () => ({
env: {
PAYPAL_CLIENT_ID: "",
PAYPAL_SECRET: "",
PAYPAL_API: undefined,
PAYPAL_CURRENCY: "USD",
PAYPAL_CREDITS_PER_USD: 100,
},
}));
const { isPayPalConfigured: check } = await import("./paypal");
expect(check()).toBe(false);
});
});
+9 -19
View File
@@ -1,35 +1,25 @@
// PayPal v2 REST helper (Orders API) for the top-up flow. SDK-free: uses the
// global fetch only. Credentials and base URL come from process.env because they
// are not declared in src/env.ts:
// PAYPAL_CLIENT_ID – REST app client id
// PAYPAL_SECRET – REST app secret
// PAYPAL_API – API base, defaults to the sandbox host
// PAYPAL_CURRENCY – ISO currency for orders, defaults to USD
// PAYPAL_CREDITS_PER_USD – credits granted per 1.00 unit, defaults to 100
//
// The website has no dedicated balance column (see prisma/schema.prisma — User
// carries `credits`, the in-game wallet), so a top-up credits the buyer's
// `credits` wallet via sendCurrency(), exactly like the voucher flow.
// global fetch only. Credentials and base URL come from env (see src/env.ts).
import { env } from "@/env";
export const PAYPAL_API =
process.env.PAYPAL_API?.replace(/\/+$/, "") ??
env.PAYPAL_API?.replace(/\/+$/, "") ??
"https://api-m.sandbox.paypal.com";
export const PAYPAL_CURRENCY = (
process.env.PAYPAL_CURRENCY ?? "USD"
).toUpperCase();
export const PAYPAL_CURRENCY = env.PAYPAL_CURRENCY.toUpperCase();
/** Credits granted per 1.00 of the order currency (configurable, sane default). */
export function creditsPerUnit(): number {
const n = Number(process.env.PAYPAL_CREDITS_PER_USD ?? "100");
const n = env.PAYPAL_CREDITS_PER_USD;
return Number.isFinite(n) && n > 0 ? n : 100;
}
export class PayPalConfigError extends Error {}
function credentials(): { clientId: string; secret: string } {
const clientId = process.env.PAYPAL_CLIENT_ID;
const secret = process.env.PAYPAL_SECRET;
const clientId = env.PAYPAL_CLIENT_ID;
const secret = env.PAYPAL_SECRET;
if (!clientId || !secret) {
throw new PayPalConfigError(
"PayPal is not configured. Set PAYPAL_CLIENT_ID and PAYPAL_SECRET.",
@@ -40,7 +30,7 @@ function credentials(): { clientId: string; secret: string } {
/** True when both PayPal credentials are present. */
export function isPayPalConfigured(): boolean {
return Boolean(process.env.PAYPAL_CLIENT_ID && process.env.PAYPAL_SECRET);
return Boolean(env.PAYPAL_CLIENT_ID && env.PAYPAL_SECRET);
}
/** OAuth2 client-credentials token (short-lived; we fetch one per request). */
+15
View File
@@ -63,6 +63,10 @@ class SiteSettings {
return map;
}
async getAll(): Promise<Map<string, string>> {
return await this.load();
}
async get(
key: string,
fallback: string | null = null,
@@ -74,6 +78,17 @@ class SiteSettings {
return fallback;
}
async getMany(
keys: string[],
): Promise<Record<string, string | null>> {
const map = await this.load();
const result: Record<string, string | null> = {};
for (const key of keys) {
result[key] = map.get(key) ?? (key in DEFAULTS ? DEFAULTS[key] as string : null);
}
return result;
}
async getBool(key: string, fallback = false): Promise<boolean> {
const v = await this.get(key, null);
if (v === null) return fallback;
-49
View File
@@ -536,53 +536,4 @@ export function extractIconFromSwf(
}
}
// ── Backward-compatible wrapper ────────────────────────────────────
export function convertSwfToNitroBuffer(
swfBuffer: Buffer,
classname: string,
): Buffer {
return convertSwfToNitro(swfBuffer, classname).bundle;
}
// ── Batch Conversion ───────────────────────────────────────────────
export function convertSwfToNitroBatch(
items: BatchConversionItem[],
): BatchConversionResult[] {
return items.map((item) => {
try {
const result = convertSwfToNitro(item.swfBuffer, item.classname);
return {
classname: item.classname,
success: true,
bundle: result.bundle,
dimensions: result.dimensions,
directions: result.directions,
spriteCount: result.spriteCount,
warnings: result.warnings,
};
} catch (err) {
return {
classname: item.classname,
success: false,
warnings: [],
error: (err as Error).message,
};
}
});
}
// ── Utility: Try to decompress nitro-style data (zlib or gzip) ─────
export function nitroDecompress(data: Buffer): Buffer {
try {
return inflateSync(data);
} catch {
try {
return gunzipSync(data);
} catch {
return data;
}
}
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from "vitest";
const findUnique = vi.hoisted(() => vi.fn());
const mockFetch = vi.hoisted(() => vi.fn().mockResolvedValue({ ok: true }));
vi.mock("@/lib/prisma", () => ({
prisma: { websiteSetting: { findUnique } },
}));
vi.mock("@/env", () => ({
env: {
DISCORD_WEBHOOK_URL: "https://discord.com/api/webhooks/test",
TELEGRAM_BOT_TOKEN: "",
TELEGRAM_CHAT_ID: "",
},
}));
global.fetch = mockFetch;
import { notify } from "./webhook";
describe("webhook", () => {
it("sends a Discord notification when webhook URL is configured", async () => {
findUnique.mockResolvedValue(null);
notify({
action: "ban",
actor: "admin",
target: "user1",
targetId: 123,
});
await vi.waitFor(() => {
expect(mockFetch).toHaveBeenCalledWith(
"https://discord.com/api/webhooks/test",
expect.objectContaining({
method: "POST",
headers: { "Content-Type": "application/json" },
}),
);
});
});
it("does not throw when fetch fails", async () => {
mockFetch.mockRejectedValueOnce(new Error("network error"));
findUnique.mockResolvedValue(null);
expect(() =>
notify({ action: "ban", actor: "admin", target: "user1" }),
).not.toThrow();
await vi.waitFor(() => {
expect(mockFetch).toHaveBeenCalled();
});
});
});
+3 -2
View File
@@ -1,3 +1,4 @@
import { logger } from "@/lib/logger";
import { env } from "@/env";
import { prisma } from "../prisma";
@@ -78,7 +79,7 @@ async function sendDiscord(payload: WebhookPayload): Promise<void> {
signal: AbortSignal.timeout(5000),
});
} catch (err) {
console.error("[Webhook] Discord send failed:", {
logger.error("[Webhook] Discord send failed", {
action: payload.action,
error: (err as Error).message,
});
@@ -113,7 +114,7 @@ async function sendTelegram(payload: WebhookPayload): Promise<void> {
signal: AbortSignal.timeout(5000),
});
} catch (err) {
console.error("[Webhook] Telegram send failed:", {
logger.error("[Webhook] Telegram send failed", {
action: payload.action,
error: (err as Error).message,
});