feat(custom-widgets): complete JSX v2

This commit is contained in:
Thomas Camlong committed 2026-07-18 15:33:25 +02:00
1 parent c0f1d6624c
commit eae48f50fd
263 files changed
+65503 -17816

No files matched your search

@@ -1,179 +1,50 @@
import { z } from "zod/v4";
import { validateCustomJsxTemplate } from "../jsx/analyzer";
import { customWidgetMethods } from "./schema-types";
import { isCredentialKeyName, validateCredentialFreeExport, validatePrototypeKeys } from "./definition-security";
import { validateCustomWidgetOptions } from "./options";
import { customWidgetOptionsSchemaSchema } from "./options-schema";
import { customJsxRequestSchema, customWidgetIdentifierSchema, customWidgetSourceSchema } from "./request-schema";
import type { CustomJsxRequest } from "./request-schema";
import { customWidgetAuthTypes, customWidgetSecretKinds } from "./schema-types";
export const customJsxNetworkScopes = ["public", "private", "loopback"] as const;
export type CustomJsxNetworkScope = (typeof customJsxNetworkScopes)[number];
export * from "./options-schema";
export * from "./request-schema";
export type CustomWidgetOptionsSchema = z.infer<typeof customWidgetOptionsSchemaSchema>;
export const customJsxRequestParameterTypes = ["string", "number", "boolean"] as const;
export type CustomJsxRequestParameterType = (typeof customJsxRequestParameterTypes)[number];
const requestIdSchema = z
export const customWidgetStateTypes = [
"string",
"number",
"boolean",
"date",
"string[]",
"number[]",
"date[]",
] as const;
export const customWidgetBindingIdentifierSchema = z
.string()
.min(1)
.max(64)
.regex(
/^[a-z][a-z0-9_-]*$/,
"Request IDs must start with a letter and contain only lowercase letters, numbers, - or _",
);
const requestParametersSchema = z
.record(requestIdSchema, z.enum(customJsxRequestParameterTypes))
.refine((parameters) => Object.keys(parameters).length <= 32, "A request can declare at most 32 parameters");
const reservedRequestHeaders = new Set([
"authorization",
"connection",
"content-length",
"cookie",
"expect",
"forwarded",
"host",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via",
]);
const staticHeadersSchema = z
.record(z.string().min(1).max(128), z.string().max(8192))
.refine((headers) => Object.keys(headers).length <= 32, "A request can declare at most 32 static headers")
.refine(
(headers) =>
Object.keys(headers).every((name) => {
const normalized = name.trim().toLowerCase();
return (
!reservedRequestHeaders.has(normalized) &&
!normalized.startsWith("proxy-") &&
!normalized.startsWith("sec-") &&
!normalized.startsWith("x-forwarded-")
);
}),
"Static headers cannot override authentication, cookies, routing, forwarding, proxy, or hop-by-hop headers",
);
const collectBodyParameterNames = (value: unknown, result = new Set<string>()): Set<string> => {
if (Array.isArray(value)) {
value.forEach((entry) => collectBodyParameterNames(entry, result));
return result;
}
if (value === null || typeof value !== "object") return result;
const entries = Object.entries(value);
if (entries.length === 1 && entries[0]?.[0] === "$param" && typeof entries[0][1] === "string") {
result.add(entries[0][1]);
return result;
}
entries.forEach(([, entry]) => collectBodyParameterNames(entry, result));
return result;
};
export const customJsxRequestSchema = z
.object({
id: requestIdSchema,
kind: z.enum(["query", "action"]),
method: z.enum(customWidgetMethods),
pathTemplate: z
.string()
.min(1)
.max(2048)
.startsWith("/")
.refine((path) => !path.startsWith("//"), "Path templates must be same-origin paths")
.refine((path) => !path.includes("\\"), "Path templates cannot contain backslashes")
.refine((path) => !path.includes("#"), "Path templates cannot contain URL fragments"),
parameters: requestParametersSchema,
bodyTemplate: z.json().optional(),
staticHeaders: staticHeadersSchema.optional(),
auth: z.enum(["inherit", "none"]),
minimumBoardPermission: z.enum(["view", "modify", "full"]),
cacheTtlSeconds: z.number().int().min(0).max(3600).optional(),
allowViewerExecution: z.literal(true).optional(),
})
.superRefine((request, ctx) => {
if (request.kind === "query" && request.method !== "GET") {
ctx.addIssue({
code: "custom",
path: ["method"],
message: "Query requests must use GET",
});
}
if (request.kind === "action" && request.method === "GET") {
ctx.addIssue({
code: "custom",
path: ["method"],
message: "Action requests must use POST, PUT, PATCH, or DELETE",
});
}
if (request.kind === "query" && request.minimumBoardPermission !== "view") {
ctx.addIssue({
code: "custom",
path: ["minimumBoardPermission"],
message: "Query requests use view permission",
});
}
if (request.method === "DELETE" && request.minimumBoardPermission !== "full") {
ctx.addIssue({
code: "custom",
path: ["minimumBoardPermission"],
message: "DELETE actions require full board permission",
});
}
if (
request.kind === "action" &&
request.method !== "DELETE" &&
request.minimumBoardPermission === "view" &&
request.allowViewerExecution !== true
) {
ctx.addIssue({
code: "custom",
path: ["allowViewerExecution"],
message: "Viewer actions require explicit allowViewerExecution approval",
});
}
if (request.kind === "query" && request.bodyTemplate !== undefined) {
ctx.addIssue({
code: "custom",
path: ["bodyTemplate"],
message: "GET query requests cannot define a request body",
});
}
if (request.kind === "action" && request.cacheTtlSeconds !== undefined && request.cacheTtlSeconds !== 0) {
ctx.addIssue({
code: "custom",
path: ["cacheTtlSeconds"],
message: "Actions cannot be cached",
});
}
const declaredParameters = new Set(Object.keys(request.parameters));
const pathParameters = [...request.pathTemplate.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1] ?? "");
for (const parameter of [...pathParameters, ...collectBodyParameterNames(request.bodyTemplate)]) {
if (!declaredParameters.has(parameter)) {
.regex(/^[A-Za-z][A-Za-z0-9_-]*$/u, "Binding names must start with a letter and contain letters, numbers, - or _");
export const customWidgetStateSchemaSchema = z
.record(customWidgetBindingIdentifierSchema, z.enum(customWidgetStateTypes))
.superRefine((schema, ctx) => {
for (const key of Object.keys(schema)) {
if (isCredentialKeyName(key)) {
ctx.addIssue({
code: "custom",
path: [request.bodyTemplate === undefined ? "pathTemplate" : "parameters"],
message: `Placeholder '${parameter}' is not declared in request parameters`,
path: [key],
message: "Credentials must use source authentication, not local state",
});
}
}
});
export type CustomWidgetStateSchema = z.infer<typeof customWidgetStateSchemaSchema>;
export type CustomJsxRequest = z.infer<typeof customJsxRequestSchema>;
const customJsxTemplateSchema = z
export const customJsxTemplateSchema = z
.string()
.min(1)
.max(50000)
.max(50_000)
.superRefine((template, ctx) => {
for (const diagnostic of validateCustomJsxTemplate(template)) {
if (diagnostic.severity === "error") {
@@ -183,81 +54,235 @@ const customJsxTemplateSchema = z
});
}
}
})
.describe(
"JSX template string using whitelisted Mantine components. Access API data via {data.fieldName}. Direct fetch and XMLHttpRequest access are unavailable; v2 templates reference named requests.",
);
export const customJsxDisplayConfigV1Schema = z.object({
type: z
.literal("customJsx")
.describe("Display type discriminator — must be 'customJsx' when displayType is customJsx"),
template: customJsxTemplateSchema,
jsxApiVersion: z.never().optional(),
networkScope: z.never().optional(),
requests: z.never().optional(),
});
export const customJsxDisplayConfigV2Schema = z
.object({
type: z.literal("customJsx"),
jsxApiVersion: z.literal(2),
template: customJsxTemplateSchema,
networkScope: z.enum(customJsxNetworkScopes),
requests: z.array(customJsxRequestSchema).max(64),
})
.superRefine((config, ctx) => {
const requestsById = new Map<string, CustomJsxRequest>();
for (const [index, request] of config.requests.entries()) {
if (requestsById.has(request.id)) {
ctx.addIssue({
code: "custom",
path: ["requests", index, "id"],
message: `Duplicate request ID: ${request.id}`,
});
}
requestsById.set(request.id, request);
}
const networkComponentPattern = /<(SubFetch|ActionButton|ToggleSwitch)\b([^>]*)>/g;
for (const match of config.template.matchAll(networkComponentPattern)) {
const component = match[1] as "SubFetch" | "ActionButton" | "ToggleSwitch";
const attributes = match[2] ?? "";
const idMatch = attributes.match(/\brequestId\s*=\s*(?:"([^"]+)"|'([^']+)')/);
const requestId = idMatch?.[1] ?? idMatch?.[2];
if (!requestId) {
ctx.addIssue({
code: "custom",
path: ["template"],
message: `${component} must use a literal requestId`,
});
continue;
}
const request = requestsById.get(requestId);
const expectedKind = component === "SubFetch" ? "query" : "action";
if (!request) {
ctx.addIssue({
code: "custom",
path: ["template"],
message: `${component} references unknown request '${requestId}'`,
});
} else if (request.kind !== expectedKind) {
ctx.addIssue({
code: "custom",
path: ["template"],
message: `${component} requires a ${expectedKind} request, but '${requestId}' is ${request.kind}`,
});
}
if (/\b(?:url|method|headers|body)\s*=/.test(attributes)) {
ctx.addIssue({
code: "custom",
path: ["template"],
message: `${component} cannot declare inline network settings`,
});
}
}
});
export type CustomJsxDisplayConfigV2 = z.infer<typeof customJsxDisplayConfigV2Schema>;
export const customWidgetSecretInputSchema = z.object({
sourceId: customWidgetIdentifierSchema,
kind: z.enum(customWidgetSecretKinds),
value: z.string().min(1).max(8_192),
});
export const customWidgetSecretsInputSchema = z
.array(customWidgetSecretInputSchema)
.max(24)
.superRefine((secrets, ctx) => {
const identities = new Set<string>();
secrets.forEach((secret, index) => {
const identity = `${secret.sourceId}:${secret.kind}`;
if (identities.has(identity)) {
ctx.addIssue({ code: "custom", path: [index], message: "A widget secret can only be supplied once" });
}
identities.add(identity);
});
});
export const customWidgetDefinitionSchema = z
.object({
$schema: z.literal("homarr-custom-widget-v2"),
name: z.string().trim().min(1).max(128),
description: z.string().max(512).optional(),
iconUrl: z
.string()
.url()
.refine((value) => {
const url = new URL(value);
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
}, "Widget icons must use HTTP or HTTPS without embedded credentials")
.optional(),
sources: z.array(customWidgetSourceSchema).min(1).max(8),
requests: z.array(customJsxRequestSchema).max(64),
optionsSchema: customWidgetOptionsSchemaSchema,
defaultOptions: z.record(z.string(), z.unknown()),
stateSchema: customWidgetStateSchemaSchema.optional(),
defaultState: z.record(z.string(), z.unknown()).optional(),
template: customJsxTemplateSchema,
})
.superRefine((definition, ctx) => {
for (const issue of validateCustomWidgetOptions(definition.optionsSchema, definition.defaultOptions)) {
ctx.addIssue({
code: "custom",
path: ["defaultOptions", ...issue.path.split(".").slice(1)],
message: issue.message,
});
}
const sourceIds = validateSourceIds(definition.sources, ctx);
validateDefaultState(definition.stateSchema ?? {}, definition.defaultState ?? {}, ctx);
const requests = validateRequests(definition, sourceIds, ctx);
validateDynamicOptions(definition.optionsSchema, requests, ctx);
validateTemplateRequests(definition.template, requests, ctx);
validateTemplateStateBindings(definition.template, definition.stateSchema ?? {}, ctx);
validateCredentialFreeExport(definition, ctx);
validatePrototypeKeys(definition, ctx);
});
type Definition = z.infer<typeof customWidgetDefinitionSchema>;
function validateSourceIds(sources: Definition["sources"], ctx: z.RefinementCtx) {
const ids = new Set<string>();
sources.forEach((source, index) => {
if (ids.has(source.id))
ctx.addIssue({ code: "custom", path: ["sources", index, "id"], message: `Duplicate source ID: ${source.id}` });
ids.add(source.id);
});
return ids;
}
function validateDynamicOptions(
schema: unknown,
requests: Map<string, CustomJsxRequest>,
ctx: z.RefinementCtx,
path: Array<string | number> = ["optionsSchema"],
) {
if (schema === null || typeof schema !== "object" || Array.isArray(schema)) return;
const node = schema as Record<string, unknown>;
const presentation = node["x-homarr"];
if (presentation !== null && typeof presentation === "object" && !Array.isArray(presentation)) {
const source = (presentation as Record<string, unknown>).optionsSource;
if (source !== null && typeof source === "object" && !Array.isArray(source)) {
const requestId = (source as Record<string, unknown>).requestId;
const request = typeof requestId === "string" ? requests.get(requestId) : undefined;
if (!request || request.kind !== "query") {
ctx.addIssue({
code: "custom",
path: [...path, "x-homarr", "optionsSource", "requestId"],
message: `Dynamic options require a query request named '${String(requestId)}'`,
});
}
}
}
if (node.properties !== null && typeof node.properties === "object" && !Array.isArray(node.properties)) {
for (const [key, child] of Object.entries(node.properties))
validateDynamicOptions(child, requests, ctx, [...path, "properties", key]);
}
if (node.items !== undefined) validateDynamicOptions(node.items, requests, ctx, [...path, "items"]);
for (const branch of ["if", "then", "else"] as const) {
if (node[branch] !== undefined) validateDynamicOptions(node[branch], requests, ctx, [...path, branch]);
}
}
function validateDefaultState(
schema: NonNullable<Definition["stateSchema"]>,
state: NonNullable<Definition["defaultState"]>,
ctx: z.RefinementCtx,
) {
for (const [key, value] of Object.entries(state)) {
const type = schema[key];
if (!type) ctx.addIssue({ code: "custom", path: ["defaultState", key], message: `Unknown state key: ${key}` });
else if (!matchesStateType(type, value)) {
ctx.addIssue({ code: "custom", path: ["defaultState", key], message: `Expected ${type}` });
}
}
}
function matchesStateType(type: CustomWidgetStateSchema[string], value: unknown) {
if (type === "date") return typeof value === "string";
if (type === "string[]" || type === "date[]")
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
if (type === "number[]") return Array.isArray(value) && value.every((entry) => typeof entry === "number");
return typeof value === type;
}
function validateRequests(definition: Definition, sourceIds: Set<string>, ctx: z.RefinementCtx) {
const requests = new Map<string, CustomJsxRequest>();
definition.requests.forEach((request, index) => {
if (requests.has(request.id))
ctx.addIssue({ code: "custom", path: ["requests", index, "id"], message: `Duplicate request ID: ${request.id}` });
if (!sourceIds.has(request.sourceId)) {
ctx.addIssue({
code: "custom",
path: ["requests", index, "sourceId"],
message: `Unknown source ID: ${request.sourceId}`,
});
}
const source = definition.sources.find((candidate) => candidate.id === request.sourceId);
if (source?.auth.type === "apiKeyHeader" && request.auth === "inherit") {
const authHeader = source.auth.headerName.toLowerCase();
if (Object.keys(request.staticHeaders ?? {}).some((header) => header.toLowerCase() === authHeader)) {
ctx.addIssue({
code: "custom",
path: ["requests", index, "staticHeaders"],
message: "Static headers cannot override the source authentication header",
});
}
}
if (source?.auth.type === "apiKeyQuery" && request.auth === "inherit") {
const authParameter = source.auth.parameterName.toLowerCase();
if (Object.keys(request.queryTemplate ?? {}).some((parameter) => parameter.toLowerCase() === authParameter)) {
ctx.addIssue({
code: "custom",
path: ["requests", index, "queryTemplate"],
message: "Query templates cannot override the source authentication parameter",
});
}
}
requests.set(request.id, request);
});
definition.requests.forEach((request, index) => {
request.invalidates?.forEach((requestId, invalidationIndex) => {
const target = requests.get(requestId);
if (!target || target.kind !== "query") {
ctx.addIssue({
code: "custom",
path: ["requests", index, "invalidates", invalidationIndex],
message: `Invalidation target '${requestId}' must be a query request`,
});
}
});
});
return requests;
}
function validateTemplateRequests(template: string, requests: Map<string, CustomJsxRequest>, ctx: z.RefinementCtx) {
for (const match of template.matchAll(/<(SubFetch|ActionButton|ToggleSwitch)\b([^>]*)>/g)) {
const component = match[1] as "SubFetch" | "ActionButton" | "ToggleSwitch";
const idMatch = (match[2] ?? "").match(/\brequestId\s*=\s*(?:"([^"]+)"|'([^']+)')/);
const requestId = idMatch?.[1] ?? idMatch?.[2];
if (!requestId) {
ctx.addIssue({ code: "custom", path: ["template"], message: `${component} must use a literal requestId` });
continue;
}
const request = requests.get(requestId);
const expectedKind = component === "SubFetch" ? "query" : "action";
if (!request)
ctx.addIssue({
code: "custom",
path: ["template"],
message: `${component} references unknown request '${requestId}'`,
});
else if (request.kind !== expectedKind) {
ctx.addIssue({
code: "custom",
path: ["template"],
message: `${component} requires a ${expectedKind} request, but '${requestId}' is ${request.kind}`,
});
}
}
}
function validateTemplateStateBindings(template: string, stateSchema: CustomWidgetStateSchema, ctx: z.RefinementCtx) {
for (const match of template.matchAll(/<[A-Z][A-Za-z0-9.]*(?:\s[^<>]*?)?\bbind\s*=\s*(?:"([^"]+)"|'([^']+)'|\{)/gu)) {
const stateName = match[1] ?? match[2];
if (!stateName) {
ctx.addIssue({ code: "custom", path: ["template"], message: "bind must use a literal state name" });
} else if (!Object.hasOwn(stateSchema, stateName)) {
ctx.addIssue({ code: "custom", path: ["template"], message: `bind references unknown state '${stateName}'` });
}
}
}
export type HomarrCustomWidgetV2 = z.infer<typeof customWidgetDefinitionSchema>;
export const customWidgetCreateSchema = customWidgetDefinitionSchema.safeExtend({
secrets: customWidgetSecretsInputSchema.default([]),
});
export const customWidgetUpdateSchema = z
.object(customWidgetDefinitionSchema.shape)
.partial()
.extend({
id: z.string().min(1),
secrets: customWidgetSecretsInputSchema.optional(),
});
export const customWidgetImportSchema = customWidgetDefinitionSchema;
export type CustomWidgetCreateInput = z.infer<typeof customWidgetCreateSchema>;
export type CustomWidgetUpdateInput = z.infer<typeof customWidgetUpdateSchema>;
export type CustomWidgetImport = z.infer<typeof customWidgetImportSchema>;
export const customWidgetAuthTypeSchema = z.enum(customWidgetAuthTypes);