fix: reject HTML tags in settings API to prevent stored XSS

PUT /api/v1/settings now returns 400 if any key or value contains HTML
tags. Settings are configuration values - there is no legitimate use
case for HTML in them.
This commit is contained in:
Siddharth Kumar Sah
2026-03-28 19:08:17 +08:00
parent fb84f5ce8d
commit 8a62093130
2 changed files with 45 additions and 0 deletions
+9
View File
@@ -11,6 +11,8 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { db, schema } from "../db/index.js";
import { requireAdmin, requireAuth } from "../plugins/auth.js";
const HTML_TAG_PATTERN = /<[a-z/!][^>]*>/i;
export async function settingsRoutes(app: FastifyInstance): Promise<void> {
// GET /api/v1/settings — Get all settings as a key-value object
app.get("/api/v1/settings", async (request: FastifyRequest, reply: FastifyReply) => {
@@ -49,6 +51,13 @@ export async function settingsRoutes(app: FastifyInstance): Promise<void> {
const strValue = typeof value === "string" ? value : JSON.stringify(value);
if (HTML_TAG_PATTERN.test(key) || HTML_TAG_PATTERN.test(strValue)) {
return reply.status(400).send({
error: "Settings keys and values must not contain HTML tags",
code: "VALIDATION_ERROR",
});
}
// Upsert: insert or update on conflict
const existing = db.select().from(schema.settings).where(eq(schema.settings.key, key)).get();
+36
View File
@@ -1395,6 +1395,42 @@ describe("Settings", () => {
});
expect(JSON.parse(res.body).value).toBe("updated");
});
it("rejects HTML tags in setting values", async () => {
const res = await app.inject({
method: "PUT",
url: "/api/v1/settings",
headers: { authorization: `Bearer ${adminToken}` },
payload: { app_name: "<script>alert('xss')</script>" },
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.code).toBe("VALIDATION_ERROR");
});
it("rejects HTML tags in setting keys", async () => {
const res = await app.inject({
method: "PUT",
url: "/api/v1/settings",
headers: { authorization: `Bearer ${adminToken}` },
payload: { "<img src=x onerror=alert(1)>": "test" },
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.code).toBe("VALIDATION_ERROR");
});
it("allows normal setting values without HTML", async () => {
const res = await app.inject({
method: "PUT",
url: "/api/v1/settings",
headers: { authorization: `Bearer ${adminToken}` },
payload: { app_name: "My App (v2.0) - Production" },
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.ok).toBe(true);
});
});
describe("GET /api/v1/settings/:key", () => {