feat(sagi): custom pets — Codex pet bundles, images, featured downloads

The mascot can wear a pet. Right-click it for Hide pet, Size (48-250
px), Choose pet (Sagi, featured, your own - deletable), Upload your
own..., Import .codex-pet bundle..., Find more on codex-pets.net and
Pet settings.... The worn pet and its size are viewer prefs
(agenthub.pet, agenthub.pet.size); the pets live on the server under
<data dir>/pets/<id>/ (server/lib/pets.js, /api/pets).

A Codex pet is the .codex-pet.zip format: pet.json + a 1536x1872
spritesheet.webp, 8x9 frames of 192x208, one row per state.
PetSprite.tsx plays the row of the mascot's mood; an uploaded image
bobs. Only the two bundle files are read, sizes are checked from the
zip directory before inflating, the sheet's WebP header must match,
uploads are raster only (no SVG), ids are made by the server, every
write is same-origin.

The four featured pets (Goku, Bac Ho, Border Collie, 11) are
codex-pets.net uploads with no redistribution licence, so none is
bundled: a pick downloads it from codex-pets.net by a fixed id.
This commit is contained in:
2026-10-03 16:25:42 +07:00
parent 8098f446b6
commit ed1bf20e6b
18 changed files with 1615 additions and 55 deletions
+268
View File
@@ -0,0 +1,268 @@
/**
* @file pets.test.js
* @description `/api/pets` and `server/lib/pets.js`: importing a
* `.codex-pet.zip` (root or one folder deep; refused when a file is missing,
* the sheet is not a 1536×1872 WebP, or an entry is too large BEFORE it is
* inflated), uploading an image (raster only — SVG refused), installing a
* featured pet only from codex-pets.net by its fixed id, deleting, serving the
* sprite with nosniff, ids made by the server, and every write same-origin.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
"use strict";
const { describe, it, before, after, beforeEach } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const http = require("node:http");
const AdmZip = require("adm-zip");
const ROOT = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pets-")));
process.env.DASHBOARD_DB_PATH = path.join(ROOT, "t.db");
process.env.CLAUDE_HOME = path.join(ROOT, "claude");
process.env.DASHBOARD_DATA_DIR = path.join(ROOT, "data");
process.env.DASHBOARD_REMOTE_SYNC_MS = "0";
process.env.DASHBOARD_LIVENESS_PROBE = "0";
const { createApp } = require("../index");
const pets = require("../lib/pets");
let server;
let base;
/** A WebP header (VP8X) claiming `w`×`h` — the server never decodes pixels. */
function webp(w = 1536, h = 1872, pad = 64) {
const b = Buffer.alloc(30 + pad);
b.write("RIFF", 0);
b.writeUInt32LE(b.length - 8, 4);
b.write("WEBP", 8);
b.write("VP8X", 12);
b.writeUInt32LE(10, 16);
b.writeUIntLE(w - 1, 24, 3);
b.writeUIntLE(h - 1, 27, 3);
return b;
}
const PNG = Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
Buffer.alloc(32),
]);
function bundle(files) {
const zip = new AdmZip();
for (const [name, data] of Object.entries(files))
zip.addFile(name, Buffer.isBuffer(data) ? data : Buffer.from(JSON.stringify(data)));
return zip.toBuffer();
}
function request(method, url, { body, headers = {} } = {}) {
return new Promise((resolve, reject) => {
const req = http.request(
`${base}${url}`,
{
method,
headers: {
...(body ? { "content-type": "application/octet-stream" } : {}),
...headers,
},
},
(res) => {
const chunks = [];
res.on("data", (c) => chunks.push(c));
res.on("end", () => {
const buf = Buffer.concat(chunks);
let json = null;
try {
json = JSON.parse(buf.toString("utf8"));
} catch {
/* a sprite */
}
resolve({ status: res.statusCode, headers: res.headers, json, buf });
});
}
);
req.on("error", reject);
if (body) req.write(body);
req.end();
});
}
before(async () => {
const app = createApp();
server = http.createServer(app);
await new Promise((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${server.address().port}`;
});
after(() => {
server.close();
pets.__setFetch(null);
fs.rmSync(ROOT, { recursive: true, force: true });
});
beforeEach(() => {
fs.rmSync(path.join(ROOT, "data", "pets"), { recursive: true, force: true });
pets.__setFetch(() => {
throw new Error("no network in tests");
});
});
describe("importing a .codex-pet bundle", () => {
it("stores pet.json + spritesheet.webp under an id the server makes, and serves the sheet", async () => {
const r = await request("POST", "/api/pets/import", {
body: bundle({
"pet.json": { id: "../../evil", displayName: " Corgi\nByte ", description: "A corgi." },
"spritesheet.webp": webp(),
}),
});
assert.equal(r.status, 201);
assert.match(r.json.pet.id, /^p-[0-9a-f]{12}$/);
assert.equal(r.json.pet.displayName, "Corgi Byte");
assert.equal(r.json.pet.kind, "codex");
const list = await request("GET", "/api/pets");
assert.deepEqual(
list.json.pets.map((p) => p.id),
[r.json.pet.id]
);
assert.deepEqual(list.json.sheet, {
width: 1536,
height: 1872,
cellWidth: 192,
cellHeight: 208,
});
const sprite = await request("GET", `/api/pets/${r.json.pet.id}/sprite`);
assert.equal(sprite.status, 200);
assert.equal(sprite.headers["content-type"], "image/webp");
assert.equal(sprite.headers["x-content-type-options"], "nosniff");
});
it("accepts the two files one folder deep", async () => {
const r = await request("POST", "/api/pets/import", {
body: bundle({
"corgi/pet.json": { displayName: "Corgi" },
"corgi/spritesheet.webp": webp(),
}),
});
assert.equal(r.status, 201);
});
it("refuses a bundle missing a file, a sheet of the wrong size, and a non-zip", async () => {
const missing = await request("POST", "/api/pets/import", { body: bundle({ "pet.json": {} }) });
assert.equal(missing.status, 400);
assert.equal(missing.json.error.code, "EBADPET");
const wrong = await request("POST", "/api/pets/import", {
body: bundle({ "pet.json": {}, "spritesheet.webp": webp(512, 512) }),
});
assert.equal(wrong.status, 400);
assert.match(wrong.json.error.message, /512×512/);
const notZip = await request("POST", "/api/pets/import", { body: Buffer.from("hello") });
assert.equal(notZip.json.error.code, "EBADPET");
assert.deepEqual((await request("GET", "/api/pets")).json.pets, []);
});
it("refuses an oversized entry from its header, before inflating it", async () => {
const r = await request("POST", "/api/pets/import", {
body: bundle({
"pet.json": {},
"spritesheet.webp": Buffer.concat([webp(), Buffer.alloc(7 * 1024 * 1024)]),
}),
});
assert.equal(r.status, 413);
assert.equal(r.json.error.code, "ETOOBIG");
});
});
describe("uploading an image", () => {
it("keeps a raster image as a still pet, named after its file", async () => {
const r = await request("POST", "/api/pets/upload?name=My%20cat.png", { body: PNG });
assert.equal(r.status, 201);
assert.equal(r.json.pet.kind, "image");
assert.equal(r.json.pet.displayName, "My cat");
const sprite = await request("GET", `/api/pets/${r.json.pet.id}/sprite`);
assert.equal(sprite.headers["content-type"], "image/png");
});
it("refuses SVG and anything that is not a known raster", async () => {
const svg = await request("POST", "/api/pets/upload?name=x.svg", {
body: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'),
});
assert.equal(svg.status, 400);
assert.equal(svg.json.error.code, "EBADPET");
});
});
describe("featured pets", () => {
it("installs one only from codex-pets.net by its fixed id, once per id", async () => {
const urls = [];
pets.__setFetch(async (url) => {
urls.push(url);
const body = url.endsWith("/spritesheet")
? webp()
: Buffer.from(JSON.stringify({ pet: { description: "A martial artist." } }));
return { ok: true, status: 200, headers: { get: () => null }, arrayBuffer: async () => body };
});
const r = await request("POST", "/api/pets/featured/goku");
assert.equal(r.status, 201);
assert.equal(r.json.pet.id, "cp-goku");
assert.equal(r.json.pet.source, "featured");
assert.equal(r.json.pet.description, "A martial artist.");
assert.deepEqual(urls, [
"https://codex-pets.net/api/pets/goku",
"https://codex-pets.net/api/pets/goku/spritesheet",
]);
await request("POST", "/api/pets/featured/goku");
const list = await request("GET", "/api/pets");
assert.equal(list.json.pets.length, 1);
assert.equal(list.json.featured.find((f) => f.id === "goku").installed, true);
});
it("refuses an id that is not featured without any request", async () => {
let called = false;
pets.__setFetch(async () => {
called = true;
});
const r = await request("POST", "/api/pets/featured/some-other-pet");
assert.equal(r.status, 404);
assert.equal(called, false);
});
it("reports a failed download as EFETCH and a bad sheet as EBADPET", async () => {
pets.__setFetch(async () => ({ ok: false, status: 503, headers: { get: () => null } }));
const down = await request("POST", "/api/pets/featured/goku");
assert.equal(down.status, 502);
assert.equal(down.json.error.code, "EFETCH");
pets.__setFetch(async () => ({
ok: true,
status: 200,
headers: { get: () => null },
arrayBuffer: async () => webp(100, 100),
}));
const bad = await request("POST", "/api/pets/featured/goku");
assert.equal(bad.json.error.code, "EBADPET");
});
});
describe("deleting and serving", () => {
it("deletes a pet, and answers 404 for an unknown or path-shaped id", async () => {
const r = await request("POST", "/api/pets/upload?name=a.png", { body: PNG });
const del = await request("DELETE", `/api/pets/${r.json.pet.id}`);
assert.equal(del.status, 200);
assert.deepEqual((await request("GET", "/api/pets")).json.pets, []);
assert.equal((await request("DELETE", `/api/pets/${r.json.pet.id}`)).status, 404);
assert.equal((await request("GET", "/api/pets/..%2F..%2Ft.db/sprite")).status, 404);
assert.equal((await request("DELETE", "/api/pets/p-nothere00000")).status, 404);
});
});
describe("same-origin", () => {
it("refuses every write from another origin", async () => {
const headers = { origin: "https://evil.example" };
assert.equal(
(await request("POST", "/api/pets/upload?name=a.png", { body: PNG, headers })).status,
403
);
assert.equal((await request("POST", "/api/pets/import", { body: PNG, headers })).status, 403);
assert.equal((await request("POST", "/api/pets/featured/goku", { headers })).status, 403);
assert.equal((await request("DELETE", "/api/pets/p-000000000000", { headers })).status, 403);
});
});
+2
View File
@@ -91,6 +91,7 @@ const lanesRouter = require("./routes/lanes");
const projectsRouter = require("./routes/projects");
const laneSourcesRouter = require("./routes/lane-sources");
const locksRouter = require("./routes/locks");
const petsRouter = require("./routes/pets");
const APP_VERSION = (() => {
try {
@@ -134,6 +135,7 @@ function createApp() {
app.use("/api/lanes", lanesRouter);
app.use("/api/projects", projectsRouter);
app.use("/api/locks", locksRouter);
app.use("/api/pets", petsRouter);
app.use("/api/alerts", alertsRouter);
app.use("/api/webhooks", webhooksRouter);
app.use("/api/remote-sources", remoteSourcesRouter);
+328
View File
@@ -0,0 +1,328 @@
/**
* @file pets.js
* @description Custom pets for the dashboard mascot (Sagi). A pet is a folder
* `<data dir>/pets/<id>/` holding `meta.json` (written here) and either a
* Codex pet's `spritesheet.webp` — the `.codex-pet.zip` format: an 8×9 grid of
* 192×208 frames, one row per animation state — or one uploaded image. Pets
* come from exactly three places: an uploaded `.codex-pet.zip`, an uploaded
* image, or one of the FEATURED pets, downloaded from codex-pets.net by a fixed
* id — never a URL or a path from a request. None is bundled with AgentHub:
* the featured pets are other people's uploads with no redistribution
* licence, so each install fetches its own copy from the site that hosts
* them. An id is always made here; SVG is refused, because an SVG served from
* the dashboard's origin runs script when opened.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const AdmZip = require("adm-zip");
const { getDataDir } = require("./claude-home");
const MAX_BUNDLE_BYTES = 8 * 1024 * 1024;
const MAX_SHEET_BYTES = 6 * 1024 * 1024;
const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
const MAX_MANIFEST_BYTES = 16 * 1024;
const MAX_PETS = 50;
/** The Codex atlas: 8 columns × 9 rows of 192×208 frames. */
const SHEET = { width: 1536, height: 1872, cellWidth: 192, cellHeight: 208 };
const FEATURED_HOST = "https://codex-pets.net";
/** Offered in the pet menu, installed only on a click. `id` is codex-pets.net's. */
const FEATURED = [
{ id: "goku", displayName: "Goku", by: "hackminit" },
{ id: "bac-ho", displayName: "Bac Ho", by: "k0nkupa" },
{ id: "border-collie", displayName: "Border Collie", by: "dev-minsoo" },
{ id: "11", displayName: "11", by: "ct" },
];
const ID_RE = /^(?:p-[0-9a-f]{12}|cp-[a-z0-9-]{1,40})$/;
const IMAGE_TYPES = {
png: "image/png",
jpg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
};
let fetchImpl = (...args) => fetch(...args);
/** Test seam: replace the HTTP client the featured install uses. */
function __setFetch(fn) {
fetchImpl = fn || ((...args) => fetch(...args));
}
const fail = (code, message) => Object.assign(new Error(message), { code });
function petsRoot() {
return path.join(getDataDir(), "pets");
}
function petDir(id) {
if (!ID_RE.test(String(id))) throw fail("ENOPET", "pet not found");
return path.join(petsRoot(), id);
}
/** Width and height from a WebP header (VP8X, VP8 or VP8L), else null. */
function webpSize(buf) {
if (buf.length < 30) return null;
if (buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WEBP")
return null;
const chunk = buf.toString("ascii", 12, 16);
if (chunk === "VP8X")
return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };
if (chunk === "VP8 ")
return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
if (chunk === "VP8L") {
const bits = buf.readUInt32LE(21);
return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff) };
}
return null;
}
/** The raster type of an uploaded image by its magic bytes, else null. */
function sniffImage(buf) {
if (
buf.length >= 8 &&
buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
)
return "png";
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpg";
if (buf.length >= 6 && /^GIF8[79]a$/.test(buf.toString("ascii", 0, 6))) return "gif";
if (
webpSize(buf) ||
(buf.length >= 12 &&
buf.toString("ascii", 8, 12) === "WEBP" &&
buf.toString("ascii", 0, 4) === "RIFF")
)
return "webp";
return null;
}
/** A display string from untrusted input: trimmed, single-line, capped. */
function cleanText(value, max) {
return typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, max) : "";
}
function checkSheet(buf) {
if (buf.length > MAX_SHEET_BYTES) throw fail("ETOOBIG", "the spritesheet is larger than 6 MB");
const size = webpSize(buf);
if (!size) throw fail("EBADPET", "the spritesheet is not a WebP image");
if (size.width !== SHEET.width || size.height !== SHEET.height)
throw fail(
"EBADPET",
`the spritesheet is ${size.width}×${size.height}; a Codex pet is ${SHEET.width}×${SHEET.height}`
);
}
function readMeta(id) {
try {
return JSON.parse(fs.readFileSync(path.join(petDir(id), "meta.json"), "utf8"));
} catch {
return null;
}
}
function view(id, meta) {
return {
id,
displayName: meta.displayName,
description: meta.description || "",
kind: meta.kind,
source: meta.source,
...(meta.featuredId ? { featuredId: meta.featuredId } : {}),
...(meta.by ? { by: meta.by } : {}),
};
}
function listPets() {
let names = [];
try {
names = fs.readdirSync(petsRoot());
} catch {
return [];
}
return names
.filter((n) => ID_RE.test(n))
.map((n) => [n, readMeta(n)])
.filter(([, meta]) => meta && (meta.kind === "codex" || meta.kind === "image"))
.sort((a, b) => String(a[1].addedAt).localeCompare(String(b[1].addedAt)))
.map(([n, meta]) => view(n, meta));
}
/** Writes a pet atomically: a temp folder renamed into place. */
function store(id, meta, file, body) {
const existing = listPets();
if (!existing.some((p) => p.id === id) && existing.length >= MAX_PETS)
throw fail("ETOOMANY", `at most ${MAX_PETS} pets`);
const root = petsRoot();
fs.mkdirSync(root, { recursive: true });
const tmp = fs.mkdtempSync(path.join(root, ".new-"));
try {
fs.writeFileSync(path.join(tmp, file), body);
fs.writeFileSync(
path.join(tmp, "meta.json"),
JSON.stringify({ ...meta, file, addedAt: new Date().toISOString() })
);
fs.rmSync(petDir(id), { recursive: true, force: true });
fs.renameSync(tmp, petDir(id));
} catch (err) {
fs.rmSync(tmp, { recursive: true, force: true });
throw err;
}
return view(id, readMeta(id));
}
const newId = () => `p-${crypto.randomBytes(6).toString("hex")}`;
/** Imports a `.codex-pet.zip`: `pet.json` + `spritesheet.webp`, at the root
* or in one top-level folder. Nothing else in the archive is read. */
function importBundle(buf) {
if (!Buffer.isBuffer(buf) || !buf.length) throw fail("EBADPET", "no file");
if (buf.length > MAX_BUNDLE_BYTES) throw fail("ETOOBIG", "the bundle is larger than 8 MB");
let entries;
try {
entries = new AdmZip(buf).getEntries();
} catch {
throw fail("EBADPET", "not a zip archive");
}
const pick = (name) =>
entries.find(
(e) =>
!e.isDirectory &&
/^(?:[^/]+\/)?[^/]+$/.test(e.entryName) &&
path.posix.basename(e.entryName) === name
);
const manifest = pick("pet.json");
const sheet = pick("spritesheet.webp");
if (!manifest || !sheet)
throw fail("EBADPET", "a .codex-pet bundle holds pet.json and spritesheet.webp");
// Sizes from the central directory, checked BEFORE inflating (zip bombs).
if (manifest.header.size > MAX_MANIFEST_BYTES) throw fail("EBADPET", "pet.json is too large");
if (sheet.header.size > MAX_SHEET_BYTES)
throw fail("ETOOBIG", "the spritesheet is larger than 6 MB");
let pet;
try {
pet = JSON.parse(manifest.getData().toString("utf8"));
} catch {
throw fail("EBADPET", "pet.json is not valid JSON");
}
const body = sheet.getData();
checkSheet(body);
const displayName =
cleanText(pet && pet.displayName, 60) || cleanText(pet && pet.id, 60) || "Pet";
return store(
newId(),
{
kind: "codex",
source: "upload",
displayName,
description: cleanText(pet && pet.description, 300),
},
"spritesheet.webp",
body
);
}
/** Adds one uploaded image (PNG, JPEG, GIF or WebP) as a still pet. */
function addImage(buf, name) {
if (!Buffer.isBuffer(buf) || !buf.length) throw fail("EBADPET", "no file");
if (buf.length > MAX_IMAGE_BYTES) throw fail("ETOOBIG", "the image is larger than 4 MB");
const ext = sniffImage(buf);
if (!ext) throw fail("EBADPET", "only PNG, JPEG, GIF or WebP images");
const displayName = cleanText(String(name || "").replace(/\.[^.]+$/, ""), 60) || "Pet";
return store(
newId(),
{ kind: "image", source: "upload", displayName, type: ext },
`image.${ext}`,
buf
);
}
async function fetchCapped(url, max) {
const res = await fetchImpl(url, { signal: AbortSignal.timeout(20_000), redirect: "error" });
if (!res.ok) throw fail("EFETCH", `codex-pets.net answered ${res.status}`);
const len = Number(res.headers?.get?.("content-length"));
if (len > max) throw fail("ETOOBIG", "the download is too large");
const body = Buffer.from(await res.arrayBuffer());
if (body.length > max) throw fail("ETOOBIG", "the download is too large");
return body;
}
/** Downloads one FEATURED pet from codex-pets.net into this install. */
async function installFeatured(featuredId) {
const f = FEATURED.find((x) => x.id === featuredId);
if (!f) throw fail("ENOPET", "not a featured pet");
const base = `${FEATURED_HOST}/api/pets/${encodeURIComponent(f.id)}`;
let description = "";
try {
const meta = JSON.parse((await fetchCapped(base, MAX_MANIFEST_BYTES * 4)).toString("utf8"));
description = cleanText(meta && meta.pet && meta.pet.description, 300);
} catch (err) {
if (err.code === "ETOOBIG") throw err;
/* the description is optional; the spritesheet is not */
}
let body;
try {
body = await fetchCapped(`${base}/spritesheet`, MAX_SHEET_BYTES);
} catch (err) {
if (err.code) throw err;
throw fail("EFETCH", `could not reach codex-pets.net: ${err.message}`);
}
checkSheet(body);
return store(
`cp-${f.id}`,
{
kind: "codex",
source: "featured",
featuredId: f.id,
by: f.by,
displayName: f.displayName,
description,
},
"spritesheet.webp",
body
);
}
function removePet(id) {
const dir = petDir(id);
if (!readMeta(id)) throw fail("ENOPET", "pet not found");
fs.rmSync(dir, { recursive: true, force: true });
}
/** The file to serve for a pet and its content type. */
function spriteFile(id) {
const meta = readMeta(id);
if (!meta || (meta.file !== "spritesheet.webp" && !/^image\.(png|jpg|gif|webp)$/.test(meta.file)))
throw fail("ENOPET", "pet not found");
const ext = meta.file.split(".").pop();
return { path: path.join(petDir(id), meta.file), type: IMAGE_TYPES[ext] };
}
function featured() {
const installed = new Set(
listPets()
.map((p) => p.featuredId)
.filter(Boolean)
);
return FEATURED.map((f) => ({
...f,
installed: installed.has(f.id),
page: `${FEATURED_HOST}/#/pets/${f.id}`,
}));
}
module.exports = {
SHEET,
FEATURED,
MAX_BUNDLE_BYTES,
MAX_IMAGE_BYTES,
listPets,
featured,
importBundle,
addImage,
installFeatured,
removePet,
spriteFile,
webpSize,
__setFetch,
};
+99
View File
@@ -0,0 +1,99 @@
/**
* @file pets.js (routes)
* @description `/api/pets` — the mascot's custom pets (`server/lib/pets.js`):
* the list plus the featured ones, a pet's sprite, importing a `.codex-pet.zip`,
* uploading an image, installing a featured pet from codex-pets.net by its
* fixed id, and deleting one. Every write is same-origin; no route takes a
* URL or a path.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
"use strict";
const express = require("express");
const pets = require("../lib/pets");
const { sameOriginGuard } = require("../lib/same-origin");
const router = express.Router();
const STATUS = {
ENOPET: 404,
ETOOBIG: 413,
ETOOMANY: 409,
EFETCH: 502,
EBADORIGIN: 403,
};
function sendError(res, err) {
if (err && typeof err.code === "string" && /^E[A-Z]+$/.test(err.code)) {
return res
.status(STATUS[err.code] || 400)
.json({ error: { code: err.code, message: err.message } });
}
return res
.status(500)
.json({ error: { code: "EINTERNAL", message: String(err?.message || err) } });
}
router.get("/", (_req, res) => {
try {
res.json({ pets: pets.listPets(), featured: pets.featured(), sheet: pets.SHEET });
} catch (err) {
sendError(res, err);
}
});
router.get("/:id/sprite", (req, res) => {
try {
const file = pets.spriteFile(req.params.id);
res.set("Content-Type", file.type);
res.set("X-Content-Type-Options", "nosniff");
res.set("Cache-Control", "private, max-age=3600");
res.sendFile(file.path);
} catch (err) {
sendError(res, err);
}
});
const raw = (limit) => express.raw({ type: () => true, limit });
router.post("/import", sameOriginGuard, raw(pets.MAX_BUNDLE_BYTES), (req, res) => {
try {
res.status(201).json({ pet: pets.importBundle(req.body) });
} catch (err) {
sendError(res, err);
}
});
router.post("/upload", sameOriginGuard, raw(pets.MAX_IMAGE_BYTES), (req, res) => {
try {
res.status(201).json({ pet: pets.addImage(req.body, req.query.name) });
} catch (err) {
sendError(res, err);
}
});
router.post("/featured/:id", sameOriginGuard, async (req, res) => {
try {
res.status(201).json({ pet: await pets.installFeatured(req.params.id) });
} catch (err) {
sendError(res, err);
}
});
router.delete("/:id", sameOriginGuard, (req, res) => {
try {
pets.removePet(req.params.id);
res.json({ ok: true });
} catch (err) {
sendError(res, err);
}
});
// An upload past its limit reaches here as express.raw's 413.
router.use((err, _req, res, next) => {
if (err && err.type === "entity.too.large")
return res.status(413).json({ error: { code: "ETOOBIG", message: "the file is too large" } });
return next(err);
});
module.exports = router;