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

+115 -148
View File
@@ -1,168 +1,135 @@
import { customJsxExamples } from "./examples";
import { enabledCustomJsxComponents } from "./component-registry";
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
const PROMPT_HEADER = `You are configuring a Homarr custom widget. Ask a concise clarifying question only when the requested behavior is ambiguous.
export const CUSTOM_WIDGET_MANTINE_VERSION = "9.4.1";
For Custom JSX, return a Homarr authoring bundle with exactly two fenced code blocks:
1. A \`json\` block containing the complete import object. Set \`displayConfig.template\` to \`"__HOMARR_TEMPLATE__"\`.
2. A \`jsx\` block containing the readable, multiline template with no JSON escaping.
const AUTHORING_PROMPT = `You create Homarr Custom JSX v2 widgets. Return exactly two fenced blocks: a json block containing one complete widget object with template set to "__HOMARR_TEMPLATE__", then a jsx block containing the readable template.
The user can paste both blocks together into Homarr. Homarr combines and validates them before import. For non-Custom-JSX display types, return only the complete JSON block.
Use $schema "homarr-custom-widget-v2". A widget contains metadata, inline API sources, named requests, an options schema, defaults, optional local state, and one JSX template. Never include credentials. Use one source named "default" unless the widget genuinely combines APIs.
## Rules
- Use \`"$schema": "homarr-custom-widget-v3"\`.
- \`displayType\` and \`displayConfig.type\` must match.
- Prefer \`customJsx\` with \`jsxApiVersion: 2\` for custom layouts.
- The base widget request must use GET. Mutations belong in named action requests.
- JSX cannot call \`fetch\` or use event handlers. Use SubFetch, ActionButton, ToggleSwitch, and RefreshButton.
- Version 2 network components reference a literal \`requestId\` and pass only declared \`params\`.
- SubFetch can reference query requests only. ActionButton and ToggleSwitch can reference action requests only.
- Prefer the SubFetch function-as-children API for fetched data. The callback receives \`(response, metadata)\` and may return any safe JSX tree. Use SubData only for very small path-based displays.
- SubFetch owns loading, failure, retry, cancellation, and stale-response handling. The render callback runs only when response data is available.
- Named request paths are same-origin paths beginning with \`/\`. Do not put credentials in a template or export.
- Query requests use GET and view permission. POST, PUT, and PATCH actions default to modify. DELETE requires full permission and confirmation.
- Use only components in the generated component reference below.
- Template output must fit inside a dashboard widget and remain usable at narrow widths.
- Return the complete import object, not a template fragment. Preserve unrelated fields from the current configuration.
- Include stable keys for rendered collections, accessible labels for controls and images, useful empty states, and concise content that works in light and dark themes.
- Prefer one clear information hierarchy over nested cards. Use ActionButton and ToggleSwitch only when the named action and required permission are declared.
This Homarr release uses Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}. When connected, read homarr://custom-widgets/schema and homarr://custom-widgets/components instead of guessing the installed surface.
## Named request shape
\`\`\`ts
interface CustomJsxRequest {
id: string;
kind: "query" | "action";
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
pathTemplate: \`/\${string}\`;
parameters: Record<string, "string" | "number" | "boolean">;
bodyTemplate?: unknown;
staticHeaders?: Record<string, string>;
auth: "inherit" | "none";
minimumBoardPermission: "view" | "modify" | "full";
cacheTtlSeconds?: number;
}
\`\`\`
Queries and actions may use GET, POST, PUT, PATCH, or DELETE. Set kind to query for reads and action for user-triggered changes. Actions never use trigger "load". Declare every path, query, or body parameter. Use {name} in paths and {"$param":"name"} in query/body templates. Use SubFetch for manual queries, ActionButton or ToggleSwitch for actions, and load-triggered queries through data.<requestId>.
Path parameters use \`{name}\`. JSON body parameters use \`{ "$param": "name" }\` and preserve the declared type.
Source authentication is exactly one of {"type":"none"}, {"type":"bearer"}, {"type":"basic"}, {"type":"apiKeyHeader","headerName":"X-API-Key"}, or {"type":"apiKeyQuery","parameterName":"api_key"}. Credentials are configured separately by the user.
## SubFetch rendering
Use a render child when a named query needs its own layout:
Templates can read data, status, options, and state. Bind supported Mantine controls with bind="stateName" instead of event handlers. Use Mantine Core, Dates, and Charts components. Do not use imports, hooks, refs, event callbacks, component/renderRoot, arbitrary portals, raw HTML, fetch, eval, npm packages, or credentials. Design for compact and wide dashboard sizes with useful loading, empty, and error states.
\`\`\`jsx
<SubFetch requestId="service-detail" params={{ id: data.serviceId }}>
{(detail, meta) =>
<Stack gap="xs">
<Group justify="space-between">
<Text fw={700}>{detail.name}</Text>
<Badge color={meta.ok ? "green" : "red"}>HTTP {meta.status}</Badge>
</Group>
{detail.metrics.map((metric) =>
<Group key={metric.name} justify="space-between">
<Text size="sm">{metric.name}</Text>
<Text fw={600}>{metric.value}</Text>
</Group>
)}
</Stack>
}
</SubFetch>
\`\`\`
Options use a restricted object JSON Schema. x-homarr controls include text, textarea, number, switch, select, multi-select, slider, date, time, color, icon, url, duration, timeZone, and json. Dynamic selects use x-homarr.optionsSource with requestId, optional itemsPath for wrapped arrays, valuePath, and labelPath. Local state types are string, number, boolean, date, string[], number[], or date[].
The callback is an interpreter-managed inline arrow function. Do not use native callbacks, event handlers, global state, or direct network access. Keep list keys stable and design for narrow and wide widget sizes.
`;
Widget shape:
{ "$schema":"homarr-custom-widget-v2", "name":"...", "description":"...", "iconUrl":"https://...", "sources":[{ "id":"default", "name":"API", "baseUrl":"https://host", "networkScope":"public|private|loopback", "auth":{ "type":"none|bearer|basic|apiKeyHeader|apiKeyQuery" } }], "requests":[{ "id":"data", "sourceId":"default", "kind":"query|action", "method":"GET|POST|PUT|PATCH|DELETE", "pathTemplate":"/api/path", "parameters":{}, "queryTemplate":{}, "bodyTemplate":{}, "auth":"inherit|none", "minimumBoardPermission":"view|modify|full", "trigger":"load|manual", "confirmation":{ "title":"...", "message":"...", "destructive":false }, "invalidates":[] }], "optionsSchema":{ "type":"object", "properties":{}, "additionalProperties":false }, "defaultOptions":{}, "stateSchema":{}, "defaultState":{}, "template":"__HOMARR_TEMPLATE__" }
const PROMPT_NO_RESPONSE = `No sample response is available. Leave this marker in your reasoning and ask the user for a representative response if its shape is required:
Keep the result concise, accessible, responsive, and valid. Preserve unrelated fields when fixing an existing widget.`;
\`\`\`json
PASTE_API_RESPONSE_HERE
\`\`\`
`;
export const CUSTOM_WIDGET_AUTHORING_PROMPT = AUTHORING_PROMPT;
function buildComponentReference() {
const categories = new Map<string, string[]>();
for (const component of enabledCustomJsxComponents) {
const names = categories.get(component.category) ?? [];
names.push(component.name);
categories.set(component.category, names);
}
export const CUSTOM_WIDGET_MCP_AUTHORING_PROMPT = `Author one Homarr Custom JSX v2 widget at a time. Repeat this workflow independently when the user asks for several widgets.
return [...categories.entries()].map(([category, names]) => `- ${category}: ${names.join(", ")}`).join("\n");
}
1. Read homarr://custom-widgets/schema, homarr://custom-widgets/components, and homarr://custom-widgets/skill.
2. Read the external API documentation and construct one credential-free homarr-custom-widget-v2 document.
3. Call customWidget_validate before saving, then customWidget_previewCreate.
4. Test queries with customWidget_previewQuery and actions with customWidget_previewAction. Actions are simulated until the user explicitly enables live preview actions.
5. Open the preview URL, inspect customWidget_previewJournal, and iterate with customWidget_templatePatch or another preview session.
6. Use customWidget_secretSet only for a credential the user supplied and only with dedicated permission. Otherwise call customWidget_secretRequestUser and poll its completion status; never receive or repeat the plaintext.
7. Call customWidget_create only after validation, request tests, action simulation, and visual inspection pass.
function buildExamples() {
return customJsxExamples
.map(
(example) => `### ${example.title}
${example.description}
\`\`\`json
${JSON.stringify(
{
displayType: "customJsx",
displayConfig: {
type: "customJsx",
jsxApiVersion: 2,
networkScope: "public",
template: "__HOMARR_TEMPLATE__",
requests: example.requests,
},
},
null,
2,
)}
\`\`\`
\`\`\`jsx
${example.template}
\`\`\``,
)
.join("\n\n");
Use inline sources, named queries/actions, restricted JSON Schema options, session-local typed state, declarative bind controls, and safe Mantine JSX. Use kind, not method, to distinguish reads from user-triggered changes. Never include credentials, imports, hooks, refs, callbacks, browser requests, arbitrary JavaScript, npm packages, polymorphic roots, or arbitrary portals. Make the widget responsive, accessible, loading-aware, empty-aware, and error-aware. The live schema and component resources are authoritative for the installed Homarr release.`;
export function buildCustomWidgetMcpPrompt(request?: string | null, documentationUrl?: string | null) {
const sections = [CUSTOM_WIDGET_MCP_AUTHORING_PROMPT];
if (documentationUrl) sections.push(`API documentation: ${redactUrl(documentationUrl)}`);
if (request?.trim()) sections.push(`User request: ${redactText(request.trim())}`);
return sections.join("\n\n");
}
export function buildCustomWidgetAiPrompt(
jsonSchema: unknown,
_jsonSchema?: unknown,
rawResponse?: string | null,
currentConfig?: Record<string, unknown> | null,
currentConfig?: Partial<HomarrCustomWidgetV2> | Record<string, unknown> | null,
request?: string | null,
documentationUrl?: string | null,
) {
const responseSection = rawResponse
? `## API response\n\n\`\`\`json\n${rawResponse}\n\`\`\`\n`
: `## API response\n\n${PROMPT_NO_RESPONSE}`;
const currentDisplayConfig = currentConfig?.displayConfig;
const currentTemplate =
currentDisplayConfig && typeof currentDisplayConfig === "object" && "template" in currentDisplayConfig
? currentDisplayConfig.template
: null;
const readableCurrentConfig = currentConfig
? {
...currentConfig,
...(currentTemplate && typeof currentTemplate === "string"
? {
displayConfig: {
...(currentDisplayConfig as Record<string, unknown>),
template: "__HOMARR_TEMPLATE__",
},
}
: {}),
}
: null;
const configSection = readableCurrentConfig
? `## Current configuration\n\nUse this as the starting point and preserve unrelated settings.\n\n\`\`\`json\n${JSON.stringify(readableCurrentConfig, null, 2)}\n\`\`\`\n${typeof currentTemplate === "string" ? `\n\`\`\`jsx\n${currentTemplate}\n\`\`\`\n` : ""}`
: "";
return `${PROMPT_HEADER}
## Import schema
The \`__HOMARR_TEMPLATE__\` value is an authoring transport placeholder. Homarr replaces it with the following JSX block before schema and AST validation.
\`\`\`json
${JSON.stringify(jsonSchema, null, 2)}
\`\`\`
## Generated component reference
${buildComponentReference()}
## Tested examples
${buildExamples()}
${responseSection}
${configSection}
## Requested widget
Describe what the widget should show and which interactions it needs:
`;
const sections = [AUTHORING_PROMPT];
if (documentationUrl) sections.push(`API documentation: ${redactUrl(documentationUrl)}`);
sections.push(`Requested widget: ${redactText(request?.trim() || "Describe the widget you want to create.")}`);
if (rawResponse) sections.push(`Sample API response:\n\n\`\`\`json\n${redactResponse(rawResponse)}\n\`\`\``);
if (currentConfig) {
sections.push(`Current widget:\n\n\`\`\`json\n${JSON.stringify(redactValue(currentConfig), null, 2)}\n\`\`\``);
}
return sections.join("\n\n").slice(0, 8_000);
}
export function buildCustomWidgetFixPrompt(input: {
currentConfig: Partial<HomarrCustomWidgetV2> | Record<string, unknown>;
request?: string | null;
documentationUrl?: string | null;
diagnostics: string;
journal: unknown;
}) {
const sections = [AUTHORING_PROMPT];
if (input.documentationUrl) sections.push(`API documentation: ${redactUrl(input.documentationUrl)}`);
sections.push(`Original request: ${redactText(input.request?.trim() || "Fix the current widget.")}`);
sections.push(`Current widget:\n\n\`\`\`json\n${JSON.stringify(redactValue(input.currentConfig), null, 2)}\n\`\`\``);
sections.push(
`Validation diagnostics:\n\n\`\`\`text\n${redactText(input.diagnostics) || "No static diagnostics."}\n\`\`\``,
);
sections.push(
`Redacted request journal:\n\n\`\`\`json\n${JSON.stringify(redactValue(input.journal), null, 2)}\n\`\`\``,
);
return sections.join("\n\n");
}
const sensitiveKey =
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
function redactValue(value: unknown, key = ""): unknown {
if (sensitiveKey.test(key)) return "[REDACTED]";
if (Array.isArray(value)) return value.map((entry) => redactValue(entry));
if (value !== null && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([entryKey, entry]) => [entryKey, redactValue(entry, entryKey)]),
);
}
if (typeof value === "string") {
if (["sources", "requests", "optionsSchema", "defaultOptions", "stateSchema", "defaultState"].includes(key)) {
try {
return redactValue(JSON.parse(value) as unknown);
} catch {
// Keep invalid editor JSON useful while applying the text redactor below.
}
}
return key === "baseUrl" || key === "iconUrl" ? redactUrl(value) : redactText(value);
}
return value;
}
function redactResponse(value: string) {
try {
return JSON.stringify(redactValue(JSON.parse(value) as unknown), null, 2);
} catch {
return "[REDACTED_URL]";
}
}
function redactUrl(value: string): string {
try {
const url = new URL(value);
url.username = "";
url.password = "";
url.search = "";
url.hash = "";
return url.toString();
} catch {
return "[REDACTED_URL]";
}
}
function redactText(value: string): string {
return value
.replace(/\bhttps?:\/\/[^\s"'<>]+/giu, (candidate) => redactUrl(candidate))
.replace(/\b(authorization\s*:\s*bearer)\s+[^\s,;]+/giu, "$1 [REDACTED]")
.replace(
/\b(api[ _-]?key|access[ _-]?token|refresh[ _-]?token|client[ _-]?secret|token|password|passwd|secret)["']?\s*[:=]\s*["']?[^\s,;"'}]+/giu,
"$1: [REDACTED]",
);
}
@@ -0,0 +1,94 @@
import {
customJsxBindableComponentNames,
customJsxComponentByName,
enabledCustomJsxComponents,
} from "./component-registry";
import { customJsxExamples } from "./examples";
import { customJsxTablerIconNames } from "./tabler-icons";
export const CUSTOM_WIDGET_SKILL_VERSION = "2.0.0";
export const CUSTOM_WIDGET_SKILL_DOWNLOAD_URL = "https://homarr.dev/downloads/homarr-custom-widget-2.0.0.zip";
export const CUSTOM_WIDGET_SKILL_SHA256 = "5571b74b2faafe8a9e230231c1915193e889c7afa95acef38a1f70befe14a9e1";
export const CUSTOM_WIDGET_SKILL_MD = `---
name: homarr-custom-widget
description: Author, validate, preview, and install safe Homarr Custom JSX v2 widgets from API documentation. Use when creating or fixing Homarr custom widgets, including multi-source dashboards, queries, actions, options, local state, and Mantine JSX.
license: Apache-2.0
metadata:
version: "2.0.0"
---
# Homarr Custom Widget
Create one widget at a time. Repeat the workflow when the user asks for several widgets; do not invent packs or shared connections.
## Connected workflow
1. Get \`homarr-custom-widget-author\`, then read \`homarr://custom-widgets/schema\` and \`homarr://custom-widgets/components\`.
2. Read the API documentation supplied by the user. Ask for missing base URLs and credentials only when needed.
3. Build one \`homarr-custom-widget-v2\` document. Keep credentials outside the document.
4. Call \`customWidget_validate\`, fix every error, and treat advisory Mantine prop warnings as review items.
5. Call \`customWidget_previewCreate\`, then test load/manual queries with \`customWidget_previewQuery\` and actions with \`customWidget_previewAction\`.
6. If credentials are missing, call \`customWidget_secretRequestUser\`. Use \`customWidget_secretSet\` only when the user already supplied a credential and the tool is authorized.
7. Inspect the preview URL and \`customWidget_previewJournal\`. Patch JSX with \`customWidget_templatePatch\` or update the draft and repeat.
8. Call \`customWidget_create\` only after validation and preview pass. Continue with the next widget independently.
## Output rules
- Use inline sources, named requests, definition-owned options, session-local state, and one safe JSX template.
- Use \`kind\`, not the HTTP method, to distinguish reads from user-triggered actions.
- Never put a credential in JSX, options, headers, URLs, examples, exports, logs, or chat output.
- Use declarative \`bind\` controls and Homarr request components; never emit imports, hooks, callbacks, browser requests, or arbitrary JavaScript.
- Include responsive loading, empty, error, and success states.
- Keep actions explicit, permission-scoped, confirmed when destructive, and followed by targeted invalidation.
Read [references/schema.md](references/schema.md), [references/runtime.md](references/runtime.md), and [references/security.md](references/security.md) before offline authoring. When connected, prefer live resources because installed Mantine components can differ by Homarr release.
`;
export function getCustomWidgetSkill() {
return {
name: "homarr-custom-widget",
version: CUSTOM_WIDGET_SKILL_VERSION,
skillMd: CUSTOM_WIDGET_SKILL_MD,
downloadUrl: CUSTOM_WIDGET_SKILL_DOWNLOAD_URL,
sha256: CUSTOM_WIDGET_SKILL_SHA256,
};
}
export function getCustomWidgetComponentCatalog() {
return enabledCustomJsxComponents.map(({ name, package: packageName, category, supportedProps, subcomponents }) => ({
name,
package: packageName,
category,
propCount: supportedProps.filter((prop) => prop !== "bind").length,
bindSupported: customJsxBindableComponentNames.has(name),
subcomponents,
detailUri: `homarr://custom-widgets/components/${encodeURIComponent(name)}`,
}));
}
export function getCustomWidgetComponent(name: string) {
const component = customJsxComponentByName.get(name);
if (!component) return null;
return {
name: component.name,
package: component.package,
category: component.category,
safety: component.safety,
knownProps: component.supportedProps.filter((prop) => prop !== "bind"),
bindSupported: customJsxBindableComponentNames.has(component.name),
subcomponents: component.subcomponents,
accessibilityRequirements: component.accessibilityRequirements,
documentationUrl: component.documentationUrl,
knownValues: component.name === "TablerIcon" ? { name: customJsxTablerIconNames } : undefined,
deniedReason: component.safety === "denied" ? component.reason : undefined,
propPolicy:
component.safety === "denied"
? "This component is blocked."
: "Ordinary serializable Mantine props pass through. Unsafe capabilities, callbacks, polymorphic roots, and escaping styles are blocked.",
};
}
export function getCustomWidgetExample(name: string) {
return customJsxExamples.find((example) => example.id === name) ?? null;
}
@@ -1,235 +0,0 @@
import { z } from "zod/v4";
export const singleValueDisplayConfigSchema = z.object({
type: z
.literal("singleValue")
.describe("Display type discriminator — must be 'singleValue' when displayType is singleValue"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract the value from the API response (e.g. $.data.count, $.items[0].name, $.status). Use $ for the root object.",
),
label: z
.string()
.describe("Human-readable label shown alongside the extracted value (e.g. 'CPU Temperature', 'Total Users')"),
unit: z
.string()
.describe("Unit suffix displayed after the value (e.g. '°C', '%', 'GB'). Leave empty string if no unit is needed."),
valueSize: z
.enum(["sm", "md", "lg", "xl"])
.optional()
.describe(
"Font size of the displayed value: 'sm' (small), 'md' (medium), 'lg' (large, default), 'xl' (extra large)",
),
labelPosition: z
.enum(["above", "below"])
.optional()
.describe("Position of the label relative to the value: 'above' or 'below' (default: below)"),
});
const keyValueMappingSchema = z.object({
label: z.string().min(1).describe("Label for this key-value pair (e.g. 'CPU', 'Memory', 'Uptime')"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract this value from the API response (e.g. $.cpu.percent, $.memory.used). Use $ for the root object.",
),
unit: z
.string()
.describe("Unit suffix for this value (e.g. '%', 'GB', 'ms'). Leave empty string if no unit is needed."),
});
export const keyValueDisplayConfigSchema = z.object({
type: z.literal("keyValue").describe("Display type discriminator — must be 'keyValue' when displayType is keyValue"),
mappings: z
.array(keyValueMappingSchema)
.min(1)
.describe("Array of label/jsonPath/unit mappings — each entry becomes one labeled value in the widget"),
layout: z
.enum(["list", "grid"])
.optional()
.describe("Layout style: 'list' (vertical stack, default) or 'grid' (multi-column grid)"),
columns: z
.number()
.int()
.min(1)
.max(3)
.optional()
.describe("Number of columns when layout is 'grid' (1–3, default: 2)"),
});
const tableColumnSchema = z.object({
header: z.string().min(1).describe("Column header text shown in the table (e.g. 'Name', 'Status', 'Size')"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression relative to each row object to extract the cell value (e.g. $.name, $.status, $.size). Do not include the array path here — that goes in tablePath.",
),
});
export const tableDisplayConfigSchema = z.object({
type: z.literal("table").describe("Display type discriminator — must be 'table' when displayType is table"),
tablePath: z
.string()
.min(1)
.describe(
"JSONPath expression to the array of row objects in the API response (e.g. $.data.items, $.results, $.users[*])",
),
columns: z
.array(tableColumnSchema)
.min(1)
.describe("Column definitions — each column has a header and a jsonPath relative to each row"),
striped: z
.boolean()
.optional()
.describe("Whether to alternate row background colors for readability (default: true)"),
compact: z.boolean().optional().describe("Whether to use compact row spacing (default: false)"),
});
const statGridItemSchema = z.object({
label: z.string().min(1).describe("Label for this stat card (e.g. 'Movies', 'Series', 'Episodes')"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract the stat value from the API response (e.g. $.library.movies, $.counts.series)",
),
unit: z.string().describe("Unit suffix for the stat (e.g. '', 'GB', '%'). Leave empty string if no unit is needed."),
color: z
.string()
.optional()
.describe("Mantine color name for the stat card (e.g. 'blue', 'green', 'red', 'orange', 'violet'). Default: blue"),
});
export const statGridDisplayConfigSchema = z.object({
type: z.literal("statGrid").describe("Display type discriminator — must be 'statGrid' when displayType is statGrid"),
items: z
.array(statGridItemSchema)
.min(1)
.describe("Array of stat cards — each item shows a labeled value in a colored card"),
columns: z.number().int().min(1).max(4).optional().describe("Number of columns in the stat grid (1–4, default: 2)"),
cardStyle: z
.enum(["filled", "outline", "subtle"])
.optional()
.describe(
"Visual style of stat cards: 'filled' (solid background, default), 'outline' (border only), 'subtle' (light tint)",
),
});
const progressBarItemSchema = z.object({
label: z.string().min(1).describe("Label for this progress bar (e.g. 'Disk Usage', 'Memory', 'Quota')"),
valuePath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract the current value (numerator) from the API response (e.g. $.disk.used, $.memory.used_bytes)",
),
maxPath: z
.string()
.optional()
.describe(
"JSONPath expression to extract the maximum value (denominator). If omitted, defaults to 100. Use for ratios like used/total (e.g. $.disk.total)",
),
unit: z
.string()
.describe("Unit suffix shown alongside values (e.g. 'GB', 'MB', '%'). Leave empty string if no unit is needed."),
color: z
.string()
.optional()
.describe("Mantine color name for the progress bar fill (e.g. 'blue', 'green', 'red'). Default: blue"),
});
export const progressBarsDisplayConfigSchema = z.object({
type: z
.literal("progressBars")
.describe("Display type discriminator — must be 'progressBars' when displayType is progressBars"),
bars: z
.array(progressBarItemSchema)
.min(1)
.describe("Array of progress bar definitions — each bar shows value/max as a visual progress indicator"),
showPercentage: z.boolean().optional().describe("Whether to display the percentage next to each bar (default: true)"),
barSize: z
.enum(["sm", "md", "lg"])
.optional()
.describe("Height of progress bars: 'sm' (small), 'md' (medium, default), 'lg' (large)"),
});
const statusIndicatorItemSchema = z.object({
label: z.string().min(1).describe("Label for this status indicator (e.g. 'Web Server', 'Database', 'API')"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract the status value from the API response (e.g. $.services.web.status, $.health.database)",
),
goodValues: z
.array(z.string())
.min(1)
.describe(
"Array of string values considered 'healthy/good' — case-insensitive match (e.g. ['online', 'up', 'true', 'healthy', 'ok'])",
),
});
export const statusIndicatorDisplayConfigSchema = z.object({
type: z
.literal("statusIndicator")
.describe("Display type discriminator — must be 'statusIndicator' when displayType is statusIndicator"),
items: z
.array(statusIndicatorItemSchema)
.min(1)
.describe("Array of status indicators — each shows a green dot if the value matches goodValues, red otherwise"),
layout: z
.enum(["list", "grid"])
.optional()
.describe("Layout style: 'list' (vertical, default) or 'grid' (multi-column)"),
dotSize: z
.enum(["sm", "md", "lg"])
.optional()
.describe("Size of status dots: 'sm' (small), 'md' (medium, default), 'lg' (large)"),
});
const countGridItemSchema = z.object({
label: z.string().min(1).describe("Label for this count (e.g. 'Movies', 'Shows', 'Albums')"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract the count value from the API response (e.g. $.counts.movies, $.stats.total)",
),
unit: z.string().describe("Unit suffix for the count (e.g. '', 'items'). Leave empty string if no unit is needed."),
});
export const countGridDisplayConfigSchema = z.object({
type: z
.literal("countGrid")
.describe("Display type discriminator — must be 'countGrid' when displayType is countGrid"),
items: z
.array(countGridItemSchema)
.min(1)
.describe("Array of count items — each shows a number with a label in a simple grid (no colors)"),
columns: z.number().int().min(2).max(4).optional().describe("Number of columns in the count grid (2–4, default: 2)"),
valueSize: z
.enum(["sm", "md", "lg"])
.optional()
.describe("Font size of count values: 'sm' (small), 'md' (medium, default), 'lg' (large)"),
});
export const rawDisplayConfigSchema = z.object({
type: z.literal("raw").describe("Display type discriminator — must be 'raw' when displayType is raw"),
jsonPath: z
.string()
.min(1)
.describe(
"JSONPath expression to extract the data to display (e.g. $ for entire response, $.data, $.result). The extracted value is pretty-printed as JSON.",
),
maxHeight: z
.number()
.int()
.min(50)
.max(1000)
.optional()
.describe("Maximum height of the raw JSON display area in pixels (50–1000, default: 300)"),
});
@@ -0,0 +1,92 @@
import * as Charts from "@mantine/charts";
import * as Core from "@mantine/core";
import * as Dates from "@mantine/dates";
import { subcomponentsByName } from "./component-descriptor";
import type { CustomJsxComponentCategory, CustomJsxComponentPackage } from "./component-types";
type Namespace = Readonly<Record<string, unknown>>;
const packageDefinitions: ReadonlyArray<{
package: CustomJsxComponentPackage;
namespace: Namespace;
}> = [
{ package: "@mantine/core", namespace: Core as Namespace },
{ package: "@mantine/dates", namespace: Dates as Namespace },
{ package: "@mantine/charts", namespace: Charts as Namespace },
];
function looksLikePublicComponent(name: string, value: unknown) {
if (!/^[A-Z][A-Za-z0-9]*$/u.test(name) || !/[a-z]/u.test(name)) return false;
if (typeof value === "function") return true;
if (value === null || typeof value !== "object") return false;
const reactType = (value as { $$typeof?: unknown }).$$typeof;
return reactType === Symbol.for("react.forward_ref") || reactType === Symbol.for("react.memo");
}
function inferCoreCategory(name: string): CustomJsxComponentCategory {
if (
/^(?:Alert|Loader|LoadingOverlay|Notification|Overlay|Progress|RingProgress|SemiCircleProgress|Skeleton)/u.test(
name,
)
) {
return "feedback";
}
if (
/^(?:Accordion|Anchor|Breadcrumbs|Collapse|HoverCard|Menu|NavLink|Popover|Spoiler|Stepper|Tabs|Tooltip|Transition|Tree)/u.test(
name,
)
) {
return "navigation";
}
if (
/(?:Button|Checkbox|Chip|Input|Pagination|Picker|Radio|Rating|Select|Slider|Switch)$/u.test(name) ||
/^(?:ActionIcon|Autocomplete|Burger|CloseButton|CopyButton|MultiSelect|NumberInput|PasswordInput|PinInput|SegmentedControl|TagsInput|TextInput|Textarea)/u.test(
name,
)
) {
return "interaction";
}
if (
/^(?:AspectRatio|Box|Card|Center|Container|Divider|Fieldset|Flex|FloatingIndicator|Grid|Group|Paper|ScrollArea|SimpleGrid|Space|Splitter|Stack|Typography)/u.test(
name,
)
) {
return "layout";
}
return "content";
}
export interface DiscoveredMantineComponent {
name: string;
package: CustomJsxComponentPackage;
category: CustomJsxComponentCategory;
}
export const discoveredSubcomponentsByName: Readonly<Record<string, readonly string[]>> = {};
export const discoveredMantineComponents: readonly DiscoveredMantineComponent[] = packageDefinitions.flatMap(
({ package: packageName, namespace }) =>
Object.entries(namespace).flatMap(([name, value]) => {
if (!looksLikePublicComponent(name, value)) return [];
const category =
packageName === "@mantine/charts"
? "charts"
: packageName === "@mantine/dates"
? "dates"
: inferCoreCategory(name);
const reflectedSubcomponents =
value && (typeof value === "object" || typeof value === "function")
? Object.entries(value).flatMap(([property, child]) =>
looksLikePublicComponent(property, child) ? [`${name}.${property}`] : [],
)
: [];
const subcomponents = [...new Set([...(subcomponentsByName[name] ?? []), ...reflectedSubcomponents])];
(discoveredSubcomponentsByName as Record<string, readonly string[]>)[name] = subcomponents;
return [name, ...subcomponents].map((componentName) => ({
name: componentName,
package: packageName,
category,
}));
}),
);
File diff suppressed because it is too large. Load diff
@@ -151,7 +151,6 @@ export const categorySafeProps: Record<CustomJsxComponentCategory, readonly stri
"withDots",
"gridAxis",
"unit",
"valueFormatter",
"strokeWidth",
"fillOpacity",
"connectNulls",
@@ -212,10 +211,8 @@ export const categorySafeProps: Record<CustomJsxComponentCategory, readonly stri
"successMessage",
"errorMessage",
"confirmMessage",
"invalidate",
"refreshInterval",
"trigger",
"render",
"path",
"as",
"fallback",
@@ -225,6 +222,7 @@ export const categorySafeProps: Record<CustomJsxComponentCategory, readonly stri
"size",
"radius",
"disabled",
"fullWidth",
],
blocked: [],
};
@@ -1,218 +1,62 @@
import { describe } from "./component-descriptor";
import { accessibilityByCategory, documentationUrl } from "./component-descriptor";
import type { CustomJsxComponentDescriptor } from "./component-descriptor";
import { discoveredMantineComponents } from "./component-discovery";
export const customJsxDeniedComponentRegistry: readonly CustomJsxComponentDescriptor[] = [
...describe(
"@mantine/core",
"blocked",
"denied",
[
"AppShell",
"Affix",
"ComboboxPopover",
"Dialog",
"Drawer",
"FloatingWindow",
"FocusTrap",
"Menubar",
"Modal",
"ModalBase",
"Portal",
"Popover",
"RemoveScroll",
],
"Escapes the widget layout or focus boundary",
),
...describe(
"@mantine/core",
"blocked",
"denied",
[
"AngleSlider",
"Autocomplete",
"Checkbox",
"ColorInput",
"ColorPicker",
"Combobox",
"FileButton",
"FileInput",
"Input",
"InputBase",
"JsonInput",
"MaskInput",
"MultiSelect",
"NativeSelect",
"NumberInput",
"PasswordInput",
"PillsInput",
"PinInput",
"Radio",
"Select",
"TagsInput",
"Textarea",
"TextInput",
"TreeSelect",
"UnstyledButton",
],
"Arbitrary form controls are not connected to the declarative action model",
),
...describe(
"@mantine/core",
"blocked",
"denied",
["OverflowList", "Scroller", "Splitter", "TableOfContents"],
"Requires callback, document, or layout capabilities that are not exposed to templates",
),
...describe(
"@mantine/core",
"blocked",
"denied",
[
"AccordionChevron",
"ActionIconGroup",
"ActionIconGroupSection",
"AlphaSlider",
"AppShellAside",
"AppShellFooter",
"AppShellHeader",
"AppShellMain",
"AppShellNavbar",
"AppShellSection",
"ButtonGroup",
"ButtonGroupSection",
"CheckIcon",
"CheckboxCard",
"CheckboxGroup",
"CheckboxIndicator",
"CloseIcon",
"ColorSchemeScript",
"ComboboxChevron",
"ComboboxClearButton",
"ComboboxDropdown",
"ComboboxDropdownTarget",
"ComboboxEmpty",
"ComboboxEventsTarget",
"ComboboxFooter",
"ComboboxGroup",
"ComboboxHeader",
"ComboboxHiddenInput",
"ComboboxOption",
"ComboboxOptions",
"ComboboxPopoverTarget",
"ComboboxSearch",
"ComboboxTarget",
"DirectionProvider",
"DrawerBody",
"DrawerCloseButton",
"DrawerContent",
"DrawerHeader",
"DrawerOverlay",
"DrawerRoot",
"DrawerStack",
"DrawerTitle",
"FlatTreeNode",
"FloatingArrow",
"FocusTrapInitialFocus",
"HeadlessMantineProvider",
"HoverCardGroup",
"HueSlider",
"InlineStyles",
"InputClearButton",
"InputClearSection",
"InputDescription",
"InputError",
"InputLabel",
"InputPlaceholder",
"InputSuccess",
"InputWrapper",
"MantineProvider",
"MantineThemeProvider",
"MenuCheckboxGroup",
"MenuCheckboxItem",
"MenuContextMenu",
"MenuRadioGroup",
"MenuRadioItem",
"MenuSearch",
"MenuSub",
"MenuSubDropdown",
"MenuSubItem",
"MenuSubTarget",
"MenubarDropdown",
"MenubarMenu",
"MenubarTarget",
"ModalBaseBody",
"ModalBaseCloseButton",
"ModalBaseContent",
"ModalBaseHeader",
"ModalBaseOverlay",
"ModalBaseTitle",
"ModalBody",
"ModalCloseButton",
"ModalContent",
"ModalHeader",
"ModalOverlay",
"ModalRoot",
"ModalStack",
"ModalTitle",
"NativeScrollArea",
"OptionalPortal",
"OptionsDropdown",
"PaginationControl",
"PaginationDots",
"PaginationFirst",
"PaginationItems",
"PaginationLabel",
"PaginationLast",
"PaginationNext",
"PaginationPrevious",
"PaginationRoot",
"PillGroup",
"PillsInputField",
"PopoverContextMenu",
"PopoverDropdown",
"PopoverTarget",
"ProgressLabel",
"ProgressRoot",
"RadioCard",
"RadioGroup",
"RadioIcon",
"RadioIndicator",
"RangeSlider",
"ScrollAreaAutosize",
"SplitterPane",
"StepperCompleted",
"SwitchGroup",
"TableScrollContainer",
"TooltipFloating",
"TooltipGroup",
"TreeSelectOption",
],
"Internal, provider, compound-control, form, portal, or document-level export outside the safe declarative surface",
),
...describe(
"@mantine/charts",
"blocked",
"denied",
["AreaGradient"],
"Low-level chart implementation helper that is not a standalone declarative display component",
),
...describe(
"@mantine/dates",
"blocked",
"denied",
[
"DatesProvider",
"HiddenDatesInput",
"TimeInput",
"TimePicker",
"PickerInputBase",
"DateInput",
"DateTimePicker",
"InlineDateTimePicker",
"YearPickerInput",
"MonthPickerInput",
"DatePickerInput",
],
"Input and provider components are outside the read-only template surface",
),
const exactReasons = new Map<string, string>([
["Affix", "Escapes the widget layout boundary"],
["ColorSchemeScript", "Writes global document state"],
["Dialog", "Escapes the widget layout and focus boundary"],
["FloatingWindow", "Creates a separate browser window"],
["InlineStyles", "Writes unscoped style rules"],
["RemoveScroll", "Changes global page scrolling"],
["Transition", "Requires an authored render callback"],
["AreaGradient", "Low-level chart implementation helper"],
["HiddenDatesInput", "Internal date-input primitive"],
["PickerInputBase", "Internal date-input primitive"],
]);
const familyReasons: ReadonlyArray<[RegExp, string]> = [
[
/^(?:AppShell|Drawer|FloatingWindow|Modal|RemoveScroll)/u,
"Escapes or replaces the widget layout, focus, scrolling, or overlay boundary",
],
[
/^(?:Combobox|Input|Menubar|OptionsDropdown|PillsInput)/u,
"Low-level composition primitive that requires authored callbacks",
],
[
/^(?:DatesProvider|DirectionProvider|HeadlessMantineProvider|MantineProvider|MantineThemeProvider)/u,
"Replaces a Homarr-owned provider boundary",
],
[/(?:Context|Provider)$/u, "Exposes or replaces an internal React context boundary"],
[/(?:Portal)$/u, "Can render outside the widget root"],
[/^(?:FileButton|FileInput)/u, "Requests local file-system access"],
[/^(?:FocusTrap)/u, "Can capture focus outside the widget interaction flow"],
];
export function getDeniedCustomJsxComponentReason(name: string): string | undefined {
const exact = exactReasons.get(name);
if (exact) return exact;
return familyReasons.find(([pattern]) => pattern.test(name))?.[1];
}
export const customJsxDeniedComponentRegistry: readonly CustomJsxComponentDescriptor[] =
discoveredMantineComponents.flatMap(({ name, package: packageName }) => {
const reason = getDeniedCustomJsxComponentReason(name);
if (!reason) return [];
return [
{
name,
package: packageName,
category: "blocked" as const,
safety: "denied" as const,
supportedProps: [],
subcomponents: [],
accessibilityRequirements: accessibilityByCategory.blocked,
documentationUrl: documentationUrl(packageName, name),
reason,
},
];
});
export const deniedCustomJsxComponentNames = new Set(customJsxDeniedComponentRegistry.map((entry) => entry.name));
@@ -1,167 +1,37 @@
/**
* The source of truth for the Custom JSX public component surface.
*
* Components marked `wrapped` require a runtime wrapper that removes unsafe props
* or supplies inert/read-only behavior. `denied` entries are deliberately kept in
* the registry so Mantine upgrades cannot silently expand the template surface.
*/
import { accessibilityByCategory, describe, documentationUrl, subcomponentsByName } from "./component-descriptor";
import type { CustomJsxComponentDescriptor } from "./component-descriptor";
import { discoveredMantineComponents, discoveredSubcomponentsByName } from "./component-discovery";
import { deniedCustomJsxComponentNames } from "./component-registry-denied";
import { categorySafeProps, commonSafeProps } from "./component-props";
import generatedComponentProps from "./component-props.generated.json";
const enabledMantineComponents = discoveredMantineComponents.flatMap(
({ name, package: packageName, category }): CustomJsxComponentDescriptor[] =>
deniedCustomJsxComponentNames.has(name)
? []
: [
{
name,
package: packageName,
category,
safety: "wrapped",
supportedProps: [
...new Set([
...commonSafeProps,
...categorySafeProps[category],
...((generatedComponentProps as Record<string, string[]>)[name] ?? []),
"bind",
]),
],
subcomponents: discoveredSubcomponentsByName[name] ?? subcomponentsByName[name] ?? [],
accessibilityRequirements: accessibilityByCategory[category],
documentationUrl: documentationUrl(packageName, name),
},
],
);
export const customJsxEnabledComponentRegistry: readonly CustomJsxComponentDescriptor[] = [
...describe("@mantine/core", "layout", "allowed", [
"Box",
"Stack",
"Group",
"Flex",
"Grid",
"Grid.Col",
"SimpleGrid",
"Center",
"Space",
"Container",
"AspectRatio",
"ScrollArea",
"Paper",
"Card",
"Card.Section",
"Divider",
"Fieldset",
"VisuallyHidden",
"Typography",
"FloatingIndicator",
]),
...describe("@mantine/core", "content", "allowed", [
"Text",
"Title",
"Code",
"Highlight",
"Mark",
"Kbd",
"Blockquote",
"NumberFormatter",
"Badge",
"ThemeIcon",
"ColorSwatch",
"Table",
"Table.Thead",
"Table.Tbody",
"Table.Tfoot",
"Table.Caption",
"Table.Tr",
"Table.Th",
"Table.Td",
"List",
"List.Item",
"Timeline",
"Timeline.Item",
"Indicator",
"Pill",
"Image",
"Avatar",
"Avatar.Group",
"BackgroundImage",
"DataList",
"DataList.Item",
"DataList.ItemLabel",
"DataList.ItemValue",
"EmptyState",
"EmptyState.Indicator",
"EmptyState.Title",
"EmptyState.Description",
"EmptyState.Actions",
"Marquee",
"RollingNumber",
]),
...describe("@mantine/core", "feedback", "allowed", [
"Alert",
"Progress",
"Progress.Section",
"RingProgress",
"SemiCircleProgress",
"Skeleton",
"Loader",
]),
...describe("@mantine/core", "feedback", "wrapped", ["Notification", "LoadingOverlay", "Overlay"]),
...describe("@mantine/core", "navigation", "allowed", [
"Accordion",
"Accordion.Item",
"Accordion.Control",
"Accordion.Panel",
"Tabs",
"Tabs.List",
"Tabs.Tab",
"Tabs.Panel",
"Stepper.Step",
"HoverCard",
"HoverCard.Target",
"HoverCard.Dropdown",
"Menu",
"Menu.Target",
"Menu.Dropdown",
"Menu.Item",
"Menu.Label",
"Menu.Divider",
"Tooltip",
"Spoiler",
"Collapse",
"Transition",
]),
...describe("@mantine/core", "navigation", "wrapped", ["Anchor", "NavLink", "Breadcrumbs", "Stepper", "Tree"]),
...describe("@mantine/core", "interaction", "wrapped", [
"Button",
"ActionIcon",
"Burger",
"CloseButton",
"Chip",
"Chip.Group",
"CopyButton",
"Pagination",
"Rating",
"SegmentedControl",
"Slider",
"Switch",
]),
...describe("@mantine/charts", "charts", "allowed", [
"AreaChart",
"BarChart",
"BarsList",
"BubbleChart",
"ChartLegend",
"ChartTooltip",
"CompositeChart",
"DonutChart",
"FunnelChart",
"Heatmap",
"LineChart",
"PieChart",
"RadarChart",
"RadialBarChart",
"SankeyChart",
"ScatterChart",
"Sparkline",
"Treemap",
]),
...describe("@mantine/dates", "dates", "wrapped", [
"Calendar",
"MiniCalendar",
"DatePicker",
"Day",
"WeekdaysRow",
"Month",
"CalendarHeader",
"YearPicker",
"MonthPicker",
"TimeGrid",
"PickerControl",
"YearsList",
"MonthsList",
"DecadeLevel",
"YearLevel",
"MonthLevel",
"LevelsGroup",
"DecadeLevelGroup",
"YearLevelGroup",
"MonthLevelGroup",
]),
...describe("@mantine/dates", "dates", "allowed", ["TimeValue"]),
...enabledMantineComponents,
...describe("@homarr/widgets", "interaction", "allowed", [
"PaginatedList",
"TabsContainer",
@@ -188,5 +58,3 @@ export const customJsxEnabledComponentRegistry: readonly CustomJsxComponentDescr
documentationUrl: documentationUrl("@homarr/widgets", "TablerIcon"),
},
];
import { accessibilityByCategory, describe, documentationUrl } from "./component-descriptor";
import type { CustomJsxComponentDescriptor } from "./component-descriptor";
@@ -17,3 +17,51 @@ export const customJsxComponentByName = new Map(customJsxComponentRegistry.map((
export const customJsxSupportedPropsByName = new Map(
customJsxComponentRegistry.map((entry) => [entry.name, new Set(entry.supportedProps)]),
);
export const customJsxBindableComponentNames: ReadonlySet<string> = new Set([
"Accordion",
"Autocomplete",
"Calendar",
"Checkbox",
"Checkbox.Group",
"Chip.Group",
"ColorInput",
"ColorPicker",
"DateInput",
"DatePicker",
"DatePickerInput",
"DateTimePicker",
"HoverCard",
"JsonInput",
"InlineDateTimePicker",
"MaskInput",
"Menu",
"MiniCalendar",
"MonthPicker",
"MonthPickerInput",
"MultiSelect",
"NativeSelect",
"NumberInput",
"Pagination",
"PasswordInput",
"PinInput",
"Popover",
"Radio.Group",
"RangeSlider",
"Rating",
"SegmentedControl",
"Select",
"Slider",
"Stepper",
"Switch",
"Switch.Group",
"Tabs",
"TagsInput",
"TextInput",
"Textarea",
"TimeInput",
"TimePicker",
"TreeSelect",
"YearPicker",
"YearPickerInput",
]);
@@ -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);
@@ -1,184 +1,12 @@
import { z } from "zod/v4";
import type { CustomJsxDisplayConfigV2 } from "./custom-jsx-schema";
import { displayConfigSchema } from "./display-config-schema";
import type { DisplayConfig } from "./display-config-schema";
import {
customWidgetAuthTypes,
customWidgetDisplayTypes,
customWidgetMethods,
customWidgetSecretKinds,
} from "./schema-types";
import type { CustomWidgetMethod } from "./schema-types";
const displayTypesMatch = (displayType?: string, configType?: string): boolean => {
if (!displayType) return true;
if (!configType) return true;
return displayType === configType;
};
const displayTypeMatchMessage = {
message: "displayType must match displayConfig.type",
path: ["displayConfig", "type"],
};
const isCustomJsxV2 = (config: DisplayConfig | undefined): config is CustomJsxDisplayConfigV2 =>
config?.type === "customJsx" && "jsxApiVersion" in config && config.jsxApiVersion === 2;
const validateDefinitionDisplay = (
definition: { method?: CustomWidgetMethod; displayType?: string; displayConfig?: DisplayConfig },
ctx: z.RefinementCtx,
) => {
if (!displayTypesMatch(definition.displayType, definition.displayConfig?.type)) {
ctx.addIssue({
code: "custom",
message: displayTypeMatchMessage.message,
path: displayTypeMatchMessage.path,
});
}
if (isCustomJsxV2(definition.displayConfig) && definition.method !== undefined && definition.method !== "GET") {
ctx.addIssue({
code: "custom",
message: "Custom JSX v2 base data requests must use GET; mutations belong in named actions",
path: ["method"],
});
}
};
const baseDefinitionSchema = z.object({
name: z
.string()
.min(1)
.max(128)
.describe("Human-readable name for the widget, displayed in the dashboard and management UI"),
description: z
.string()
.max(512)
.optional()
.describe("Optional longer description of what this widget shows, shown in tooltips and management UI"),
iconUrl: z
.string()
.url()
.optional()
.describe(
"Optional URL to an icon image for the widget (e.g. https://example.com/icon.png). Shown in widget picker.",
),
url: z
.string()
.min(1)
.describe(
"Full URL to the API endpoint to fetch data from (e.g. https://myapp.local/api/stats). Must include protocol.",
),
authType: z
.enum(customWidgetAuthTypes)
.describe(
"Authentication method: 'none' for public APIs, 'bearer' for Bearer token, 'basic' for Basic auth, 'apiKeyHeader' for API key sent as a custom header, 'apiKeyQuery' for API key as query parameter. Secrets are configured separately in the UI.",
),
headerName: z
.string()
.max(256)
.optional()
.describe(
"Custom header or query parameter name for API key auth. For apiKeyHeader: the HTTP header name (default: X-API-Key). For apiKeyQuery: the query param name (default: api_key). Ignored for other auth types.",
),
method: z
.enum(customWidgetMethods)
.describe(
"HTTP method for the API request: 'GET' (fetch data, most common), 'POST'/'PUT'/'PATCH' (with optional requestBody), 'DELETE' (destructive actions)",
),
requestBody: z
.string()
.optional()
.describe(
'JSON string body sent with POST/PUT/PATCH requests. Must be valid JSON as a string (e.g. \'{"action":"restart"}\'). Omit for GET requests.',
),
displayType: z
.enum(customWidgetDisplayTypes)
.describe(
"How to render the API response: 'singleValue' (one big number/text), 'keyValue' (labeled pairs), 'table' (rows/columns), 'statGrid' (colored stat cards), 'progressBars' (usage bars), 'statusIndicator' (health dots), 'countGrid' (simple counts), 'raw' (JSON debug view), 'actionButton' (clickable action), 'customJsx' (custom JSX template with Mantine components)",
),
displayConfig: displayConfigSchema,
});
const secretsInputSchema = z.array(
z.object({
kind: z
.enum(customWidgetSecretKinds)
.describe(
"Secret type: 'apiKey' (token/key for bearer/apiKey auth), 'username' (for basic auth), 'password' (for basic auth)",
),
value: z
.string()
.min(1)
.describe("The secret value. Never include in exported JSON — configure in the UI after import."),
}),
);
export const customWidgetCreateSchema = baseDefinitionSchema
.extend({ secrets: secretsInputSchema })
.superRefine(validateDefinitionDisplay);
export const customWidgetUpdateSchema = baseDefinitionSchema
.partial()
.extend({ id: z.string(), secrets: secretsInputSchema.optional() })
.superRefine(validateDefinitionDisplay);
const customWidgetImportFieldsSchema = z.object({
name: z
.string()
.min(1)
.max(128)
.describe("Human-readable name for the widget, displayed in the dashboard and management UI"),
description: z
.string()
.max(512)
.nullish()
.describe("Optional longer description of what this widget shows. Use null or omit if not needed."),
iconUrl: z
.string()
.url()
.nullish()
.describe("Optional URL to an icon image for the widget. Use null or omit if not needed."),
authType: z
.enum(customWidgetAuthTypes)
.describe(
"Authentication method: 'none' for public APIs, 'bearer' for Bearer token, 'basic' for Basic auth, 'apiKeyHeader' for API key sent as a custom header, 'apiKeyQuery' for API key as query parameter",
),
headerName: z
.string()
.max(256)
.nullish()
.describe(
"Custom header or query parameter name for API key auth. For apiKeyHeader: HTTP header name (default: X-API-Key). For apiKeyQuery: query param name (default: api_key).",
),
method: z
.enum(customWidgetMethods)
.describe(
"HTTP method: 'GET' (fetch data), 'POST'/'PUT'/'PATCH' (with requestBody), 'DELETE' (destructive). Use GET unless the API requires otherwise.",
),
requestBody: z.string().nullish().describe("JSON string body for POST/PUT/PATCH. Use null or omit for GET requests."),
displayType: z
.enum(customWidgetDisplayTypes)
.describe(
"How to render the API response: 'singleValue', 'keyValue', 'table', 'statGrid', 'progressBars', 'statusIndicator', 'countGrid', 'raw', 'actionButton', or 'customJsx'",
),
displayConfig: displayConfigSchema,
});
export const customWidgetImportSchema = customWidgetImportFieldsSchema
.extend({
$schema: z
.enum(["homarr-custom-widget-v2", "homarr-custom-widget-v3"])
.optional()
.describe("Schema version identifier. New exports use 'homarr-custom-widget-v3'; v2 remains importable."),
url: z
.string()
.min(1)
.describe(
"Full URL to the API endpoint to fetch data from (e.g. https://myapp.local/api/stats). Must include protocol.",
),
})
.superRefine(validateDefinitionDisplay);
export type CustomWidgetImport = z.infer<typeof customWidgetImportSchema>;
export {
customWidgetCreateSchema,
customWidgetDefinitionSchema,
customWidgetImportSchema,
customWidgetUpdateSchema,
} from "./custom-jsx-schema";
export type {
CustomWidgetCreateInput,
CustomWidgetImport,
CustomWidgetUpdateInput,
HomarrCustomWidgetV2,
} from "./custom-jsx-schema";
@@ -0,0 +1,104 @@
import type { RefinementCtx } from "zod/v4";
import type { CustomJsxRequest } from "./request-schema";
const credentialKeyPattern =
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
const credentialTextPattern =
/(?:\bauthorization\s*[:=]\s*["']?bearer\s+[A-Za-z0-9._~+/%-]{8,}|\b(?:api[ _-]?key|access[ _-]?token|refresh[ _-]?token|client[ _-]?secret|token|password|passwd|secret)\s*[:=]\s*["'][^"']{4,}["'])/iu;
const bearerHeaderValuePattern = /^\s*bearer\s+\S{8,}\s*$/iu;
const blockedObjectKeys = new Set(["__proto__", "prototype", "constructor"]);
interface SecurityDefinition {
defaultOptions: Record<string, unknown>;
defaultState?: Record<string, unknown>;
requests: CustomJsxRequest[];
template: string;
iconUrl?: string;
optionsSchema: unknown;
}
export function isCredentialKeyName(value: string) {
return credentialKeyPattern.test(value);
}
export function validateCredentialFreeExport(definition: SecurityDefinition, ctx: RefinementCtx) {
if (containsCredentialLikeValue(definition.defaultOptions)) {
ctx.addIssue({ code: "custom", path: ["defaultOptions"], message: "Default options cannot contain credentials" });
}
if (containsCredentialLikeValue(definition.defaultState)) {
ctx.addIssue({ code: "custom", path: ["defaultState"], message: "Default state cannot contain credentials" });
}
definition.requests.forEach((request, index) => {
if (
containsCredentialLikeValue(request.queryTemplate) ||
containsCredentialLikeValue(request.bodyTemplate) ||
Object.entries(request.staticHeaders ?? {}).some(
([name, value]) => containsCredentialLikeValue(value, name) || bearerHeaderValuePattern.test(value),
)
) {
ctx.addIssue({
code: "custom",
path: ["requests", index],
message: "Static request templates cannot contain credentials",
});
}
});
if (credentialTextPattern.test(definition.template)) {
ctx.addIssue({ code: "custom", path: ["template"], message: "Templates cannot contain literal credentials" });
}
if (definition.iconUrl) {
const icon = new URL(definition.iconUrl);
if ([...icon.searchParams].some(([key, value]) => isCredentialKeyName(key) && value.trim().length > 0)) {
ctx.addIssue({ code: "custom", path: ["iconUrl"], message: "Widget icon URLs cannot contain credentials" });
}
}
}
function containsCredentialLikeValue(value: unknown, key = ""): boolean {
if (isCredentialKeyName(key) && typeof value === "string" && value.trim().length > 0) return true;
if (Array.isArray(value)) return value.some((entry) => containsCredentialLikeValue(entry));
if (value === null || typeof value !== "object") return false;
const entries = Object.entries(value);
if (entries.length === 1 && entries[0]?.[0] === "$param" && typeof entries[0][1] === "string") return false;
return entries.some(([childKey, child]) => containsCredentialLikeValue(child, childKey));
}
export function validatePrototypeKeys(definition: SecurityDefinition, ctx: RefinementCtx) {
const values: Array<[Array<string | number>, unknown]> = [
[["optionsSchema"], definition.optionsSchema],
[["defaultOptions"], definition.defaultOptions],
[["defaultState"], definition.defaultState],
];
definition.requests.forEach((request, index) => {
values.push([["requests", index, "queryTemplate"], request.queryTemplate]);
values.push([["requests", index, "bodyTemplate"], request.bodyTemplate]);
});
for (const [path, value] of values) {
const blockedPath = findBlockedObjectKey(value);
if (blockedPath) {
ctx.addIssue({
code: "custom",
path: [...path, ...blockedPath],
message: "Prototype-pollution keys are not allowed",
});
}
}
}
function findBlockedObjectKey(value: unknown, path: string[] = []): string[] | null {
if (Array.isArray(value)) {
for (const [index, entry] of value.entries()) {
const found = findBlockedObjectKey(entry, [...path, String(index)]);
if (found) return found;
}
return null;
}
if (value === null || typeof value !== "object") return null;
for (const [key, child] of Object.entries(value)) {
if (blockedObjectKeys.has(key.toLowerCase())) return [...path, key];
const found = findBlockedObjectKey(child, [...path, key]);
if (found) return found;
}
return null;
}
@@ -1,57 +0,0 @@
import { z } from "zod/v4";
import {
countGridDisplayConfigSchema,
keyValueDisplayConfigSchema,
progressBarsDisplayConfigSchema,
rawDisplayConfigSchema,
singleValueDisplayConfigSchema,
statGridDisplayConfigSchema,
statusIndicatorDisplayConfigSchema,
tableDisplayConfigSchema,
} from "./built-in-display-schemas";
import { customJsxDisplayConfigV1Schema, customJsxDisplayConfigV2Schema } from "./custom-jsx-schema";
const actionButtonDisplayConfigSchema = z.object({
type: z
.literal("actionButton")
.describe("Display type discriminator — must be 'actionButton' when displayType is actionButton"),
buttonLabel: z
.string()
.min(1)
.describe("Text shown on the action button (e.g. 'Restart Service', 'Clear Cache', 'Run Backup')"),
buttonColor: z
.string()
.optional()
.describe("Mantine color name for the button (e.g. 'blue', 'red', 'green'). Default: blue"),
confirmText: z
.string()
.optional()
.describe(
"If set, shows a confirmation dialog with this message before executing the API request. Omit for immediate execution.",
),
successMessage: z
.string()
.optional()
.describe("Notification message shown after successful API execution. Omit for a generic success message."),
});
export const displayConfigSchema = z
.union([
singleValueDisplayConfigSchema,
keyValueDisplayConfigSchema,
tableDisplayConfigSchema,
statGridDisplayConfigSchema,
progressBarsDisplayConfigSchema,
statusIndicatorDisplayConfigSchema,
countGridDisplayConfigSchema,
rawDisplayConfigSchema,
actionButtonDisplayConfigSchema,
customJsxDisplayConfigV2Schema,
customJsxDisplayConfigV1Schema,
])
.describe(
"Configuration for how API response data is displayed. The 'type' field MUST match the top-level 'displayType' field exactly. Choose the variant that matches your displayType.",
);
export type DisplayConfig = z.infer<typeof displayConfigSchema>;
@@ -1,123 +0,0 @@
import { JSONPath } from "jsonpath-plus";
import type { DisplayConfig } from "./display-config-schema";
import type { CustomWidgetDisplayType } from "./schema-types";
export type ExtractedDisplayData = Record<string, unknown>;
const query = (json: unknown, path: string) => JSONPath({ path, json: json as object, wrap: false }) as unknown;
const queryRows = (json: unknown, path: string): unknown[] => {
const rows = JSONPath({ path, json: json as object, wrap: true }) as unknown[];
return Array.isArray(rows[0]) ? (rows[0] as unknown[]) : rows;
};
const toNumber = (value: unknown, fallback: number): number => Number(value) || fallback;
export function extractDisplayData(
json: unknown,
_displayType: CustomWidgetDisplayType,
config: DisplayConfig,
): ExtractedDisplayData {
switch (config.type) {
case "singleValue":
return {
...config,
value: query(json, config.jsonPath),
valueSize: config.valueSize ?? "lg",
labelPosition: config.labelPosition ?? "below",
};
case "keyValue":
return {
type: config.type,
entries: config.mappings.map((mapping) => ({ ...mapping, value: query(json, mapping.jsonPath) })),
layout: config.layout ?? "list",
columns: config.columns ?? 2,
};
case "table": {
const rows = queryRows(json, config.tablePath);
return {
type: config.type,
columns: config.columns.map((column) => column.header),
rows: rows.map((row) => config.columns.map((column) => query(row, column.jsonPath))),
striped: config.striped ?? true,
compact: config.compact ?? false,
};
}
case "statGrid":
return {
type: config.type,
items: config.items.map((item) => ({
...item,
color: item.color ?? "blue",
value: query(json, item.jsonPath),
})),
columns: config.columns ?? 2,
cardStyle: config.cardStyle ?? "filled",
};
case "progressBars":
return {
type: config.type,
bars: config.bars.map((bar) => ({
...bar,
color: bar.color ?? "blue",
value: toNumber(query(json, bar.valuePath), 0),
max: bar.maxPath ? toNumber(query(json, bar.maxPath), 100) : undefined,
})),
showPercentage: config.showPercentage ?? true,
barSize: config.barSize ?? "md",
};
case "statusIndicator":
return {
type: config.type,
items: config.items.map((item) => {
const value = query(json, item.jsonPath);
return {
label: item.label,
value: String(value ?? "unknown"),
isGood: item.goodValues.some((good) => String(value).toLowerCase() === good.toLowerCase()),
};
}),
layout: config.layout ?? "list",
dotSize: config.dotSize ?? "md",
};
case "countGrid":
return {
type: config.type,
items: config.items.map((item) => ({ ...item, value: query(json, item.jsonPath) })),
columns: config.columns ?? 2,
valueSize: config.valueSize ?? "md",
};
case "raw":
return { type: config.type, data: query(json, config.jsonPath), maxHeight: config.maxHeight ?? 300 };
case "actionButton":
return {
...config,
buttonColor: config.buttonColor ?? "blue",
confirmText: config.confirmText ?? "",
successMessage: config.successMessage ?? "",
};
case "customJsx":
return {
type: config.type,
template: config.template,
data: json,
jsxApiVersion: "jsxApiVersion" in config ? config.jsxApiVersion : 1,
requestCapabilities: Array.isArray(config.requests)
? config.requests.map(({ id, kind, method, minimumBoardPermission }) => ({
id,
kind,
method,
minimumBoardPermission,
}))
: [],
};
}
}
export const extractDisplayDataWithFallback = extractDisplayData;
export function extractActionButtonDisplay(config: DisplayConfig): ExtractedDisplayData {
if (config.type !== "actionButton") throw new Error("Display configuration is not an action button");
return extractDisplayData(null, "actionButton", config);
}
@@ -1,264 +0,0 @@
import { customJsxExamples } from "./examples";
import { customJsxRequestSchema, displayConfigSchema } from "./schema";
import type { DisplayConfig } from "./schema";
import type { CustomWidgetDisplayType } from "./schema";
function hydrateDisplayFormValues(displayType: string, config: Record<string, unknown>) {
const base = {
displayType,
jsonPath: "$",
label: "",
unit: "",
valueSize: "lg",
labelPosition: "below",
mappings: [{ label: "", jsonPath: "$", unit: "" }],
kvLayout: "list",
kvColumns: 2,
tablePath: "$",
columns: [{ header: "", jsonPath: "$" }],
striped: true,
compact: false,
statGridItems: [{ label: "", jsonPath: "$", unit: "", color: "blue" }],
statGridColumns: 2,
cardStyle: "filled",
progressBars: [{ label: "", valuePath: "$", maxPath: "", unit: "", color: "blue" }],
showPercentage: true,
barSize: "md",
statusItems: [{ label: "", jsonPath: "$", goodValues: "online,true" }],
statusLayout: "list",
dotSize: "md",
countGridItems: [{ label: "", jsonPath: "$", unit: "" }],
countGridColumns: 2,
countValueSize: "md",
rawJsonPath: "$",
rawMaxHeight: 300,
buttonLabel: "Execute",
buttonColor: "blue",
confirmText: "",
successMessage: "",
template: CUSTOM_JSX_STARTER,
jsxApiVersion: "2",
networkScope: "public",
requestManifest: "[]",
};
const typeOverrides: Record<string, () => Record<string, unknown>> = {
singleValue: () => ({
jsonPath: (config.jsonPath as string) ?? "$",
label: (config.label as string) ?? "",
unit: (config.unit as string) ?? "",
valueSize: (config.valueSize as string) ?? "lg",
labelPosition: (config.labelPosition as string) ?? "below",
}),
keyValue: () => ({
mappings: (config.mappings as typeof base.mappings) ?? base.mappings,
kvLayout: (config.layout as string) ?? "list",
kvColumns: (config.columns as number) ?? 2,
}),
table: () => ({
tablePath: (config.tablePath as string) ?? "$",
columns: (config.columns as typeof base.columns) ?? base.columns,
striped: (config.striped as boolean) ?? true,
compact: (config.compact as boolean) ?? false,
}),
statGrid: () => ({
statGridItems: (config.items as typeof base.statGridItems) ?? base.statGridItems,
statGridColumns: (config.columns as number) ?? 2,
cardStyle: (config.cardStyle as string) ?? "filled",
}),
progressBars: () => ({
progressBars: (
(config.bars as Array<{ label: string; valuePath: string; maxPath?: string; unit: string; color?: string }>) ??
[]
).map((bar) => ({ ...bar, maxPath: bar.maxPath ?? "", color: bar.color ?? "blue" })),
showPercentage: (config.showPercentage as boolean) ?? true,
barSize: (config.barSize as string) ?? "md",
}),
statusIndicator: () => ({
statusItems: ((config.items as Array<{ label: string; jsonPath: string; goodValues: string[] }>) ?? []).map(
(item) => ({ ...item, goodValues: item.goodValues.join(", ") }),
),
statusLayout: (config.layout as string) ?? "list",
dotSize: (config.dotSize as string) ?? "md",
}),
countGrid: () => ({
countGridItems: (config.items as typeof base.countGridItems) ?? base.countGridItems,
countGridColumns: (config.columns as number) ?? 2,
countValueSize: (config.valueSize as string) ?? "md",
}),
raw: () => ({
rawJsonPath: (config.jsonPath as string) ?? "$",
rawMaxHeight: (config.maxHeight as number) ?? 300,
}),
actionButton: () => ({
buttonLabel: (config.buttonLabel as string) ?? "Execute",
buttonColor: (config.buttonColor as string) ?? "blue",
confirmText: (config.confirmText as string) ?? "",
successMessage: (config.successMessage as string) ?? "",
}),
customJsx: () => ({
template:
typeof config.template === "string" && config.template.trim().length > 0 ? config.template : CUSTOM_JSX_STARTER,
jsxApiVersion: String((config.jsxApiVersion as number | undefined) ?? 1),
networkScope: (config.networkScope as string) ?? "public",
requestManifest: JSON.stringify((config.requests as unknown[] | undefined) ?? [], null, 2),
}),
};
return { ...base, ...typeOverrides[displayType]?.() };
}
const starterExample = customJsxExamples.find((example) => example.id === "simple-metric");
if (!starterExample) throw new Error("The simple-metric Custom JSX fixture is required");
export const CUSTOM_JSX_STARTER = starterExample.template;
export type CustomWidgetDisplayFormValues = ReturnType<typeof hydrateDisplayFormValues>;
const displayConfigBuilders: Record<string, (values: CustomWidgetDisplayFormValues) => Record<string, unknown>> = {
singleValue: (values) => ({
type: "singleValue",
jsonPath: values.jsonPath,
label: values.label,
unit: values.unit,
valueSize: values.valueSize,
labelPosition: values.labelPosition,
}),
keyValue: (values) => ({
type: "keyValue",
mappings: values.mappings,
layout: values.kvLayout,
columns: values.kvColumns,
}),
table: (values) => ({
type: "table",
tablePath: values.tablePath,
columns: values.columns,
striped: values.striped,
compact: values.compact,
}),
statGrid: (values) => ({
type: "statGrid",
items: values.statGridItems,
columns: values.statGridColumns,
cardStyle: values.cardStyle,
}),
progressBars: (values) => ({
type: "progressBars",
bars: values.progressBars.map((bar) => ({ ...bar, maxPath: bar.maxPath || undefined })),
showPercentage: values.showPercentage,
barSize: values.barSize,
}),
statusIndicator: (values) => ({
type: "statusIndicator",
items: values.statusItems.map((item) => ({
...item,
goodValues: item.goodValues
.split(",")
.map((value) => value.trim())
.filter(Boolean),
})),
layout: values.statusLayout,
dotSize: values.dotSize,
}),
countGrid: (values) => ({
type: "countGrid",
items: values.countGridItems,
columns: values.countGridColumns,
valueSize: values.countValueSize,
}),
raw: (values) => ({ type: "raw", jsonPath: values.rawJsonPath, maxHeight: values.rawMaxHeight }),
actionButton: (values) => ({
type: "actionButton",
buttonLabel: values.buttonLabel,
buttonColor: values.buttonColor,
confirmText: values.confirmText || undefined,
successMessage: values.successMessage || undefined,
}),
customJsx: (values) =>
values.jsxApiVersion === "2"
? {
type: "customJsx",
jsxApiVersion: 2,
template: values.template.trim() || CUSTOM_JSX_STARTER,
networkScope: values.networkScope,
requests: parseRequestManifest(values.requestManifest),
}
: { type: "customJsx", template: values.template.trim() || CUSTOM_JSX_STARTER },
};
export type CustomWidgetDisplayIcon =
| "action"
| "code"
| "count"
| "grid"
| "json"
| "keyValue"
| "number"
| "progress"
| "status"
| "table";
export interface CustomWidgetDisplayDescriptor {
type: CustomWidgetDisplayType;
icon: CustomWidgetDisplayIcon;
supportsActions: boolean;
supportsNamedRequests: boolean;
defaults(): CustomWidgetDisplayFormValues;
hydrate(config: Record<string, unknown>): CustomWidgetDisplayFormValues;
serialize(values: CustomWidgetDisplayFormValues): DisplayConfig;
validate(config: unknown): DisplayConfig;
}
const descriptorMetadata = [
["singleValue", "number", false, false],
["keyValue", "keyValue", false, false],
["table", "table", false, false],
["statGrid", "grid", false, false],
["progressBars", "progress", false, false],
["statusIndicator", "status", false, false],
["countGrid", "count", false, false],
["raw", "json", false, false],
["actionButton", "action", true, false],
["customJsx", "code", true, true],
] as const satisfies readonly [CustomWidgetDisplayType, CustomWidgetDisplayIcon, boolean, boolean][];
export const customWidgetDisplayDescriptors: readonly CustomWidgetDisplayDescriptor[] = descriptorMetadata.map(
([type, icon, supportsActions, supportsNamedRequests]) => ({
type,
icon,
supportsActions,
supportsNamedRequests,
defaults: () => hydrateDisplayFormValues(type, {}),
hydrate: (config) => hydrateDisplayFormValues(type, config),
serialize: (values) => {
const build = displayConfigBuilders[type];
if (!build) throw new Error(`Unsupported custom-widget display type: ${type}`);
return displayConfigSchema.parse(build(values));
},
validate: (config) => displayConfigSchema.parse(config),
}),
);
export function getCustomWidgetDisplayDescriptor(type: string): CustomWidgetDisplayDescriptor {
const descriptor = customWidgetDisplayDescriptors.find((candidate) => candidate.type === type);
if (!descriptor) throw new Error(`Unsupported custom-widget display type: ${type}`);
return descriptor;
}
export function buildDisplayFormValues(displayType: string, config: Record<string, unknown>) {
return getCustomWidgetDisplayDescriptor(displayType).hydrate(config);
}
export function buildDisplayConfigFromFormValues(values: CustomWidgetDisplayFormValues): DisplayConfig {
return getCustomWidgetDisplayDescriptor(values.displayType).serialize(values);
}
function parseRequestManifest(value: string) {
let parsed: unknown;
try {
parsed = JSON.parse(value);
} catch {
return [];
}
const result = customJsxRequestSchema.array().safeParse(parsed);
return result.success ? result.data : [];
}
+69 -287
View File
@@ -1,300 +1,82 @@
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
export interface CustomJsxExample {
id: string;
title: string;
description: string;
template: string;
requests: readonly Record<string, unknown>[];
widget: HomarrCustomWidgetV2;
}
export const CUSTOM_JSX_STARTER = `<Stack gap="xs" p="sm">
<Group justify="space-between">
<Text fw={600}>Service status</Text>
<Badge color={data.status === "online" ? "green" : "red"}>{data.status ?? "unknown"}</Badge>
</Group>
<Text size="sm" c="dimmed">Configure a load query or paste sample data to start.</Text>
</Stack>`;
export const CUSTOM_WIDGET_STARTER: HomarrCustomWidgetV2 = {
$schema: "homarr-custom-widget-v2",
name: "New custom widget",
description: "",
sources: [
{
id: "default",
name: "API",
baseUrl: "https://example.com",
networkScope: "public",
auth: { type: "none" },
},
],
requests: [],
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
defaultOptions: {},
stateSchema: {},
defaultState: {},
template: CUSTOM_JSX_STARTER,
};
export const customJsxExamples: readonly CustomJsxExample[] = [
{
id: "simple-metric",
title: "Simple metric",
description: "A compact status and metric display with no nested requests.",
template: `<Stack gap="xs" p="sm">
id: "service-status",
title: "Service status",
description: "A compact status widget backed by one load query.",
widget: {
$schema: "homarr-custom-widget-v2",
name: "Service status",
sources: [
{
id: "default",
name: "Service API",
baseUrl: "https://example.com",
networkScope: "public",
auth: { type: "none" },
},
],
requests: [
{
id: "status",
sourceId: "default",
kind: "query",
method: "GET",
pathTemplate: "/api/status",
parameters: {},
auth: "inherit",
minimumBoardPermission: "view",
trigger: "load",
},
],
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
defaultOptions: {},
stateSchema: {},
defaultState: {},
template: `<Stack gap="xs" p="sm">
<Group justify="space-between">
<Text fw={600}>{data.name}</Text>
<Badge color={data.status === "online" ? "green" : "red"}>{data.status}</Badge>
<Text fw={600}>{data.status.name ?? "Service"}</Text>
<Badge color={data.status.online ? "green" : "red"}>{data.status.online ? "Online" : "Offline"}</Badge>
</Group>
<Title order={2}>{data.value}</Title>
<Text size="sm" c="dimmed">{data.status.message ?? "No additional details"}</Text>
</Stack>`,
requests: [],
},
{
id: "pokedex-detail",
title: "Pokédex detail list",
description: "Paginates the list and fetches details only for visible Pokémon.",
template: `<Stack gap="sm" p="xs">
<Title order={3}>Pokédex</Title>
<PaginatedList pageSize={5}>
{data.results.map((pokemon) =>
<Card key={pokemon.name} withBorder p="xs" mb="xs">
<Text fw={700} tt="capitalize">{pokemon.name}</Text>
<SubFetch requestId="pokemon-detail" params={{ name: pokemon.name }}>
{(detail, meta) =>
<Stack gap={4}>
<Group gap="xs">
{detail.types.map((entry) => <Badge key={entry.type.name} color="red">{entry.type.name}</Badge>)}
</Group>
<Text size="xs">HP {detail.stats[0].base_stat} · HTTP {meta.status}</Text>
</Stack>
}
</SubFetch>
</Card>
)}
</PaginatedList>
</Stack>`,
requests: [
{
id: "pokemon-detail",
kind: "query",
method: "GET",
pathTemplate: "/api/v2/pokemon/{name}",
parameters: { name: "string" },
auth: "none",
minimumBoardPermission: "view",
cacheTtlSeconds: 300,
},
],
},
{
id: "stocks-dashboard",
title: "Stocks dashboard",
description: "Responsive portfolio values and chart with parent refresh.",
template: `<Stack gap="md" p="sm">
<Group justify="space-between">
<Title order={3}>Portfolio</Title>
<RefreshButton label="Refresh" size="xs" />
</Group>
<SimpleGrid cols={3}>
{data.holdings.map((stock) =>
<Card key={stock.symbol} withBorder p="xs">
<Text fw={700}>{stock.symbol}</Text>
<NumberFormatter value={stock.price} prefix="$" decimalScale={2} />
<Sparkline data={stock.history} h={40} color={stock.change > 0 ? "green" : "red"} />
</Card>
)}
</SimpleGrid>
<LineChart h={200} data={data.timeline} dataKey="date" series={[{ name: "value", color: "blue" }]} />
</Stack>`,
requests: [],
},
{
id: "navidrome-player",
title: "Navidrome mini-player",
description: "Media controls backed by named actions with explicit permissions.",
template: `<Stack gap="sm" p="sm">
<Group wrap="nowrap">
<Image src={data.albumArt} alt={data.album} w={80} h={80} radius="sm" />
<Stack gap={2} style={{ flex: 1 }}>
<Text fw={700} lineClamp={1}>{data.title}</Text>
<Text size="sm" c="dimmed" lineClamp={1}>{data.artist}</Text>
<Progress value={data.progress} size="xs" color="red" />
</Stack>
</Group>
<Group justify="center" gap="sm">
<ActionButton requestId="previous" label="Previous" size="xs" variant="subtle" />
<ActionButton requestId="toggle-playback" label={data.playing ? "Pause" : "Play"} icon="play" color="red" invalidate={["parent"]} />
<ActionButton requestId="next" label="Next" size="xs" variant="subtle" />
</Group>
<ToggleSwitch requestId="shuffle" onParams={{ enabled: true }} offParams={{ enabled: false }} initialValue={data.shuffle} label="Shuffle" size="xs" />
</Stack>`,
requests: [
{
id: "previous",
kind: "action",
method: "POST",
pathTemplate: "/api/player/previous",
parameters: {},
auth: "inherit",
minimumBoardPermission: "modify",
},
{
id: "toggle-playback",
kind: "action",
method: "POST",
pathTemplate: "/api/player/toggle",
parameters: {},
auth: "inherit",
minimumBoardPermission: "modify",
},
{
id: "next",
kind: "action",
method: "POST",
pathTemplate: "/api/player/next",
parameters: {},
auth: "inherit",
minimumBoardPermission: "modify",
},
{
id: "shuffle",
kind: "action",
method: "PUT",
pathTemplate: "/api/player/shuffle",
parameters: { enabled: "boolean" },
bodyTemplate: { enabled: { $param: "enabled" } },
auth: "inherit",
minimumBoardPermission: "modify",
},
],
},
{
id: "pokedex-interactive",
title: "Interactive Pokédex",
description:
"A full-featured Pokédex with paginated list, detail SubFetch, type badges, stats with progress bars, moves grid, and evolution chain. Exercises filter(Boolean), pop(), find, reduce, sort, replaceAll, padStart, arithmetic, and nested SubFetch.",
template: `<Stack gap="sm" p="sm" style={{ minWidth: 0 }}>
<Group justify="space-between" wrap="nowrap">
<Group gap="sm" wrap="nowrap">
<ThemeIcon size="lg" radius="xl" variant="light" color="red">P</ThemeIcon>
<Box>
<Title order={3}>Pokédex</Title>
<Text size="xs" c="dimmed"><NumberFormatter value={data.count} thousandSeparator /> Pokémon discovered</Text>
</Box>
</Group>
<RefreshButton label="Refresh" size="xs" />
</Group>
<PaginatedList pageSize={5}>
{data.results.map((pokemon, index) =>
<Accordion key={pokemon.name} variant="separated" radius="md">
<Accordion.Item value={pokemon.name}>
<Accordion.Control>
<Group justify="space-between" wrap="nowrap" pr="xs">
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
<Avatar size="sm" radius="md" src={"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/" + (index + 1) + ".png"} />
<Box style={{ minWidth: 0 }}>
<Text size="xs" c="dimmed">#{String(index + 1).padStart(4, "0")}</Text>
<Text fw={700} tt="capitalize" lineClamp={1}>{pokemon.name.replaceAll("-", " ")}</Text>
</Box>
</Group>
<Badge size="xs" variant="outline">Details</Badge>
</Group>
</Accordion.Control>
<Accordion.Panel>
<SubFetch requestId="pokemon-detail" params={{ name: pokemon.name }}>
{(detail, meta) =>
<Stack gap="sm">
<Grid gutter="sm">
<Grid.Col span={{ base: 12, sm: 5 }}>
<Center>
<Image src={detail.sprites.front_default} alt={detail.name} fit="contain" h={120} />
</Center>
</Grid.Col>
<Grid.Col span={{ base: 12, sm: 7 }}>
<Stack gap="xs">
<Group gap="xs">
{detail.types.map((entry) =>
<Badge key={entry.type.name} tt="capitalize">{entry.type.name}</Badge>
)}
</Group>
<SimpleGrid cols={3} spacing="xs">
<Box><Text size="xs" c="dimmed">Height</Text><Text fw={700}><NumberFormatter value={detail.height / 10} decimalScale={1} suffix=" m" /></Text></Box>
<Box><Text size="xs" c="dimmed">Weight</Text><Text fw={700}><NumberFormatter value={detail.weight / 10} decimalScale={1} suffix=" kg" /></Text></Box>
<Box><Text size="xs" c="dimmed">Base XP</Text><Text fw={700}>{detail.base_experience || "—"}</Text></Box>
</SimpleGrid>
<Group gap="xs">
{detail.abilities.map((entry) =>
<Badge key={entry.ability.name} variant="light" size="xs" tt="capitalize">
{entry.ability.name.replaceAll("-", " ")}{entry.is_hidden ? " ·H" : ""}
</Badge>
)}
</Group>
</Stack>
</Grid.Col>
</Grid>
<Tabs defaultValue="stats" variant="outline" radius="md">
<Tabs.List>
<Tabs.Tab value="stats">Stats</Tabs.Tab>
<Tabs.Tab value="moves">Moves</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="stats" pt="sm">
<Stack gap="xs">
{detail.stats.map((entry) =>
<Box key={entry.stat.name}>
<Group justify="space-between" mb={2}>
<Text size="xs" tt="capitalize">{entry.stat.name.replaceAll("-", " ")}</Text>
<Text size="xs" fw={700}>{entry.base_stat}</Text>
</Group>
<Progress value={Math.min(100, entry.base_stat / 2.55)} size="sm" radius="xl" />
</Box>
)}
<Group justify="space-between">
<Text size="sm" fw={700}>Total</Text>
<Badge>{detail.stats.reduce((sum, s) => sum + s.base_stat, 0)}</Badge>
</Group>
</Stack>
</Tabs.Panel>
<Tabs.Panel value="moves" pt="sm">
<ScrollArea h={120} type="auto">
<SimpleGrid cols={{ base: 2, sm: 3 }} spacing="xs">
{detail.moves.slice(0, 30).map((entry) =>
<Badge key={entry.move.name} variant="light" size="xs" tt="capitalize" style={{ whiteSpace: "normal" }}>
{entry.move.name.replaceAll("-", " ")}
</Badge>
)}
</SimpleGrid>
</ScrollArea>
</Tabs.Panel>
</Tabs>
<Text size="xs" c="dimmed">Status: {meta.status}</Text>
</Stack>
}
</SubFetch>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
)}
</PaginatedList>
</Stack>`,
requests: [
{
id: "pokemon-detail",
kind: "query",
method: "GET",
pathTemplate: "/api/v2/pokemon/{name}",
parameters: { name: "string" },
auth: "none",
minimumBoardPermission: "view",
cacheTtlSeconds: 3600,
},
],
},
{
id: "smart-home-control",
title: "Smart-home control",
description: "A stateful light control with an explicit destructive confirmation.",
template: `<Stack gap="md" p="sm">
<Group justify="space-between">
<Title order={4}>Living room</Title>
<Badge color={data.state === "on" ? "yellow" : "gray"}>{data.state}</Badge>
</Group>
<ToggleSwitch requestId="set-light" onParams={{ state: "on" }} offParams={{ state: "off" }} initialValue={data.state === "on"} label="Power" color="yellow" />
<ActionButton requestId="delete-scene" label="Delete scene" color="red" icon="trash" confirmMessage="Delete this scene?" />
</Stack>`,
requests: [
{
id: "set-light",
kind: "action",
method: "PUT",
pathTemplate: "/api/lights/living-room",
parameters: { state: "string" },
bodyTemplate: { state: { $param: "state" } },
auth: "inherit",
minimumBoardPermission: "modify",
},
{
id: "delete-scene",
kind: "action",
method: "DELETE",
pathTemplate: "/api/scenes/living-room",
parameters: {},
auth: "inherit",
minimumBoardPermission: "full",
},
],
},
},
];
+36 -69
View File
@@ -1,8 +1,10 @@
import { customWidgetImportSchema } from "./custom-jsx-schema";
export interface ImportReview {
name: string;
origin: string;
authType: string;
networkScope: string;
origins: string[];
authTypes: string[];
networkScopes: string[];
methods: string[];
permissions: string[];
hasActions: boolean;
@@ -10,99 +12,64 @@ export interface ImportReview {
function extractFencedBlock(text: string, acceptedLanguages: readonly string[]): string | undefined {
let cursor = 0;
while (cursor < text.length) {
const fenceStart = text.indexOf("```", cursor);
if (fenceStart === -1) return undefined;
const headerStart = fenceStart + 3;
const headerEnd = text.indexOf("\n", headerStart);
if (headerEnd === -1) return undefined;
const contentStart = headerEnd + 1;
const fenceEnd = text.indexOf("```", contentStart);
if (fenceEnd === -1) return undefined;
const language = text.slice(headerStart, headerEnd).trim().toLowerCase();
if (acceptedLanguages.includes(language)) return text.slice(contentStart, fenceEnd);
cursor = fenceEnd + 3;
}
return undefined;
}
export function parseCustomWidgetClipboard(text: string): Record<string, unknown> | null {
const result = parseCustomWidgetClipboardDetailed(text);
return result.success ? result.widget : null;
}
export function parseCustomWidgetClipboardDetailed(
text: string,
): { success: true; widget: Record<string, unknown> } | { success: false; error: string } {
try {
const jsonBlock = extractFencedBlock(text, ["", "json"]);
const jsxBlock = extractFencedBlock(text, ["jsx", "tsx"])?.trim();
const value: unknown = JSON.parse(jsonBlock ?? text);
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const widget = value as Record<string, unknown>;
if (
typeof widget.name !== "string" ||
typeof widget.url !== "string" ||
typeof widget.displayType !== "string" ||
!widget.displayConfig ||
typeof widget.displayConfig !== "object" ||
Array.isArray(widget.displayConfig)
) {
return null;
if (!value || typeof value !== "object" || Array.isArray(value)) {
return { success: false, error: "The response must contain one widget JSON object" };
}
if (jsxBlock && widget.displayType === "customJsx") {
const displayConfig = widget.displayConfig as Record<string, unknown>;
if (displayConfig.template === "__HOMARR_TEMPLATE__" || !displayConfig.template) {
displayConfig.template = jsxBlock;
}
const widget = { ...(value as Record<string, unknown>) };
if (jsxBlock && (widget.template === "__HOMARR_TEMPLATE__" || !widget.template)) widget.template = jsxBlock;
const parsed = customWidgetImportSchema.safeParse(widget);
if (!parsed.success) {
const issue = parsed.error.issues[0];
return {
success: false,
error: `${issue?.path.map(String).join(".") || "widget"}: ${issue?.message ?? "Invalid widget"}`,
};
}
return widget;
} catch {
return null;
return { success: true, widget };
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : "The response is not valid JSON" };
}
}
export function getImportReview(value: Record<string, unknown> | null): ImportReview | null {
if (!value) return null;
const displayConfig = value.displayConfig as Record<string, unknown>;
const requests = Array.isArray(displayConfig.requests)
? displayConfig.requests.filter(
(request): request is Record<string, unknown> =>
request !== null && typeof request === "object" && !Array.isArray(request),
)
: [];
const baseMethod = typeof value.method === "string" ? value.method : "GET";
const methods = [
...new Set([
baseMethod,
...requests.map((request) => request.method).filter((method): method is string => typeof method === "string"),
]),
];
const permissions = [
...new Set(
requests
.map((request) => request.minimumBoardPermission)
.filter(
(permission): permission is string =>
permission === "view" || permission === "modify" || permission === "full",
),
),
];
if (permissions.length === 0) permissions.push(baseMethod === "GET" ? "view" : "modify");
let origin = value.url;
try {
origin = new URL(value.url as string).origin;
} catch {
// The server returns the localized validation error after confirmation.
}
const parsed = customWidgetImportSchema.safeParse(value);
if (!parsed.success) return null;
const widget = parsed.data;
return {
name: value.name as string,
origin: String(origin),
authType: typeof value.authType === "string" ? value.authType : "none",
networkScope: typeof displayConfig.networkScope === "string" ? displayConfig.networkScope : "legacy",
methods,
permissions,
hasActions: methods.some((method) => method !== "GET"),
name: widget.name,
origins: widget.sources.map((source) => new URL(source.baseUrl).origin),
authTypes: [...new Set(widget.sources.map((source) => source.auth.type))],
networkScopes: [...new Set(widget.sources.map((source) => source.networkScope))],
methods: [...new Set(widget.requests.map((request) => request.method))],
permissions: [...new Set(widget.requests.map((request) => request.minimumBoardPermission))],
hasActions: widget.requests.some((request) => request.kind === "action"),
};
}
+3 -2
View File
@@ -1,7 +1,8 @@
export * from "./ai-prompt";
export * from "./authoring-resources";
export * from "./component-registry";
export * from "./display-data";
export * from "./display-form";
export * from "./examples";
export * from "./import";
export * from "./options";
export * from "./schema";
export * from "./tabler-icons";
@@ -0,0 +1,8 @@
export function matchesDeclaredOptionType(type: unknown, value: unknown) {
if (type === undefined) return true;
if (type === "object") return value !== null && typeof value === "object" && !Array.isArray(value);
if (type === "array") return Array.isArray(value);
if (type === "integer") return typeof value === "number" && Number.isInteger(value);
if (type === "null") return value === null;
return typeof value === type;
}
@@ -0,0 +1,300 @@
import { z } from "zod/v4";
import { matchesDeclaredOptionType } from "./option-value-types";
const optionSchemaKeys = new Set([
"type",
"title",
"description",
"default",
"enum",
"const",
"minimum",
"maximum",
"multipleOf",
"minLength",
"maxLength",
"minItems",
"maxItems",
"format",
"items",
"properties",
"required",
"additionalProperties",
"if",
"then",
"else",
"x-homarr",
]);
const optionTypes = new Set(["object", "array", "string", "number", "integer", "boolean", "null"]);
const optionControls = new Set([
"text",
"textarea",
"number",
"switch",
"select",
"multi-select",
"slider",
"date",
"time",
"color",
"icon",
"url",
"duration",
"timeZone",
"json",
]);
const optionFormats = new Set(["date", "date-time", "time", "color", "uri", "icon", "duration", "time-zone"]);
const credentialOptionName =
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
const controlsByType: Readonly<Record<string, ReadonlySet<string>>> = {
string: new Set(["text", "textarea", "select", "date", "time", "color", "icon", "url", "timeZone", "json"]),
number: new Set(["number", "select", "slider", "duration", "json"]),
integer: new Set(["number", "select", "slider", "duration", "json"]),
boolean: new Set(["switch", "select", "json"]),
array: new Set(["multi-select", "json"]),
object: new Set(["json"]),
null: new Set(["json"]),
};
function validateOptionsSource(value: unknown, ctx: z.RefinementCtx, path: Array<string | number>) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
ctx.addIssue({ code: "custom", path, message: "optionsSource must be an object" });
return;
}
const keys = Object.keys(value);
if (
keys.some((key) => !["requestId", "itemsPath", "valuePath", "labelPath"].includes(key)) ||
!["requestId", "valuePath", "labelPath"].every((key) => {
const candidate = (value as Record<string, unknown>)[key];
return typeof candidate === "string" && candidate.length > 0;
})
) {
ctx.addIssue({ code: "custom", path, message: "optionsSource requires requestId, valuePath, and labelPath" });
}
const itemsPath = (value as Record<string, unknown>).itemsPath;
if (itemsPath !== undefined && (typeof itemsPath !== "string" || itemsPath.length === 0)) {
ctx.addIssue({ code: "custom", path: [...path, "itemsPath"], message: "itemsPath must be a non-empty path" });
}
}
function validatePresentation(
value: unknown,
schema: Record<string, unknown>,
ctx: z.RefinementCtx,
path: Array<string | number>,
) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
ctx.addIssue({ code: "custom", path, message: "x-homarr must be an object" });
return;
}
const metadata = value as Record<string, unknown>;
const allowed = new Set(["control", "placeholder", "advanced", "order", "optionsSource"]);
for (const key of Object.keys(metadata)) {
if (!allowed.has(key))
ctx.addIssue({ code: "custom", path: [...path, key], message: `Unsupported x-homarr field '${key}'` });
}
if (
metadata.control !== undefined &&
(typeof metadata.control !== "string" || !optionControls.has(metadata.control))
) {
ctx.addIssue({ code: "custom", path: [...path, "control"], message: "Unknown Homarr option control" });
} else if (
typeof metadata.control === "string" &&
typeof schema.type === "string" &&
!controlsByType[schema.type]?.has(metadata.control)
) {
ctx.addIssue({
code: "custom",
path: [...path, "control"],
message: `Control '${metadata.control}' does not support ${schema.type} values`,
});
}
if (metadata.placeholder !== undefined && typeof metadata.placeholder !== "string") {
ctx.addIssue({ code: "custom", path: [...path, "placeholder"], message: "placeholder must be a string" });
}
if (metadata.advanced !== undefined && typeof metadata.advanced !== "boolean") {
ctx.addIssue({ code: "custom", path: [...path, "advanced"], message: "advanced must be a boolean" });
}
if (metadata.order !== undefined && (typeof metadata.order !== "number" || !Number.isFinite(metadata.order))) {
ctx.addIssue({ code: "custom", path: [...path, "order"], message: "order must be a finite number" });
}
if (metadata.optionsSource !== undefined) {
validateOptionsSource(metadata.optionsSource, ctx, [...path, "optionsSource"]);
if (metadata.control !== "select" && metadata.control !== "multi-select") {
ctx.addIssue({
code: "custom",
path: [...path, "optionsSource"],
message: "Dynamic options require a select or multi-select control",
});
}
}
}
function validateOptionSchemaNode(
value: unknown,
ctx: z.RefinementCtx,
path: Array<string | number>,
isRoot = false,
requiresType = true,
propertyTypesRequired = true,
): void {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
ctx.addIssue({ code: "custom", path, message: "Option schemas must be objects" });
return;
}
const schema = value as Record<string, unknown>;
for (const key of Object.keys(schema)) {
if (!optionSchemaKeys.has(key)) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `Unsupported option schema keyword '${key}'` });
}
}
if (
(requiresType && typeof schema.type !== "string") ||
(schema.type !== undefined && !optionTypes.has(String(schema.type)))
) {
ctx.addIssue({ code: "custom", path: [...path, "type"], message: "Every option schema needs one supported type" });
}
for (const key of ["title", "description"] as const) {
if (schema[key] !== undefined && typeof schema[key] !== "string") {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a string` });
}
}
for (const key of ["minimum", "maximum", "multipleOf"] as const) {
if (schema[key] !== undefined && (typeof schema[key] !== "number" || !Number.isFinite(schema[key]))) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a finite number` });
}
}
if (typeof schema.multipleOf === "number" && schema.multipleOf <= 0) {
ctx.addIssue({ code: "custom", path: [...path, "multipleOf"], message: "multipleOf must be greater than zero" });
}
if (typeof schema.minimum === "number" && typeof schema.maximum === "number" && schema.minimum > schema.maximum) {
ctx.addIssue({ code: "custom", path, message: "minimum cannot be greater than maximum" });
}
for (const key of ["minLength", "maxLength", "minItems", "maxItems"] as const) {
if (
schema[key] !== undefined &&
(typeof schema[key] !== "number" || !Number.isInteger(schema[key]) || schema[key] < 0)
) {
ctx.addIssue({ code: "custom", path: [...path, key], message: `${key} must be a non-negative integer` });
}
}
if (
typeof schema.minLength === "number" &&
typeof schema.maxLength === "number" &&
schema.minLength > schema.maxLength
) {
ctx.addIssue({ code: "custom", path, message: "minLength cannot be greater than maxLength" });
}
if (typeof schema.minItems === "number" && typeof schema.maxItems === "number" && schema.minItems > schema.maxItems) {
ctx.addIssue({ code: "custom", path, message: "minItems cannot be greater than maxItems" });
}
if (schema.format !== undefined && (typeof schema.format !== "string" || !optionFormats.has(schema.format))) {
ctx.addIssue({ code: "custom", path: [...path, "format"], message: "Unsupported option format" });
}
if (schema.format !== undefined && schema.type !== "string") {
ctx.addIssue({ code: "custom", path: [...path, "format"], message: "Option formats require a string type" });
}
if (
schema.enum !== undefined &&
(!Array.isArray(schema.enum) || schema.enum.length === 0 || schema.enum.length > 100)
) {
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "enum must contain between 1 and 100 values" });
} else if (
Array.isArray(schema.enum) &&
schema.enum.some((entry) => !matchesDeclaredOptionType(schema.type, entry))
) {
ctx.addIssue({ code: "custom", path: [...path, "enum"], message: "Every enum value must match the option type" });
}
if (schema.const !== undefined && !matchesDeclaredOptionType(schema.type, schema.const)) {
ctx.addIssue({ code: "custom", path: [...path, "const"], message: "const must match the option type" });
}
if (isRoot && schema.type !== "object") {
ctx.addIssue({ code: "custom", path: [...path, "type"], message: "The root options schema must be an object" });
}
if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {
ctx.addIssue({
code: "custom",
path: [...path, "additionalProperties"],
message: "additionalProperties can only be false",
});
}
if (schema.type === "object" && schema.additionalProperties !== false) {
ctx.addIssue({
code: "custom",
path: [...path, "additionalProperties"],
message: "Object options must set additionalProperties to false",
});
}
if (schema.properties !== undefined) {
if (schema.type !== undefined && schema.type !== "object") {
ctx.addIssue({ code: "custom", path: [...path, "properties"], message: "properties require an object type" });
}
if (schema.properties === null || typeof schema.properties !== "object" || Array.isArray(schema.properties)) {
ctx.addIssue({ code: "custom", path: [...path, "properties"], message: "properties must be an object" });
} else {
for (const [key, child] of Object.entries(schema.properties)) {
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u.test(key)) {
ctx.addIssue({
code: "custom",
path: [...path, "properties", key],
message: "Option names must start with a letter and contain letters, numbers, - or _",
});
}
if (credentialOptionName.test(key)) {
ctx.addIssue({
code: "custom",
path: [...path, "properties", key],
message: "Credentials must use source authentication, not widget options",
});
}
validateOptionSchemaNode(child, ctx, [...path, "properties", key], false, propertyTypesRequired);
}
}
}
if (schema.required !== undefined && !Array.isArray(schema.required)) {
ctx.addIssue({ code: "custom", path: [...path, "required"], message: "required must be an array" });
} else if (
Array.isArray(schema.required) &&
schema.properties !== null &&
typeof schema.properties === "object" &&
!Array.isArray(schema.properties)
) {
for (const key of schema.required) {
if (typeof key !== "string" || !Object.hasOwn(schema.properties, key)) {
ctx.addIssue({ code: "custom", path: [...path, "required"], message: "required contains an unknown option" });
}
}
}
if (schema.type === "array" && schema.items === undefined) {
ctx.addIssue({ code: "custom", path: [...path, "items"], message: "Array options require an items schema" });
}
if (schema.items !== undefined) {
if (schema.type !== undefined && schema.type !== "array") {
ctx.addIssue({ code: "custom", path: [...path, "items"], message: "items require an array type" });
}
validateOptionSchemaNode(schema.items, ctx, [...path, "items"]);
}
for (const branch of ["if", "then", "else"] as const) {
if (schema[branch] !== undefined) {
validateOptionSchemaNode(schema[branch], ctx, [...path, branch], false, false, branch !== "if");
}
}
if (schema["x-homarr"] !== undefined) validatePresentation(schema["x-homarr"], schema, ctx, [...path, "x-homarr"]);
}
export const customWidgetOptionsSchemaSchema = z
.object({
type: z.literal("object"),
properties: z.record(z.string(), z.unknown()).default({}),
required: z.array(z.string()).optional(),
additionalProperties: z.literal(false).default(false),
title: z.string().optional(),
description: z.string().optional(),
if: z.unknown().optional(),
// oxlint-disable-next-line unicorn/no-thenable -- JSON Schema uses the standard `then` keyword.
then: z.unknown().optional(),
else: z.unknown().optional(),
})
.strict()
.superRefine((schema, ctx) => validateOptionSchemaNode(schema, ctx, [], true));
+108
View File
@@ -0,0 +1,108 @@
export interface CustomWidgetOptionIssue {
path: string;
message: string;
}
type JsonSchema = Record<string, unknown>;
export function validateCustomWidgetOptions(
schema: JsonSchema,
value: Record<string, unknown>,
): CustomWidgetOptionIssue[] {
const issues: CustomWidgetOptionIssue[] = [];
validateValue(schema, value, "configuration", issues);
return issues;
}
function validateValue(schema: JsonSchema, value: unknown, path: string, issues: CustomWidgetOptionIssue[]): void {
if (schema.const !== undefined && !Object.is(value, schema.const)) {
issues.push({ path, message: "Value does not match the required constant" });
return;
}
if (Array.isArray(schema.enum) && !schema.enum.some((candidate) => Object.is(candidate, value))) {
issues.push({ path, message: "Value is not one of the allowed choices" });
return;
}
const type = schema.type;
if (typeof type === "string" && !matchesType(type, value)) {
issues.push({ path, message: `Expected ${type}` });
return;
}
if (typeof value === "string") {
if (typeof schema.minLength === "number" && value.length < schema.minLength)
issues.push({ path, message: `Must contain at least ${schema.minLength} characters` });
if (typeof schema.maxLength === "number" && value.length > schema.maxLength)
issues.push({ path, message: `Must contain at most ${schema.maxLength} characters` });
if (schema.format === "uri" && !URL.canParse(value)) issues.push({ path, message: "Must be a valid URL" });
}
if (typeof value === "number") {
if (typeof schema.minimum === "number" && value < schema.minimum)
issues.push({ path, message: `Must be at least ${schema.minimum}` });
if (typeof schema.maximum === "number" && value > schema.maximum)
issues.push({ path, message: `Must be at most ${schema.maximum}` });
if (typeof schema.multipleOf === "number" && schema.multipleOf > 0 && value % schema.multipleOf !== 0)
issues.push({ path, message: `Must be a multiple of ${schema.multipleOf}` });
}
if (Array.isArray(value)) {
if (typeof schema.minItems === "number" && value.length < schema.minItems)
issues.push({ path, message: `Choose at least ${schema.minItems} values` });
if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
issues.push({ path, message: `Choose at most ${schema.maxItems} values` });
const items = schema.items;
if (isRecord(items)) value.forEach((entry, index) => validateValue(items, entry, `${path}.${index}`, issues));
}
if (isRecord(value)) {
const branch =
isRecord(schema.if) && matchesSchema(schema.if, value)
? schema.then
: isRecord(schema.if)
? schema.else
: undefined;
const branchSchema = isRecord(branch) ? branch : {};
const properties = {
...(isRecord(schema.properties) ? schema.properties : {}),
...(isRecord(branchSchema.properties) ? branchSchema.properties : {}),
};
const required = [
...(Array.isArray(schema.required) ? schema.required : []),
...(Array.isArray(branchSchema.required) ? branchSchema.required : []),
].filter((entry): entry is string => typeof entry === "string");
for (const key of required) {
if (value[key] === undefined) issues.push({ path: `${path}.${key}`, message: "This field is required" });
}
for (const [key, child] of Object.entries(value)) {
const childSchema = properties[key];
if (isRecord(childSchema)) validateValue(childSchema, child, `${path}.${key}`, issues);
else if (schema.additionalProperties === false)
issues.push({ path: `${path}.${key}`, message: "Unknown option" });
}
}
if (isRecord(schema.if) && !isRecord(value)) {
const branch = matchesSchema(schema.if, value) ? schema.then : schema.else;
if (isRecord(branch)) validateValue(branch, value, path, issues);
}
}
function matchesSchema(schema: JsonSchema, value: unknown): boolean {
const issues: CustomWidgetOptionIssue[] = [];
validateValue(schema, value, "value", issues);
return issues.length === 0;
}
function matchesType(type: string, value: unknown): boolean {
if (type === "object") return isRecord(value);
if (type === "array") return Array.isArray(value);
if (type === "integer") return typeof value === "number" && Number.isInteger(value);
if (type === "null") return value === null;
return typeof value === type;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -0,0 +1,204 @@
import { z } from "zod/v4";
import { customWidgetMethods } from "./schema-types";
export const customJsxNetworkScopes = ["public", "private", "loopback"] as const;
export type CustomJsxNetworkScope = (typeof customJsxNetworkScopes)[number];
export const customJsxRequestParameterTypes = ["string", "number", "boolean"] as const;
export type CustomJsxRequestParameterType = (typeof customJsxRequestParameterTypes)[number];
export const customWidgetIdentifierSchema = z
.string()
.min(1)
.max(64)
.regex(/^[a-z][a-z0-9_-]*$/, "IDs must start with a letter and contain lowercase letters, numbers, - or _");
export const customWidgetParameterIdentifierSchema = z
.string()
.min(1)
.max(64)
.regex(/^[A-Za-z][A-Za-z0-9_-]*$/u, "Parameter names must start with a letter and contain letters, numbers, - or _");
const requestParametersSchema = z
.record(customWidgetParameterIdentifierSchema, 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 headerNameSchema = z
.string()
.min(1)
.max(256)
.regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, "Header names must be valid HTTP tokens")
.refine((name) => {
const normalized = name.toLowerCase();
return (
!reservedRequestHeaders.has(normalized) &&
!normalized.startsWith("proxy-") &&
!normalized.startsWith("sec-") &&
!normalized.startsWith("x-forwarded-")
);
}, "Authentication cannot use a reserved, proxy, forwarding, or hop-by-hop header");
const staticHeadersSchema = z
.record(headerNameSchema, 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",
)
.refine(
(headers) =>
Object.entries(headers).every(
([name, value]) =>
!/(^|[-_])(api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu.test(
name,
) || value.trim().length === 0,
),
"Credential-like static headers must use source authentication",
);
const collectParameterNames = (value: unknown, result = new Set<string>()): Set<string> => {
if (Array.isArray(value)) {
value.forEach((entry) => collectParameterNames(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]) => collectParameterNames(entry, result));
return result;
};
const hasNoControlCharacters = (value: string) =>
[...value].every((character) => {
const codePoint = character.codePointAt(0) ?? 0;
return codePoint >= 0x20 && codePoint !== 0x7f;
});
const authSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("none") }),
z.object({ type: z.literal("bearer") }),
z.object({ type: z.literal("basic") }),
z.object({ type: z.literal("apiKeyHeader"), headerName: headerNameSchema }),
z.object({
type: z.literal("apiKeyQuery"),
parameterName: z
.string()
.min(1)
.max(256)
.refine(hasNoControlCharacters, "Query authentication parameter names cannot contain control characters"),
}),
]);
export const customWidgetSourceSchema = z.object({
id: customWidgetIdentifierSchema,
name: z.string().trim().min(1).max(128),
baseUrl: z
.string()
.url()
.max(2048)
.superRefine((value, ctx) => {
const url = new URL(value);
if (url.protocol !== "http:" && url.protocol !== "https:") {
ctx.addIssue({ code: "custom", message: "API sources must use HTTP or HTTPS" });
}
if (url.username || url.password) {
ctx.addIssue({ code: "custom", message: "Credentials must not be embedded in an API source URL" });
}
if (url.search || url.hash) {
ctx.addIssue({ code: "custom", message: "API source URLs cannot contain a query string or fragment" });
}
}),
networkScope: z.enum(customJsxNetworkScopes),
auth: authSchema,
});
export type CustomWidgetSource = z.infer<typeof customWidgetSourceSchema>;
export const customJsxRequestSchema = z
.object({
id: customWidgetIdentifierSchema,
sourceId: customWidgetIdentifierSchema,
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,
queryTemplate: z.record(z.string().min(1).max(256), z.json()).optional(),
bodyTemplate: z.json().optional(),
staticHeaders: staticHeadersSchema.optional(),
auth: z.enum(["inherit", "none"]),
minimumBoardPermission: z.enum(["view", "modify", "full"]),
trigger: z.enum(["load", "manual"]).default("manual"),
cacheTtlSeconds: z.number().int().min(0).max(3600).optional(),
confirmation: z
.object({
title: z.string().min(1).max(128),
message: z.string().min(1).max(512),
confirmLabel: z.string().min(1).max(64).optional(),
destructive: z.boolean().optional(),
})
.optional(),
invalidates: z.array(customWidgetIdentifierSchema).max(32).optional(),
})
.superRefine((request, ctx) => {
if (request.kind === "action" && request.trigger === "load") {
ctx.addIssue({ code: "custom", path: ["trigger"], message: "Actions cannot run automatically" });
}
if (request.kind === "action" && request.cacheTtlSeconds !== undefined && request.cacheTtlSeconds !== 0) {
ctx.addIssue({ code: "custom", path: ["cacheTtlSeconds"], message: "Actions cannot be cached" });
}
if (request.kind === "query" && request.confirmation !== undefined) {
ctx.addIssue({ code: "custom", path: ["confirmation"], message: "Only actions can require confirmation" });
}
if (request.kind === "query" && request.invalidates !== undefined) {
ctx.addIssue({ code: "custom", path: ["invalidates"], message: "Only actions can invalidate queries" });
}
if (request.method === "DELETE" && request.minimumBoardPermission !== "full") {
ctx.addIssue({
code: "custom",
path: ["minimumBoardPermission"],
message: "DELETE requests require full permission",
});
}
const declared = new Set(Object.keys(request.parameters));
const used = [...request.pathTemplate.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1] ?? "");
collectParameterNames(request.queryTemplate).forEach((name) => used.push(name));
collectParameterNames(request.bodyTemplate).forEach((name) => used.push(name));
for (const name of used) {
if (!declared.has(name)) {
ctx.addIssue({ code: "custom", path: ["parameters"], message: `Placeholder '${name}' is not declared` });
}
}
});
export type CustomJsxRequest = z.infer<typeof customJsxRequestSchema>;
@@ -1,20 +1,6 @@
export const customWidgetAuthTypes = ["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery"] as const;
export type CustomWidgetAuthType = (typeof customWidgetAuthTypes)[number];
export const customWidgetDisplayTypes = [
"singleValue",
"keyValue",
"table",
"statGrid",
"progressBars",
"statusIndicator",
"countGrid",
"raw",
"actionButton",
"customJsx",
] as const;
export type CustomWidgetDisplayType = (typeof customWidgetDisplayTypes)[number];
export const customWidgetMethods = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const;
export type CustomWidgetMethod = (typeof customWidgetMethods)[number];
+15 -2
View File
@@ -1,5 +1,18 @@
export * from "./built-in-display-schemas";
import { z } from "zod/v4";
import { customWidgetImportSchema } from "./custom-jsx-schema";
export * from "./custom-jsx-schema";
export * from "./definition-schemas";
export * from "./display-config-schema";
export * from "./schema-types";
let customWidgetJsonSchema: Record<string, unknown> | undefined;
export function getCustomWidgetJsonSchema() {
customWidgetJsonSchema ??= {
...z.toJSONSchema(customWidgetImportSchema),
title: "Homarr Custom JSX v2 widget",
description: "The only supported Homarr custom-widget format. Secrets are configured separately.",
};
return customWidgetJsonSchema;
}
@@ -0,0 +1,103 @@
export const customJsxTablerIconNames = [
"activity",
"alert-circle",
"alert-triangle",
"api",
"arrow-down",
"arrow-left",
"arrow-right",
"arrow-up",
"bell",
"bluetooth",
"bolt",
"bookmark",
"bug",
"calendar",
"camera",
"chart-bar",
"chart-line",
"chart-pie",
"check",
"chevron-down",
"chevron-left",
"chevron-right",
"chevron-up",
"circle-check",
"circle-x",
"clipboard",
"clock",
"cloud",
"cloud-off",
"code",
"compass",
"copy",
"cpu",
"database",
"device-desktop",
"device-mobile",
"download",
"droplet",
"edit",
"external-link",
"eye",
"eye-off",
"file",
"flag",
"flame",
"folder",
"gauge",
"git-branch",
"heart",
"heartbeat",
"history",
"home",
"info-circle",
"key",
"link",
"loader",
"lock",
"lock-open",
"mail",
"map",
"map-pin",
"minus",
"moon",
"music",
"network",
"photo",
"pin",
"player-pause",
"player-play",
"player-skip-back",
"player-skip-forward",
"player-stop",
"plus",
"power",
"progress",
"pulse",
"refresh",
"reload",
"search",
"server",
"settings",
"shield",
"speedboat",
"star",
"sun",
"terminal",
"thermometer",
"trash",
"trending-down",
"trending-up",
"upload",
"user",
"users",
"video",
"volume",
"volume-2",
"volume-off",
"wifi",
"wifi-off",
"world",
"x",
] as const;