Serve avatars from Habbo imager instead of broken self-hosted proxy.
Local Build and Deploy / deploy (push) Successful in 56s

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-07-15 21:51:02 +02:00
1 parent 2c68fb7e5a
commit 8cce8837bc
6 files changed
+107 -51

No files matched your search

@@ -17,6 +17,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getAvatarUrl } from "@/lib/imager";
// ── Shared types ───────────────────────────────────────────────────────────── // ── Shared types ─────────────────────────────────────────────────────────────
@@ -115,11 +116,15 @@ function AvatarPreview({ type, id }: { type?: string; id?: number }) {
return <Shirt className="w-8 h-8 text-muted-foreground/60" />; return <Shirt className="w-8 h-8 text-muted-foreground/60" />;
} }
const figure = buildPreviewFigure(type, id); const figure = buildPreviewFigure(type, id);
const headOnly = HEAD_TYPES.has(type) ? "&headonly=1" : "";
return ( return (
// biome-ignore lint/performance/noImgElement: dynamic avatar imaging, not a Next asset // biome-ignore lint/performance/noImgElement: dynamic avatar imaging, not a Next asset
<img <img
src={`/api/imaging/avatar?figure=${encodeURIComponent(figure)}&size=l&direction=2&head_direction=3${headOnly}`} src={getAvatarUrl(figure, {
size: "l",
direction: 2,
headDirection: 3,
headOnly: HEAD_TYPES.has(type),
})}
alt={`${type}-${id}`} alt={`${type}-${id}`}
className="max-h-full object-contain image-pixelated" className="max-h-full object-contain image-pixelated"
onError={() => setFailed(true)} onError={() => setFailed(true)}
@@ -91,13 +91,15 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [
fields: [ fields: [
{ {
key: "habbo_imaging_url", key: "habbo_imaging_url",
label: "Habbo imaging upstream", label: "Habbo imager URL",
type: "url", type: "url",
defaultValue: "https://www.habbo.com/habbo-imaging/avatarimage", defaultValue: "https://www.habbo.com/habbo-imaging/avatarimage",
description:
"Public Habbo avatar endpoint used in the browser. Do not point this at /api/imaging/avatar.",
}, },
{ {
key: "imaging_use_habbo_fallback", key: "imaging_use_habbo_fallback",
label: "Use Habbo.com as avatar fallback", label: "Use Habbo.com as avatar fallback (legacy proxy)",
type: "boolean", type: "boolean",
defaultValue: "1", defaultValue: "1",
}, },
+24 -37
View File
@@ -1,14 +1,12 @@
import { type NextRequest, NextResponse } from "next/server"; import { type NextRequest, NextResponse } from "next/server";
import { clientIp, rateLimit } from "@/lib/rate-limit"; import { HABBO_IMAGER_URL, resolveImagerBase } from "@/lib/imager";
import { import { siteSettings } from "@/lib/services/site-settings";
type AvatarRenderResult,
renderAvatar,
} from "@/lib/services/imager/avatar-renderer";
/** /**
* GET /api/imaging/avatar?figure=hr-115-42.hd-195-19&size=l&direction=2&... * GET /api/imaging/avatar?figure=…&size=l&direction=2&…
* *
* Self-hosted avatar imager with disk + memory cache and Habbo upstream fallback. * Redirects to Habbo's public imager. Server-side proxying fails in production
* (Habbo blocks datacenter IPs), so the browser loads the image from Habbo.
*/ */
const FIGURE_RE = /^[a-z]{2}-\d+/i; const FIGURE_RE = /^[a-z]{2}-\d+/i;
@@ -16,15 +14,6 @@ const FIGURE_MAX_LEN = 512;
const FIGURE_MAX_PARTS = 24; const FIGURE_MAX_PARTS = 24;
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const ip = await clientIp();
const limited = await rateLimit(`avatar-imaging:${ip}`, 60, 60_000);
if (!limited.ok) {
return new NextResponse(null, {
status: 429,
headers: { "Retry-After": String(limited.retryAfter) },
});
}
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
const figure = ( const figure = (
@@ -68,35 +57,33 @@ export async function GET(request: NextRequest) {
const gesture = searchParams.get("gesture") ?? undefined; const gesture = searchParams.get("gesture") ?? undefined;
const action = searchParams.get("action") ?? undefined; const action = searchParams.get("action") ?? undefined;
const result: AvatarRenderResult = await renderAvatar({ const params = new URLSearchParams({
figure, figure,
direction: String(direction),
head_direction: String(headDirection),
size, size,
direction,
headDirection,
headOnly,
gesture,
action,
}); });
if (headOnly) params.set("headonly", "1");
if (gesture) params.set("gesture", gesture);
if (action) params.set("action", action);
const ifNoneMatch = request.headers.get("if-none-match"); let base = HABBO_IMAGER_URL;
if (ifNoneMatch && ifNoneMatch === result.etag) { try {
return new NextResponse(null, { const configured = await siteSettings.get(
status: 304, "habbo_imaging_url",
headers: { HABBO_IMAGER_URL,
ETag: result.etag, );
"Cache-Control": "public, max-age=604800, immutable", base = resolveImagerBase(configured);
}, } catch {
}); base = HABBO_IMAGER_URL;
} }
return new NextResponse(new Uint8Array(result.buffer), { const target = `${base}?${params.toString()}`;
status: 200, return NextResponse.redirect(target, {
status: 302,
headers: { headers: {
"Content-Type": "image/png", "Cache-Control": "public, max-age=3600",
"Cache-Control": "public, max-age=604800, immutable",
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
ETag: result.etag,
"X-Imager-Source": result.source,
}, },
}); });
} }
+5 -2
View File
@@ -1,16 +1,19 @@
import { resolveImagerBase } from "@/lib/imager";
/** Build a Habbo avatar-imager URL for a figure string. */ /** Build a Habbo avatar-imager URL for a figure string. */
export function avatarImageUrl( export function avatarImageUrl(
base: string, base: string,
look: string, look: string,
opts: { size?: "s" | "m" | "l"; headOnly?: boolean; direction?: number } = {}, opts: { size?: "s" | "m" | "l"; headOnly?: boolean; direction?: number } = {},
): string { ): string {
const resolved = resolveImagerBase(base);
const params = new URLSearchParams({ figure: look }); const params = new URLSearchParams({ figure: look });
if (opts.size) params.set("size", opts.size); if (opts.size) params.set("size", opts.size);
if (opts.headOnly) params.set("headonly", "1"); if (opts.headOnly) params.set("headonly", "1");
if (opts.direction !== undefined) if (opts.direction !== undefined)
params.set("direction", String(opts.direction)); params.set("direction", String(opts.direction));
const sep = base.includes("?") ? "&" : "?"; const sep = resolved.includes("?") ? "&" : "?";
return `${base}${sep}${params.toString()}`; return `${resolved}${sep}${params.toString()}`;
} }
/** URL-safe slug from a title (lowercase, ascii, hyphenated). */ /** URL-safe slug from a title (lowercase, ascii, hyphenated). */
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { getAvatarUrl, HABBO_IMAGER_URL, resolveImagerBase } from "./imager";
describe("resolveImagerBase", () => {
it("defaults to Habbo imager", () => {
expect(resolveImagerBase()).toBe(HABBO_IMAGER_URL);
expect(resolveImagerBase("")).toBe(HABBO_IMAGER_URL);
expect(resolveImagerBase(null)).toBe(HABBO_IMAGER_URL);
});
it("rejects the broken self-hosted proxy", () => {
expect(resolveImagerBase("/api/imaging/avatar")).toBe(HABBO_IMAGER_URL);
expect(
resolveImagerBase("https://www.epicnabbo.nl/api/imaging/avatar"),
).toBe(HABBO_IMAGER_URL);
});
it("keeps a custom Habbo-compatible base", () => {
expect(
resolveImagerBase("https://www.habbo.com/habbo-imaging/avatarimage/"),
).toBe("https://www.habbo.com/habbo-imaging/avatarimage");
});
});
describe("getAvatarUrl", () => {
it("builds a Habbo imager URL", () => {
const url = getAvatarUrl("hr-115-42.hd-180-1", {
size: "l",
headOnly: true,
direction: 2,
});
expect(url.startsWith(`${HABBO_IMAGER_URL}?`)).toBe(true);
expect(url).toContain("figure=hr-115-42.hd-180-1");
expect(url).toContain("size=l");
expect(url).toContain("headonly=1");
expect(url).toContain("direction=2");
});
});
+29 -8
View File
@@ -1,18 +1,38 @@
/** /**
* Centralized Habbo avatar imager utility. * Habbo avatar imager helpers.
* Points to the self-hosted imager API (`/api/imaging/avatar`) which handles *
* disk + memory caching and (Phase 2) local rendering from .nitro bundles. * Images are loaded directly from Habbo's public imager. The old self-hosted
* Override with NEXT_PUBLIC_IMAGER_URL when needed (e.g. CDN in front). * `/api/imaging/avatar` proxy fails in production (Habbo blocks server-side
* fetches), so the browser always hits Habbo.com instead.
*/ */
const IMAGER_URL = process.env.NEXT_PUBLIC_IMAGER_URL || "/api/imaging/avatar";
export type { AvatarOptions } from "@/types/admin"; export type { AvatarOptions } from "@/types/admin";
import type { AvatarOptions } from "@/types/admin"; import type { AvatarOptions } from "@/types/admin";
/** Official Habbo avatar imaging endpoint. */
export const HABBO_IMAGER_URL =
"https://www.habbo.com/habbo-imaging/avatarimage";
/** /**
* Build an avatar image URL served by the self-hosted imager. * Resolve a usable imager base URL.
* Rejects the broken self-hosted proxy if it was stored in settings.
*/
export function resolveImagerBase(configured?: string | null): string {
const fromEnv = process.env.NEXT_PUBLIC_IMAGER_URL?.trim();
if (fromEnv && !fromEnv.includes("/api/imaging/avatar")) {
return fromEnv.replace(/\/+$/, "");
}
const v = (configured ?? "").trim();
if (!v || v.includes("/api/imaging/avatar")) {
return HABBO_IMAGER_URL;
}
return v.replace(/\/+$/, "");
}
/**
* Build an avatar image URL (Habbo imager by default).
* *
* @example * @example
* getAvatarUrl('hr-893-45.hd-180-1.ch-210-66.lg-270-82') * getAvatarUrl('hr-893-45.hd-180-1.ch-210-66.lg-270-82')
@@ -43,5 +63,6 @@ export function getAvatarUrl(
if (gesture) params.set("gesture", gesture); if (gesture) params.set("gesture", gesture);
if (action) params.set("action", action); if (action) params.set("action", action);
return `${IMAGER_URL}?${params.toString()}`; const base = resolveImagerBase();
return `${base}?${params.toString()}`;
} }