fix: harden v2 custom widgets and Workshop (#6480)
This commit is contained in:
1 parent
e8a2c87c2d
commit
557ebe0a2f
138 files changed
+5151
-1976
No files matched your search
@@ -1,12 +1,17 @@
|
||||
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
|
||||
import { customJsxAuthoringCatalog } from "./component-catalog";
|
||||
import {
|
||||
getCustomWidgetCredentialKeyRisk,
|
||||
isHarmlessCustomWidgetCredentialSetting,
|
||||
redactCustomWidgetCredentialLiterals,
|
||||
} from "./definition-security";
|
||||
import { customJsxExamples } from "./examples";
|
||||
|
||||
export const CUSTOM_WIDGET_MANTINE_VERSION = customJsxAuthoringCatalog.mantineVersion;
|
||||
const CUSTOM_WIDGET_AI_PROMPT_LIMIT = 12_000;
|
||||
|
||||
export const CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION =
|
||||
"Return exactly one complete `json` fenced block followed by one complete `jsx` fenced block. Do not include prose outside those blocks.";
|
||||
"Return exactly one complete `json` fenced block containing the entire widget. Put the complete JSX source directly in the `template` string and JSON-escape it correctly. Do not include prose or additional code blocks.";
|
||||
|
||||
const RECOMMENDED_COMPONENTS = [
|
||||
"Stack",
|
||||
@@ -76,14 +81,13 @@ const leanShape = `{
|
||||
"category": { "label": "Category", "control": "text", "default": "all" },
|
||||
"limit": { "label": "Result limit", "control": "number", "default": 20, "min": 1, "max": 100 }
|
||||
},
|
||||
"template": "__HOMARR_TEMPLATE__"
|
||||
"template": "<Stack><Text>{data.items?.name}</Text></Stack>"
|
||||
}`;
|
||||
|
||||
function compactExample(index: number) {
|
||||
const example = customJsxExamples[index];
|
||||
if (!example) return "";
|
||||
const { template, ...manifest } = example.widget;
|
||||
return `Example — ${example.title}:\n\n\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``;
|
||||
return `Example — ${example.title}:\n\n\`\`\`json\n${JSON.stringify(example.widget, null, 2)}\n\`\`\``;
|
||||
}
|
||||
|
||||
const AUTHORING_PROMPT = `You are writing one safe Homarr Custom JSX v2 dashboard widget for Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}.
|
||||
@@ -93,7 +97,7 @@ ${leanShape}
|
||||
|
||||
Sources are keyed by name and must include "default". Auth is "none", "bearer", "basic", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Use the stable public API URL for public services and a clear suggested URL for self-hosted services; Homarr asks the installer for their own server URL. Never put credentials in the manifest.
|
||||
|
||||
Requests are keyed by ID. Defaults are source "default", kind "query", method "GET", query trigger "load", inherited auth, and permission "view" for queries or "modify" for actions. Actions are always manual. DELETE requires full permission and receives confirmation automatically. Use {option:name} or {"$option":"name"} for saved options. Use {param:name} or {"$param":"name"} only for invocation-time params supplied by SubFetch, ActionButton, or ToggleSwitch. Load queries cannot use params. Values and primitive types are inferred from references; do not declare parameters or option bindings. Paths and query values must be primitive; JSON bodies may bind structured options.
|
||||
Requests are keyed by ID. Defaults are source "default", kind "query", method "GET", query trigger "load", inherited auth, and permission "view" for queries or "modify" for actions. Actions are always manual. DELETE is valid only for actions, requires full permission, and receives confirmation automatically. Use {option:name} or {"$option":"name"} for saved options. Use {param:name} or {"$param":"name"} only for invocation-time params supplied by SubFetch, ActionButton, or ToggleSwitch. Load queries cannot use params. Values and primitive types are inferred from references; do not declare parameters or option bindings. Paths and query values must be primitive; JSON bodies may bind structured options.
|
||||
|
||||
Options are keyed by name. Every option has label, control, and default. Controls: text, textarea, number, switch, select, multiSelect, slider, date, time, color, icon, url, duration, timeZone, json. Select choices use \`"choices": [{"label":"...","value":"..."}]\`. Dynamic choices must use \`"choicesFrom": {"request":"requestId","itemsPath":"optional.path","valuePath":"id","labelPath":"name"}\`, never an object under \`choices\`. Options are configured outside the widget and read through \`options.name\`; a bound control writes only to \`inputs.name\` and never changes an option.
|
||||
|
||||
@@ -117,7 +121,7 @@ ${compactExample(0)}
|
||||
|
||||
${compactExample(1)}
|
||||
|
||||
Output the manifest with template set exactly to "__HOMARR_TEMPLATE__", then put the complete template in the JSX block.`;
|
||||
Output one complete JSON manifest. Put the complete JSX directly in its template string so the user can copy one code block and paste it into Homarr once.`;
|
||||
|
||||
export const CUSTOM_WIDGET_AUTHORING_PROMPT = AUTHORING_PROMPT;
|
||||
|
||||
@@ -165,25 +169,42 @@ export function buildCustomWidgetAiPrompt(
|
||||
return `${truncatePromptText(sections.join("\n\n"), CUSTOM_WIDGET_AI_PROMPT_LIMIT - footer.length)}${footer}`;
|
||||
}
|
||||
|
||||
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));
|
||||
function redactValue(value: unknown, path: Array<string | number> = []): unknown {
|
||||
if (Array.isArray(value)) return value.map((entry, index) => redactValue(entry, [...path, index]));
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([entryKey, entry]) => [entryKey, redactValue(entry, entryKey)]),
|
||||
Object.entries(value).map(([entryKey, entry]) => {
|
||||
const entryPath = [...path, entryKey];
|
||||
const risk = getCustomWidgetCredentialKeyRisk(entryKey);
|
||||
if (
|
||||
risk === "strong" &&
|
||||
!isSchemaAuthenticationControl(entryPath) &&
|
||||
!isHarmlessCustomWidgetCredentialSetting(entry)
|
||||
) {
|
||||
return [entryKey, "[REDACTED]"];
|
||||
}
|
||||
if (
|
||||
risk === "ambiguous" &&
|
||||
typeof entry === "string" &&
|
||||
redactCustomWidgetCredentialLiterals(entry) !== entry
|
||||
) {
|
||||
return [entryKey, "[REDACTED]"];
|
||||
}
|
||||
return [entryKey, redactValue(entry, entryPath)];
|
||||
}),
|
||||
);
|
||||
if (typeof value === "string") {
|
||||
const key = typeof path.at(-1) === "string" ? (path.at(-1) as string) : "";
|
||||
if (["sources", "requests", "options"].includes(key)) {
|
||||
try {
|
||||
return redactValue(JSON.parse(value) as unknown);
|
||||
return redactValue(JSON.parse(value) as unknown, path);
|
||||
} catch {
|
||||
/* Keep invalid editor JSON useful. */
|
||||
}
|
||||
}
|
||||
return key === "baseUrl" || key === "iconUrl" ? redactUrl(value) : redactText(value);
|
||||
return key === "baseUrl" || key === "iconUrl"
|
||||
? redactCustomWidgetCredentialLiterals(redactUrl(value))
|
||||
: redactText(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -210,13 +231,18 @@ function redactUrl(value: string): string {
|
||||
}
|
||||
|
||||
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]",
|
||||
);
|
||||
return redactCustomWidgetCredentialLiterals(
|
||||
value.replace(/\bhttps?:\/\/[^\s"'<>]+/giu, (candidate) => redactUrl(candidate)),
|
||||
);
|
||||
}
|
||||
|
||||
function isSchemaAuthenticationControl(path: Array<string | number>): boolean {
|
||||
return (
|
||||
path.length === 3 &&
|
||||
path[2] === "auth" &&
|
||||
(path[0] === "sources" || path[0] === "requests") &&
|
||||
typeof path[1] === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function formatBudgetedCodeSection(label: string, content: string, budget: number): string | null {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "./request-schema";
|
||||
import type { CustomJsxRequest } from "./request-schema";
|
||||
import { customWidgetSecretKinds } from "./schema-types";
|
||||
import { getCustomWidgetHttpUrlIssue } from "./url-policy";
|
||||
|
||||
export * from "./options-schema";
|
||||
export * from "./request-schema";
|
||||
@@ -67,12 +68,12 @@ export const customWidgetDefinitionSchema = z
|
||||
description: z.string().max(512).optional(),
|
||||
iconUrl: z
|
||||
.string()
|
||||
.refine(
|
||||
(value) => getCustomWidgetHttpUrlIssue(value) === null,
|
||||
"Widget icons must use an unambiguous HTTP or HTTPS URL without embedded credentials",
|
||||
)
|
||||
.url()
|
||||
.refine((value) => {
|
||||
if (!URL.canParse(value)) return false;
|
||||
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")
|
||||
.max(2048)
|
||||
.optional(),
|
||||
sources: customWidgetSourcesSchema,
|
||||
requests: customWidgetRequestsSchema,
|
||||
|
||||
@@ -1,38 +1,210 @@
|
||||
import type { z } from "zod/v4";
|
||||
|
||||
const credentialKey =
|
||||
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
|
||||
type DefinitionPath = Array<string | number>;
|
||||
|
||||
const harmlessCredentialSettings = new Set([
|
||||
"anonymous",
|
||||
"authentication",
|
||||
"basic",
|
||||
"bearer",
|
||||
"configured",
|
||||
"default",
|
||||
"disabled",
|
||||
"enabled",
|
||||
"example",
|
||||
"false",
|
||||
"inherit",
|
||||
"missing",
|
||||
"none",
|
||||
"optional",
|
||||
"placeholder",
|
||||
"public",
|
||||
"redacted",
|
||||
"required",
|
||||
"separate",
|
||||
"separately",
|
||||
"source",
|
||||
"true",
|
||||
"unset",
|
||||
]);
|
||||
|
||||
const commonCredentialLiteralPattern =
|
||||
/\b(?:sk|pk|rk)-(?:[A-Za-z0-9][A-Za-z0-9._-]{7,})\b|\b(?:sk_(?:live|test)|github_pat|glpat|gh[pousr]|hf_|xox[baprs])-?[A-Za-z0-9._-]{8,}\b|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[0-9A-Za-z_-]{20,}\b|\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/giu;
|
||||
const authorizationSchemePattern = /\b(bearer|basic)([\s:_-]+)(["']?)([A-Za-z0-9._~+/%=-]{8,})/giu;
|
||||
const credentialAssignmentPattern =
|
||||
/\b(authorization|auth(?:entication)?(?:[ _-]?(?:tokens?|keys?|credentials?))?|credentials?|api[ _-]?keys?|passwords?|passwds?|secrets?|tokens?|access[ _-]?(?:tokens?|keys?)|refresh[ _-]?tokens?|client[ _-]?secrets?|private[ _-]?keys?|signing[ _-]?keys?)((?:["']?\s*[:=]\s*["']?))([^\s,;"'}<>]+)/giu;
|
||||
|
||||
export function validateCredentialFreeExport(definition: Record<string, unknown>, ctx: z.RefinementCtx) {
|
||||
inspect(definition.options, ["options"], ctx);
|
||||
inspect(definition.requests, ["requests"], ctx);
|
||||
if (typeof definition.iconUrl === "string" && URL.canParse(definition.iconUrl)) {
|
||||
const url = new URL(definition.iconUrl);
|
||||
if ([...url.searchParams.keys()].some((key) => credentialKey.test(key))) {
|
||||
ctx.addIssue({ code: "custom", path: ["iconUrl"], message: "Credentials must not be embedded in the icon URL" });
|
||||
const { secrets: _secrets, ...exportedDefinition } = definition;
|
||||
inspect(exportedDefinition, [], ctx);
|
||||
inspectRequestPathQueries(definition.requests, ctx);
|
||||
inspectUrlQuery(definition.iconUrl, ["iconUrl"], "Widget icon URLs", ctx);
|
||||
}
|
||||
|
||||
function inspect(value: unknown, path: DefinitionPath, ctx: z.RefinementCtx): void {
|
||||
if (Array.isArray(value)) return value.forEach((entry, index) => inspect(entry, [...path, index], ctx));
|
||||
if (typeof value === "string") {
|
||||
if (containsCustomWidgetCredentialLiteral(value)) {
|
||||
ctx.addIssue({ code: "custom", path, message: "Credentials must use source authentication" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof definition.template === "string" &&
|
||||
/(?:authorization\s*:\s*bearer|api[-_ ]?key\s*[:=]|password\s*[:=]|secret\s*[:=]|token\s*[:=])\s*["']?[A-Za-z0-9._~+/%=-]{8,}/iu.test(
|
||||
definition.template,
|
||||
)
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: ["template"], message: "Credentials must not be embedded in JSX" });
|
||||
if (!value || typeof value !== "object") return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const childPath = [...path, key];
|
||||
const keyRisk = getCustomWidgetCredentialKeyRisk(key);
|
||||
if (
|
||||
keyRisk === "strong" &&
|
||||
!isSchemaAuthenticationControl(childPath) &&
|
||||
hasCredentialFieldValue(child) &&
|
||||
!isHarmlessCustomWidgetCredentialSetting(child)
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path: childPath, message: "Credentials must use source authentication" });
|
||||
continue;
|
||||
}
|
||||
if (keyRisk === "ambiguous" && typeof child === "string" && containsCustomWidgetCredentialLiteral(child)) {
|
||||
ctx.addIssue({ code: "custom", path: childPath, message: "Credentials must use source authentication" });
|
||||
continue;
|
||||
}
|
||||
inspect(child, childPath, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
function inspect(value: unknown, path: Array<string | number>, ctx: z.RefinementCtx): void {
|
||||
if (Array.isArray(value)) return value.forEach((entry, index) => inspect(entry, [...path, index], ctx));
|
||||
if (!value || typeof value !== "object") return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (credentialKey.test(key) && typeof child === "string" && child.trim()) {
|
||||
ctx.addIssue({ code: "custom", path: [...path, key], message: "Credentials must use source authentication" });
|
||||
function inspectRequestPathQueries(value: unknown, ctx: z.RefinementCtx): void {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
||||
for (const [requestId, candidate] of Object.entries(value)) {
|
||||
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue;
|
||||
const path = (candidate as Record<string, unknown>).path;
|
||||
if (typeof path !== "string") continue;
|
||||
const queryStart = path.indexOf("?");
|
||||
if (queryStart < 0) continue;
|
||||
const query = path.slice(queryStart + 1);
|
||||
for (const [key, queryValue] of parseQueryEntries(query)) {
|
||||
const keyRisk = getCustomWidgetCredentialKeyRisk(key);
|
||||
if (
|
||||
(keyRisk === "strong" && queryValue.length > 0 && !isHarmlessCustomWidgetCredentialSetting(queryValue)) ||
|
||||
containsCustomWidgetCredentialLiteral(queryValue)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["requests", requestId, "path"],
|
||||
message: "Request query credentials must use source authentication",
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
inspect(child, [...path, key], ctx);
|
||||
}
|
||||
}
|
||||
|
||||
function inspectUrlQuery(value: unknown, path: DefinitionPath, label: string, ctx: z.RefinementCtx): void {
|
||||
if (typeof value !== "string" || !URL.canParse(value)) return;
|
||||
const url = new URL(value);
|
||||
if (
|
||||
parseQueryEntries(url.search).some(
|
||||
([key, queryValue]) =>
|
||||
(getCustomWidgetCredentialKeyRisk(key) === "strong" && queryValue.length > 0) ||
|
||||
containsCustomWidgetCredentialLiteral(queryValue),
|
||||
)
|
||||
) {
|
||||
ctx.addIssue({ code: "custom", path, message: `${label} cannot contain credentials` });
|
||||
}
|
||||
}
|
||||
|
||||
function parseQueryEntries(search: string): Array<[string, string]> {
|
||||
const query = search.startsWith("?") ? search.slice(1) : search;
|
||||
if (!query) return [];
|
||||
return query.split("&").map((entry) => {
|
||||
const separatorIndex = entry.indexOf("=");
|
||||
const key = separatorIndex < 0 ? entry : entry.slice(0, separatorIndex);
|
||||
const value = separatorIndex < 0 ? "" : entry.slice(separatorIndex + 1);
|
||||
return [decodeQueryPart(key), decodeQueryPart(value)];
|
||||
});
|
||||
}
|
||||
|
||||
function decodeQueryPart(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value.replaceAll("+", " "));
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
export function getCustomWidgetCredentialKeyRisk(key: string): "strong" | "ambiguous" | null {
|
||||
const normalized = key
|
||||
.replace(/([a-z0-9])([A-Z])/gu, "$1 $2")
|
||||
.replace(/[^A-Za-z0-9]+/gu, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!normalized) return null;
|
||||
const phrases = [
|
||||
"authorization",
|
||||
"authentication",
|
||||
"auth",
|
||||
"credential",
|
||||
"credentials",
|
||||
"api key",
|
||||
"api keys",
|
||||
"password",
|
||||
"passwords",
|
||||
"passwd",
|
||||
"passwds",
|
||||
"secret",
|
||||
"secrets",
|
||||
"token",
|
||||
"tokens",
|
||||
"access token",
|
||||
"access tokens",
|
||||
"access key",
|
||||
"access keys",
|
||||
"refresh token",
|
||||
"refresh tokens",
|
||||
"client secret",
|
||||
"client secrets",
|
||||
"private key",
|
||||
"private keys",
|
||||
"signing key",
|
||||
"signing keys",
|
||||
];
|
||||
if (phrases.some((phrase) => normalized === phrase || normalized.endsWith(` ${phrase}`))) return "strong";
|
||||
return normalized === "key" || normalized.endsWith(" key") || normalized === "keys" || normalized.endsWith(" keys")
|
||||
? "ambiguous"
|
||||
: null;
|
||||
}
|
||||
|
||||
export function isHarmlessCustomWidgetCredentialSetting(value: unknown): boolean {
|
||||
if (value === null || value === undefined || value === "" || typeof value === "boolean") return true;
|
||||
return typeof value === "string" && harmlessCredentialSettings.has(value.trim().toLowerCase());
|
||||
}
|
||||
|
||||
export function containsCustomWidgetCredentialLiteral(value: string): boolean {
|
||||
return redactCustomWidgetCredentialLiterals(value) !== value;
|
||||
}
|
||||
|
||||
export function redactCustomWidgetCredentialLiterals(value: string): string {
|
||||
return value
|
||||
.replace(commonCredentialLiteralPattern, "[REDACTED]")
|
||||
.replace(authorizationSchemePattern, (match, scheme: string, separator: string, quote: string, candidate: string) =>
|
||||
isHarmlessCustomWidgetCredentialSetting(candidate) ? match : `${scheme}${separator}${quote}[REDACTED]`,
|
||||
)
|
||||
.replace(credentialAssignmentPattern, (match, key: string, separator: string, candidate: string) =>
|
||||
isHarmlessCustomWidgetCredentialSetting(candidate) ? match : `${key}${separator}[REDACTED]`,
|
||||
);
|
||||
}
|
||||
|
||||
function isSchemaAuthenticationControl(path: DefinitionPath): boolean {
|
||||
return (
|
||||
path.length === 3 &&
|
||||
path[2] === "auth" &&
|
||||
(path[0] === "sources" || path[0] === "requests") &&
|
||||
typeof path[1] === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function hasCredentialFieldValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined || value === "") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function validatePrototypeKeys(value: unknown, ctx: z.RefinementCtx) {
|
||||
walk(value, [], ctx);
|
||||
}
|
||||
|
||||
@@ -69,10 +69,6 @@ function removedStateIssues(value: Record<string, unknown>): CustomWidgetImportI
|
||||
);
|
||||
}
|
||||
|
||||
function isTemplatePlaceholder(value: unknown) {
|
||||
return typeof value === "string" && value.replace(/[\\*_`\s]/gu, "").toUpperCase() === "HOMARRTEMPLATE";
|
||||
}
|
||||
|
||||
type ParsedWidgetValue =
|
||||
| { success: true; value: Record<string, unknown> }
|
||||
| { success: false; issue: CustomWidgetImportIssue };
|
||||
@@ -100,24 +96,10 @@ export function parseCustomWidgetClipboard(text: string): HomarrCustomWidgetV2 |
|
||||
export function parseCustomWidgetClipboardDetailed(text: string): CustomWidgetParseResult {
|
||||
const blocks = extractFencedBlocks(text);
|
||||
const jsonBlock = blocks.find((block) => block.language === "json" || block.language === "");
|
||||
const jsxBlock = blocks.find((block) => block.language === "jsx" || block.language === "tsx");
|
||||
const source = jsonBlock?.content ?? text;
|
||||
const parsedValue = parseWidgetValue(source);
|
||||
if (!parsedValue.success) return { success: false, issues: [parsedValue.issue] };
|
||||
const widget = { ...parsedValue.value };
|
||||
if (jsonBlock && isTemplatePlaceholder(widget.template) && !jsxBlock) {
|
||||
return {
|
||||
success: false,
|
||||
issues: [
|
||||
{
|
||||
code: "MISSING_JSX_BLOCK",
|
||||
path: ["template"],
|
||||
message: "The manifest uses a template placeholder but no fenced JSX block was provided.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (jsxBlock && isTemplatePlaceholder(widget.template)) widget.template = jsxBlock.content.trim();
|
||||
const removedIssues = removedStateIssues(widget);
|
||||
if (removedIssues.length > 0) return { success: false, issues: removedIssues };
|
||||
const parsed = customWidgetImportSchema.safeParse(widget);
|
||||
@@ -128,20 +110,17 @@ export function parseCustomWidgetClipboardDetailed(text: string): CustomWidgetPa
|
||||
export function parseCustomWidgetAiResponse(text: string): CustomWidgetParseResult {
|
||||
const blocks = extractFencedBlocks(text);
|
||||
const jsonBlocks = blocks.filter((block) => block.language === "json" || block.language === "");
|
||||
const jsxBlocks = blocks.filter((block) => block.language === "jsx" || block.language === "tsx");
|
||||
const formatIssues: CustomWidgetImportIssue[] = [];
|
||||
if (jsonBlocks.length !== 1)
|
||||
formatIssues.push({ code: "AI_JSON_BLOCK_REQUIRED", message: "Expected exactly one fenced json block." });
|
||||
if (jsxBlocks.length !== 1)
|
||||
formatIssues.push({ code: "AI_JSX_BLOCK_REQUIRED", message: "Expected exactly one fenced jsx block." });
|
||||
if (blocks.length !== jsonBlocks.length)
|
||||
formatIssues.push({
|
||||
code: "AI_SINGLE_JSON_BLOCK_REQUIRED",
|
||||
message: "Expected one JSON block only. Put the complete JSX directly in its template field.",
|
||||
});
|
||||
const source = jsonBlocks[0]?.content ?? text;
|
||||
const parsedValue = parseWidgetValue(source);
|
||||
if (!parsedValue.success) {
|
||||
if (/\\_/u.test(source))
|
||||
formatIssues.push({
|
||||
code: "INVALID_JSON_ESCAPE",
|
||||
message: 'JSON does not allow \\_ escapes. The template placeholder must be "__HOMARR_TEMPLATE__".',
|
||||
});
|
||||
if (/"(?:stateSchema|defaultState)"\s*:/u.test(source))
|
||||
formatIssues.push({
|
||||
code: "REMOVED_LOCAL_STATE",
|
||||
@@ -153,15 +132,6 @@ export function parseCustomWidgetAiResponse(text: string): CustomWidgetParseResu
|
||||
const removedIssues = removedStateIssues(widget);
|
||||
if (removedIssues.length > 0) formatIssues.push(...removedIssues);
|
||||
const warnings: CustomWidgetImportIssue[] = [];
|
||||
if (jsxBlocks[0]) {
|
||||
if (isTemplatePlaceholder(widget.template) || !widget.template) widget.template = jsxBlocks[0].content.trim();
|
||||
else if (widget.template !== jsxBlocks[0].content.trim())
|
||||
formatIssues.push({
|
||||
code: "AI_TEMPLATE_PLACEHOLDER_REQUIRED",
|
||||
path: ["template"],
|
||||
message: 'The manifest template must be "__HOMARR_TEMPLATE__" when a separate JSX block is returned.',
|
||||
});
|
||||
}
|
||||
if (formatIssues.length > 0) return { success: false, issues: formatIssues.slice(0, MAX_IMPORT_ISSUES) };
|
||||
const parsed = customWidgetImportSchema.safeParse(widget);
|
||||
if (!parsed.success) return { success: false, issues: zodIssues(parsed.error) };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { customWidgetMethods } from "./schema-types";
|
||||
import { getCustomWidgetHttpUrlIssue } from "./url-policy";
|
||||
|
||||
export const customJsxNetworkScopes = ["public", "private", "loopback"] as const;
|
||||
export type CustomJsxNetworkScope = (typeof customJsxNetworkScopes)[number];
|
||||
@@ -26,10 +27,9 @@ const authSchema = z.union([
|
||||
export type CustomWidgetSourceUrlIssue = "invalid" | "protocol" | "credentials" | "queryOrFragment";
|
||||
|
||||
export function getCustomWidgetSourceUrlIssue(value: string): CustomWidgetSourceUrlIssue | null {
|
||||
if (!URL.canParse(value)) return "invalid";
|
||||
const issue = getCustomWidgetHttpUrlIssue(value);
|
||||
if (issue) return issue;
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return "protocol";
|
||||
if (url.username || url.password) return "credentials";
|
||||
if (url.search || url.hash) return "queryOrFragment";
|
||||
return null;
|
||||
}
|
||||
@@ -45,12 +45,12 @@ export const customWidgetSourceSchema = z.strictObject({
|
||||
name: z.string().trim().min(1).max(128).optional(),
|
||||
baseUrl: z
|
||||
.string()
|
||||
.url()
|
||||
.max(2048)
|
||||
.superRefine((value, ctx) => {
|
||||
const issue = getCustomWidgetSourceUrlIssue(value);
|
||||
if (issue && issue !== "invalid") ctx.addIssue({ code: "custom", message: sourceUrlIssueMessages[issue] });
|
||||
}),
|
||||
if (issue) ctx.addIssue({ code: "custom", message: sourceUrlIssueMessages[issue] });
|
||||
})
|
||||
.url()
|
||||
.max(2048),
|
||||
networkScope: z.enum(customJsxNetworkScopes),
|
||||
auth: authSchema.default("none"),
|
||||
});
|
||||
@@ -157,6 +157,15 @@ export const customJsxRequestSchema = z
|
||||
confirmation: confirmationSchema.optional(),
|
||||
invalidates: z.array(customWidgetIdentifierSchema).max(32).optional(),
|
||||
})
|
||||
.superRefine((request, context) => {
|
||||
if (request.method === "DELETE" && request.kind !== "action") {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["kind"],
|
||||
message: "DELETE requests must be manual actions",
|
||||
});
|
||||
}
|
||||
})
|
||||
.transform((request) => {
|
||||
const confirmation =
|
||||
request.method === "DELETE" && request.confirmation === undefined
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
export type CustomWidgetHttpUrlIssue = "invalid" | "protocol" | "credentials";
|
||||
|
||||
const forbiddenUnicodeCodePointRanges = [
|
||||
[0x0000, 0x0020],
|
||||
[0x007f, 0x00a0],
|
||||
[0x1680, 0x1680],
|
||||
[0x2000, 0x200f],
|
||||
[0x2028, 0x202f],
|
||||
[0x205f, 0x206f],
|
||||
[0x3000, 0x3000],
|
||||
[0xfeff, 0xfeff],
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Applies the conservative URL syntax shared by Homarr and the Workshop
|
||||
* validator. WHATWG URL parsing intentionally accepts and normalizes several
|
||||
* ambiguous spellings (for example IPv4 integers, backslashes and escaped
|
||||
* hostnames). Definitions are persisted and later used for network requests,
|
||||
* so authoring accepts only an unambiguous authority spelling.
|
||||
*/
|
||||
export function getCustomWidgetHttpUrlIssue(value: string): CustomWidgetHttpUrlIssue | null {
|
||||
if (hasForbiddenUrlCharacter(value) || value.includes("\\")) return "invalid";
|
||||
if (!URL.canParse(value)) return "invalid";
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return "invalid";
|
||||
}
|
||||
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return "protocol";
|
||||
|
||||
const authority = getRawAuthority(value);
|
||||
if (authority === null) return "invalid";
|
||||
if (authority.includes("@") || url.username || url.password) return "credentials";
|
||||
if (authority.includes("%") || /[。.。]/u.test(authority)) return "invalid";
|
||||
|
||||
const hostAndPort = splitHostAndPort(authority);
|
||||
if (!hostAndPort || !hasCanonicalPort(hostAndPort.port)) return "invalid";
|
||||
|
||||
const rawHostname = withoutTrailingRootDot(hostAndPort.hostname);
|
||||
const parsedHostname = withoutTrailingRootDot(url.hostname);
|
||||
if (!rawHostname || !hasCanonicalParsedHostname(parsedHostname)) return "invalid";
|
||||
if (
|
||||
rawHostname.startsWith("[") &&
|
||||
parsedHostname.startsWith("[") &&
|
||||
!rawHostname.includes(".") &&
|
||||
rawHostname.toLowerCase() !== parsedHostname
|
||||
) {
|
||||
return "invalid";
|
||||
}
|
||||
|
||||
if (looksNumeric(rawHostname) && !isStrictIpv4(rawHostname)) return "invalid";
|
||||
if (isStrictIpv4(parsedHostname) && rawHostname !== parsedHostname) return "invalid";
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getRawAuthority(value: string): string | null {
|
||||
const match = value.match(/^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/u);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function splitHostAndPort(authority: string): { hostname: string; port: string } | null {
|
||||
if (authority.startsWith("[")) {
|
||||
const closingBracket = authority.indexOf("]");
|
||||
if (closingBracket < 0) return null;
|
||||
const hostname = authority.slice(0, closingBracket + 1);
|
||||
const suffix = authority.slice(closingBracket + 1);
|
||||
if (suffix && !suffix.startsWith(":")) return null;
|
||||
return { hostname, port: suffix ? suffix.slice(1) : "" };
|
||||
}
|
||||
|
||||
const firstColon = authority.indexOf(":");
|
||||
if (firstColon !== authority.lastIndexOf(":")) return null;
|
||||
return {
|
||||
hostname: firstColon < 0 ? authority : authority.slice(0, firstColon),
|
||||
port: firstColon < 0 ? "" : authority.slice(firstColon + 1),
|
||||
};
|
||||
}
|
||||
|
||||
function hasCanonicalPort(value: string): boolean {
|
||||
if (!value) return true;
|
||||
if (!/^(?:0|[1-9]\d{0,4})$/u.test(value)) return false;
|
||||
return Number(value) <= 65_535;
|
||||
}
|
||||
|
||||
function hasCanonicalParsedHostname(value: string): boolean {
|
||||
if (value.startsWith("[") && value.endsWith("]")) return true;
|
||||
if (!value || value.length > 253 || !/^[A-Za-z0-9._-]+$/u.test(value)) return false;
|
||||
return value
|
||||
.split(".")
|
||||
.every((label) => Boolean(label) && label.length <= 63 && !label.startsWith("-") && !label.endsWith("-"));
|
||||
}
|
||||
|
||||
function looksNumeric(value: string): boolean {
|
||||
const parts = value.split(".");
|
||||
return parts.every((part) => /^(?:\d+|0[xX][0-9A-Fa-f]+)$/u.test(part));
|
||||
}
|
||||
|
||||
function isStrictIpv4(value: string): boolean {
|
||||
const parts = value.split(".");
|
||||
return parts.length === 4 && parts.every((part) => /^(?:0|[1-9]\d{0,2})$/u.test(part) && Number(part) <= 255);
|
||||
}
|
||||
|
||||
function withoutTrailingRootDot(value: string): string {
|
||||
return value.endsWith(".") ? value.slice(0, -1) : value;
|
||||
}
|
||||
|
||||
function hasForbiddenUrlCharacter(value: string): boolean {
|
||||
return [...value].some((character) => {
|
||||
const codePoint = character.codePointAt(0) ?? 0;
|
||||
return forbiddenUnicodeCodePointRanges.some(([minimum, maximum]) => codePoint >= minimum && codePoint <= maximum);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user