feat(custom-widgets): complete JSX v2
This commit is contained in:
263 files changed
+65503
-17816
No files matched your search
@@ -14,7 +14,8 @@
|
||||
"./websocket": "./src/websocket.ts",
|
||||
"./shared": "./src/shared.ts",
|
||||
"./open-api": "./src/open-api.ts",
|
||||
"./mcp": "./src/mcp.ts"
|
||||
"./mcp": "./src/mcp.ts",
|
||||
"./custom-widget-secrets": "./src/router/custom-widget/secret-requests.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf .turbo node_modules",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
interface CacheVersionDefinition {
|
||||
sources: string;
|
||||
requests: string;
|
||||
secrets: Array<{ sourceId: string; kind: string; encryptedValue: string }>;
|
||||
}
|
||||
|
||||
export function getCustomWidgetCacheVersion(definition: CacheVersionDefinition) {
|
||||
const secrets = definition.secrets
|
||||
.map(({ sourceId, kind, encryptedValue }) => ({ sourceId, kind, encryptedValue }))
|
||||
.toSorted((left, right) => `${left.sourceId}:${left.kind}`.localeCompare(`${right.sourceId}:${right.kind}`));
|
||||
return createHash("sha256")
|
||||
.update(JSON.stringify([definition.sources, definition.requests, secrets]))
|
||||
.digest("hex")
|
||||
.slice(0, 16);
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { stringify as stringifySuperJson } from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import { eq } from "@homarr/db";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { and, eq, notInArray } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import {
|
||||
customWidgetCreateSchema,
|
||||
customWidgetDefinitionSchema,
|
||||
customWidgetUpdateSchema,
|
||||
customJsxDisplayConfigV2Schema,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
|
||||
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
|
||||
@@ -19,210 +18,156 @@ import { metadataProcedures } from "./metadata-procedures";
|
||||
import { previewActionProcedures } from "./preview-action-procedures";
|
||||
import { previewBaseProcedures } from "./preview-base-procedures";
|
||||
import { previewQueryProcedures } from "./preview-query-procedures";
|
||||
import { parseDisplayConfig } from "./parse-display-config";
|
||||
import { transferProcedures } from "./transfer-procedures";
|
||||
import { parseStoredCustomWidgetDefinition, serializeCustomWidgetDefinition } from "./stored-definition";
|
||||
import { templateProcedures } from "./template-procedures";
|
||||
import { transferProcedures } from "./transfer-procedures";
|
||||
import { assertSecretSources, requiredSecretKinds } from "./secret-policy";
|
||||
import { secretProcedures } from "./secret-procedures";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
|
||||
const updateFieldSerializers: Record<string, (value: unknown) => unknown> = {
|
||||
displayConfig: (value) => stringifySuperJson(value),
|
||||
};
|
||||
|
||||
export const customWidgetRouter = createTRPCRouter({
|
||||
...metadataProcedures,
|
||||
|
||||
...managementQueryProcedures,
|
||||
|
||||
create: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Create a validated custom widget. Admin only. Call customWidget_schema and customWidget_validate first. For Custom JSX use jsxApiVersion 2, named requests, a GET base method, and no inline credentials.",
|
||||
},
|
||||
})
|
||||
create: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Create one validated Custom JSX widget." } })
|
||||
.input(customWidgetCreateSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { secrets, ...candidate } = input;
|
||||
if (secrets.length > 0 && !ctx.session.user.permissions.includes("custom-widget-secret-write")) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Writing custom widget secrets requires dedicated permission",
|
||||
});
|
||||
}
|
||||
const definition = customWidgetDefinitionSchema.parse(candidate);
|
||||
assertSecretSources(definition.sources, secrets);
|
||||
const id = createId();
|
||||
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
name: input.name,
|
||||
description: input.description,
|
||||
iconUrl: input.iconUrl,
|
||||
url: input.url,
|
||||
authType: input.authType,
|
||||
headerName: input.headerName,
|
||||
method: input.method,
|
||||
requestBody: input.requestBody,
|
||||
displayType: input.displayType,
|
||||
displayConfig: stringifySuperJson(input.displayConfig),
|
||||
...serializeCustomWidgetDefinition(definition),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
|
||||
if (input.secrets.length > 0) {
|
||||
if (secrets.length > 0) {
|
||||
await ctx.db.insert(customWidgetSecrets).values(
|
||||
input.secrets.map((secret) => ({
|
||||
kind: secret.kind,
|
||||
value: encryptSecret(secret.value),
|
||||
secrets.map((secret) => ({
|
||||
definitionId: id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
logger.info("Created custom widget definition", { id, name: input.name });
|
||||
logger.info("Created custom widget definition", { id, name: definition.name });
|
||||
return { id };
|
||||
}),
|
||||
|
||||
update: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Update an existing custom widget. Admin only. REQUIRED: id. Read it with customWidget_byId, preserve unrelated fields, validate the resulting complete draft, then send the changed fields. Omit secrets to preserve stored credentials.",
|
||||
},
|
||||
})
|
||||
update: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Update one Custom JSX widget." } })
|
||||
.input(customWidgetUpdateSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
if (!existing) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const effectiveDisplayConfig =
|
||||
input.displayConfig ??
|
||||
parseDisplayConfig(existing.displayConfig, input.id, logger, "Corrupt displayConfig in custom widget update");
|
||||
const effectiveMethod = input.method ?? existing.method;
|
||||
if (customJsxDisplayConfigV2Schema.safeParse(effectiveDisplayConfig).success && effectiveMethod !== "GET") {
|
||||
const current = parseStoredCustomWidgetDefinition(existing);
|
||||
const { id, secrets, ...changes } = input;
|
||||
if (secrets?.length && !ctx.session.user.permissions.includes("custom-widget-secret-write")) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Custom JSX v2 base data requests must use GET; mutations belong in named actions",
|
||||
code: "FORBIDDEN",
|
||||
message: "Writing custom widget secrets requires dedicated permission",
|
||||
});
|
||||
}
|
||||
const definition = customWidgetDefinitionSchema.parse({ ...current, ...changes });
|
||||
if (secrets) assertSecretSources(definition.sources, secrets);
|
||||
|
||||
const { id, secrets, ...updateFields } = input;
|
||||
const updateValues: Record<string, unknown> = { updatedAt: new Date() };
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ ...serializeCustomWidgetDefinition(definition), updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, id));
|
||||
|
||||
for (const [key, value] of Object.entries(updateFields)) {
|
||||
if (value === undefined) continue;
|
||||
const serialize = updateFieldSerializers[key];
|
||||
if (serialize) {
|
||||
updateValues[key] = serialize(value);
|
||||
} else {
|
||||
updateValues[key] = value;
|
||||
}
|
||||
await ctx.db.delete(customWidgetSecrets).where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, id),
|
||||
notInArray(
|
||||
customWidgetSecrets.sourceId,
|
||||
definition.sources.map((source) => source.id),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (const source of definition.sources) {
|
||||
const kinds = [...requiredSecretKinds(source.auth.type)];
|
||||
const where = and(eq(customWidgetSecrets.definitionId, id), eq(customWidgetSecrets.sourceId, source.id));
|
||||
await ctx.db
|
||||
.delete(customWidgetSecrets)
|
||||
.where(kinds.length > 0 ? and(where, notInArray(customWidgetSecrets.kind, kinds)) : where);
|
||||
}
|
||||
|
||||
await ctx.db.update(customWidgetDefinitions).set(updateValues).where(eq(customWidgetDefinitions.id, id));
|
||||
|
||||
if (secrets !== undefined) {
|
||||
const effectiveAuthType = (updateFields.authType as string | undefined) ?? existing.authType;
|
||||
|
||||
if (secrets.length > 0) {
|
||||
await ctx.db.delete(customWidgetSecrets).where(eq(customWidgetSecrets.definitionId, id));
|
||||
await ctx.db.insert(customWidgetSecrets).values(
|
||||
secrets.map((secret) => ({
|
||||
kind: secret.kind,
|
||||
value: encryptSecret(secret.value),
|
||||
definitionId: id,
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
);
|
||||
} else if (
|
||||
effectiveAuthType === "none" ||
|
||||
(typeof updateFields.authType === "string" && updateFields.authType !== existing.authType)
|
||||
) {
|
||||
await ctx.db.delete(customWidgetSecrets).where(eq(customWidgetSecrets.definitionId, id));
|
||||
for (const secret of secrets) {
|
||||
await ctx.db
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, id),
|
||||
eq(customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
await ctx.db.insert(customWidgetSecrets).values({
|
||||
definitionId: id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("Updated custom widget definition", { id });
|
||||
}),
|
||||
|
||||
toggleEnabled: adminProcedure
|
||||
...secretProcedures,
|
||||
|
||||
toggleEnabled: manageProcedure
|
||||
.input(z.object({ id: z.string(), enabled: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ enabled: input.enabled, updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, input.id));
|
||||
}),
|
||||
|
||||
delete: adminProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
|
||||
delete: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Delete one Custom JSX widget." } })
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ctx.db.delete(customWidgetDefinitions).where(eq(customWidgetDefinitions.id, input.id));
|
||||
logger.info("Deleted custom widget definition", { id: input.id });
|
||||
}),
|
||||
|
||||
duplicate: manageProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
await ctx.db.delete(customWidgetDefinitions).where(eq(customWidgetDefinitions.id, input.id));
|
||||
logger.info("Deleted custom widget definition", { id: input.id });
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
const current = parseStoredCustomWidgetDefinition(existing);
|
||||
const id = createId();
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
...serializeCustomWidgetDefinition({ ...current, name: `${current.name} (copy)` }),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
return { id, name: `${current.name} (copy)` };
|
||||
}),
|
||||
|
||||
...templateProcedures,
|
||||
|
||||
...transferProcedures,
|
||||
|
||||
...previewBaseProcedures,
|
||||
...previewQueryProcedures,
|
||||
...previewActionProcedures,
|
||||
|
||||
duplicate: adminProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
with: { secrets: true },
|
||||
});
|
||||
|
||||
if (!definition) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const newId = createId();
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id: newId,
|
||||
name: `${definition.name} (copy)`,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl,
|
||||
url: definition.url,
|
||||
authType: definition.authType,
|
||||
headerName: definition.headerName,
|
||||
method: definition.method,
|
||||
requestBody: definition.requestBody,
|
||||
displayType: definition.displayType,
|
||||
displayConfig: definition.displayConfig,
|
||||
enabled: definition.enabled,
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
|
||||
if (definition.secrets.length > 0) {
|
||||
await ctx.db.insert(customWidgetSecrets).values(
|
||||
definition.secrets.map((s) => ({
|
||||
kind: s.kind,
|
||||
value: s.value,
|
||||
definitionId: newId,
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
logger.info("Duplicated custom widget definition", { sourceId: input.id, newId });
|
||||
return { id: newId, name: `${definition.name} (copy)` };
|
||||
}),
|
||||
});
|
||||
@@ -1,51 +1,51 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { eq, or } from "@homarr/db";
|
||||
import { boards, customWidgetDefinitions } from "@homarr/db/schema";
|
||||
|
||||
import { permissionRequiredProcedure, protectedProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
import { parseDisplayConfig } from "./parse-display-config";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
import { executeCustomWidgetRequest } from "./request-executor";
|
||||
import { hashRuntimeParams, renderRequestBody, renderRequestTarget } from "./request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import { getCustomWidgetCacheVersion } from "./cache-version";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
|
||||
export const managementQueryProcedures = {
|
||||
all: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"List all custom-widget definitions. Admin only. Use the returned ID to inspect or update a widget.",
|
||||
},
|
||||
})
|
||||
list: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "List all Custom JSX widgets." } })
|
||||
.query(async ({ ctx }) => {
|
||||
const definitions = await ctx.db.query.customWidgetDefinitions.findMany({
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
});
|
||||
return definitions.map((definition) => ({
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl,
|
||||
url: definition.url,
|
||||
method: definition.method,
|
||||
displayType: definition.displayType,
|
||||
authType: definition.authType,
|
||||
enabled: definition.enabled,
|
||||
}));
|
||||
return definitions.map((definition) => {
|
||||
const widget = parseStoredCustomWidgetDefinition(definition);
|
||||
return {
|
||||
id: definition.id,
|
||||
name: widget.name,
|
||||
description: widget.description,
|
||||
iconUrl: widget.iconUrl,
|
||||
sources: widget.sources.map(({ id, name, baseUrl, networkScope, auth }) => ({
|
||||
id,
|
||||
name,
|
||||
origin: new URL(baseUrl).origin,
|
||||
networkScope,
|
||||
authType: auth.type,
|
||||
})),
|
||||
requestCount: widget.requests.length,
|
||||
defaultOptions: widget.defaultOptions,
|
||||
updatedAt: definition.updatedAt,
|
||||
enabled: definition.enabled,
|
||||
};
|
||||
});
|
||||
}),
|
||||
|
||||
byId: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Get one complete custom-widget definition for iterative editing. REQUIRED: id. Stored secret values are never returned; only their presence is reported.",
|
||||
},
|
||||
})
|
||||
get: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Get one Custom JSX widget without secret values." } })
|
||||
.input(z.object({ id: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
@@ -54,14 +54,13 @@ export const managementQueryProcedures = {
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
return {
|
||||
...definition,
|
||||
displayConfig: parseDisplayConfig(
|
||||
definition.displayConfig,
|
||||
input.id,
|
||||
logger,
|
||||
"Corrupt displayConfig in custom widget",
|
||||
),
|
||||
id: definition.id,
|
||||
...parseStoredCustomWidgetDefinition(definition),
|
||||
enabled: definition.enabled,
|
||||
createdAt: definition.createdAt,
|
||||
updatedAt: definition.updatedAt,
|
||||
secrets: definition.secrets.map((secret) => ({
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
hasValue: true,
|
||||
updatedAt: secret.updatedAt,
|
||||
@@ -73,12 +72,114 @@ export const managementQueryProcedures = {
|
||||
.input(z.object({ boardId: z.string(), currentId: z.string().optional() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
|
||||
return ctx.db.query.customWidgetDefinitions.findMany({
|
||||
const definitions = await ctx.db.query.customWidgetDefinitions.findMany({
|
||||
where: input.currentId
|
||||
? or(eq(customWidgetDefinitions.enabled, true), eq(customWidgetDefinitions.id, input.currentId))
|
||||
: eq(customWidgetDefinitions.enabled, true),
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
columns: { id: true, name: true, description: true, iconUrl: true, displayType: true },
|
||||
});
|
||||
return definitions.map((definition) => {
|
||||
const widget = parseStoredCustomWidgetDefinition(definition);
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl,
|
||||
optionsSchema: widget.optionsSchema,
|
||||
defaultOptions: widget.defaultOptions,
|
||||
template: widget.template,
|
||||
stateSchema: widget.stateSchema ?? {},
|
||||
defaultState: widget.defaultState ?? {},
|
||||
sources: widget.sources.map(({ id, name, networkScope, auth }) => ({
|
||||
id,
|
||||
name,
|
||||
networkScope,
|
||||
authType: auth.type,
|
||||
})),
|
||||
requestCapabilities: widget.requests.map(
|
||||
({ id, kind, method, trigger, minimumBoardPermission, confirmation, invalidates }) => ({
|
||||
id,
|
||||
kind,
|
||||
method,
|
||||
trigger,
|
||||
minimumBoardPermission,
|
||||
confirmation,
|
||||
invalidates,
|
||||
}),
|
||||
),
|
||||
optionRequests: widget.requests
|
||||
.filter((request) => request.kind === "query")
|
||||
.map(({ id, parameters }) => ({ id, parameters })),
|
||||
updatedAt: definition.updatedAt,
|
||||
};
|
||||
});
|
||||
}),
|
||||
|
||||
optionRequest: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
boardId: z.string(),
|
||||
definitionId: z.string(),
|
||||
requestId: z.string(),
|
||||
params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
|
||||
const stored = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!stored || !stored.enabled) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget not found" });
|
||||
const definition = parseStoredCustomWidgetDefinition(stored);
|
||||
const request = definition.requests.find(
|
||||
(candidate) => candidate.id === input.requestId && candidate.kind === "query",
|
||||
);
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND", message: "Option query not found" });
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), request.minimumBoardPermission);
|
||||
const source = definition.sources.find((candidate) => candidate.id === request.sourceId);
|
||||
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Option query source not found" });
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category: "query",
|
||||
userId: ctx.session.user.id,
|
||||
itemId: `configuration:${input.boardId}`,
|
||||
definitionId: input.definitionId,
|
||||
});
|
||||
try {
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: source.baseUrl,
|
||||
targetUrl: renderRequestTarget(source.baseUrl, request, input.params),
|
||||
method: request.method,
|
||||
body: renderRequestBody(request.bodyTemplate, input.params),
|
||||
staticHeaders: request.staticHeaders,
|
||||
auth:
|
||||
request.auth === "none" || source.auth.type === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: source.auth.type,
|
||||
secrets: stored.secrets
|
||||
.filter((secret) => secret.sourceId === source.id)
|
||||
.map((secret) => ({ kind: secret.kind, value: decryptSecret(secret.encryptedValue) })),
|
||||
headerName:
|
||||
source.auth.type === "apiKeyHeader"
|
||||
? source.auth.headerName
|
||||
: source.auth.type === "apiKeyQuery"
|
||||
? source.auth.parameterName
|
||||
: undefined,
|
||||
},
|
||||
networkScope: source.networkScope,
|
||||
kind: "query",
|
||||
cacheKey: `custom-widget:options:${input.definitionId}:${getCustomWidgetCacheVersion(stored)}:${request.id}:${hashRuntimeParams(input.params)}`,
|
||||
cacheTtlSeconds: request.cacheTtlSeconds ?? 30,
|
||||
});
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
data: response.data,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}),
|
||||
};
|
||||
@@ -1,41 +1,38 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
import {
|
||||
CUSTOM_WIDGET_MCP_AUTHORING_PROMPT,
|
||||
customWidgetImportSchema,
|
||||
getCustomWidgetJsonSchema,
|
||||
getCustomWidgetSkill,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure, publicProcedure } from "../../trpc";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
let schemaCache: Record<string, unknown> | undefined;
|
||||
|
||||
function getImportJsonSchema() {
|
||||
schemaCache ??= {
|
||||
...z.toJSONSchema(customWidgetImportSchema),
|
||||
title: "Homarr Custom Widget",
|
||||
description:
|
||||
"Schema for importing/exporting custom widget definitions in Homarr. All jsonPath fields use JSONPath syntax. The displayConfig must match displayType. Secrets are configured separately after import.",
|
||||
};
|
||||
return schemaCache;
|
||||
}
|
||||
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
export const metadataProcedures = {
|
||||
schema: publicProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Get the JSON Schema for Homarr custom-widget imports. Use this before generating a widget and before calling validate, create, or update.",
|
||||
},
|
||||
})
|
||||
.query(() => getImportJsonSchema()),
|
||||
.meta({ mcp: { enabled: true, description: "Get the current Custom JSX widget JSON Schema." } })
|
||||
.query(() => getCustomWidgetJsonSchema()),
|
||||
|
||||
validate: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Validate a complete custom-widget JSON draft without saving or making network requests. Returns structured issue paths so an agent can correct and validate again.",
|
||||
},
|
||||
})
|
||||
getAuthoringPrompt: publicProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Get the current Custom Widget authoring instructions." } })
|
||||
.query(() => ({
|
||||
version: 2,
|
||||
prompt: CUSTOM_WIDGET_MCP_AUTHORING_PROMPT,
|
||||
resources: [
|
||||
"homarr://custom-widgets/schema",
|
||||
"homarr://custom-widgets/components",
|
||||
"homarr://custom-widgets/skill",
|
||||
],
|
||||
})),
|
||||
|
||||
getSkill: publicProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Get the portable Homarr Custom Widget skill." } })
|
||||
.query(() => getCustomWidgetSkill()),
|
||||
|
||||
validate: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Validate one Custom JSX widget without saving it." } })
|
||||
.input(z.object({ widget: z.unknown() }))
|
||||
.query(({ input }) => {
|
||||
const result = customWidgetImportSchema.safeParse(input.widget);
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { parse as parseSuperJson } from "superjson";
|
||||
|
||||
import type { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { displayConfigSchema } from "@homarr/custom-widgets/core";
|
||||
import type { DisplayConfig } from "@homarr/custom-widgets/core";
|
||||
|
||||
type Logger = ReturnType<typeof createLogger>;
|
||||
|
||||
export function parseDisplayConfig(raw: string, id: string, logger: Logger, context: string): DisplayConfig {
|
||||
try {
|
||||
return displayConfigSchema.parse(parseSuperJson(raw));
|
||||
} catch {
|
||||
logger.error(context, { id });
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Widget has corrupt display configuration" });
|
||||
}
|
||||
}
|
||||
@@ -2,50 +2,23 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { previewSessionRequestSchema, recordPreviewJournal } from "./preview-procedure-helpers";
|
||||
import { executeCustomWidgetRequest } from "./request-executor";
|
||||
import {
|
||||
getPreviewRequestSource,
|
||||
previewSessionRequestSchema,
|
||||
recordPreviewJournal,
|
||||
} from "./preview-procedure-helpers";
|
||||
import { executeCustomWidgetRequest, invalidateCustomWidgetResponseCache } from "./request-executor";
|
||||
import { renderRequestBody, renderRequestTarget } from "./request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import { getPreviewSession, getPreviewSessionSecrets } from "./preview-sessions";
|
||||
import { getPreviewSession } from "./preview-sessions";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
|
||||
export const previewActionProcedures = {
|
||||
simulatePreviewAction: adminProcedure
|
||||
previewAction: manageProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Validate and simulate one named custom-widget action without sending a network request. REQUIRED: sessionId from customWidget_preview, action requestId, and typed params. Confirms parameter substitution and records a simulated journal entry. Returns requiredPermission as the action's minimum board permission (view, modify, or full), not as an execution result. This MCP tool never enables or executes live actions.",
|
||||
},
|
||||
mcp: { enabled: true, description: "Simulate or run one named action in a custom widget preview session." },
|
||||
})
|
||||
.input(previewSessionRequestSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
|
||||
const request = session.requests.find(
|
||||
(candidate) => candidate.id === input.requestId && candidate.kind === "action",
|
||||
);
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND", message: "Preview action was not found" });
|
||||
renderRequestTarget(session.baseUrl, request, input.params);
|
||||
renderRequestBody(request.bodyTemplate, input.params);
|
||||
await recordPreviewJournal(session, {
|
||||
requestId: request.id,
|
||||
kind: "action",
|
||||
method: request.method,
|
||||
pathTemplate: request.pathTemplate,
|
||||
status: null,
|
||||
durationMs: 0,
|
||||
simulated: true,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
simulated: true as const,
|
||||
requestId: request.id,
|
||||
method: request.method,
|
||||
requiredPermission: request.minimumBoardPermission,
|
||||
};
|
||||
}),
|
||||
previewAction: adminProcedure
|
||||
.input(previewSessionRequestSchema.extend({ confirmed: z.boolean().optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
|
||||
@@ -53,7 +26,9 @@ export const previewActionProcedures = {
|
||||
(candidate) => candidate.id === input.requestId && candidate.kind === "action",
|
||||
);
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND", message: "Preview action was not found" });
|
||||
const targetUrl = renderRequestTarget(session.baseUrl, request, input.params);
|
||||
const resolved = getPreviewRequestSource(session, request.sourceId);
|
||||
if (!resolved) throw new TRPCError({ code: "NOT_FOUND", message: "Preview source was not found" });
|
||||
const targetUrl = renderRequestTarget(resolved.source.baseUrl, request, input.params);
|
||||
const body = renderRequestBody(request.bodyTemplate, input.params);
|
||||
if (!session.liveActions) {
|
||||
await recordPreviewJournal(session, {
|
||||
@@ -67,8 +42,8 @@ export const previewActionProcedures = {
|
||||
});
|
||||
return { ok: true, status: 0, statusText: "Simulated", data: null, simulated: true as const };
|
||||
}
|
||||
if (request.method === "DELETE" && input.confirmed !== true) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "DELETE actions require confirmation" });
|
||||
if ((request.confirmation || request.method === "DELETE") && input.confirmed !== true) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "This action requires confirmation" });
|
||||
}
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category: request.method === "DELETE" ? "delete" : "action",
|
||||
@@ -79,22 +54,20 @@ export const previewActionProcedures = {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: session.baseUrl,
|
||||
baseUrl: resolved.source.baseUrl,
|
||||
targetUrl,
|
||||
method: request.method,
|
||||
body,
|
||||
staticHeaders: request.staticHeaders,
|
||||
auth:
|
||||
request.auth === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: session.authType,
|
||||
secrets: getPreviewSessionSecrets(session),
|
||||
headerName: session.headerName,
|
||||
},
|
||||
networkScope: session.networkScope,
|
||||
auth: request.auth === "none" ? undefined : resolved.auth,
|
||||
networkScope: resolved.source.networkScope,
|
||||
kind: "action",
|
||||
});
|
||||
if (response.ok && request.invalidates?.length) {
|
||||
invalidateCustomWidgetResponseCache(
|
||||
request.invalidates.map((requestId) => `custom-jsx:preview:${session.id}:${requestId}:`),
|
||||
);
|
||||
}
|
||||
await recordPreviewJournal(session, {
|
||||
requestId: request.id,
|
||||
kind: "action",
|
||||
|
||||
@@ -2,158 +2,110 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { customWidgetDefinitionSchema, customWidgetSecretsInputSchema } from "@homarr/custom-widgets/core";
|
||||
import { eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import {
|
||||
customWidgetAuthTypes,
|
||||
customWidgetDisplayTypes,
|
||||
customWidgetMethods,
|
||||
customWidgetSecretKinds,
|
||||
customJsxDisplayConfigV2Schema,
|
||||
displayConfigSchema,
|
||||
extractActionButtonDisplay,
|
||||
extractDisplayDataWithFallback,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { recordPreviewJournal } from "./preview-procedure-helpers";
|
||||
import { executeCustomWidgetRequest } from "./request-executor";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import { createPreviewSession, getPreviewSession } from "./preview-sessions";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
const previewCreateInputSchema = z.object({
|
||||
definition: customWidgetDefinitionSchema,
|
||||
secrets: customWidgetSecretsInputSchema.default([]),
|
||||
definitionId: z.string().optional(),
|
||||
});
|
||||
|
||||
const previewCreateProcedure = manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Create a short-lived preview session for one unsaved custom widget." } })
|
||||
.input(previewCreateInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.secrets.length > 0 && !ctx.session.user.permissions.includes("custom-widget-secret-write")) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Writing preview secrets requires dedicated permission" });
|
||||
}
|
||||
const secrets = [...input.secrets];
|
||||
if (input.definitionId) {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
for (const secret of existing.secrets) {
|
||||
if (!secrets.some((candidate) => candidate.sourceId === secret.sourceId && candidate.kind === secret.kind)) {
|
||||
secrets.push({ sourceId: secret.sourceId, kind: secret.kind, value: decryptSecret(secret.encryptedValue) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const invalid = secrets.find((secret) => {
|
||||
const source = input.definition.sources.find((candidate) => candidate.id === secret.sourceId);
|
||||
const kinds =
|
||||
source?.auth.type === "basic"
|
||||
? ["username", "password"]
|
||||
: source && ["bearer", "apiKeyHeader", "apiKeyQuery"].includes(source.auth.type)
|
||||
? ["apiKey"]
|
||||
: [];
|
||||
return !source || !kinds.includes(secret.kind);
|
||||
});
|
||||
if (invalid) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `Unknown secret source '${invalid.sourceId}'` });
|
||||
}
|
||||
|
||||
const previewSession = await createPreviewSession({
|
||||
userId: ctx.session.user.id,
|
||||
sources: input.definition.sources,
|
||||
requests: input.definition.requests,
|
||||
name: input.definition.name,
|
||||
template: input.definition.template,
|
||||
optionsSchema: input.definition.optionsSchema,
|
||||
defaultOptions: input.definition.defaultOptions,
|
||||
stateSchema: input.definition.stateSchema ?? {},
|
||||
defaultState: input.definition.defaultState ?? {},
|
||||
secrets,
|
||||
definitionId: input.definitionId,
|
||||
});
|
||||
return {
|
||||
success: true as const,
|
||||
previewSession,
|
||||
previewUrl: new URL(
|
||||
`/manage/custom-widgets/preview/${previewSession.id}`,
|
||||
ctx.baseUrl ?? "http://localhost",
|
||||
).toString(),
|
||||
definition: {
|
||||
template: input.definition.template,
|
||||
defaultOptions: input.definition.defaultOptions,
|
||||
defaultState: input.definition.defaultState ?? {},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const previewBaseProcedures = {
|
||||
preview: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Test a custom-widget draft through Homarr's hardened preview executor. Admin only. GET only; actions remain simulated. REQUIRED: url, method GET, authType, displayType, displayConfig. OPTIONAL: definitionId reuses that saved widget's stored credentials; omit secrets whenever possible. Returns sanitized response data, HTTP status, and a short-lived preview session for named query testing.",
|
||||
},
|
||||
})
|
||||
.input(
|
||||
z.object({
|
||||
url: z.string().url(),
|
||||
method: z.enum(customWidgetMethods),
|
||||
authType: z.enum(customWidgetAuthTypes),
|
||||
headerName: z.string().optional(),
|
||||
requestBody: z.string().optional(),
|
||||
displayType: z.enum(customWidgetDisplayTypes),
|
||||
displayConfig: displayConfigSchema,
|
||||
secrets: z.array(z.object({ kind: z.enum(customWidgetSecretKinds), value: z.string() })).default([]),
|
||||
definitionId: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const secrets = [...input.secrets];
|
||||
|
||||
if (input.definitionId) {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (existing) {
|
||||
for (const dbSecret of existing.secrets) {
|
||||
if (!secrets.some((s) => s.kind === dbSecret.kind)) {
|
||||
secrets.push({ kind: dbSecret.kind, value: decryptSecret(dbSecret.value) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const v2Config = customJsxDisplayConfigV2Schema.safeParse(input.displayConfig);
|
||||
const previewSession = v2Config.success
|
||||
? await createPreviewSession({
|
||||
userId: ctx.session.user.id,
|
||||
baseUrl: input.url,
|
||||
authType: input.authType,
|
||||
headerName: input.headerName,
|
||||
secrets,
|
||||
networkScope: v2Config.data.networkScope,
|
||||
requests: v2Config.data.requests,
|
||||
definitionId: input.definitionId,
|
||||
})
|
||||
: null;
|
||||
const storedPreviewSession = previewSession
|
||||
? await getPreviewSession(previewSession.id, ctx.session.user.id)
|
||||
: null;
|
||||
|
||||
if (input.method !== "GET") {
|
||||
return {
|
||||
success: true as const,
|
||||
simulated: true as const,
|
||||
responseInfo: null,
|
||||
rawResponse: null,
|
||||
displayData: input.displayType === "actionButton" ? extractActionButtonDisplay(input.displayConfig) : null,
|
||||
previewSession,
|
||||
};
|
||||
}
|
||||
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category: "query",
|
||||
userId: ctx.session.user.id,
|
||||
itemId: `preview:${ctx.session.user.id}`,
|
||||
definitionId: input.definitionId ?? `preview:${ctx.session.user.id}`,
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: input.url,
|
||||
method: input.method,
|
||||
body: undefined,
|
||||
auth: { type: input.authType, secrets, headerName: input.headerName },
|
||||
networkScope: v2Config.success ? v2Config.data.networkScope : "private",
|
||||
kind: "query",
|
||||
});
|
||||
if (storedPreviewSession) {
|
||||
await recordPreviewJournal(storedPreviewSession, {
|
||||
requestId: "base",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: new URL(input.url).pathname,
|
||||
status: response.status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
simulated: false,
|
||||
});
|
||||
}
|
||||
const responseInfo = { status: response.status, statusText: response.statusText };
|
||||
if (!response.ok) {
|
||||
return {
|
||||
success: false as const,
|
||||
error: `HTTP ${response.status}: ${response.statusText}`,
|
||||
responseInfo,
|
||||
rawResponse: typeof response.data === "string" ? response.data : JSON.stringify(response.data, null, 2),
|
||||
previewSession,
|
||||
};
|
||||
}
|
||||
|
||||
const displayData = extractDisplayDataWithFallback(response.data, input.displayType, input.displayConfig);
|
||||
|
||||
return {
|
||||
success: true as const,
|
||||
responseInfo,
|
||||
rawResponse: typeof response.data === "string" ? response.data : JSON.stringify(response.data, null, 2),
|
||||
displayData,
|
||||
previewSession,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof TRPCError) throw error;
|
||||
logger.error("Custom widget preview failed", {
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
});
|
||||
return {
|
||||
success: false as const,
|
||||
error: error instanceof Error ? error.message : "Failed to fetch data",
|
||||
responseInfo: null,
|
||||
rawResponse: null,
|
||||
previewSession,
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}),
|
||||
previewCreate: previewCreateProcedure,
|
||||
previewGet: manageProcedure.input(z.object({ sessionId: z.string() })).query(async ({ ctx, input }) => {
|
||||
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
|
||||
return {
|
||||
id: session.id,
|
||||
name: session.name,
|
||||
expiresAt: session.expiresAt,
|
||||
template: session.template,
|
||||
optionsSchema: session.optionsSchema,
|
||||
defaultOptions: session.defaultOptions,
|
||||
stateSchema: session.stateSchema,
|
||||
defaultState: session.defaultState,
|
||||
requests: session.requests.map(
|
||||
({ id, kind, method, minimumBoardPermission, trigger, parameters, confirmation, invalidates }) => ({
|
||||
id,
|
||||
kind,
|
||||
method,
|
||||
minimumBoardPermission,
|
||||
trigger,
|
||||
parameters,
|
||||
confirmation,
|
||||
invalidates,
|
||||
}),
|
||||
),
|
||||
liveActions: session.liveActions,
|
||||
};
|
||||
}),
|
||||
};
|
||||
@@ -2,6 +2,8 @@ import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { appendPreviewJournal } from "./preview-sessions";
|
||||
import { getPreviewSessionSecrets } from "./preview-sessions";
|
||||
import type { CustomWidgetPreviewSession } from "./preview-sessions";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget-preview" });
|
||||
|
||||
@@ -21,3 +23,22 @@ export const recordPreviewJournal = async (...args: Parameters<typeof appendPrev
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getPreviewRequestSource = (session: CustomWidgetPreviewSession, sourceId: string) => {
|
||||
const source = session.sources.find((candidate) => candidate.id === sourceId);
|
||||
if (!source) return null;
|
||||
const auth =
|
||||
source.auth.type === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: source.auth.type,
|
||||
secrets: getPreviewSessionSecrets(session, source.id),
|
||||
headerName:
|
||||
source.auth.type === "apiKeyHeader"
|
||||
? source.auth.headerName
|
||||
: source.auth.type === "apiKeyQuery"
|
||||
? source.auth.parameterName
|
||||
: undefined,
|
||||
};
|
||||
return { source, auth };
|
||||
};
|
||||
@@ -2,26 +2,24 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { previewSessionRequestSchema, recordPreviewJournal } from "./preview-procedure-helpers";
|
||||
import { executeCustomWidgetRequest } from "./request-executor";
|
||||
import { hashRuntimeParams, renderRequestTarget } from "./request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import {
|
||||
getPreviewJournal,
|
||||
getPreviewSession,
|
||||
getPreviewSessionSecrets,
|
||||
setPreviewSessionLiveActions,
|
||||
} from "./preview-sessions";
|
||||
getPreviewRequestSource,
|
||||
previewSessionRequestSchema,
|
||||
recordPreviewJournal,
|
||||
} from "./preview-procedure-helpers";
|
||||
import { executeCustomWidgetRequest } from "./request-executor";
|
||||
import { hashRuntimeParams, renderRequestBody, renderRequestTarget } from "./request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import { getPreviewJournal, getPreviewSession, setPreviewSessionLiveActions } from "./preview-sessions";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
|
||||
export const previewQueryProcedures = {
|
||||
previewQuery: adminProcedure
|
||||
previewQuery: manageProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Run one named GET query from a short-lived custom-widget preview session. REQUIRED: sessionId from customWidget_preview, requestId declared as a query, and typed params. Uses the hardened executor and returns sanitized response data for another validate/update iteration.",
|
||||
description: "Run one named query from a short-lived custom widget preview session.",
|
||||
},
|
||||
})
|
||||
.input(previewSessionRequestSchema)
|
||||
@@ -31,7 +29,10 @@ export const previewQueryProcedures = {
|
||||
(candidate) => candidate.id === input.requestId && candidate.kind === "query",
|
||||
);
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND", message: "Preview query was not found" });
|
||||
const targetUrl = renderRequestTarget(session.baseUrl, request, input.params);
|
||||
const resolved = getPreviewRequestSource(session, request.sourceId);
|
||||
if (!resolved) throw new TRPCError({ code: "NOT_FOUND", message: "Preview source was not found" });
|
||||
const targetUrl = renderRequestTarget(resolved.source.baseUrl, request, input.params);
|
||||
const body = renderRequestBody(request.bodyTemplate, input.params);
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category: "query",
|
||||
userId: ctx.session.user.id,
|
||||
@@ -41,19 +42,13 @@ export const previewQueryProcedures = {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: session.baseUrl,
|
||||
baseUrl: resolved.source.baseUrl,
|
||||
targetUrl,
|
||||
method: "GET",
|
||||
method: request.method,
|
||||
body,
|
||||
staticHeaders: request.staticHeaders,
|
||||
auth:
|
||||
request.auth === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: session.authType,
|
||||
secrets: getPreviewSessionSecrets(session),
|
||||
headerName: session.headerName,
|
||||
},
|
||||
networkScope: session.networkScope,
|
||||
auth: request.auth === "none" ? undefined : resolved.auth,
|
||||
networkScope: resolved.source.networkScope,
|
||||
kind: "query",
|
||||
cacheKey: `custom-jsx:preview:${session.id}:${request.id}:${hashRuntimeParams(input.params)}`,
|
||||
cacheTtlSeconds: request.cacheTtlSeconds,
|
||||
@@ -61,7 +56,7 @@ export const previewQueryProcedures = {
|
||||
await recordPreviewJournal(session, {
|
||||
requestId: request.id,
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
method: request.method,
|
||||
pathTemplate: request.pathTemplate,
|
||||
status: response.status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
@@ -79,18 +74,17 @@ export const previewQueryProcedures = {
|
||||
}
|
||||
}),
|
||||
|
||||
setPreviewLiveActions: adminProcedure
|
||||
setPreviewLiveActions: manageProcedure
|
||||
.input(z.object({ sessionId: z.string().min(1), enabled: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) =>
|
||||
setPreviewSessionLiveActions(input.sessionId, ctx.session.user.id, input.enabled),
|
||||
),
|
||||
|
||||
previewJournal: adminProcedure
|
||||
previewJournal: manageProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Read the redacted request journal for a custom-widget preview session. REQUIRED: sessionId. Use it to inspect statuses and durations; credentials and parameter values are never returned.",
|
||||
description: "Read the redacted request journal for a custom widget preview session.",
|
||||
},
|
||||
})
|
||||
.input(z.object({ sessionId: z.string().min(1) }))
|
||||
|
||||
@@ -76,4 +76,7 @@ export const appendPreviewJournal = (
|
||||
entry: Omit<CustomWidgetPreviewJournalEntry, "id" | "timestamp">,
|
||||
) => call(() => getService().appendJournal(session, entry));
|
||||
export const getPreviewJournal = (id: string, userId: string) => call(() => getService().getJournal(id, userId));
|
||||
export const getPreviewSessionSecrets = (session: CustomWidgetPreviewSession) => getService().getSecrets(session);
|
||||
export const getPreviewSessionSecrets = (session: CustomWidgetPreviewSession, sourceId: string) =>
|
||||
getService().getSecrets(session, sourceId);
|
||||
export const setPreviewSessionSecrets = (id: string, userId: string, secrets: CreatePreviewSessionInput["secrets"]) =>
|
||||
call(() => getService().setSecrets(id, userId, secrets));
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
assertSafeStaticHeaders as assertDomainSafeStaticHeaders,
|
||||
classifyAddress,
|
||||
executeCustomWidgetRequest as executeDomainRequest,
|
||||
invalidateCustomWidgetResponseCache as invalidateDomainResponseCache,
|
||||
MAX_REQUEST_BODY_BYTES,
|
||||
MAX_RESPONSE_BODY_BYTES,
|
||||
MAX_RESPONSE_JSON_DEPTH,
|
||||
@@ -81,3 +82,6 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const invalidateCustomWidgetResponseCache = (prefixes: readonly string[]) =>
|
||||
invalidateDomainResponseCache(prefixes);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
export function requiredSecretKinds(authType: string) {
|
||||
if (authType === "basic") return ["username", "password"] as const;
|
||||
if (authType === "bearer" || authType === "apiKeyHeader" || authType === "apiKeyQuery") {
|
||||
return ["apiKey"] as const;
|
||||
}
|
||||
return [] as const;
|
||||
}
|
||||
|
||||
export function assertSecretSources(
|
||||
sources: readonly { id: string; auth: { type: string } }[],
|
||||
secrets: readonly { sourceId: string; kind: "apiKey" | "username" | "password" }[],
|
||||
) {
|
||||
const invalid = secrets.find((secret) => {
|
||||
const source = sources.find((candidate) => candidate.id === secret.sourceId);
|
||||
return !source || !new Set<string>(requiredSecretKinds(source.auth.type)).has(secret.kind);
|
||||
});
|
||||
if (invalid) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Secret does not match source '${invalid.sourceId}' authentication`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { and, eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import { customWidgetSecretInputSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { createCustomWidgetSecretRequest, getCustomWidgetSecretRequestForUser } from "./secret-requests";
|
||||
import { assertSecretSources, requiredSecretKinds } from "./secret-policy";
|
||||
import { getPreviewSession } from "./preview-sessions";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
const secretWriteProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-secret-write");
|
||||
|
||||
const secretRequestInputSchema = z
|
||||
.object({
|
||||
requestId: z.string().optional(),
|
||||
definitionId: z.string().optional(),
|
||||
previewSessionId: z.string().optional(),
|
||||
sourceId: z.string().optional(),
|
||||
})
|
||||
.superRefine((input, ctx) => {
|
||||
if (input.requestId) {
|
||||
if (input.definitionId || input.previewSessionId || input.sourceId) {
|
||||
ctx.addIssue({ code: "custom", message: "Status checks only accept requestId" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (Boolean(input.definitionId) === Boolean(input.previewSessionId)) {
|
||||
ctx.addIssue({ code: "custom", message: "Provide exactly one definitionId or previewSessionId" });
|
||||
}
|
||||
if (!input.sourceId) ctx.addIssue({ code: "custom", message: "sourceId is required" });
|
||||
});
|
||||
|
||||
export const secretProcedures = {
|
||||
secretSet: secretWriteProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Set one encrypted secret for a custom widget source." } })
|
||||
.input(z.object({ definitionId: z.string(), secret: customWidgetSecretInputSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
});
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
const definition = parseStoredCustomWidgetDefinition(existing);
|
||||
assertSecretSources(definition.sources, [input.secret]);
|
||||
await ctx.db
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(customWidgetSecrets.sourceId, input.secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, input.secret.kind),
|
||||
),
|
||||
);
|
||||
await ctx.db.insert(customWidgetSecrets).values({
|
||||
definitionId: input.definitionId,
|
||||
sourceId: input.secret.sourceId,
|
||||
kind: input.secret.kind,
|
||||
encryptedValue: encryptSecret(input.secret.value),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, input.definitionId));
|
||||
return { sourceId: input.secret.sourceId, kind: input.secret.kind, isSet: true };
|
||||
}),
|
||||
|
||||
secretRequestUser: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Create or check a short-lived user credential-entry request." } })
|
||||
.input(secretRequestInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.requestId) {
|
||||
const request = await getCustomWidgetSecretRequestForUser(input.requestId, ctx.session.user.id);
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
return { requestId: request.id, status: request.status, expiresAt: request.expiresAt };
|
||||
}
|
||||
|
||||
let widgetName: string;
|
||||
let source: { id: string; name: string; auth: { type: string } } | undefined;
|
||||
let target: { type: "definition"; id: string } | { type: "preview"; id: string };
|
||||
if (input.definitionId) {
|
||||
const stored = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
});
|
||||
if (!stored) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
const definition = parseStoredCustomWidgetDefinition(stored);
|
||||
widgetName = definition.name;
|
||||
source = definition.sources.find((candidate) => candidate.id === input.sourceId);
|
||||
target = { type: "definition", id: input.definitionId };
|
||||
} else {
|
||||
const preview = await getPreviewSession(input.previewSessionId ?? "", ctx.session.user.id);
|
||||
widgetName = "Custom widget preview";
|
||||
source = preview.sources.find((candidate) => candidate.id === input.sourceId);
|
||||
target = { type: "preview", id: preview.id };
|
||||
}
|
||||
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Widget source not found" });
|
||||
const kinds = [...requiredSecretKinds(source.auth.type)];
|
||||
if (kinds.length === 0) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "This source does not require a secret" });
|
||||
}
|
||||
const request = await createCustomWidgetSecretRequest({
|
||||
userId: ctx.session.user.id,
|
||||
target,
|
||||
widgetName,
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
kinds,
|
||||
});
|
||||
return {
|
||||
requestId: request.id,
|
||||
status: request.status,
|
||||
expiresAt: request.expiresAt,
|
||||
url: new URL(`/custom-widget-secret/${request.id}`, ctx.baseUrl ?? "http://localhost").toString(),
|
||||
};
|
||||
}),
|
||||
|
||||
secretClear: secretWriteProcedure
|
||||
.input(
|
||||
z.object({ definitionId: z.string(), sourceId: z.string(), kind: z.enum(["apiKey", "username", "password"]) }),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
});
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
await ctx.db
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(customWidgetSecrets.sourceId, input.sourceId),
|
||||
eq(customWidgetSecrets.kind, input.kind),
|
||||
),
|
||||
);
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, input.definitionId));
|
||||
return { sourceId: input.sourceId, kind: input.kind, isSet: false };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { createRedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import type { RedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import type { CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
|
||||
|
||||
const SECRET_REQUEST_TTL_MS = 10 * 60_000;
|
||||
const SECRET_REQUEST_PREFIX = "custom-widget:secret-request:";
|
||||
const SECRET_REQUEST_LOCK_PREFIX = "custom-widget:secret-request-lock:";
|
||||
|
||||
export interface CustomWidgetSecretRequest {
|
||||
id: string;
|
||||
userId: string;
|
||||
target: { type: "definition"; id: string } | { type: "preview"; id: string };
|
||||
widgetName: string;
|
||||
sourceId: string;
|
||||
sourceName: string;
|
||||
kinds: CustomWidgetSecretKind[];
|
||||
expiresAt: number;
|
||||
status: "pending" | "completed";
|
||||
}
|
||||
|
||||
const localRequests = new Map<string, CustomWidgetSecretRequest>();
|
||||
const localLocks = new Set<string>();
|
||||
let redis: RedisClient | undefined;
|
||||
|
||||
function getRedis() {
|
||||
if (process.env.CI !== undefined || process.env.NODE_ENV === "test") return undefined;
|
||||
redis ??= createRedisClient();
|
||||
return redis;
|
||||
}
|
||||
|
||||
async function save(request: CustomWidgetSecretRequest) {
|
||||
const ttl = Math.max(1, request.expiresAt - Date.now());
|
||||
const client = getRedis();
|
||||
if (client) await client.set(`${SECRET_REQUEST_PREFIX}${request.id}`, JSON.stringify(request), "PX", ttl);
|
||||
else localRequests.set(request.id, request);
|
||||
}
|
||||
|
||||
export async function createCustomWidgetSecretRequest(
|
||||
input: Omit<CustomWidgetSecretRequest, "id" | "expiresAt" | "status">,
|
||||
) {
|
||||
const request: CustomWidgetSecretRequest = {
|
||||
...input,
|
||||
id: createId(),
|
||||
expiresAt: Date.now() + SECRET_REQUEST_TTL_MS,
|
||||
status: "pending",
|
||||
};
|
||||
await save(request);
|
||||
return request;
|
||||
}
|
||||
|
||||
export async function getCustomWidgetSecretRequest(id: string) {
|
||||
const client = getRedis();
|
||||
const candidate = client ? await client.get(`${SECRET_REQUEST_PREFIX}${id}`) : localRequests.get(id);
|
||||
if (!candidate) return null;
|
||||
try {
|
||||
const request = (typeof candidate === "string" ? JSON.parse(candidate) : candidate) as CustomWidgetSecretRequest;
|
||||
if (request.expiresAt <= Date.now()) {
|
||||
if (client) await client.del(`${SECRET_REQUEST_PREFIX}${id}`);
|
||||
else localRequests.delete(id);
|
||||
return null;
|
||||
}
|
||||
return request;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCustomWidgetSecretRequestForUser(id: string, userId: string) {
|
||||
const request = await getCustomWidgetSecretRequest(id);
|
||||
return request?.userId === userId ? request : null;
|
||||
}
|
||||
|
||||
export async function completeCustomWidgetSecretRequest(id: string) {
|
||||
const request = await getCustomWidgetSecretRequest(id);
|
||||
if (!request || request.status !== "pending") return null;
|
||||
const completed = { ...request, status: "completed" as const };
|
||||
await save(completed);
|
||||
await releaseCustomWidgetSecretRequest(id);
|
||||
return completed;
|
||||
}
|
||||
|
||||
export async function claimCustomWidgetSecretRequest(id: string) {
|
||||
const request = await getCustomWidgetSecretRequest(id);
|
||||
if (!request || request.status !== "pending") return null;
|
||||
const client = getRedis();
|
||||
if (client) {
|
||||
const claimed = await client.set(`${SECRET_REQUEST_LOCK_PREFIX}${id}`, "1", "PX", 60_000, "NX");
|
||||
return claimed === "OK" ? request : null;
|
||||
}
|
||||
if (localLocks.has(id)) return null;
|
||||
localLocks.add(id);
|
||||
return request;
|
||||
}
|
||||
|
||||
export async function releaseCustomWidgetSecretRequest(id: string) {
|
||||
const client = getRedis();
|
||||
if (client) await client.del(`${SECRET_REQUEST_LOCK_PREFIX}${id}`);
|
||||
else localLocks.delete(id);
|
||||
}
|
||||
|
||||
export { setPreviewSessionSecrets } from "./preview-sessions";
|
||||
@@ -0,0 +1,50 @@
|
||||
import { parse as parseSuperJson, stringify as stringifySuperJson } from "superjson";
|
||||
|
||||
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetDefinition } from "@homarr/db/schema";
|
||||
|
||||
export function serializeCustomWidgetDefinition(definition: HomarrCustomWidgetV2) {
|
||||
return {
|
||||
name: definition.name,
|
||||
description: definition.description ?? null,
|
||||
iconUrl: definition.iconUrl ?? null,
|
||||
sources: stringifySuperJson(definition.sources),
|
||||
requests: stringifySuperJson(definition.requests),
|
||||
optionsSchema: stringifySuperJson(definition.optionsSchema),
|
||||
defaultOptions: stringifySuperJson(definition.defaultOptions),
|
||||
stateSchema: definition.stateSchema ? stringifySuperJson(definition.stateSchema) : null,
|
||||
defaultState: definition.defaultState ? stringifySuperJson(definition.defaultState) : null,
|
||||
template: definition.template,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseStoredCustomWidgetDefinition(
|
||||
definition: Pick<
|
||||
CustomWidgetDefinition,
|
||||
| "name"
|
||||
| "description"
|
||||
| "iconUrl"
|
||||
| "sources"
|
||||
| "requests"
|
||||
| "optionsSchema"
|
||||
| "defaultOptions"
|
||||
| "stateSchema"
|
||||
| "defaultState"
|
||||
| "template"
|
||||
>,
|
||||
): HomarrCustomWidgetV2 {
|
||||
return customWidgetDefinitionSchema.parse({
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: definition.name,
|
||||
description: definition.description ?? undefined,
|
||||
iconUrl: definition.iconUrl ?? undefined,
|
||||
sources: parseSuperJson(definition.sources),
|
||||
requests: parseSuperJson(definition.requests),
|
||||
optionsSchema: parseSuperJson(definition.optionsSchema),
|
||||
defaultOptions: parseSuperJson(definition.defaultOptions),
|
||||
stateSchema: definition.stateSchema ? parseSuperJson(definition.stateSchema) : undefined,
|
||||
defaultState: definition.defaultState ? parseSuperJson(definition.defaultState) : undefined,
|
||||
template: definition.template,
|
||||
});
|
||||
}
|
||||
@@ -1,26 +1,26 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { stringify as stringifySuperJson } from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { displayConfigSchema } from "@homarr/custom-widgets/core";
|
||||
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
import { eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { parseDisplayConfig } from "./parse-display-config";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
|
||||
const getTemplateRevision = (template: string) => createHash("sha256").update(template).digest("hex").slice(0, 16);
|
||||
|
||||
const validateUpdatedTemplate = (displayConfig: Record<string, unknown>, template: string) => {
|
||||
displayConfig.template = template;
|
||||
const result = displayConfigSchema.safeParse(displayConfig);
|
||||
const validateTemplate = (definition: ReturnType<typeof parseStoredCustomWidgetDefinition>, template: string) => {
|
||||
if (template.trim().length === 0) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Template must not be empty" });
|
||||
}
|
||||
const result = customWidgetDefinitionSchema.safeParse({ ...definition, template });
|
||||
if (!result.success) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
@@ -29,67 +29,29 @@ const validateUpdatedTemplate = (displayConfig: Record<string, unknown>, templat
|
||||
.join("; "),
|
||||
});
|
||||
}
|
||||
return result.data;
|
||||
return result.data.template;
|
||||
};
|
||||
|
||||
export const templateProcedures = {
|
||||
readTemplate: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Read the JSX template of a custom widget definition as plain text. Returns the template string separately from the full widget config, making it easier to inspect and edit.",
|
||||
},
|
||||
})
|
||||
.input(z.object({ id: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
readTemplate: manageProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
const template = parseStoredCustomWidgetDefinition(definition).template;
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
template,
|
||||
templateLines: template.split("\n"),
|
||||
revision: getTemplateRevision(template),
|
||||
};
|
||||
}),
|
||||
|
||||
if (!definition) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
}
|
||||
|
||||
const config = parseDisplayConfig(
|
||||
definition.displayConfig,
|
||||
input.id,
|
||||
logger,
|
||||
"Corrupt displayConfig in custom widget readTemplate",
|
||||
);
|
||||
|
||||
if (config.type !== "customJsx") {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Widget is not using customJsx display type",
|
||||
});
|
||||
}
|
||||
|
||||
const template = (config.template as string | undefined) ?? "";
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
template,
|
||||
templateLines: template.split("\n"),
|
||||
revision: getTemplateRevision(template),
|
||||
};
|
||||
}),
|
||||
|
||||
writeTemplate: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Update only the JSX template of a custom widget definition. Accepts either a single template string or templateLines (array of strings joined with newlines). Validates the template AST before saving. This avoids needing to send the full widget JSON for template-only edits.",
|
||||
},
|
||||
})
|
||||
writeTemplate: manageProcedure
|
||||
.input(
|
||||
z
|
||||
.object({
|
||||
id: z.string(),
|
||||
template: z.string().optional(),
|
||||
templateLines: z.array(z.string()).optional(),
|
||||
})
|
||||
.object({ id: z.string(), template: z.string().optional(), templateLines: z.array(z.string()).optional() })
|
||||
.refine((data) => data.template !== undefined || data.templateLines !== undefined, {
|
||||
message: "Provide either template or templateLines",
|
||||
})
|
||||
@@ -98,62 +60,22 @@ export const templateProcedures = {
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const resolvedTemplate =
|
||||
input.templateLines !== undefined ? input.templateLines.join("\n") : (input.template ?? "");
|
||||
|
||||
const resolved = input.templateLines?.join("\n") ?? input.template ?? "";
|
||||
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
}
|
||||
|
||||
const displayConfig = parseDisplayConfig(
|
||||
existing.displayConfig,
|
||||
input.id,
|
||||
logger,
|
||||
"Corrupt displayConfig in custom widget writeTemplate",
|
||||
);
|
||||
|
||||
if (displayConfig.type !== "customJsx") {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Widget is not using customJsx display type",
|
||||
});
|
||||
}
|
||||
|
||||
if (resolvedTemplate.trim().length === 0) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Template must not be empty" });
|
||||
}
|
||||
if (resolvedTemplate.length > 50_000) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Template exceeds the 50,000 character limit" });
|
||||
}
|
||||
|
||||
const validatedConfig = validateUpdatedTemplate(displayConfig, resolvedTemplate);
|
||||
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
const template = validateTemplate(parseStoredCustomWidgetDefinition(existing), resolved);
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ displayConfig: stringifySuperJson(validatedConfig), updatedAt: new Date() })
|
||||
.set({ template, updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, input.id));
|
||||
|
||||
logger.info("Updated custom widget template", { id: input.id });
|
||||
return {
|
||||
id: input.id,
|
||||
template: resolvedTemplate,
|
||||
templateLines: resolvedTemplate.split("\n"),
|
||||
revision: getTemplateRevision(resolvedTemplate),
|
||||
};
|
||||
return { id: input.id, template, templateLines: template.split("\n"), revision: getTemplateRevision(template) };
|
||||
}),
|
||||
|
||||
patchTemplate: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Patch selected lines of a Custom JSX template without rewriting the whole template. First call customWidget_readTemplate and pass its revision as expectedRevision. Each edit uses a 1-based startLine, deleteCount, and replacementLines. Edits are applied atomically, then the complete template and named-request references are validated before saving. A stale revision is rejected so the agent can re-read and retry safely.",
|
||||
},
|
||||
})
|
||||
templatePatch: manageProcedure
|
||||
.meta({ mcp: { enabled: true, description: "Patch selected JSX template lines using an optimistic revision." } })
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
@@ -175,26 +97,15 @@ export const templateProcedures = {
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
if (!existing) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
|
||||
const displayConfig = parseDisplayConfig(
|
||||
existing.displayConfig,
|
||||
input.id,
|
||||
logger,
|
||||
"Corrupt displayConfig in custom widget patchTemplate",
|
||||
);
|
||||
if (displayConfig.type !== "customJsx") {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Widget is not using customJsx display type" });
|
||||
}
|
||||
|
||||
const currentTemplate = (displayConfig.template as string | undefined) ?? "";
|
||||
if (getTemplateRevision(currentTemplate) !== input.expectedRevision) {
|
||||
const definition = parseStoredCustomWidgetDefinition(existing);
|
||||
if (getTemplateRevision(definition.template) !== input.expectedRevision) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Template changed since it was read. Read the template again and retry the patch.",
|
||||
message: "Template changed since it was read. Read it again and retry.",
|
||||
});
|
||||
}
|
||||
|
||||
const lines = currentTemplate.split("\n");
|
||||
const lines = definition.template.split("\n");
|
||||
const edits = input.edits.toSorted((left, right) => right.startLine - left.startLine);
|
||||
let nextHigherStart = lines.length + 2;
|
||||
for (const edit of edits) {
|
||||
@@ -208,19 +119,12 @@ export const templateProcedures = {
|
||||
lines.splice(edit.startLine - 1, edit.deleteCount, ...edit.replacementLines);
|
||||
}
|
||||
|
||||
const template = lines.join("\n");
|
||||
const validatedConfig = validateUpdatedTemplate(displayConfig, template);
|
||||
const template = validateTemplate(definition, lines.join("\n"));
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ displayConfig: stringifySuperJson(validatedConfig), updatedAt: new Date() })
|
||||
.set({ template, updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, input.id));
|
||||
|
||||
logger.info("Patched custom widget template", { id: input.id, editCount: input.edits.length });
|
||||
return {
|
||||
id: input.id,
|
||||
template,
|
||||
templateLines: lines,
|
||||
revision: getTemplateRevision(template),
|
||||
};
|
||||
return { id: input.id, template, templateLines: lines, revision: getTemplateRevision(template) };
|
||||
}),
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { stringify as stringifySuperJson } from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
@@ -9,72 +8,28 @@ import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { parseDisplayConfig } from "./parse-display-config";
|
||||
import { parseStoredCustomWidgetDefinition, serializeCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
|
||||
export const transferProcedures = {
|
||||
export: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Export one custom widget as a homarr-custom-widget-v3 object. REQUIRED: id. Secrets are excluded.",
|
||||
},
|
||||
})
|
||||
.input(z.object({ id: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
return {
|
||||
$schema: "homarr-custom-widget-v3" as const,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl,
|
||||
url: definition.url,
|
||||
authType: definition.authType,
|
||||
headerName: definition.headerName,
|
||||
method: definition.method,
|
||||
requestBody: definition.requestBody,
|
||||
displayType: definition.displayType,
|
||||
displayConfig: parseDisplayConfig(
|
||||
definition.displayConfig,
|
||||
input.id,
|
||||
logger,
|
||||
"Corrupt displayConfig during export",
|
||||
),
|
||||
};
|
||||
}),
|
||||
export: manageProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
return parseStoredCustomWidgetDefinition(definition);
|
||||
}),
|
||||
|
||||
import: adminProcedure
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Create a custom widget from a validated homarr-custom-widget-v3 import object. Secrets are omitted and configured separately.",
|
||||
},
|
||||
})
|
||||
.input(customWidgetImportSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const id = createId();
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
name: input.name,
|
||||
description: input.description,
|
||||
iconUrl: input.iconUrl,
|
||||
url: input.url,
|
||||
authType: input.authType,
|
||||
headerName: input.headerName,
|
||||
method: input.method,
|
||||
requestBody: input.requestBody,
|
||||
displayType: input.displayType,
|
||||
displayConfig: stringifySuperJson(input.displayConfig),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
logger.info("Imported custom widget definition", { id, name: input.name });
|
||||
return { id };
|
||||
}),
|
||||
import: manageProcedure.input(customWidgetImportSchema).mutation(async ({ ctx, input }) => {
|
||||
const id = createId();
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
...serializeCustomWidgetDefinition(input),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
logger.info("Imported custom widget definition", { id, name: input.name });
|
||||
return { id };
|
||||
}),
|
||||
};
|
||||
@@ -1,67 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
appendPreviewJournal,
|
||||
createPreviewSession,
|
||||
getPreviewJournal,
|
||||
getPreviewSession,
|
||||
getPreviewSessionSecrets,
|
||||
setPreviewSessionLiveActions,
|
||||
} from "../../custom-widget/preview-sessions";
|
||||
|
||||
const queryRequest = {
|
||||
id: "status",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/status/{id}",
|
||||
parameters: { id: "string" },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
} as const;
|
||||
|
||||
describe("custom widget preview sessions", () => {
|
||||
test("stores encrypted credentials in a short-lived user-bound manifest", async () => {
|
||||
const created = await createPreviewSession({
|
||||
userId: "admin-1",
|
||||
baseUrl: "https://example.com/api",
|
||||
authType: "bearer",
|
||||
secrets: [{ kind: "apiKey", value: "plain-secret" }],
|
||||
networkScope: "public",
|
||||
requests: [queryRequest],
|
||||
});
|
||||
|
||||
const session = await getPreviewSession(created.id, "admin-1");
|
||||
|
||||
expect(session.secrets[0]?.value).not.toContain("plain-secret");
|
||||
expect(getPreviewSessionSecrets(session)).toEqual([{ kind: "apiKey", value: "plain-secret" }]);
|
||||
await expect(getPreviewSession(created.id, "admin-2")).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
});
|
||||
|
||||
test("keeps actions simulated until explicitly enabled", async () => {
|
||||
const created = await createPreviewSession({
|
||||
userId: "admin-1",
|
||||
baseUrl: "https://example.com/api",
|
||||
authType: "none",
|
||||
secrets: [],
|
||||
networkScope: "public",
|
||||
requests: [queryRequest],
|
||||
});
|
||||
|
||||
expect((await getPreviewSession(created.id, "admin-1")).liveActions).toBe(false);
|
||||
await setPreviewSessionLiveActions(created.id, "admin-1", true);
|
||||
const session = await getPreviewSession(created.id, "admin-1");
|
||||
expect(session.liveActions).toBe(true);
|
||||
await appendPreviewJournal(session, {
|
||||
requestId: "status",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/status/{id}",
|
||||
status: 200,
|
||||
durationMs: 12,
|
||||
simulated: false,
|
||||
});
|
||||
expect(await getPreviewJournal(created.id, "admin-1")).toEqual([
|
||||
expect.objectContaining({ requestId: "status", pathTemplate: "/status/{id}", durationMs: 12 }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
claimCustomWidgetSecretRequest,
|
||||
completeCustomWidgetSecretRequest,
|
||||
createCustomWidgetSecretRequest,
|
||||
getCustomWidgetSecretRequestForUser,
|
||||
releaseCustomWidgetSecretRequest,
|
||||
} from "../../custom-widget/secret-requests";
|
||||
|
||||
describe("custom widget credential requests", () => {
|
||||
it("is user-scoped, one-time, and reports completion without a secret", async () => {
|
||||
const request = await createCustomWidgetSecretRequest({
|
||||
userId: "user-1",
|
||||
target: { type: "preview", id: "preview-1" },
|
||||
widgetName: "Printer",
|
||||
sourceId: "default",
|
||||
sourceName: "Printer API",
|
||||
kinds: ["apiKey"],
|
||||
});
|
||||
|
||||
expect(await getCustomWidgetSecretRequestForUser(request.id, "user-2")).toBeNull();
|
||||
expect(await claimCustomWidgetSecretRequest(request.id)).toMatchObject({ status: "pending" });
|
||||
expect(await claimCustomWidgetSecretRequest(request.id)).toBeNull();
|
||||
await releaseCustomWidgetSecretRequest(request.id);
|
||||
expect(await claimCustomWidgetSecretRequest(request.id)).not.toBeNull();
|
||||
await completeCustomWidgetSecretRequest(request.id);
|
||||
expect(await getCustomWidgetSecretRequestForUser(request.id, "user-1")).toMatchObject({ status: "completed" });
|
||||
expect(await claimCustomWidgetSecretRequest(request.id)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,224 +0,0 @@
|
||||
import { stringify as stringifySuperJson } from "superjson";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import { eq } from "@homarr/db";
|
||||
import { boardUserPermissions, boards, customWidgetDefinitions, items, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
executeRequest: vi.fn(async () => ({ ok: true, status: 200, statusText: "OK", data: { value: 42 } })),
|
||||
}));
|
||||
|
||||
vi.mock("../../custom-widget/request-executor", () => ({
|
||||
executeCustomWidgetRequest: mocks.executeRequest,
|
||||
resolveSameOriginTarget: (_baseUrl: string, targetUrl: string | URL) => new URL(targetUrl),
|
||||
}));
|
||||
|
||||
vi.mock("../../custom-widget/request-limits", () => ({
|
||||
acquireCustomWidgetRequestLimit: vi.fn(async () => async () => undefined),
|
||||
}));
|
||||
|
||||
import { customApiRouter } from "../../widgets/custom-api";
|
||||
|
||||
const createSession = (userId: string): Session => ({
|
||||
user: { id: userId, permissions: [], colorScheme: "light" },
|
||||
expires: new Date(Date.now() + 60_000).toISOString(),
|
||||
});
|
||||
|
||||
const queryRequest = {
|
||||
id: "status",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/status/{name}",
|
||||
parameters: { name: "string" },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
} as const;
|
||||
|
||||
const actionRequest = {
|
||||
id: "toggle",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/toggle",
|
||||
parameters: { enabled: "boolean" },
|
||||
bodyTemplate: { enabled: { $param: "enabled" } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
} as const;
|
||||
|
||||
const deleteRequest = {
|
||||
id: "delete",
|
||||
kind: "action",
|
||||
method: "DELETE",
|
||||
pathTemplate: "/resource",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "full",
|
||||
} as const;
|
||||
|
||||
const setup = async ({
|
||||
isPublic = true,
|
||||
method = "GET",
|
||||
requests = [queryRequest, actionRequest, deleteRequest],
|
||||
}: {
|
||||
isPublic?: boolean;
|
||||
method?: "GET" | "POST";
|
||||
requests?: readonly Record<string, unknown>[];
|
||||
} = {}) => {
|
||||
const db = createDb();
|
||||
const ownerId = createId();
|
||||
const boardId = createId();
|
||||
const itemId = createId();
|
||||
const definitionId = createId();
|
||||
await db.insert(users).values({ id: ownerId });
|
||||
await db.insert(boards).values({ id: boardId, name: createId(), creatorId: ownerId, isPublic });
|
||||
await db.insert(customWidgetDefinitions).values({
|
||||
id: definitionId,
|
||||
name: "Custom JSX",
|
||||
url: "https://example.com/api",
|
||||
method,
|
||||
authType: "none",
|
||||
displayType: "customJsx",
|
||||
displayConfig: stringifySuperJson({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
template: "<Text>{data.value}</Text>",
|
||||
networkScope: "public",
|
||||
requests,
|
||||
}),
|
||||
creatorId: ownerId,
|
||||
});
|
||||
await db.insert(items).values({
|
||||
id: itemId,
|
||||
boardId,
|
||||
kind: "customApi",
|
||||
options: stringifySuperJson({ definitionId, refreshInterval: 30 }),
|
||||
});
|
||||
return { db, ownerId, boardId, itemId, definitionId };
|
||||
};
|
||||
|
||||
describe("customApiRouter v2", () => {
|
||||
beforeEach(() => mocks.executeRequest.mockClear());
|
||||
|
||||
test("does not expose the removed raw subFetch procedure", () => {
|
||||
expect(Object.hasOwn(customApiRouter._def.procedures, "subFetch")).toBe(false);
|
||||
});
|
||||
|
||||
test("allows anonymous queries only through a public board placement", async () => {
|
||||
const { db, itemId } = await setup();
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
const result = await caller.queryRequest({ itemId, requestId: "status", params: { name: "homarr" } });
|
||||
|
||||
expect(result).toMatchObject({ ok: true, status: 200, data: { value: 42 } });
|
||||
expect(mocks.executeRequest).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("does not expose a placed definition through an inaccessible board", async () => {
|
||||
const { db, itemId } = await setup({ isPublic: false });
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await expect(caller.getData({ itemId })).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does not execute non-GET base data requests automatically", async () => {
|
||||
const { db, itemId } = await setup({ method: "POST" });
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await expect(caller.getData({ itemId })).resolves.toEqual({ type: "networkAccessNeedsReview" });
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("cannot select a request from a definition that is not attached to the item", async () => {
|
||||
const { db, itemId, ownerId } = await setup({ requests: [] });
|
||||
const otherDefinitionId = createId();
|
||||
await db.insert(customWidgetDefinitions).values({
|
||||
id: otherDefinitionId,
|
||||
name: "Other",
|
||||
url: "https://example.com/api",
|
||||
method: "GET",
|
||||
authType: "none",
|
||||
displayType: "customJsx",
|
||||
displayConfig: stringifySuperJson({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
template: "<Text />",
|
||||
networkScope: "public",
|
||||
requests: [queryRequest],
|
||||
}),
|
||||
creatorId: ownerId,
|
||||
});
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await expect(
|
||||
caller.queryRequest({ itemId, requestId: "status", params: { name: "homarr" } }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects mismatched request kinds and typed parameters", async () => {
|
||||
const { db, itemId } = await setup();
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await expect(caller.queryRequest({ itemId, requestId: "toggle", params: { enabled: true } })).rejects.toMatchObject(
|
||||
{ code: "NOT_FOUND" },
|
||||
);
|
||||
await expect(caller.queryRequest({ itemId, requestId: "status", params: { name: 42 } })).rejects.toMatchObject({
|
||||
code: "BAD_REQUEST",
|
||||
});
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects disabled definitions before any network request", async () => {
|
||||
const { db, itemId, definitionId } = await setup();
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ enabled: false })
|
||||
.where(eq(customWidgetDefinitions.id, definitionId));
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await expect(caller.getData({ itemId })).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("requires modify permission for named actions", async () => {
|
||||
const { db, itemId } = await setup();
|
||||
const viewerId = createId();
|
||||
await db.insert(users).values({ id: viewerId });
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(viewerId) });
|
||||
|
||||
await expect(
|
||||
caller.executeAction({ itemId, requestId: "toggle", params: { enabled: true } }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("executes an authorized named action once with typed body substitution", async () => {
|
||||
const { db, itemId, boardId } = await setup({ isPublic: false });
|
||||
const editorId = createId();
|
||||
await db.insert(users).values({ id: editorId });
|
||||
await db.insert(boardUserPermissions).values({ boardId, userId: editorId, permission: "modify" });
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(editorId) });
|
||||
|
||||
const result = await caller.executeAction({ itemId, requestId: "toggle", params: { enabled: true } });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(mocks.executeRequest).toHaveBeenCalledOnce();
|
||||
expect(mocks.executeRequest).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ method: "POST", body: '{"enabled":true}' }),
|
||||
);
|
||||
});
|
||||
|
||||
test("requires explicit confirmation before DELETE", async () => {
|
||||
const { db, itemId, ownerId } = await setup({ isPublic: false });
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(ownerId) });
|
||||
|
||||
await expect(caller.executeAction({ itemId, requestId: "delete", params: {} })).rejects.toMatchObject({
|
||||
code: "PRECONDITION_FAILED",
|
||||
});
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -3,25 +3,19 @@ import { parse as parseSuperJson } from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { eq } from "@homarr/db";
|
||||
import { boards, customWidgetDefinitions, items } from "@homarr/db/schema";
|
||||
import type { BoardPermission } from "@homarr/definitions";
|
||||
import {
|
||||
customJsxDisplayConfigV2Schema,
|
||||
displayConfigSchema,
|
||||
extractActionButtonDisplay,
|
||||
extractDisplayDataWithFallback,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import type { CustomJsxRequest, CustomWidgetMethod, DisplayConfig } from "@homarr/custom-widgets/core";
|
||||
import { validateCustomWidgetOptions } from "@homarr/custom-widgets/core";
|
||||
import type { CustomJsxRequest, CustomWidgetSource } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
import { executeCustomWidgetRequest } from "../custom-widget/request-executor";
|
||||
import { executeCustomWidgetRequest, invalidateCustomWidgetResponseCache } from "../custom-widget/request-executor";
|
||||
import { hashRuntimeParams, renderRequestBody, renderRequestTarget } from "../custom-widget/request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "../custom-widget/request-limits";
|
||||
|
||||
const logger = createLogger({ module: "widget:customApi" });
|
||||
import { getCustomWidgetCacheVersion } from "../custom-widget/cache-version";
|
||||
import { parseStoredCustomWidgetDefinition } from "../custom-widget/stored-definition";
|
||||
|
||||
const runtimeParamsSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]));
|
||||
const itemInputSchema = z.object({ itemId: z.string().min(1) });
|
||||
@@ -30,31 +24,39 @@ const namedRequestInputSchema = itemInputSchema.extend({
|
||||
params: runtimeParamsSchema.default({}),
|
||||
});
|
||||
|
||||
interface CustomWidgetItemOptions {
|
||||
definitionId: string;
|
||||
configuration: Record<string, unknown>;
|
||||
configurationVersion: number;
|
||||
refreshInterval?: number;
|
||||
}
|
||||
|
||||
type RouterContext = Parameters<typeof throwIfActionForbiddenAsync>[0];
|
||||
type ResolvedDefinition = Awaited<ReturnType<typeof resolvePlacedDefinitionAsync>>;
|
||||
|
||||
const parseItemOptions = (raw: string): { definitionId: string } => {
|
||||
const parseItemOptions = (raw: string): CustomWidgetItemOptions => {
|
||||
try {
|
||||
const options = parseSuperJson(raw) as Record<string, unknown>;
|
||||
if (typeof options.definitionId !== "string" || options.definitionId.length === 0) throw new Error();
|
||||
return { definitionId: options.definitionId };
|
||||
return {
|
||||
definitionId: options.definitionId,
|
||||
configuration:
|
||||
options.configuration !== null &&
|
||||
typeof options.configuration === "object" &&
|
||||
!Array.isArray(options.configuration)
|
||||
? (options.configuration as Record<string, unknown>)
|
||||
: {},
|
||||
configurationVersion:
|
||||
typeof options.configurationVersion === "number" && Number.isInteger(options.configurationVersion)
|
||||
? options.configurationVersion
|
||||
: 1,
|
||||
refreshInterval: typeof options.refreshInterval === "number" ? options.refreshInterval : undefined,
|
||||
};
|
||||
} catch {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget item not found" });
|
||||
}
|
||||
};
|
||||
|
||||
const parseDisplayConfig = (raw: string): DisplayConfig => {
|
||||
try {
|
||||
return displayConfigSchema.parse(parseSuperJson(raw));
|
||||
} catch (error) {
|
||||
logger.error("Invalid custom widget display configuration", { error });
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: "Custom widget network access needs review",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
async function resolvePlacedDefinitionAsync(ctx: RouterContext, itemId: string) {
|
||||
const item = await ctx.db.query.items.findFirst({
|
||||
where: eq(items.id, itemId),
|
||||
@@ -65,83 +67,68 @@ async function resolvePlacedDefinitionAsync(ctx: RouterContext, itemId: string)
|
||||
}
|
||||
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, item.boardId), "view");
|
||||
const { definitionId } = parseItemOptions(item.options);
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, definitionId),
|
||||
const itemOptions = parseItemOptions(item.options);
|
||||
const stored = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, itemOptions.definitionId),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!definition) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
}
|
||||
if (!definition.enabled) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Widget is disabled" });
|
||||
}
|
||||
if (!stored) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget unavailable" });
|
||||
if (!stored.enabled) throw new TRPCError({ code: "FORBIDDEN", message: "Widget is disabled" });
|
||||
|
||||
return { item, definition, displayConfig: parseDisplayConfig(definition.displayConfig) };
|
||||
}
|
||||
|
||||
const getDecryptedSecrets = (resolved: ResolvedDefinition) =>
|
||||
resolved.definition.secrets.map((secret) => ({ kind: secret.kind, value: decryptSecret(secret.value) }));
|
||||
|
||||
const getAuth = (resolved: ResolvedDefinition, mode: "inherit" | "none" = "inherit") =>
|
||||
mode === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: resolved.definition.authType,
|
||||
secrets: getDecryptedSecrets(resolved),
|
||||
headerName: resolved.definition.headerName,
|
||||
};
|
||||
|
||||
const getNetworkScope = (displayConfig: DisplayConfig) =>
|
||||
displayConfig.type === "customJsx" && "jsxApiVersion" in displayConfig && displayConfig.jsxApiVersion === 2
|
||||
? displayConfig.networkScope
|
||||
: ("private" as const);
|
||||
|
||||
const getV2Config = (resolved: ResolvedDefinition) => {
|
||||
const parsed = customJsxDisplayConfigV2Schema.safeParse(resolved.displayConfig);
|
||||
if (!parsed.success) {
|
||||
const definition = parseStoredCustomWidgetDefinition(stored);
|
||||
const configuration = { ...definition.defaultOptions, ...itemOptions.configuration };
|
||||
const issues = validateCustomWidgetOptions(definition.optionsSchema, configuration);
|
||||
if (issues.length > 0) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: "This template must be reviewed and migrated to named requests",
|
||||
message: `Custom widget configuration needs repair: ${issues[0]?.path} ${issues[0]?.message}`,
|
||||
});
|
||||
}
|
||||
return parsed.data;
|
||||
};
|
||||
return { item, stored, definition, itemOptions, configuration };
|
||||
}
|
||||
|
||||
const findNamedRequest = (resolved: ResolvedDefinition, requestId: string, kind: "query" | "action") => {
|
||||
const request = getV2Config(resolved).requests.find((candidate) => candidate.id === requestId);
|
||||
if (!request || request.kind !== kind) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Named request not found" });
|
||||
}
|
||||
const findRequest = (resolved: ResolvedDefinition, requestId: string, kind: "query" | "action") => {
|
||||
const request = resolved.definition.requests.find(
|
||||
(candidate) => candidate.id === requestId && candidate.kind === kind,
|
||||
);
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND", message: "Named request not found" });
|
||||
return request;
|
||||
};
|
||||
|
||||
const getCacheKey = (
|
||||
resolved: ResolvedDefinition,
|
||||
request: CustomJsxRequest,
|
||||
params: Record<string, string | number | boolean>,
|
||||
) => {
|
||||
const digest = hashRuntimeParams(params);
|
||||
return `custom-jsx:${resolved.item.id}:${request.id}:${digest}`;
|
||||
const findSource = (resolved: ResolvedDefinition, sourceId: string) => {
|
||||
const source = resolved.definition.sources.find((candidate) => candidate.id === sourceId);
|
||||
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Widget API source not found" });
|
||||
return source;
|
||||
};
|
||||
|
||||
const assertUpstreamSuccess = (response: { ok: boolean; status: number; statusText: string }) => {
|
||||
if (!response.ok) {
|
||||
throw new TRPCError({ code: "BAD_GATEWAY", message: `API returned ${response.status}: ${response.statusText}` });
|
||||
}
|
||||
const getAuth = (resolved: ResolvedDefinition, source: CustomWidgetSource, mode: "inherit" | "none") => {
|
||||
if (mode === "none" || source.auth.type === "none") return undefined;
|
||||
const secrets = resolved.stored.secrets
|
||||
.filter((secret) => secret.sourceId === source.id)
|
||||
.map((secret) => ({ kind: secret.kind, value: decryptSecret(secret.encryptedValue) }));
|
||||
return {
|
||||
type: source.auth.type,
|
||||
secrets,
|
||||
headerName:
|
||||
source.auth.type === "apiKeyHeader"
|
||||
? source.auth.headerName
|
||||
: source.auth.type === "apiKeyQuery"
|
||||
? source.auth.parameterName
|
||||
: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const withRequestLimit = async <T>(
|
||||
ctx: RouterContext,
|
||||
resolved: ResolvedDefinition,
|
||||
category: "query" | "action" | "delete",
|
||||
request: CustomJsxRequest,
|
||||
callback: () => Promise<T>,
|
||||
) => {
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category,
|
||||
category: request.kind === "query" ? "query" : request.method === "DELETE" ? "delete" : "action",
|
||||
userId: ctx.session?.user.id,
|
||||
itemId: resolved.item.id,
|
||||
definitionId: resolved.definition.id,
|
||||
definitionId: resolved.stored.id,
|
||||
});
|
||||
try {
|
||||
return await callback();
|
||||
@@ -150,52 +137,121 @@ const withRequestLimit = async <T>(
|
||||
}
|
||||
};
|
||||
|
||||
const getCacheKey = (
|
||||
resolved: ResolvedDefinition,
|
||||
request: CustomJsxRequest,
|
||||
params: Record<string, string | number | boolean>,
|
||||
) =>
|
||||
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${request.id}:${hashRuntimeParams(params)}`;
|
||||
|
||||
const executeRequest = async (
|
||||
ctx: RouterContext,
|
||||
resolved: ResolvedDefinition,
|
||||
request: CustomJsxRequest,
|
||||
params: Record<string, string | number | boolean>,
|
||||
) => {
|
||||
await throwIfActionForbiddenAsync(
|
||||
ctx,
|
||||
eq(boards.id, resolved.item.boardId),
|
||||
request.minimumBoardPermission as BoardPermission,
|
||||
);
|
||||
const source = findSource(resolved, request.sourceId);
|
||||
const targetUrl = renderRequestTarget(source.baseUrl, request, params);
|
||||
return withRequestLimit(ctx, resolved, request, () =>
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: source.baseUrl,
|
||||
targetUrl,
|
||||
method: request.method,
|
||||
body: renderRequestBody(request.bodyTemplate, params),
|
||||
staticHeaders: request.staticHeaders,
|
||||
auth: getAuth(resolved, source, request.auth),
|
||||
networkScope: source.networkScope,
|
||||
kind: request.kind,
|
||||
cacheKey: request.kind === "query" ? getCacheKey(resolved, request, params) : undefined,
|
||||
cacheTtlSeconds: request.cacheTtlSeconds,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const getLoadParams = (resolved: ResolvedDefinition, request: CustomJsxRequest) => {
|
||||
const params: Record<string, string | number | boolean> = {};
|
||||
for (const [name, type] of Object.entries(request.parameters)) {
|
||||
const value = resolved.configuration[name];
|
||||
if (typeof value !== type) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: `Load request '${request.id}' needs option '${name}' (${type})`,
|
||||
});
|
||||
}
|
||||
params[name] = value as string | number | boolean;
|
||||
}
|
||||
return params;
|
||||
};
|
||||
|
||||
export const customApiRouter = createTRPCRouter({
|
||||
getData: publicProcedure.input(itemInputSchema).query(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
const { definition, displayConfig } = resolved;
|
||||
|
||||
if (definition.displayType === "actionButton") {
|
||||
return {
|
||||
...(extractActionButtonDisplay(displayConfig) as Record<string, unknown>),
|
||||
requiresConfirmation: definition.method === "DELETE",
|
||||
};
|
||||
}
|
||||
if (definition.method !== "GET") {
|
||||
return { type: "networkAccessNeedsReview" as const };
|
||||
}
|
||||
|
||||
const response = await withRequestLimit(ctx, resolved, "query", () =>
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: definition.url,
|
||||
method: "GET",
|
||||
auth: getAuth(resolved),
|
||||
networkScope: getNetworkScope(displayConfig),
|
||||
kind: "query",
|
||||
cacheKey: `custom-widget:base:${resolved.item.id}`,
|
||||
const loadRequests = resolved.definition.requests.filter(
|
||||
(request) => request.kind === "query" && request.trigger === "load",
|
||||
);
|
||||
const entries = await Promise.all(
|
||||
loadRequests.map(async (request) => {
|
||||
try {
|
||||
const response = await executeRequest(ctx, resolved, request, getLoadParams(resolved, request));
|
||||
return [
|
||||
request.id,
|
||||
{
|
||||
data: response.data,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
} catch (error) {
|
||||
return [
|
||||
request.id,
|
||||
{
|
||||
data: null,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: false,
|
||||
status: 0,
|
||||
error: error instanceof Error ? error.message : "Request failed",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
}),
|
||||
);
|
||||
assertUpstreamSuccess(response);
|
||||
return extractDisplayDataWithFallback(response.data, definition.displayType, displayConfig);
|
||||
|
||||
return {
|
||||
type: "customJsx" as const,
|
||||
template: resolved.definition.template,
|
||||
data: Object.fromEntries(entries.map(([id, result]) => [id, result.data])),
|
||||
status: Object.fromEntries(entries.map(([id, result]) => [id, result.status])),
|
||||
options: resolved.configuration,
|
||||
stateSchema: resolved.definition.stateSchema ?? {},
|
||||
defaultState: resolved.definition.defaultState ?? {},
|
||||
requestCapabilities: resolved.definition.requests.map((request) => ({
|
||||
id: request.id,
|
||||
kind: request.kind,
|
||||
method: request.method,
|
||||
trigger: request.trigger,
|
||||
minimumBoardPermission: request.minimumBoardPermission,
|
||||
confirmation: request.confirmation,
|
||||
invalidates: request.invalidates ?? [],
|
||||
})),
|
||||
};
|
||||
}),
|
||||
|
||||
queryRequest: publicProcedure.input(namedRequestInputSchema).query(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
const request = findNamedRequest(resolved, input.requestId, "query");
|
||||
const targetUrl = renderRequestTarget(resolved.definition.url, request, input.params);
|
||||
const response = await withRequestLimit(ctx, resolved, "query", () =>
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: resolved.definition.url,
|
||||
targetUrl,
|
||||
method: "GET",
|
||||
staticHeaders: request.staticHeaders,
|
||||
auth: getAuth(resolved, request.auth),
|
||||
networkScope: getV2Config(resolved).networkScope,
|
||||
kind: "query",
|
||||
cacheKey: getCacheKey(resolved, request, input.params),
|
||||
cacheTtlSeconds: request.cacheTtlSeconds,
|
||||
}),
|
||||
);
|
||||
const request = findRequest(resolved, input.requestId, "query");
|
||||
const response = await executeRequest(ctx, resolved, request, input.params);
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
@@ -205,71 +261,31 @@ export const customApiRouter = createTRPCRouter({
|
||||
};
|
||||
}),
|
||||
|
||||
executeBaseAction: protectedProcedure
|
||||
.input(itemInputSchema.extend({ confirmed: z.boolean().optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
const { definition } = resolved;
|
||||
if (definition.displayType !== "actionButton") {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Only actionButton widgets can use this action" });
|
||||
}
|
||||
|
||||
const permission: BoardPermission = definition.method === "DELETE" ? "full" : "modify";
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, resolved.item.boardId), permission);
|
||||
if (definition.method === "DELETE" && input.confirmed !== true) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "DELETE actions require confirmation" });
|
||||
}
|
||||
|
||||
const response = await withRequestLimit(ctx, resolved, definition.method === "DELETE" ? "delete" : "action", () =>
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: definition.url,
|
||||
method: definition.method,
|
||||
body: definition.method === "GET" ? undefined : (definition.requestBody ?? undefined),
|
||||
auth: getAuth(resolved),
|
||||
networkScope: getNetworkScope(resolved.displayConfig),
|
||||
kind: definition.method === "GET" ? "query" : "action",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
success: response.ok,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
responseInfo: { status: response.status, statusText: response.statusText },
|
||||
};
|
||||
}),
|
||||
|
||||
executeAction: protectedProcedure
|
||||
.input(namedRequestInputSchema.extend({ confirmed: z.boolean().optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
const request = findNamedRequest(resolved, input.requestId, "action");
|
||||
if (request.method === "DELETE" && input.confirmed !== true) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "DELETE actions require confirmation" });
|
||||
const request = findRequest(resolved, input.requestId, "action");
|
||||
const needsConfirmation = request.confirmation !== undefined || request.method === "DELETE";
|
||||
if (needsConfirmation && input.confirmed !== true) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "This action requires confirmation" });
|
||||
}
|
||||
const response = await executeRequest(ctx, resolved, request, input.params);
|
||||
if (response.ok && request.invalidates?.length) {
|
||||
invalidateCustomWidgetResponseCache(
|
||||
request.invalidates.flatMap((requestId) => [
|
||||
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${requestId}:`,
|
||||
`custom-widget:options:${resolved.stored.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${requestId}:`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
await throwIfActionForbiddenAsync(
|
||||
ctx,
|
||||
eq(boards.id, resolved.item.boardId),
|
||||
request.minimumBoardPermission as BoardPermission,
|
||||
);
|
||||
const targetUrl = renderRequestTarget(resolved.definition.url, request, input.params);
|
||||
const response = await withRequestLimit(ctx, resolved, request.method === "DELETE" ? "delete" : "action", () =>
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: resolved.definition.url,
|
||||
targetUrl,
|
||||
method: request.method as CustomWidgetMethod,
|
||||
body: renderRequestBody(request.bodyTemplate, input.params),
|
||||
staticHeaders: request.staticHeaders,
|
||||
auth: getAuth(resolved, request.auth),
|
||||
networkScope: getV2Config(resolved).networkScope,
|
||||
kind: "action",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
data: response.data,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
invalidates: request.invalidates ?? [],
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -38,17 +38,23 @@ test("MCP tools should contain expected procedures", () => {
|
||||
expect(toolNames).toContain("board_duplicateBoard");
|
||||
expect(toolNames).toContain("customWidget_schema");
|
||||
expect(toolNames).toContain("customWidget_validate");
|
||||
expect(toolNames).toContain("customWidget_all");
|
||||
expect(toolNames).toContain("customWidget_byId");
|
||||
expect(toolNames).toContain("customWidget_readTemplate");
|
||||
expect(toolNames).toContain("customWidget_writeTemplate");
|
||||
expect(toolNames).toContain("customWidget_patchTemplate");
|
||||
expect(toolNames).toContain("customWidget_list");
|
||||
expect(toolNames).toContain("customWidget_get");
|
||||
expect(toolNames).toContain("customWidget_templatePatch");
|
||||
expect(toolNames).toContain("customWidget_create");
|
||||
expect(toolNames).toContain("customWidget_import");
|
||||
expect(toolNames).toContain("customWidget_update");
|
||||
expect(toolNames).toContain("customWidget_preview");
|
||||
expect(toolNames).toContain("customWidget_delete");
|
||||
expect(toolNames).toContain("customWidget_previewCreate");
|
||||
expect(toolNames).toContain("customWidget_previewQuery");
|
||||
expect(toolNames).toContain("customWidget_simulatePreviewAction");
|
||||
expect(toolNames).toContain("customWidget_previewAction");
|
||||
expect(toolNames).toContain("customWidget_previewJournal");
|
||||
expect(toolNames).toContain("customWidget_secretSet");
|
||||
expect(toolNames).toContain("customWidget_secretRequestUser");
|
||||
expect(toolNames).toContain("customWidget_getAuthoringPrompt");
|
||||
expect(toolNames).toContain("customWidget_getSkill");
|
||||
expect(toolNames).not.toContain("customWidget_import");
|
||||
expect(toolNames).not.toContain("customWidget_export");
|
||||
expect(toolNames).not.toContain("customWidget_simulatePreviewAction");
|
||||
expect(toolNames).toContain("info_getInfo");
|
||||
expect(toolNames).toContain("invite_getAll");
|
||||
expect(toolNames).toContain("serverSettings_getBoardSettings");
|
||||
@@ -61,13 +67,17 @@ test("MCP tools should have descriptions", () => {
|
||||
for (const tool of tools) {
|
||||
expect(tool.description, `Tool ${tool.name} should have a description`).toBeTruthy();
|
||||
}
|
||||
|
||||
expect(tools.find((tool) => tool.name === "customWidget_getAuthoringPrompt")?.description).toBe(
|
||||
"Get the current Custom Widget authoring instructions.",
|
||||
);
|
||||
});
|
||||
|
||||
test("custom widget public procedures remain available", () => {
|
||||
expect(Object.keys(customWidgetRouter._def.procedures)).toEqual(
|
||||
expect(Object.keys(customWidgetRouter["_def"].procedures)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"all",
|
||||
"byId",
|
||||
"list",
|
||||
"get",
|
||||
"available",
|
||||
"create",
|
||||
"update",
|
||||
@@ -80,13 +90,18 @@ test("custom widget public procedures remain available", () => {
|
||||
"validate",
|
||||
"readTemplate",
|
||||
"writeTemplate",
|
||||
"patchTemplate",
|
||||
"preview",
|
||||
"templatePatch",
|
||||
"previewCreate",
|
||||
"previewGet",
|
||||
"previewQuery",
|
||||
"previewAction",
|
||||
"simulatePreviewAction",
|
||||
"setPreviewLiveActions",
|
||||
"previewJournal",
|
||||
"secretSet",
|
||||
"secretRequestUser",
|
||||
"secretClear",
|
||||
"getAuthoringPrompt",
|
||||
"getSkill",
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -13,8 +13,9 @@ import type { OpenApiMeta } from "trpc-to-openapi";
|
||||
import { ZodError } from "zod/v4";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { FlattenError } from "@homarr/common";
|
||||
import { extractBaseUrlFromHeaders, FlattenError } from "@homarr/common";
|
||||
import { userAgent } from "@homarr/common/server";
|
||||
import type { DeviceType } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { db } from "@homarr/db";
|
||||
import type { GroupPermissionKey, OnboardingStep } from "@homarr/definitions";
|
||||
@@ -36,7 +37,14 @@ const logger = createLogger({ module: "trpc" });
|
||||
*
|
||||
* @see https://trpc.io/docs/server/context
|
||||
*/
|
||||
export const createTRPCContext = (opts: { headers: Headers; session: Session | null }) => {
|
||||
interface ApiContext {
|
||||
session: Session | null;
|
||||
deviceType: DeviceType;
|
||||
baseUrl?: `${string}://${string}`;
|
||||
db: typeof db;
|
||||
}
|
||||
|
||||
export const createTRPCContext = (opts: { headers: Headers; session: Session | null }): ApiContext => {
|
||||
const session = opts.session;
|
||||
const source = opts.headers.get("x-trpc-source") ?? "unknown";
|
||||
|
||||
@@ -49,6 +57,7 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
|
||||
return {
|
||||
session,
|
||||
deviceType: userAgent(opts.headers).device.type,
|
||||
baseUrl: extractBaseUrlFromHeaders(opts.headers),
|
||||
db,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -21,6 +21,9 @@
|
||||
"scripts": {
|
||||
"clean": "rm -rf .turbo node_modules",
|
||||
"check:architecture": "node ./scripts/check-architecture.mjs",
|
||||
"generate:components": "tsx ./scripts/generate-component-metadata.ts",
|
||||
"generate:component-docs": "tsx ./scripts/generate-component-docs.ts",
|
||||
"generate": "pnpm generate:components && pnpm generate:component-docs",
|
||||
"format": "oxfmt .",
|
||||
"lint": "oxlint",
|
||||
"test": "vitest run",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { customJsxComponentRegistry } from "../src/core/component-registry";
|
||||
|
||||
const output = customJsxComponentRegistry.map(
|
||||
({ name, package: packageName, category, safety, reason, documentationUrl }) => ({
|
||||
name,
|
||||
package: packageName,
|
||||
category,
|
||||
safety,
|
||||
reason,
|
||||
documentationUrl,
|
||||
}),
|
||||
);
|
||||
|
||||
await writeFile(
|
||||
resolve(import.meta.dirname, "../../../apps/docs/src/generated/custom-jsx-components.json"),
|
||||
`${JSON.stringify(output, null, 2)}\n`,
|
||||
);
|
||||
@@ -0,0 +1,72 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import * as Charts from "@mantine/charts";
|
||||
import * as Core from "@mantine/core";
|
||||
import * as Dates from "@mantine/dates";
|
||||
import ts from "typescript";
|
||||
|
||||
import { discoveredMantineComponents } from "../src/core/component-discovery";
|
||||
import { deniedCustomJsxComponentNames } from "../src/core/component-registry-denied";
|
||||
import { isBlockedCustomJsxProp } from "../src/jsx/policy";
|
||||
|
||||
void [Core, Dates, Charts];
|
||||
|
||||
const packageRoot = resolve(import.meta.dirname, "..");
|
||||
const configPath = resolve(packageRoot, "tsconfig.json");
|
||||
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
|
||||
if (configFile.error) throw new Error(ts.flattenDiagnosticMessageText(configFile.error.messageText, "\n"));
|
||||
const config = ts.parseJsonConfigFileContent(configFile.config, ts.sys, packageRoot);
|
||||
const program = ts.createProgram({ rootNames: [...config.fileNames, import.meta.filename], options: config.options });
|
||||
const checker = program.getTypeChecker();
|
||||
const source = program.getSourceFile(import.meta.filename);
|
||||
if (!source) throw new Error("Unable to inspect the component metadata generator");
|
||||
|
||||
const moduleSymbols = new Map<string, ts.Symbol>();
|
||||
for (const declaration of source.statements) {
|
||||
if (!ts.isImportDeclaration(declaration) || !ts.isStringLiteral(declaration.moduleSpecifier)) continue;
|
||||
const moduleName = declaration.moduleSpecifier.text;
|
||||
if (!moduleName.startsWith("@mantine/")) continue;
|
||||
const symbol = checker.getSymbolAtLocation(declaration.moduleSpecifier);
|
||||
if (symbol) moduleSymbols.set(moduleName, symbol);
|
||||
}
|
||||
|
||||
function isCallableType(type: ts.Type): boolean {
|
||||
if (type.getCallSignatures().length > 0) return true;
|
||||
return type.isUnionOrIntersection() && type.types.some(isCallableType);
|
||||
}
|
||||
const metadata: Record<string, string[]> = {};
|
||||
for (const component of discoveredMantineComponents) {
|
||||
if (deniedCustomJsxComponentNames.has(component.name)) continue;
|
||||
const moduleSymbol = moduleSymbols.get(component.package);
|
||||
const rootName = component.name.split(".")[0];
|
||||
let symbol =
|
||||
moduleSymbol && checker.getExportsOfModule(moduleSymbol).find((candidate) => candidate.name === rootName);
|
||||
let location = symbol?.valueDeclaration ?? symbol?.declarations?.[0] ?? source;
|
||||
let type = symbol && checker.getTypeOfSymbolAtLocation(symbol, location);
|
||||
for (const segment of component.name.split(".").slice(1)) {
|
||||
symbol = type?.getProperty(segment);
|
||||
if (!symbol) break;
|
||||
location = symbol.valueDeclaration ?? symbol.declarations?.[0] ?? location;
|
||||
type = checker.getTypeOfSymbolAtLocation(symbol, location);
|
||||
}
|
||||
const signature = type?.getCallSignatures()[0] ?? type?.getConstructSignatures()[0];
|
||||
const parameter = signature?.parameters[0];
|
||||
const props = parameter
|
||||
? checker.getPropertiesOfType(checker.getTypeOfSymbolAtLocation(parameter, parameter.valueDeclaration ?? location))
|
||||
: [];
|
||||
metadata[component.name] = props
|
||||
.filter((prop) => {
|
||||
const declaration = prop.valueDeclaration ?? prop.declarations?.[0] ?? location;
|
||||
return (
|
||||
!isBlockedCustomJsxProp(prop.name) && !isCallableType(checker.getTypeOfSymbolAtLocation(prop, declaration))
|
||||
);
|
||||
})
|
||||
.map((prop) => prop.name)
|
||||
.toSorted();
|
||||
}
|
||||
|
||||
await writeFile(
|
||||
resolve(packageRoot, "src/core/component-props.generated.json"),
|
||||
`${JSON.stringify(metadata, null, 2)}\n`,
|
||||
);
|
||||
@@ -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 : [];
|
||||
}
|
||||
@@ -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",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -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"),
|
||||
};
|
||||
}
|
||||
@@ -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));
|
||||
@@ -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];
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -0,0 +1,66 @@
|
||||
export interface AstNode {
|
||||
type: string;
|
||||
start?: number;
|
||||
loc?: { start?: { line?: number; column?: number } };
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export const nodeOf = (value: unknown): AstNode | null =>
|
||||
value !== null && typeof value === "object" && typeof (value as { type?: unknown }).type === "string"
|
||||
? (value as AstNode)
|
||||
: null;
|
||||
|
||||
export const nodesOf = (value: unknown): AstNode[] =>
|
||||
Array.isArray(value) ? value.map(nodeOf).filter((node): node is AstNode => node !== null) : [];
|
||||
|
||||
export const staticPropertyName = (node: AstNode | null): string | undefined => {
|
||||
if (!node) return undefined;
|
||||
if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number")) {
|
||||
return String(node.value);
|
||||
}
|
||||
if (node.type === "BinaryExpression" && node.operator === "+") {
|
||||
const left = staticPropertyName(nodeOf(node.left));
|
||||
const right = staticPropertyName(nodeOf(node.right));
|
||||
return left === undefined || right === undefined ? undefined : left + right;
|
||||
}
|
||||
if (node.type === "TemplateLiteral" && Array.isArray(node.expressions) && node.expressions.length === 0) {
|
||||
return (node.quasis as Array<{ value?: { cooked?: unknown } }> | undefined)
|
||||
?.map((quasi) => String(quasi.value?.cooked ?? ""))
|
||||
.join("");
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const callbackCollectionMethods = new Set(["every", "filter", "find", "findIndex", "map", "reduce", "some", "sort"]);
|
||||
|
||||
export function containsEscapingCallback(node: AstNode): boolean {
|
||||
if (node.type === "ArrowFunctionExpression") return true;
|
||||
if (node.type === "CallExpression") {
|
||||
const callee = nodeOf(node.callee);
|
||||
if (callee && containsEscapingCallback(callee)) return true;
|
||||
const property = callee?.type === "MemberExpression" ? nodeOf(callee.property) : null;
|
||||
const method = property?.type === "Identifier" ? String(property.name) : staticPropertyName(property);
|
||||
return nodesOf(node.arguments).some((argument) => {
|
||||
if (argument.type !== "ArrowFunctionExpression" || !method || !callbackCollectionMethods.has(method)) {
|
||||
return containsEscapingCallback(argument);
|
||||
}
|
||||
const body = nodeOf(argument.body);
|
||||
return body ? containsEscapingCallback(body) : false;
|
||||
});
|
||||
}
|
||||
return containsEscapingCallbackChildren(node);
|
||||
}
|
||||
|
||||
function containsEscapingCallbackChildren(node: AstNode): boolean {
|
||||
return Object.entries(node).some(([key, value]) => {
|
||||
if (["loc", "start", "end", "type"].includes(key)) return false;
|
||||
if (Array.isArray(value)) {
|
||||
return value.some((entry) => {
|
||||
const child = nodeOf(entry);
|
||||
return child ? containsEscapingCallback(child) : false;
|
||||
});
|
||||
}
|
||||
const child = nodeOf(value);
|
||||
return child ? containsEscapingCallback(child) : false;
|
||||
});
|
||||
}
|
||||
@@ -1,20 +1,21 @@
|
||||
import { Parser } from "acorn";
|
||||
import jsx from "acorn-jsx";
|
||||
|
||||
import { customJsxComponentByName, customJsxSupportedPropsByName } from "../core/component-registry";
|
||||
import {
|
||||
customJsxBindableComponentNames,
|
||||
customJsxComponentByName,
|
||||
customJsxSupportedPropsByName,
|
||||
enabledCustomJsxComponents,
|
||||
} from "../core/component-registry";
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
CUSTOM_JSX_BLOCKED_PROPS,
|
||||
CUSTOM_JSX_LIMITS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
|
||||
interface AstNode {
|
||||
type: string;
|
||||
start?: number;
|
||||
loc?: { start?: { line?: number; column?: number } };
|
||||
[key: string]: unknown;
|
||||
}
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { containsEscapingCallback, nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
|
||||
|
||||
export interface CustomJsxTemplateDiagnostic {
|
||||
severity: "error" | "warning";
|
||||
@@ -25,6 +26,32 @@ export interface CustomJsxTemplateDiagnostic {
|
||||
}
|
||||
|
||||
const JsxParser = Parser.extend(jsx());
|
||||
const enabledComponentNames = enabledCustomJsxComponents.map((component) => component.name);
|
||||
|
||||
function closestComponentName(value: string): string | undefined {
|
||||
let closest: { name: string; distance: number } | undefined;
|
||||
for (const name of enabledComponentNames) {
|
||||
const distance = editDistance(value.toLowerCase(), name.toLowerCase());
|
||||
if (!closest || distance < closest.distance) closest = { name, distance };
|
||||
}
|
||||
return closest && closest.distance <= Math.max(2, Math.floor(value.length / 3)) ? closest.name : undefined;
|
||||
}
|
||||
|
||||
function editDistance(left: string, right: string): number {
|
||||
const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
||||
for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
|
||||
const current = [leftIndex];
|
||||
for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
|
||||
current[rightIndex] = Math.min(
|
||||
(current[rightIndex - 1] ?? 0) + 1,
|
||||
(previous[rightIndex] ?? 0) + 1,
|
||||
(previous[rightIndex - 1] ?? 0) + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),
|
||||
);
|
||||
}
|
||||
previous.splice(0, previous.length, ...current);
|
||||
}
|
||||
return previous[right.length] ?? Math.max(left.length, right.length);
|
||||
}
|
||||
|
||||
const rootBindings = new Set([
|
||||
"Array",
|
||||
@@ -38,6 +65,9 @@ const rootBindings = new Set([
|
||||
"Object",
|
||||
"String",
|
||||
"data",
|
||||
"options",
|
||||
"state",
|
||||
"status",
|
||||
"decodeURIComponent",
|
||||
"encodeURIComponent",
|
||||
"isFinite",
|
||||
@@ -47,31 +77,15 @@ const rootBindings = new Set([
|
||||
"undefined",
|
||||
]);
|
||||
|
||||
const nodeOf = (value: unknown): AstNode | null =>
|
||||
value !== null && typeof value === "object" && typeof (value as { type?: unknown }).type === "string"
|
||||
? (value as AstNode)
|
||||
: null;
|
||||
|
||||
const nodesOf = (value: unknown): AstNode[] =>
|
||||
Array.isArray(value) ? value.map(nodeOf).filter((node): node is AstNode => node !== null) : [];
|
||||
|
||||
const staticPropertyName = (node: AstNode | null): string | undefined => {
|
||||
if (!node) return undefined;
|
||||
if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number")) {
|
||||
return String(node.value);
|
||||
}
|
||||
if (node.type === "BinaryExpression" && node.operator === "+") {
|
||||
const left = staticPropertyName(nodeOf(node.left));
|
||||
const right = staticPropertyName(nodeOf(node.right));
|
||||
return left === undefined || right === undefined ? undefined : left + right;
|
||||
}
|
||||
if (node.type === "TemplateLiteral" && Array.isArray(node.expressions) && node.expressions.length === 0) {
|
||||
return (node.quasis as Array<{ value?: { cooked?: unknown } }> | undefined)
|
||||
?.map((quasi) => String(quasi.value?.cooked ?? ""))
|
||||
.join("");
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
function tagName(node: AstNode): string | null {
|
||||
if (node.type === "JSXIdentifier") return String(node.name ?? "");
|
||||
if (node.type !== "JSXMemberExpression") return null;
|
||||
const object = nodeOf(node.object);
|
||||
const property = nodeOf(node.property);
|
||||
const left = object ? tagName(object) : null;
|
||||
const right = property ? tagName(property) : null;
|
||||
return left && right ? `${left}.${right}` : null;
|
||||
}
|
||||
|
||||
export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDiagnostic[] {
|
||||
const diagnostics: CustomJsxTemplateDiagnostic[] = [];
|
||||
@@ -98,16 +112,6 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return depth <= CUSTOM_JSX_LIMITS.astDepth && operations <= CUSTOM_JSX_LIMITS.operations;
|
||||
};
|
||||
|
||||
const tagName = (node: AstNode): string | null => {
|
||||
if (node.type === "JSXIdentifier") return String(node.name ?? "");
|
||||
if (node.type !== "JSXMemberExpression") return null;
|
||||
const object = nodeOf(node.object);
|
||||
const property = nodeOf(node.property);
|
||||
const left = object ? tagName(object) : null;
|
||||
const right = property ? tagName(property) : null;
|
||||
return left && right ? `${left}.${right}` : null;
|
||||
};
|
||||
|
||||
const visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
if (!checkBudget(node, depth)) return;
|
||||
|
||||
@@ -132,8 +136,19 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
const nameNode = nodeOf(opening.name);
|
||||
const name = nameNode ? tagName(nameNode) : null;
|
||||
const descriptor = name ? customJsxComponentByName.get(name) : undefined;
|
||||
if (!descriptor || descriptor.safety === "denied") {
|
||||
add(opening, name ? `Component '${name}' is not available` : "Invalid JSX component name");
|
||||
if (descriptor?.safety === "denied") {
|
||||
add(
|
||||
opening,
|
||||
`BLOCKED_CAPABILITY: '${name}' is not available${descriptor.reason ? ` because it ${descriptor.reason.toLowerCase()}` : ""}`,
|
||||
);
|
||||
} else if (!descriptor) {
|
||||
const suggestion = name ? closestComponentName(name) : undefined;
|
||||
add(
|
||||
opening,
|
||||
name
|
||||
? `UNKNOWN_COMPONENT: '${name}' is not available${suggestion ? `. Did you mean '${suggestion}'?` : ""}`
|
||||
: "UNKNOWN_COMPONENT: Invalid JSX component name",
|
||||
);
|
||||
}
|
||||
|
||||
for (const attribute of nodesOf(opening.attributes)) {
|
||||
@@ -148,19 +163,29 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
}
|
||||
const attributeNameNode = nodeOf(attribute.name);
|
||||
const attributeName = attributeNameNode?.type === "JSXIdentifier" ? String(attributeNameNode.name) : "";
|
||||
const supportedProps = name ? customJsxSupportedPropsByName.get(name) : undefined;
|
||||
if (
|
||||
(/^on/i.test(attributeName) && !supportedProps?.has(attributeName)) ||
|
||||
CUSTOM_JSX_BLOCKED_PROPS.has(attributeName)
|
||||
) {
|
||||
add(attribute, `Prop '${attributeName}' is not allowed`);
|
||||
} else if (name && !supportedProps?.has(attributeName)) {
|
||||
add(attribute, `Prop '${attributeName}' is not supported by ${name} and will be ignored`, "warning");
|
||||
if (isBlockedCustomJsxProp(attributeName)) {
|
||||
add(attribute, `BLOCKED_CAPABILITY: Prop '${attributeName}' is not allowed`);
|
||||
} else if (name && attributeName !== "bind" && !customJsxSupportedPropsByName.get(name)?.has(attributeName)) {
|
||||
add(attribute, `UNKNOWN_MANTINE_PROP: '${attributeName}' on ${name} will be passed through`, "warning");
|
||||
} else if (name && attributeName === "bind" && !customJsxBindableComponentNames.has(name)) {
|
||||
add(attribute, `BINDING_UNAVAILABLE: '${name}' does not have a declarative binding adapter`, "warning");
|
||||
}
|
||||
const value = nodeOf(attribute.value);
|
||||
if (
|
||||
CUSTOM_JSX_URL_PROPS.has(attributeName) &&
|
||||
value?.type === "Literal" &&
|
||||
typeof value.value === "string" &&
|
||||
!isSafeLiteralUrl(value.value)
|
||||
) {
|
||||
add(attribute, `INVALID_PROP_VALUE: '${attributeName}' contains an unsafe URL`);
|
||||
}
|
||||
if (value?.type === "JSXExpressionContainer") {
|
||||
const expression = nodeOf(value.expression);
|
||||
if (expression && expression.type !== "JSXEmptyExpression") visit(expression, depth + 1, bindings);
|
||||
if (expression && containsEscapingCallback(expression)) {
|
||||
add(attribute, `BLOCKED_CAPABILITY: Callback prop '${attributeName}' is not allowed`);
|
||||
} else if (expression && expression.type !== "JSXEmptyExpression") {
|
||||
visit(expression, depth + 1, bindings);
|
||||
}
|
||||
}
|
||||
}
|
||||
nodesOf(node.children).forEach((child) => visit(child, depth + 1, bindings));
|
||||
@@ -304,3 +329,13 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function isSafeLiteralUrl(value: string) {
|
||||
if (value.startsWith("#") || (value.startsWith("/") && !value.startsWith("//"))) return true;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement, Fragment } from "react";
|
||||
|
||||
import { asNode, asNodeArray, isInterpreterCallback, SafeJsxError } from "./interpreter-foundation";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Budget, Environment, InterpreterCallback } from "./interpreter-foundation";
|
||||
import { normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { CUSTOM_JSX_BLOCKED_TAGS } from "./policy";
|
||||
|
||||
export interface JsxEmitterContext {
|
||||
@@ -54,32 +54,20 @@ export function emitJsxElement(
|
||||
if (attribute.type !== "JSXAttribute") throw new SafeJsxError(`Unsupported JSX attribute: ${attribute.type}`);
|
||||
const nameNode = asNode(attribute.name, "attribute name");
|
||||
if (nameNode.type !== "JSXIdentifier") throw new SafeJsxError("Namespaced JSX attributes are not supported");
|
||||
const name = normalizedProperty(nameNode.name);
|
||||
const rawName = String(nameNode.name);
|
||||
// `bind` is a safe declarative JSX prop even though reflective `.bind` access is blocked by the interpreter.
|
||||
const name = rawName === "bind" ? rawName : normalizedProperty(rawName);
|
||||
if (attribute.value == null) rawProps[name] = true;
|
||||
else {
|
||||
const value = asNode(attribute.value, "attribute value");
|
||||
rawProps[name] = value.type === "Literal" ? value.value : context.evaluate(value, environment, depth + 1);
|
||||
}
|
||||
}
|
||||
let children = asNodeArray(node.children, "JSX children").map((child) =>
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) =>
|
||||
context.evaluate(child, environment, depth + 1),
|
||||
);
|
||||
diagnoseCustomJsxProps(rawProps, tag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, tag);
|
||||
if (tag === "SubFetch") {
|
||||
const callbackChildren = children.filter(isInterpreterCallback);
|
||||
const callbackProp = rawProps.render;
|
||||
if (callbackProp !== undefined && !isInterpreterCallback(callbackProp)) {
|
||||
throw new SafeJsxError("SubFetch render must be an inline arrow callback");
|
||||
}
|
||||
if (callbackChildren.length > 1 || (callbackChildren.length === 1 && callbackProp !== undefined)) {
|
||||
throw new SafeJsxError("SubFetch accepts only one render callback");
|
||||
}
|
||||
const callback = isInterpreterCallback(callbackProp) ? callbackProp : callbackChildren[0];
|
||||
if (callback) {
|
||||
props.render = (value: unknown, metadata: unknown) => context.renderCallback(callback, [value, metadata]);
|
||||
children = children.filter((child) => child !== callback);
|
||||
}
|
||||
}
|
||||
context.budget.rendered();
|
||||
return createElement(component, props as never, ...(children as ReactNode[]));
|
||||
}
|
||||
|
||||
@@ -20,18 +20,31 @@ export const CUSTOM_JSX_BLOCKED_PROPERTIES: ReadonlySet<string> = new Set([
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_BLOCKED_PROPS: ReadonlySet<string> = new Set([
|
||||
"autoFocus",
|
||||
"children",
|
||||
"className",
|
||||
"classNames",
|
||||
"classes",
|
||||
"component",
|
||||
"contentEditable",
|
||||
"dangerouslySetInnerHTML",
|
||||
"form",
|
||||
"formAction",
|
||||
"formEncType",
|
||||
"formMethod",
|
||||
"formNoValidate",
|
||||
"formTarget",
|
||||
"innerRef",
|
||||
"ping",
|
||||
"popover",
|
||||
"popoverTarget",
|
||||
"popoverTargetAction",
|
||||
"portalProps",
|
||||
"ref",
|
||||
"renderRoot",
|
||||
"styles",
|
||||
"unstyled",
|
||||
"srcDoc",
|
||||
"suppressContentEditableWarning",
|
||||
"suppressHydrationWarning",
|
||||
"withinPortal",
|
||||
]);
|
||||
|
||||
@@ -47,7 +60,14 @@ export const CUSTOM_JSX_BLOCKED_TAGS: ReadonlySet<string> = new Set([
|
||||
"style",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_URL_PROPS: ReadonlySet<string> = new Set(["backgroundImage", "href", "src"]);
|
||||
export const CUSTOM_JSX_URL_PROPS: ReadonlySet<string> = new Set([
|
||||
"backgroundImage",
|
||||
"fallbackSrc",
|
||||
"href",
|
||||
"image",
|
||||
"poster",
|
||||
"src",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_BLOCKED_STYLE_KEYS: ReadonlySet<string> = new Set([
|
||||
"backdropFilter",
|
||||
@@ -60,6 +80,7 @@ export const CUSTOM_JSX_BLOCKED_STYLE_KEYS: ReadonlySet<string> = new Set([
|
||||
"left",
|
||||
"mask",
|
||||
"pointerEvents",
|
||||
"pos",
|
||||
"position",
|
||||
"right",
|
||||
"top",
|
||||
@@ -71,3 +92,14 @@ export function normalizeCustomJsxProperty(value: unknown): string {
|
||||
.normalize("NFKC")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export function isBlockedCustomJsxProp(name: string): boolean {
|
||||
return (
|
||||
/^on/iu.test(name) ||
|
||||
name.startsWith("__") ||
|
||||
/(?:Ref|^ref[A-Z])/u.test(name) ||
|
||||
CUSTOM_JSX_BLOCKED_PROPS.has(name) ||
|
||||
CUSTOM_JSX_BLOCKED_STYLE_KEYS.has(name) ||
|
||||
(name !== "bind" && CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(name)))
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement, useEffect, useRef, useState } from "react";
|
||||
import { createContext, createElement, useContext, useEffect, useRef, useState } from "react";
|
||||
import * as Core from "@mantine/core";
|
||||
import * as Charts from "@mantine/charts";
|
||||
import * as Dates from "@mantine/dates";
|
||||
|
||||
import { enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import { customJsxBindableComponentNames, enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import { ActionButton, ToggleSwitch } from "../runtime/actions";
|
||||
import { SubData } from "../runtime/data";
|
||||
import { RefreshButton } from "../runtime/refresh-button";
|
||||
@@ -31,19 +31,128 @@ function safeUrl(value: unknown) {
|
||||
return typeof value === "string" && (/^https?:\/\//iu.test(value) || value.startsWith("/") || value.startsWith("#"));
|
||||
}
|
||||
|
||||
function wrap(component: ComponentType<never>, additions: Record<string, unknown> = {}) {
|
||||
return function SafeComponent(props: Record<string, unknown>) {
|
||||
return createElement(component, { ...sanitizeCustomJsxProps(props), ...additions } as never);
|
||||
type WidgetStateValue = string | number | boolean | string[] | number[];
|
||||
interface CustomJsxStateContextValue {
|
||||
state: Record<string, WidgetStateValue>;
|
||||
stateSchema: Record<string, string>;
|
||||
setStateValue(name: string, value: WidgetStateValue): void;
|
||||
}
|
||||
|
||||
const CustomJsxStateContext = createContext<CustomJsxStateContextValue | null>(null);
|
||||
|
||||
export function CustomJsxStateProvider({
|
||||
children,
|
||||
state,
|
||||
stateSchema,
|
||||
setStateValue,
|
||||
}: CustomJsxStateContextValue & { children: ReactNode }) {
|
||||
return (
|
||||
<CustomJsxStateContext.Provider value={{ state, stateSchema, setStateValue }}>
|
||||
{children}
|
||||
</CustomJsxStateContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const checkedComponents = new Set(["Checkbox", "Switch"]);
|
||||
const openedComponents = new Set(["HoverCard", "Menu", "Popover"]);
|
||||
const activeComponents = new Set(["Stepper"]);
|
||||
const comboboxComponents = new Set(["Autocomplete", "MultiSelect", "Select", "TagsInput", "TreeSelect"]);
|
||||
const popoverInputComponents = new Set([
|
||||
"ColorInput",
|
||||
"DateInput",
|
||||
"DatePickerInput",
|
||||
"DateTimePicker",
|
||||
"MonthPickerInput",
|
||||
"YearPickerInput",
|
||||
]);
|
||||
const buttonRootComponents = new Set(["ActionIcon", "Burger", "Button", "CloseButton", "UnstyledButton"]);
|
||||
|
||||
function extractEventValue(value: unknown, checked: boolean): WidgetStateValue | null {
|
||||
if (value && typeof value === "object" && "currentTarget" in value) {
|
||||
const target = (value as { currentTarget?: { checked?: unknown; value?: unknown } }).currentTarget;
|
||||
const result = checked ? target?.checked : target?.value;
|
||||
return typeof result === "string" || typeof result === "number" || typeof result === "boolean" ? result : null;
|
||||
}
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) return value;
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "string" || entry === null)) {
|
||||
return value.filter((entry): entry is string => typeof entry === "string");
|
||||
}
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "number")) return value;
|
||||
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
function useBoundProps(componentName: string, props: Record<string, unknown>): Record<string, unknown> {
|
||||
const binding = typeof props.bind === "string" ? props.bind : undefined;
|
||||
const context = useContext(CustomJsxStateContext);
|
||||
const sanitized = sanitizeCustomJsxProps(props);
|
||||
delete sanitized.bind;
|
||||
if (!binding || !context || !customJsxBindableComponentNames.has(componentName)) return sanitized;
|
||||
const stateType = context.stateSchema[binding];
|
||||
if (!stateType) return sanitized;
|
||||
|
||||
const update = (value: unknown, checked = false) => {
|
||||
const extracted = extractEventValue(value, checked);
|
||||
context.setStateValue(binding, extracted ?? emptyStateValue(stateType));
|
||||
};
|
||||
if (componentName === "Calendar") {
|
||||
return { ...sanitized, date: context.state[binding], onDateChange: update };
|
||||
}
|
||||
if (checkedComponents.has(componentName)) {
|
||||
return {
|
||||
...sanitized,
|
||||
checked: Boolean(context.state[binding]),
|
||||
onChange: (event: unknown) => update(event, true),
|
||||
};
|
||||
}
|
||||
if (openedComponents.has(componentName)) {
|
||||
return { ...sanitized, opened: Boolean(context.state[binding]), onChange: update, withinPortal: false };
|
||||
}
|
||||
if (activeComponents.has(componentName)) {
|
||||
return { ...sanitized, active: Number(context.state[binding] ?? 0), onStepClick: update };
|
||||
}
|
||||
return { ...sanitized, value: context.state[binding], onChange: update };
|
||||
}
|
||||
|
||||
function emptyStateValue(type: string): WidgetStateValue {
|
||||
if (type.endsWith("[]")) return [];
|
||||
if (type === "number") return 0;
|
||||
if (type === "boolean") return false;
|
||||
return "";
|
||||
}
|
||||
|
||||
function wrap(componentName: string, component: ComponentType<never>, additions: Record<string, unknown> = {}) {
|
||||
return function SafeComponent(props: Record<string, unknown>) {
|
||||
const bound = useBoundProps(componentName, props);
|
||||
const scoped = { ...bound, ...additions };
|
||||
if (comboboxComponents.has(componentName)) scoped.comboboxProps = scopeOverlayProps(bound.comboboxProps);
|
||||
if (popoverInputComponents.has(componentName)) scoped.popoverProps = scopeOverlayProps(bound.popoverProps);
|
||||
return createElement(component, scoped as never, props.children as ReactNode);
|
||||
};
|
||||
}
|
||||
|
||||
function scopeOverlayProps(value: unknown) {
|
||||
const candidate =
|
||||
value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? sanitizeCustomJsxProps(value as Record<string, unknown>)
|
||||
: {};
|
||||
return { ...candidate, withinPortal: false };
|
||||
}
|
||||
|
||||
function SafeLink({ component, props }: { component: ComponentType<never>; props: Record<string, unknown> }) {
|
||||
const sanitized = sanitizeCustomJsxProps(props);
|
||||
return createElement(component, {
|
||||
...sanitized,
|
||||
href: safeUrl(props.href) ? props.href : undefined,
|
||||
rel: sanitized.target === "_blank" ? "noopener noreferrer" : sanitized.rel,
|
||||
} as never);
|
||||
const target = sanitized.target === "_blank" || sanitized.target === "_self" ? sanitized.target : undefined;
|
||||
return createElement(
|
||||
component,
|
||||
{
|
||||
...sanitized,
|
||||
href: safeUrl(props.href) ? props.href : undefined,
|
||||
target,
|
||||
rel: target === "_blank" ? "noopener noreferrer" : sanitized.rel,
|
||||
} as never,
|
||||
props.children as ReactNode,
|
||||
);
|
||||
}
|
||||
|
||||
function createCopyButton(labels: { copy: string; copied: string }) {
|
||||
@@ -90,7 +199,16 @@ export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters):
|
||||
for (const descriptor of enabledCustomJsxComponents) {
|
||||
const namespace = namespaces[descriptor.package];
|
||||
const component = namespace ? resolveExport(namespace, descriptor.name) : undefined;
|
||||
if (component) components[descriptor.name] = component;
|
||||
if (component) {
|
||||
const additions: Record<string, unknown> = {};
|
||||
if (
|
||||
["HoverCard", "Menu", "Popover", "Tooltip", "Tooltip.Floating", "TooltipFloating"].includes(descriptor.name)
|
||||
) {
|
||||
additions.withinPortal = false;
|
||||
}
|
||||
if (buttonRootComponents.has(descriptor.name)) additions.type = "button";
|
||||
components[descriptor.name] = wrap(descriptor.name, component, additions);
|
||||
}
|
||||
}
|
||||
const core = Core as unknown as Namespace;
|
||||
for (const name of [
|
||||
@@ -107,28 +225,18 @@ export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters):
|
||||
"Chip",
|
||||
] as const) {
|
||||
const component = resolveExport(core, name);
|
||||
if (component) components[name] = wrap(component);
|
||||
if (component) components[name] = wrap(name, component, buttonRootComponents.has(name) ? { type: "button" } : {});
|
||||
}
|
||||
const anchor = resolveExport(core, "Anchor");
|
||||
const navLink = resolveExport(core, "NavLink");
|
||||
if (anchor) components.Anchor = (props) => <SafeLink component={anchor} props={props} />;
|
||||
if (navLink) components.NavLink = (props) => <SafeLink component={navLink} props={props} />;
|
||||
for (const [name, additions] of Object.entries({
|
||||
Rating: { readOnly: true },
|
||||
Slider: { readOnly: true },
|
||||
Switch: { readOnly: true },
|
||||
SegmentedControl: { readOnly: true },
|
||||
Pagination: { disabled: true },
|
||||
})) {
|
||||
const component = resolveExport(core, name);
|
||||
if (component) components[name] = wrap(component, additions);
|
||||
}
|
||||
const dates = Dates as unknown as Namespace;
|
||||
for (const descriptor of enabledCustomJsxComponents.filter(
|
||||
(item) => item.package === "@mantine/dates" && item.safety === "wrapped",
|
||||
)) {
|
||||
const component = resolveExport(dates, descriptor.name);
|
||||
if (component) components[descriptor.name] = wrap(component, { static: true });
|
||||
if (component) components[descriptor.name] = wrap(descriptor.name, component);
|
||||
}
|
||||
Object.assign(components, {
|
||||
CopyButton: createCopyButton(adapters.copyLabels),
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { customJsxSupportedPropsByName } from "../core";
|
||||
import { isInterpreterCallback, SafeJsxError } from "./interpreter-foundation";
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
CUSTOM_JSX_BLOCKED_PROPS,
|
||||
CUSTOM_JSX_BLOCKED_STYLE_KEYS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
|
||||
@@ -61,7 +60,7 @@ function sanitizeStyle(value: unknown): Record<string, string | number> | undefi
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const result: Record<string, string | number> = {};
|
||||
for (const [key, styleValue] of Object.entries(value)) {
|
||||
if (CUSTOM_JSX_BLOCKED_STYLE_KEYS.has(key) || key.startsWith("--")) continue;
|
||||
if (CUSTOM_JSX_BLOCKED_STYLE_KEYS.has(key)) continue;
|
||||
if (typeof styleValue !== "string" && typeof styleValue !== "number") continue;
|
||||
if (typeof styleValue === "string" && /(?:url\s*\(|expression\s*\(|javascript:|position\s*:)/i.test(styleValue)) {
|
||||
continue;
|
||||
@@ -71,26 +70,96 @@ function sanitizeStyle(value: unknown): Record<string, string | number> | undefi
|
||||
return result;
|
||||
}
|
||||
|
||||
function sanitizeStyles(value: unknown): Record<string, Record<string, string | number>> | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const result: Record<string, Record<string, string | number>> = {};
|
||||
for (const [selector, styles] of Object.entries(value)) {
|
||||
if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(selector)) continue;
|
||||
const sanitized = sanitizeStyle(styles);
|
||||
if (sanitized) result[selector] = sanitized;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function sanitizeCustomJsxProps(
|
||||
props: Readonly<Record<string, unknown>>,
|
||||
componentName?: string,
|
||||
_componentName?: string,
|
||||
): Record<string, unknown> {
|
||||
const safe: Record<string, unknown> = {};
|
||||
const supportedProps = componentName ? customJsxSupportedPropsByName.get(componentName) : undefined;
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if ((/^on/i.test(key) && !supportedProps?.has(key)) || CUSTOM_JSX_BLOCKED_PROPS.has(key)) continue;
|
||||
if (componentName && !supportedProps?.has(key)) continue;
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) continue;
|
||||
return sanitizeObject(props);
|
||||
}
|
||||
|
||||
function sanitizeObject(value: Readonly<Record<string, unknown>>): Record<string, unknown> {
|
||||
const safe: Record<string, unknown> = Object.create(null);
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (isBlockedCustomJsxProp(key)) continue;
|
||||
if (typeof child === "function" || isInterpreterCallback(child)) continue;
|
||||
if (CUSTOM_JSX_URL_PROPS.has(key)) {
|
||||
if (isSafeUrl(value)) safe[key] = value;
|
||||
if (isSafeUrl(child)) safe[key] = child;
|
||||
continue;
|
||||
}
|
||||
if (key === "style") {
|
||||
const style = sanitizeStyle(value);
|
||||
const style = sanitizeStyle(child);
|
||||
if (style) safe.style = style;
|
||||
continue;
|
||||
}
|
||||
safe[key] = value;
|
||||
if (key === "styles") {
|
||||
const styles = sanitizeStyles(child);
|
||||
if (styles) safe.styles = styles;
|
||||
continue;
|
||||
}
|
||||
safe[key] = key === "data" || key === "series" ? sanitizeSerializableData(child) : sanitizeNestedValue(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
function sanitizeSerializableData(value: unknown): unknown {
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) return undefined;
|
||||
if (Array.isArray(value)) return value.map(sanitizeSerializableData);
|
||||
if (value !== null && typeof value === "object") {
|
||||
const safe: Record<string, unknown> = Object.create(null);
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(key))) continue;
|
||||
safe[key] = sanitizeSerializableData(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sanitizeNestedValue(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(sanitizeNestedValue);
|
||||
if (value !== null && typeof value === "object") return sanitizeObject(value as Record<string, unknown>);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function diagnoseCustomJsxProps(props: Readonly<Record<string, unknown>>, componentName: string): string[] {
|
||||
const diagnostics: string[] = [];
|
||||
diagnoseObject(props, componentName, diagnostics);
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function diagnoseObject(value: Readonly<Record<string, unknown>>, path: string, diagnostics: string[]) {
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const propertyPath = `${path}.${key}`;
|
||||
if (isBlockedCustomJsxProp(key) || typeof child === "function" || isInterpreterCallback(child)) {
|
||||
diagnostics.push(`BLOCKED_CAPABILITY: Prop '${propertyPath}' is not allowed`);
|
||||
continue;
|
||||
}
|
||||
if (CUSTOM_JSX_URL_PROPS.has(key) && !isSafeUrl(child)) {
|
||||
diagnostics.push(`INVALID_PROP_VALUE: '${propertyPath}' contains an unsafe URL`);
|
||||
continue;
|
||||
}
|
||||
if (key === "data" || key === "series") continue;
|
||||
if (Array.isArray(child)) {
|
||||
child.forEach((entry, index) => {
|
||||
if (isInterpreterCallback(entry) || typeof entry === "function") {
|
||||
diagnostics.push(`BLOCKED_CAPABILITY: Prop '${propertyPath}[${index}]' is not allowed`);
|
||||
} else if (entry !== null && typeof entry === "object") {
|
||||
diagnoseObject(entry as Record<string, unknown>, `${propertyPath}[${index}]`, diagnostics);
|
||||
}
|
||||
});
|
||||
} else if (child !== null && typeof child === "object" && key !== "style" && key !== "styles") {
|
||||
diagnoseObject(child as Record<string, unknown>, propertyPath, diagnostics);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import type { ComponentType } from "react";
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Switch } from "@mantine/core";
|
||||
import { IconCheck, IconPlayerPlay, IconPower, IconRefresh, IconTrash } from "@tabler/icons-react";
|
||||
@@ -8,7 +8,7 @@ import { useMutation } from "@tanstack/react-query";
|
||||
|
||||
import { useCustomWidgetRuntime } from "./context";
|
||||
import { normalizeParams } from "./data";
|
||||
import { MigrationRequiredAlert } from "./status";
|
||||
import { RequestIdRequiredAlert } from "./status";
|
||||
import type { CustomJsxRuntimeParams, CustomWidgetRequestResult } from "./types";
|
||||
|
||||
const ICON_MAP: Record<string, ComponentType<{ size?: number | string }>> = {
|
||||
@@ -59,7 +59,8 @@ function useActionExecutor() {
|
||||
export interface ActionButtonProps {
|
||||
requestId?: string;
|
||||
params?: CustomJsxRuntimeParams;
|
||||
label: string;
|
||||
label?: string;
|
||||
children?: ReactNode;
|
||||
color?: string;
|
||||
variant?: string;
|
||||
size?: string;
|
||||
@@ -67,21 +68,17 @@ export interface ActionButtonProps {
|
||||
successMessage?: string;
|
||||
errorMessage?: string;
|
||||
icon?: string;
|
||||
invalidate?: string[];
|
||||
disabled?: boolean | string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
body?: string;
|
||||
headers?: string;
|
||||
fullWidth?: boolean | string;
|
||||
}
|
||||
|
||||
export function ActionButton(props: ActionButtonProps) {
|
||||
const { runtime, mutation } = useActionExecutor();
|
||||
const params = normalizeParams(props.params);
|
||||
const title = props.label ?? (typeof props.children === "string" ? props.children : props.requestId) ?? "Action";
|
||||
const Icon = props.icon ? ICON_MAP[props.icon.toLowerCase()] : undefined;
|
||||
const mustConfirm = runtime.requestCapabilities.some(
|
||||
(capability) => capability.id === props.requestId && capability.kind === "action" && capability.method === "DELETE",
|
||||
const capability = runtime.requestCapabilities.find(
|
||||
(candidate) => candidate.id === props.requestId && candidate.kind === "action",
|
||||
);
|
||||
const run = async (confirmed: boolean) => {
|
||||
if (!props.requestId || !params) return;
|
||||
@@ -90,7 +87,7 @@ export function ActionButton(props: ActionButtonProps) {
|
||||
const success = result.ok;
|
||||
runtime.port.notify({
|
||||
kind: success ? "success" : "error",
|
||||
title: props.label,
|
||||
title,
|
||||
message: success
|
||||
? (props.successMessage ??
|
||||
(result.simulated ? runtime.messages.actionSimulated : runtime.messages.actionCompleted))
|
||||
@@ -100,22 +97,34 @@ export function ActionButton(props: ActionButtonProps) {
|
||||
await runtime.port.invalidate({
|
||||
itemId: runtime.itemId,
|
||||
previewSessionId: runtime.previewSessionId,
|
||||
targets: props.invalidate ?? [],
|
||||
targets: result.invalidates ?? capability?.invalidates ?? [],
|
||||
});
|
||||
} catch {
|
||||
runtime.port.notify({
|
||||
kind: "error",
|
||||
title: props.label,
|
||||
title,
|
||||
message: props.errorMessage ?? runtime.messages.requestFailed,
|
||||
});
|
||||
}
|
||||
};
|
||||
const click = async () => {
|
||||
const confirmMessage = props.confirmMessage ?? (mustConfirm ? runtime.messages.confirmDelete : undefined);
|
||||
if (confirmMessage && !(await runtime.port.confirm({ title: props.label, message: confirmMessage }))) return;
|
||||
const confirmMessage =
|
||||
props.confirmMessage ??
|
||||
capability?.confirmation?.message ??
|
||||
(capability?.method === "DELETE" ? runtime.messages.confirmDelete : undefined);
|
||||
if (
|
||||
confirmMessage &&
|
||||
!(await runtime.port.confirm({
|
||||
title: capability?.confirmation?.title ?? title,
|
||||
message: confirmMessage,
|
||||
confirmLabel: capability?.confirmation?.confirmLabel,
|
||||
destructive: capability?.confirmation?.destructive ?? capability?.method === "DELETE",
|
||||
}))
|
||||
)
|
||||
return;
|
||||
await run(Boolean(confirmMessage));
|
||||
};
|
||||
if (!props.requestId) return <MigrationRequiredAlert />;
|
||||
if (!props.requestId) return <RequestIdRequiredAlert />;
|
||||
return (
|
||||
<Button
|
||||
color={props.color ?? "blue"}
|
||||
@@ -127,8 +136,9 @@ export function ActionButton(props: ActionButtonProps) {
|
||||
disabled={
|
||||
parseBool(props.disabled) || runtime.isEditMode || (!runtime.itemId && !runtime.previewSessionId) || !params
|
||||
}
|
||||
fullWidth={parseBool(props.fullWidth)}
|
||||
>
|
||||
{props.label}
|
||||
{props.children ?? props.label ?? props.requestId}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -142,12 +152,7 @@ export interface ToggleSwitchProps {
|
||||
color?: string;
|
||||
size?: string;
|
||||
errorMessage?: string;
|
||||
invalidate?: string[];
|
||||
disabled?: boolean | string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
onBody?: string;
|
||||
offBody?: string;
|
||||
}
|
||||
|
||||
export function ToggleSwitch(props: ToggleSwitchProps) {
|
||||
@@ -157,17 +162,37 @@ export function ToggleSwitch(props: ToggleSwitchProps) {
|
||||
const locked = useRef(false);
|
||||
const onParams = normalizeParams(props.onParams);
|
||||
const offParams = normalizeParams(props.offParams);
|
||||
const capability = runtime.requestCapabilities.find(
|
||||
(candidate) => candidate.id === props.requestId && candidate.kind === "action",
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!locked.current) setChecked(initial);
|
||||
}, [initial]);
|
||||
const change = async (next: boolean) => {
|
||||
const params = next ? onParams : offParams;
|
||||
if (!props.requestId || !params || locked.current) return;
|
||||
const confirmation = capability?.confirmation;
|
||||
const confirmMessage =
|
||||
confirmation?.message ?? (capability?.method === "DELETE" ? runtime.messages.confirmDelete : undefined);
|
||||
if (
|
||||
confirmMessage &&
|
||||
!(await runtime.port.confirm({
|
||||
title: confirmation?.title ?? props.label ?? runtime.messages.toggle,
|
||||
message: confirmMessage,
|
||||
confirmLabel: confirmation?.confirmLabel,
|
||||
destructive: confirmation?.destructive ?? capability?.method === "DELETE",
|
||||
}))
|
||||
)
|
||||
return;
|
||||
locked.current = true;
|
||||
const previous = checked;
|
||||
setChecked(next);
|
||||
try {
|
||||
const result = await mutation.mutateAsync({ requestId: props.requestId, params, confirmed: false });
|
||||
const result = await mutation.mutateAsync({
|
||||
requestId: props.requestId,
|
||||
params,
|
||||
confirmed: confirmMessage !== undefined,
|
||||
});
|
||||
if (!result.ok) {
|
||||
setChecked(previous);
|
||||
runtime.port.notify({
|
||||
@@ -179,7 +204,7 @@ export function ToggleSwitch(props: ToggleSwitchProps) {
|
||||
await runtime.port.invalidate({
|
||||
itemId: runtime.itemId,
|
||||
previewSessionId: runtime.previewSessionId,
|
||||
targets: props.invalidate ?? [],
|
||||
targets: result.invalidates ?? capability?.invalidates ?? [],
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
@@ -193,7 +218,7 @@ export function ToggleSwitch(props: ToggleSwitchProps) {
|
||||
locked.current = false;
|
||||
}
|
||||
};
|
||||
if (!props.requestId) return <MigrationRequiredAlert />;
|
||||
if (!props.requestId) return <RequestIdRequiredAlert />;
|
||||
return (
|
||||
<Switch
|
||||
label={props.label}
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import { ActionIcon, Code, Group, ScrollArea, SimpleGrid, Stack, Table, Text, Tooltip } from "@mantine/core";
|
||||
import { IconExternalLink } from "@tabler/icons-react";
|
||||
|
||||
import type { CustomWidgetDisplayData } from "./display-types";
|
||||
|
||||
export function KeyValueDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const entries = (data.entries as Array<{ label: string; unit: string; value: unknown }> | undefined) ?? [];
|
||||
const content = entries.map((entry, index) => (
|
||||
<Group key={index} justify="space-between" wrap="nowrap">
|
||||
<Text size="sm" c="dimmed">
|
||||
{entry.label}
|
||||
</Text>
|
||||
<Text size="sm" fw={600}>
|
||||
{String(entry.value ?? "—")}
|
||||
{entry.unit ? ` ${entry.unit}` : ""}
|
||||
</Text>
|
||||
</Group>
|
||||
));
|
||||
return data.layout === "grid" ? (
|
||||
<SimpleGrid cols={Number(data.columns ?? 2)} spacing="xs" p="sm" h="100%">
|
||||
{content}
|
||||
</SimpleGrid>
|
||||
) : (
|
||||
<Stack h="100%" justify="center" gap="xs" p="sm">
|
||||
{content}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export function TableDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const columns = (data.columns as string[] | undefined) ?? [];
|
||||
const rows = (data.rows as unknown[][] | undefined) ?? [];
|
||||
return (
|
||||
<ScrollArea>
|
||||
<Table striped={data.striped !== false} highlightOnHover withTableBorder>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
{columns.map((column, index) => (
|
||||
<Table.Th key={index} py={data.compact ? 4 : undefined}>
|
||||
{column}
|
||||
</Table.Th>
|
||||
))}
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{rows.map((row, rowIndex) => (
|
||||
<Table.Tr key={rowIndex}>
|
||||
{row.map((cell, cellIndex) => (
|
||||
<Table.Td key={cellIndex} py={data.compact ? 2 : undefined}>
|
||||
{String(cell ?? "—")}
|
||||
</Table.Td>
|
||||
))}
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatusIndicatorDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const items = (data.items as Array<{ label: string; value: string; isGood: boolean }> | undefined) ?? [];
|
||||
const size = ({ sm: 8, md: 10, lg: 14 } as Record<string, number>)[String(data.dotSize ?? "md")] ?? 10;
|
||||
const content = items.map((item, index) => (
|
||||
<Group key={index} gap="xs" wrap="nowrap">
|
||||
<div
|
||||
aria-hidden
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
borderRadius: "50%",
|
||||
backgroundColor: item.isGood ? "var(--mantine-color-green-6)" : "var(--mantine-color-red-6)",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<Text size="sm" fw={500}>
|
||||
{item.label}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" ml="auto">
|
||||
{item.value}
|
||||
</Text>
|
||||
</Group>
|
||||
));
|
||||
return data.layout === "grid" ? (
|
||||
<SimpleGrid cols={2} spacing="xs" p="sm" h="100%">
|
||||
{content}
|
||||
</SimpleGrid>
|
||||
) : (
|
||||
<Stack h="100%" justify="center" gap="xs" p="sm">
|
||||
{content}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function openJsonInBrowser(value: unknown) {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: "application/json" }));
|
||||
window.open(url);
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
export function createRawDisplay(openJsonLabel: string) {
|
||||
return function RawDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
return (
|
||||
<Stack gap={4} p="xs">
|
||||
<Group justify="flex-end">
|
||||
<Tooltip label={openJsonLabel}>
|
||||
<ActionIcon
|
||||
aria-label={openJsonLabel}
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
onClick={() => openJsonInBrowser(data.data)}
|
||||
>
|
||||
<IconExternalLink size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
<ScrollArea mah={Number(data.maxHeight ?? 300)}>
|
||||
<Code block style={{ fontSize: 12 }}>
|
||||
{JSON.stringify(data.data, null, 2)}
|
||||
</Code>
|
||||
</ScrollArea>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -4,8 +4,12 @@ import { Alert, Badge, Box, Group, Popover, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle, IconNetwork } from "@tabler/icons-react";
|
||||
|
||||
import { renderSafeJsx } from "../jsx/interpreter";
|
||||
import { CustomJsxStateProvider } from "../jsx/runtime-components";
|
||||
import type { CustomJsxRequestCapability } from "./types";
|
||||
|
||||
type CustomWidgetStateValue = string | number | boolean | string[] | number[];
|
||||
const EMPTY_RECORD: Record<string, never> = {};
|
||||
|
||||
const methodColors: Readonly<Record<string, string>> = {
|
||||
GET: "blue",
|
||||
POST: "orange",
|
||||
@@ -27,6 +31,11 @@ export interface CustomJsxRendererMessages {
|
||||
export interface CustomJsxRendererProps {
|
||||
template: string;
|
||||
data: unknown;
|
||||
status?: Record<string, unknown>;
|
||||
options?: Record<string, unknown>;
|
||||
stateSchema?: Record<string, string>;
|
||||
defaultState?: Record<string, unknown>;
|
||||
onStateChange?(state: Record<string, CustomWidgetStateValue>): void;
|
||||
requestCapabilities: unknown;
|
||||
components: Readonly<Record<string, ComponentType<never>>>;
|
||||
createBindings(data: unknown): Readonly<Record<string, unknown>>;
|
||||
@@ -55,7 +64,15 @@ export function parseRequestCapabilities(value: unknown): CustomJsxRequestCapabi
|
||||
id: record.id,
|
||||
kind: record.kind,
|
||||
method: record.method,
|
||||
trigger: record.trigger === "load" ? "load" : "manual",
|
||||
minimumBoardPermission: record.minimumBoardPermission,
|
||||
confirmation:
|
||||
record.confirmation && typeof record.confirmation === "object"
|
||||
? (record.confirmation as CustomJsxRequestCapability["confirmation"])
|
||||
: undefined,
|
||||
invalidates: Array.isArray(record.invalidates)
|
||||
? record.invalidates.filter((entry): entry is string => typeof entry === "string")
|
||||
: [],
|
||||
} as CustomJsxRequestCapability,
|
||||
];
|
||||
});
|
||||
@@ -80,6 +97,9 @@ class RendererErrorBoundary extends Component<
|
||||
function ErrorAlert({ error }: { error: Error }) {
|
||||
return (
|
||||
<Alert color="red" variant="light" icon={<IconAlertTriangle size={16} />} p="xs">
|
||||
<Text size="xs" fw={700}>
|
||||
RUNTIME_RENDER_ERROR
|
||||
</Text>
|
||||
<Text size="xs">{error.message}</Text>
|
||||
</Alert>
|
||||
);
|
||||
@@ -88,13 +108,37 @@ function ErrorAlert({ error }: { error: Error }) {
|
||||
export function CustomJsxRenderer({
|
||||
template,
|
||||
data,
|
||||
status = EMPTY_RECORD,
|
||||
options = EMPTY_RECORD,
|
||||
stateSchema = EMPTY_RECORD,
|
||||
defaultState = EMPTY_RECORD,
|
||||
onStateChange,
|
||||
requestCapabilities: rawCapabilities,
|
||||
components,
|
||||
createBindings,
|
||||
messages,
|
||||
}: CustomJsxRendererProps) {
|
||||
const [parseErrors, setParseErrors] = useState<string[]>([]);
|
||||
const bindings = useMemo(() => createBindings(data), [createBindings, data]);
|
||||
const [state, setState] = useState<Record<string, CustomWidgetStateValue>>(() =>
|
||||
normalizeState(stateSchema, defaultState),
|
||||
);
|
||||
useEffect(() => {
|
||||
const next = normalizeState(stateSchema, defaultState);
|
||||
setState((current) => (sameWidgetState(current, next) ? current : next));
|
||||
}, [defaultState, stateSchema]);
|
||||
const setStateValue = useCallback(
|
||||
(name: string, value: CustomWidgetStateValue) => {
|
||||
const type = stateSchema[name];
|
||||
if (!type || !matchesStateType(type, value)) return;
|
||||
setState((current) => ({ ...current, [name]: value }));
|
||||
},
|
||||
[stateSchema],
|
||||
);
|
||||
useEffect(() => onStateChange?.(state), [onStateChange, state]);
|
||||
const bindings = useMemo(
|
||||
() => ({ ...createBindings(data), status, options, state }),
|
||||
[createBindings, data, options, state, status],
|
||||
);
|
||||
const capabilities = useMemo(() => parseRequestCapabilities(rawCapabilities), [rawCapabilities]);
|
||||
const rendered = useMemo(() => {
|
||||
try {
|
||||
@@ -172,9 +216,11 @@ export function CustomJsxRenderer({
|
||||
{rendered.error ? (
|
||||
<ErrorAlert error={rendered.error} />
|
||||
) : (
|
||||
<RendererErrorBoundary key={template} onError={handleError}>
|
||||
{rendered.node}
|
||||
</RendererErrorBoundary>
|
||||
<CustomJsxStateProvider state={state} stateSchema={stateSchema} setStateValue={setStateValue}>
|
||||
<RendererErrorBoundary key={template} onError={handleError}>
|
||||
{rendered.node}
|
||||
</RendererErrorBoundary>
|
||||
</CustomJsxStateProvider>
|
||||
)}
|
||||
</Box>
|
||||
{parseErrors.length > 0 && (
|
||||
@@ -192,3 +238,40 @@ export function CustomJsxRenderer({
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeState(schema: Record<string, string>, defaults: Record<string, unknown>) {
|
||||
const state: Record<string, CustomWidgetStateValue> = {};
|
||||
for (const [name, type] of Object.entries(schema)) {
|
||||
const value = defaults[name];
|
||||
state[name] = matchesStateType(type, value)
|
||||
? value
|
||||
: type.endsWith("[]")
|
||||
? []
|
||||
: type === "number"
|
||||
? 0
|
||||
: type === "boolean"
|
||||
? false
|
||||
: "";
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function matchesStateType(type: string, value: unknown): value is CustomWidgetStateValue {
|
||||
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 sameWidgetState(left: Record<string, CustomWidgetStateValue>, right: Record<string, CustomWidgetStateValue>) {
|
||||
const leftEntries = Object.entries(left);
|
||||
const rightEntries = Object.entries(right);
|
||||
if (leftEntries.length !== rightEntries.length) return false;
|
||||
return leftEntries.every(([key, value]) => {
|
||||
const candidate = right[key];
|
||||
return Array.isArray(value) && Array.isArray(candidate)
|
||||
? value.length === candidate.length && value.every((entry, index) => Object.is(entry, candidate[index]))
|
||||
: Object.is(value, candidate);
|
||||
});
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { CustomWidgetDisplayAdapters, CustomWidgetDisplayComponent } from "./display-types";
|
||||
import { createRawDisplay, KeyValueDisplay, StatusIndicatorDisplay, TableDisplay } from "./collection-displays";
|
||||
import { CountGridDisplay, ProgressBarsDisplay, SingleValueDisplay, StatGridDisplay } from "./metric-displays";
|
||||
|
||||
export function createCustomWidgetDisplayComponents(
|
||||
adapters: CustomWidgetDisplayAdapters,
|
||||
): Record<string, CustomWidgetDisplayComponent> {
|
||||
return {
|
||||
singleValue: SingleValueDisplay,
|
||||
keyValue: KeyValueDisplay,
|
||||
table: TableDisplay,
|
||||
statGrid: StatGridDisplay,
|
||||
progressBars: ProgressBarsDisplay,
|
||||
statusIndicator: StatusIndicatorDisplay,
|
||||
countGrid: CountGridDisplay,
|
||||
raw: createRawDisplay(adapters.openJsonLabel),
|
||||
actionButton: adapters.actionButton,
|
||||
customJsx: adapters.customJsx,
|
||||
} satisfies Record<string, CustomWidgetDisplayComponent>;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import type { ComponentType } from "react";
|
||||
|
||||
export type CustomWidgetDisplayData = Readonly<Record<string, unknown>>;
|
||||
export type CustomWidgetDisplayComponent = ComponentType<{ data: CustomWidgetDisplayData }>;
|
||||
|
||||
export interface CustomWidgetDisplayAdapters {
|
||||
actionButton: CustomWidgetDisplayComponent;
|
||||
customJsx: CustomWidgetDisplayComponent;
|
||||
openJsonLabel: string;
|
||||
}
|
||||
@@ -3,12 +3,10 @@ export { CustomWidgetRuntimeProvider, useCustomWidgetRuntime, useWidgetDefinitio
|
||||
export { SubData } from "./data";
|
||||
export { RefreshButton } from "./refresh-button";
|
||||
export { SubFetch } from "./sub-fetch";
|
||||
export { createCustomWidgetDisplayComponents } from "./display-registry";
|
||||
export { CustomJsxRenderer, CUSTOM_JSX_METHOD_COLORS, parseRequestCapabilities } from "./custom-jsx-renderer";
|
||||
export type { CustomJsxRendererMessages, CustomJsxRendererProps } from "./custom-jsx-renderer";
|
||||
export type { ActionButtonProps, ToggleSwitchProps } from "./actions";
|
||||
export type { SubDataProps } from "./data";
|
||||
export type { RefreshButtonProps } from "./refresh-button";
|
||||
export type { SubFetchMetadata, SubFetchProps } from "./sub-fetch";
|
||||
export type * from "./display-types";
|
||||
export type * from "./types";
|
||||
@@ -1,124 +0,0 @@
|
||||
import { Card, Flex, Group, Progress, SimpleGrid, Stack, Text, Title } from "@mantine/core";
|
||||
import { useElementSize } from "@mantine/hooks";
|
||||
|
||||
import type { CustomWidgetDisplayData } from "./display-types";
|
||||
|
||||
export function SingleValueDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const size = String(data.valueSize ?? "lg");
|
||||
const labelAbove = data.labelPosition === "above";
|
||||
const label = data.label ? (
|
||||
<Text c="dimmed" size="sm">
|
||||
{String(data.label)}
|
||||
</Text>
|
||||
) : null;
|
||||
return (
|
||||
<Stack h="100%" align="center" justify="center" gap="xs">
|
||||
{labelAbove && label}
|
||||
<Title order={size === "xl" ? 1 : size === "lg" ? 2 : size === "md" ? 3 : 4}>
|
||||
{String(data.value ?? "—")}
|
||||
{data.unit ? ` ${String(data.unit)}` : ""}
|
||||
</Title>
|
||||
{!labelAbove && label}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
interface MetricItem {
|
||||
label: string;
|
||||
unit: string;
|
||||
color: string;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
function StatGridCard({ item, cardStyle }: { item: MetricItem; cardStyle: string }) {
|
||||
const { ref, height, width } = useElementSize();
|
||||
const isWide = width > height + 20;
|
||||
const background = cardStyle === "outline" ? "transparent" : `var(--mantine-color-${item.color}-light)`;
|
||||
return (
|
||||
<Card ref={ref} p="sm" radius="md" bg={background} withBorder={cardStyle === "outline"} h="100%">
|
||||
<Flex h="100%" align="center" justify="center" direction={isWide ? "row" : "column"} gap={isWide ? 8 : 4}>
|
||||
<Flex direction="column" align={isWide ? "flex-start" : "center"} gap={0}>
|
||||
<Text size="md" fw={700} ta="center" lh={1.1}>
|
||||
{String(item.value ?? "—")}
|
||||
{item.unit ? ` ${item.unit}` : ""}
|
||||
</Text>
|
||||
{height > 38 && (
|
||||
<Text size="xs" c="dimmed" ta="center" tt="uppercase" lh={1.3}>
|
||||
{item.label}
|
||||
</Text>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatGridDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const items = (data.items as MetricItem[] | undefined) ?? [];
|
||||
const columns = Number(data.columns ?? 2);
|
||||
return (
|
||||
<SimpleGrid
|
||||
cols={columns}
|
||||
spacing="xs"
|
||||
p="xs"
|
||||
h="100%"
|
||||
style={{ gridTemplateRows: `repeat(${Math.ceil(items.length / columns)}, 1fr)` }}
|
||||
>
|
||||
{items.map((item, index) => (
|
||||
<StatGridCard key={index} item={item} cardStyle={String(data.cardStyle ?? "filled")} />
|
||||
))}
|
||||
</SimpleGrid>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProgressBarsDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const bars = (data.bars as Array<MetricItem & { value: number; max?: number }> | undefined) ?? [];
|
||||
const sizes: Record<string, number> = { sm: 8, md: 14, lg: 22 };
|
||||
return (
|
||||
<Stack h="100%" justify="center" gap="sm" p="sm">
|
||||
{bars.map((bar, index) => {
|
||||
const max = bar.max ?? 100;
|
||||
const percentage = max > 0 ? Math.min((bar.value / max) * 100, 100) : 0;
|
||||
const value =
|
||||
data.showPercentage !== false ? `${percentage.toFixed(0)}%` : `${bar.value}${bar.unit ? ` ${bar.unit}` : ""}`;
|
||||
return (
|
||||
<Stack key={index} gap={4}>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" fw={500}>
|
||||
{bar.label}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{value}
|
||||
</Text>
|
||||
</Group>
|
||||
<Progress
|
||||
value={percentage}
|
||||
size={sizes[String(data.barSize ?? "md")] ?? 14}
|
||||
color={bar.color}
|
||||
radius="sm"
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export function CountGridDisplay({ data }: { data: CustomWidgetDisplayData }) {
|
||||
const items = (data.items as MetricItem[] | undefined) ?? [];
|
||||
return (
|
||||
<SimpleGrid cols={Number(data.columns ?? 2)} spacing="xs" p="sm" h="100%">
|
||||
{items.map((item, index) => (
|
||||
<Stack key={index} align="center" justify="center" gap={0}>
|
||||
<Text size={String(data.valueSize ?? "md")} fw={700}>
|
||||
{String(item.value ?? "—")}
|
||||
{item.unit ? ` ${item.unit}` : ""}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" tt="uppercase" ta="center">
|
||||
{item.label}
|
||||
</Text>
|
||||
</Stack>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
);
|
||||
}
|
||||
@@ -5,11 +5,11 @@ import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { useCustomWidgetRuntime } from "./context";
|
||||
|
||||
export function MigrationRequiredAlert() {
|
||||
export function RequestIdRequiredAlert() {
|
||||
const { messages } = useCustomWidgetRuntime();
|
||||
return (
|
||||
<Alert color="yellow" variant="light" icon={<IconAlertTriangle size={16} />} p="xs">
|
||||
<Text size="xs">{messages.migrationRequired}</Text>
|
||||
<Text size="xs">{messages.requestIdRequired}</Text>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { useCustomWidgetRuntime } from "./context";
|
||||
import { formatDisplayValue, getByPath, normalizeParams, SubFetchDataContext } from "./data";
|
||||
import { MigrationRequiredAlert } from "./status";
|
||||
import { RequestIdRequiredAlert } from "./status";
|
||||
import type { CustomJsxRuntimeParams } from "./types";
|
||||
|
||||
export interface SubFetchMetadata {
|
||||
@@ -22,29 +22,26 @@ export interface SubFetchProps {
|
||||
params?: CustomJsxRuntimeParams;
|
||||
refreshInterval?: number;
|
||||
children?: ReactNode;
|
||||
render?: (data: unknown, metadata: SubFetchMetadata) => ReactNode;
|
||||
loadingLabel?: string;
|
||||
errorMessage?: string;
|
||||
fallback?: ReactNode;
|
||||
path?: string;
|
||||
as?: "json" | "text";
|
||||
trigger?: "auto" | "manual";
|
||||
/** @deprecated Inline targets are inert in JSX API v2. */
|
||||
url?: string;
|
||||
/** @deprecated Request manifests own the method, body, and headers. */
|
||||
method?: string;
|
||||
body?: string;
|
||||
headers?: string;
|
||||
}
|
||||
|
||||
export function SubFetch(props: SubFetchProps) {
|
||||
const { itemId, previewSessionId, port, messages } = useCustomWidgetRuntime();
|
||||
const { itemId, previewSessionId, queriesDisabled, port, messages, setQueryState } = useCustomWidgetRuntime();
|
||||
const [manualRun, setManualRun] = useState(false);
|
||||
const params = useMemo(() => normalizeParams(props.params), [props.params]);
|
||||
const paramsKey = useMemo(() => JSON.stringify(params), [params]);
|
||||
useEffect(() => setManualRun(false), [paramsKey, props.requestId, props.trigger]);
|
||||
const enabled = Boolean(
|
||||
(itemId || previewSessionId) && props.requestId && params && (props.trigger !== "manual" || manualRun),
|
||||
!queriesDisabled &&
|
||||
(itemId || previewSessionId) &&
|
||||
props.requestId &&
|
||||
params &&
|
||||
(props.trigger !== "manual" || manualRun),
|
||||
);
|
||||
const refreshMs = normalizeRefreshInterval(props.refreshInterval);
|
||||
const query = useQuery({
|
||||
@@ -55,8 +52,27 @@ export function SubFetch(props: SubFetchProps) {
|
||||
retry: 2,
|
||||
refetchInterval: refreshMs,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!props.requestId || !setQueryState) return;
|
||||
if (!enabled) {
|
||||
setQueryState(props.requestId, null);
|
||||
return;
|
||||
}
|
||||
const result = query.data;
|
||||
setQueryState(props.requestId, {
|
||||
data: result?.data ?? null,
|
||||
status: {
|
||||
loading: query.isFetching && !result,
|
||||
ok: result?.ok,
|
||||
status: result?.status,
|
||||
statusText: result?.statusText,
|
||||
error: result?.error ?? (query.error ? messages.requestFailed : undefined),
|
||||
},
|
||||
});
|
||||
}, [enabled, messages.requestFailed, props.requestId, query.data, query.error, query.isFetching, setQueryState]);
|
||||
|
||||
if (!props.requestId) return <MigrationRequiredAlert />;
|
||||
if (!props.requestId) return <RequestIdRequiredAlert />;
|
||||
if (queriesDisabled) return null;
|
||||
if (!itemId && !previewSessionId) return props.fallback ?? <Text c="dimmed">{messages.unsavedPreview}</Text>;
|
||||
if (!params) return <RequestAlert message={messages.invalidParams} />;
|
||||
if (props.trigger === "manual" && !manualRun) {
|
||||
@@ -66,6 +82,7 @@ export function SubFetch(props: SubFetchProps) {
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
if (!props.children && props.path === undefined && props.as === undefined) return null;
|
||||
|
||||
const result = query.data;
|
||||
const requestError =
|
||||
@@ -88,7 +105,7 @@ export function SubFetch(props: SubFetchProps) {
|
||||
);
|
||||
}
|
||||
|
||||
const content = renderContent(props, result?.data, result);
|
||||
const content = renderContent(props, result?.data);
|
||||
return <SubFetchDataContext.Provider value={result?.data}>{content}</SubFetchDataContext.Provider>;
|
||||
}
|
||||
|
||||
@@ -96,15 +113,9 @@ function normalizeRefreshInterval(value: number | undefined): number | false {
|
||||
return value && Number.isFinite(value) && value > 0 ? Math.max(1_000, value * 1_000) : false;
|
||||
}
|
||||
|
||||
function renderContent(props: SubFetchProps, data: unknown, result: SubFetchMetadata | undefined) {
|
||||
if (props.render) {
|
||||
return props.render(data, {
|
||||
ok: result?.ok ?? false,
|
||||
status: result?.status ?? 0,
|
||||
statusText: result?.statusText,
|
||||
});
|
||||
}
|
||||
function renderContent(props: SubFetchProps, data: unknown) {
|
||||
if (props.children) return props.children;
|
||||
if (props.path === undefined && props.as === undefined) return null;
|
||||
const value = getByPath(data, props.path);
|
||||
if (props.as === "text") return <Text size="sm">{formatDisplayValue(value)}</Text>;
|
||||
return (
|
||||
|
||||
@@ -10,13 +10,22 @@ export interface CustomWidgetRequestResult {
|
||||
data: unknown;
|
||||
error?: string;
|
||||
simulated?: boolean;
|
||||
invalidates?: string[];
|
||||
}
|
||||
|
||||
export interface CustomJsxRequestCapability {
|
||||
id: string;
|
||||
kind: "query" | "action";
|
||||
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
||||
trigger: "load" | "manual";
|
||||
minimumBoardPermission: "view" | "modify" | "full";
|
||||
confirmation?: {
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
destructive?: boolean;
|
||||
};
|
||||
invalidates?: string[];
|
||||
}
|
||||
|
||||
export interface RuntimeRequestInput {
|
||||
@@ -46,12 +55,12 @@ export interface CustomWidgetRuntimePort {
|
||||
query(input: RuntimeRequestInput, signal?: AbortSignal): Promise<CustomWidgetRequestResult>;
|
||||
executeAction(input: RuntimeActionInput): Promise<CustomWidgetRequestResult>;
|
||||
invalidate(input: RuntimeInvalidationInput): Promise<void>;
|
||||
confirm(input: { title: string; message: ReactNode }): Promise<boolean>;
|
||||
confirm(input: { title: string; message: ReactNode; confirmLabel?: string; destructive?: boolean }): Promise<boolean>;
|
||||
notify(notification: RuntimeNotification): void;
|
||||
}
|
||||
|
||||
export interface CustomWidgetRuntimeMessages {
|
||||
migrationRequired: string;
|
||||
requestIdRequired: string;
|
||||
unsavedPreview: string;
|
||||
invalidParams: string;
|
||||
loadRequest: string;
|
||||
@@ -72,8 +81,21 @@ export interface CustomWidgetRuntimeValue {
|
||||
definitionId?: string;
|
||||
previewSessionId?: string;
|
||||
previewLiveActions?: boolean;
|
||||
queriesDisabled?: boolean;
|
||||
isEditMode: boolean;
|
||||
requestCapabilities: readonly CustomJsxRequestCapability[];
|
||||
port: CustomWidgetRuntimePort;
|
||||
messages: CustomWidgetRuntimeMessages;
|
||||
setQueryState?(requestId: string, value: CustomWidgetPublishedQueryState | null): void;
|
||||
}
|
||||
|
||||
export interface CustomWidgetPublishedQueryState {
|
||||
data: unknown;
|
||||
status: {
|
||||
loading: boolean;
|
||||
ok?: boolean;
|
||||
status?: number;
|
||||
statusText?: string;
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,7 @@ export {
|
||||
assertSafeStaticHeaders,
|
||||
classifyAddress,
|
||||
executeCustomWidgetRequest,
|
||||
invalidateCustomWidgetResponseCache,
|
||||
MAX_REQUEST_BODY_BYTES,
|
||||
MAX_RESPONSE_BODY_BYTES,
|
||||
MAX_RESPONSE_JSON_DEPTH,
|
||||
@@ -24,5 +25,11 @@ export type {
|
||||
PreviewSessionServiceOptions,
|
||||
PreviewSessionStore,
|
||||
} from "./preview-sessions";
|
||||
export { hashRuntimeParams, renderRequestBody, renderRequestTarget, validateRuntimeParams } from "./request-manifest";
|
||||
export {
|
||||
hashRuntimeParams,
|
||||
renderBoundValue,
|
||||
renderRequestBody,
|
||||
renderRequestTarget,
|
||||
validateRuntimeParams,
|
||||
} from "./request-manifest";
|
||||
export type { CustomJsxRuntimeParams } from "./request-manifest";
|
||||
@@ -1,27 +1,36 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import {
|
||||
customJsxNetworkScopes,
|
||||
customJsxRequestSchema,
|
||||
customWidgetAuthTypes,
|
||||
customWidgetSecretKinds,
|
||||
customWidgetSourceSchema,
|
||||
customWidgetStateTypes,
|
||||
} from "../core";
|
||||
import type { CustomJsxNetworkScope, CustomJsxRequest, CustomWidgetAuthType } from "../core";
|
||||
import type { CustomJsxRequest, CustomWidgetSource } from "../core";
|
||||
import { CustomWidgetDomainError } from "./errors";
|
||||
|
||||
const SESSION_TTL_MS = 5 * 60_000;
|
||||
const SESSION_TTL_MS = 10 * 60_000;
|
||||
const MAX_JOURNAL_ENTRIES = 50;
|
||||
|
||||
const encryptedSecretSchema = z.object({
|
||||
sourceId: z.string(),
|
||||
kind: z.enum(customWidgetSecretKinds),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
const sessionSchema = z.object({
|
||||
id: z.string(),
|
||||
userId: z.string(),
|
||||
expiresAt: z.number(),
|
||||
baseUrl: z.string(),
|
||||
authType: z.enum(customWidgetAuthTypes),
|
||||
headerName: z.string().nullable(),
|
||||
secrets: z.array(z.object({ kind: z.enum(customWidgetSecretKinds), value: z.string() })),
|
||||
networkScope: z.enum(customJsxNetworkScopes),
|
||||
sources: z.array(customWidgetSourceSchema),
|
||||
secrets: z.array(encryptedSecretSchema),
|
||||
requests: z.array(customJsxRequestSchema),
|
||||
name: z.string(),
|
||||
template: z.string(),
|
||||
optionsSchema: z.record(z.string(), z.unknown()),
|
||||
defaultOptions: z.record(z.string(), z.unknown()),
|
||||
stateSchema: z.record(z.string(), z.enum(customWidgetStateTypes)),
|
||||
defaultState: z.record(z.string(), z.unknown()),
|
||||
definitionId: z.string().optional(),
|
||||
liveActions: z.boolean(),
|
||||
});
|
||||
@@ -42,12 +51,15 @@ export type CustomWidgetPreviewJournalEntry = z.infer<typeof journalEntrySchema>
|
||||
|
||||
export interface CreatePreviewSessionInput {
|
||||
userId: string;
|
||||
baseUrl: string;
|
||||
authType: CustomWidgetAuthType;
|
||||
headerName?: string;
|
||||
secrets: Array<{ kind: (typeof customWidgetSecretKinds)[number]; value: string }>;
|
||||
networkScope: CustomJsxNetworkScope;
|
||||
sources: CustomWidgetSource[];
|
||||
secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>;
|
||||
requests: CustomJsxRequest[];
|
||||
name: string;
|
||||
template: string;
|
||||
optionsSchema: Record<string, unknown>;
|
||||
defaultOptions: Record<string, unknown>;
|
||||
stateSchema: Record<string, (typeof customWidgetStateTypes)[number]>;
|
||||
defaultState: Record<string, unknown>;
|
||||
definitionId?: string;
|
||||
}
|
||||
|
||||
@@ -77,16 +89,26 @@ export class CustomWidgetPreviewSessionService {
|
||||
}
|
||||
|
||||
public async create(input: CreatePreviewSessionInput) {
|
||||
const sourceIds = new Set(input.sources.map((source) => source.id));
|
||||
if (input.secrets.some((secret) => !sourceIds.has(secret.sourceId))) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "A preview secret references an unknown source",
|
||||
});
|
||||
}
|
||||
const session: CustomWidgetPreviewSession = {
|
||||
id: this.options.createId(),
|
||||
userId: input.userId,
|
||||
expiresAt: this.now() + SESSION_TTL_MS,
|
||||
baseUrl: input.baseUrl,
|
||||
authType: input.authType,
|
||||
headerName: input.headerName ?? null,
|
||||
secrets: input.secrets.map((secret) => ({ kind: secret.kind, value: this.options.encrypt(secret.value) })),
|
||||
networkScope: input.networkScope,
|
||||
sources: input.sources,
|
||||
secrets: input.secrets.map((secret) => ({ ...secret, value: this.options.encrypt(secret.value) })),
|
||||
requests: input.requests,
|
||||
name: input.name,
|
||||
template: input.template,
|
||||
optionsSchema: input.optionsSchema,
|
||||
defaultOptions: input.defaultOptions,
|
||||
stateSchema: input.stateSchema,
|
||||
defaultState: input.defaultState,
|
||||
definitionId: input.definitionId,
|
||||
liveActions: false,
|
||||
};
|
||||
@@ -132,8 +154,35 @@ export class CustomWidgetPreviewSessionService {
|
||||
});
|
||||
}
|
||||
|
||||
public getSecrets(session: CustomWidgetPreviewSession) {
|
||||
return session.secrets.map((secret) => ({ kind: secret.kind, value: this.options.decrypt(secret.value) }));
|
||||
public getSecrets(session: CustomWidgetPreviewSession, sourceId: string) {
|
||||
return session.secrets
|
||||
.filter((secret) => secret.sourceId === sourceId)
|
||||
.map((secret) => ({ kind: secret.kind, value: this.options.decrypt(secret.value) }));
|
||||
}
|
||||
|
||||
public async setSecrets(
|
||||
id: string,
|
||||
userId: string,
|
||||
secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>,
|
||||
) {
|
||||
const session = await this.get(id, userId);
|
||||
const sourceIds = new Set(session.sources.map((source) => source.id));
|
||||
if (secrets.some((secret) => !sourceIds.has(secret.sourceId))) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "A preview secret references an unknown source",
|
||||
});
|
||||
}
|
||||
const replacements = new Set(secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
|
||||
const next = {
|
||||
...session,
|
||||
secrets: [
|
||||
...session.secrets.filter((secret) => !replacements.has(`${secret.sourceId}:${secret.kind}`)),
|
||||
...secrets.map((secret) => ({ ...secret, value: this.options.encrypt(secret.value) })),
|
||||
],
|
||||
};
|
||||
await this.save(next);
|
||||
return { id, expiresAt: next.expiresAt };
|
||||
}
|
||||
|
||||
private async save(session: CustomWidgetPreviewSession): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { fetch, Headers } from "undici";
|
||||
import type { Response } from "undici";
|
||||
import { STATUS_CODES } from "node:http";
|
||||
import { Headers, Response } from "undici";
|
||||
|
||||
import type { CustomJsxNetworkScope, CustomWidgetMethod } from "../core";
|
||||
import { applyAuth } from "./auth";
|
||||
@@ -61,6 +61,7 @@ export interface CustomWidgetHttpResponse {
|
||||
}
|
||||
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse }>();
|
||||
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
|
||||
let cacheEpoch = 0;
|
||||
|
||||
async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
|
||||
assertRequest(input);
|
||||
@@ -75,15 +76,15 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
|
||||
const headers = buildHeaders(input, currentUrl);
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
let response: Response;
|
||||
let responseData: Awaited<ReturnType<typeof dispatcher.request>>;
|
||||
try {
|
||||
response = await fetch(currentUrl, {
|
||||
responseData = await dispatcher.request({
|
||||
origin: currentUrl.origin,
|
||||
path: `${currentUrl.pathname}${currentUrl.search}`,
|
||||
method: input.method,
|
||||
headers,
|
||||
body: input.method === "GET" ? undefined : input.body,
|
||||
redirect: "manual",
|
||||
body: input.body,
|
||||
signal: controller.signal,
|
||||
dispatcher,
|
||||
});
|
||||
} catch (error) {
|
||||
await dispatcher.close();
|
||||
@@ -101,8 +102,14 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
if (![301, 302, 303, 307, 308].includes(response.status)) {
|
||||
if (![301, 302, 303, 307, 308].includes(responseData.statusCode)) {
|
||||
try {
|
||||
const body = await responseData.body.arrayBuffer();
|
||||
const response = new Response(body.byteLength > 0 ? body : null, {
|
||||
status: responseData.statusCode,
|
||||
statusText: STATUS_CODES[responseData.statusCode] ?? "",
|
||||
headers: normalizeResponseHeaders(responseData.headers),
|
||||
});
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
@@ -113,11 +120,14 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
|
||||
await dispatcher.close();
|
||||
}
|
||||
}
|
||||
await response.body?.cancel();
|
||||
await dispatcher.close();
|
||||
try {
|
||||
await responseData.body.dump();
|
||||
} finally {
|
||||
await dispatcher.close();
|
||||
}
|
||||
if (redirects >= maxRedirects)
|
||||
throw new CustomWidgetDomainError({ code: "BAD_GATEWAY", message: "Upstream redirect limit exceeded" });
|
||||
const location = response.headers.get("location");
|
||||
const location = normalizeResponseHeaders(responseData.headers).get("location");
|
||||
if (!location)
|
||||
throw new CustomWidgetDomainError({ code: "BAD_GATEWAY", message: "Upstream redirect is missing a location" });
|
||||
const redirected = validateCustomWidgetUrl(new URL(location, currentUrl));
|
||||
@@ -127,11 +137,16 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeResponseHeaders(values: Record<string, string | string[] | undefined>) {
|
||||
const headers = new Headers();
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
if (Array.isArray(value)) value.forEach((entry) => headers.append(name, entry));
|
||||
else if (value !== undefined) headers.set(name, value);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function assertRequest(input: CustomWidgetHttpRequest): void {
|
||||
if (input.kind === "query" && input.method !== "GET")
|
||||
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: "Queries must use GET" });
|
||||
if (input.kind === "action" && input.method === "GET")
|
||||
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: "Actions cannot use GET" });
|
||||
if (input.body !== undefined && Buffer.byteLength(input.body, "utf8") > MAX_REQUEST_BODY_BYTES)
|
||||
throw new CustomWidgetDomainError({ code: "PAYLOAD_TOO_LARGE", message: "Request body exceeds the 10 KiB limit" });
|
||||
assertSafeStaticHeaders(input.staticHeaders);
|
||||
@@ -149,26 +164,37 @@ function buildHeaders(input: CustomWidgetHttpRequest, url: URL): Headers {
|
||||
}
|
||||
|
||||
export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
|
||||
const key = input.method === "GET" ? input.cacheKey : undefined;
|
||||
const key = input.kind === "query" ? input.cacheKey : undefined;
|
||||
if (!key) return performRequest(input);
|
||||
const cached = cache.get(key);
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.response;
|
||||
if (cached) cache.delete(key);
|
||||
const pending = inFlight.get(key);
|
||||
if (pending) return pending;
|
||||
const request = performRequest(input)
|
||||
const requestEpoch = cacheEpoch;
|
||||
let request: Promise<CustomWidgetHttpResponse>;
|
||||
request = performRequest(input)
|
||||
.then((response) => {
|
||||
if (response.ok && (input.cacheTtlSeconds ?? 0) > 0) {
|
||||
if (response.ok && (input.cacheTtlSeconds ?? 0) > 0 && requestEpoch === cacheEpoch) {
|
||||
pruneCache();
|
||||
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response });
|
||||
}
|
||||
return response;
|
||||
})
|
||||
.finally(() => inFlight.delete(key));
|
||||
.finally(() => {
|
||||
if (inFlight.get(key) === request) inFlight.delete(key);
|
||||
});
|
||||
inFlight.set(key, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
export function invalidateCustomWidgetResponseCache(prefixes: readonly string[]): void {
|
||||
if (prefixes.length === 0) return;
|
||||
cacheEpoch += 1;
|
||||
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) cache.delete(key);
|
||||
for (const key of inFlight.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) inFlight.delete(key);
|
||||
}
|
||||
|
||||
function pruneCache(): void {
|
||||
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) cache.delete(key);
|
||||
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES) {
|
||||
|
||||
@@ -27,11 +27,7 @@ export const validateRuntimeParams = (request: CustomJsxRequest, params: CustomJ
|
||||
}
|
||||
};
|
||||
|
||||
export const renderRequestBody = (
|
||||
template: CustomJsxRequest["bodyTemplate"],
|
||||
params: CustomJsxRuntimeParams,
|
||||
): string | undefined => {
|
||||
if (template === undefined) return undefined;
|
||||
export const renderBoundValue = (template: unknown, params: CustomJsxRuntimeParams): unknown => {
|
||||
const substitute = (value: unknown): unknown => {
|
||||
if (Array.isArray(value)) return value.map(substitute);
|
||||
if (value !== null && typeof value === "object") {
|
||||
@@ -50,7 +46,15 @@ export const renderRequestBody = (
|
||||
}
|
||||
return value;
|
||||
};
|
||||
return JSON.stringify(substitute(template));
|
||||
return substitute(template);
|
||||
};
|
||||
|
||||
export const renderRequestBody = (
|
||||
template: CustomJsxRequest["bodyTemplate"],
|
||||
params: CustomJsxRuntimeParams,
|
||||
): string | undefined => {
|
||||
if (template === undefined) return undefined;
|
||||
return JSON.stringify(renderBoundValue(template, params));
|
||||
};
|
||||
|
||||
export const renderRequestTarget = (baseUrl: string, request: CustomJsxRequest, params: CustomJsxRuntimeParams) => {
|
||||
@@ -68,7 +72,18 @@ export const renderRequestTarget = (baseUrl: string, request: CustomJsxRequest,
|
||||
message: "Path template contains an invalid placeholder",
|
||||
});
|
||||
}
|
||||
return resolveSameOriginTarget(baseUrl, new URL(path, baseUrl));
|
||||
const target = resolveSameOriginTarget(baseUrl, new URL(path, baseUrl));
|
||||
for (const [name, template] of Object.entries(request.queryTemplate ?? {})) {
|
||||
const value = renderBoundValue(template, params);
|
||||
if (!["string", "number", "boolean"].includes(typeof value)) {
|
||||
throw new CustomWidgetDomainError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Query parameter '${name}' must resolve to a string, number, or boolean`,
|
||||
});
|
||||
}
|
||||
target.searchParams.set(name, String(value));
|
||||
}
|
||||
return target;
|
||||
};
|
||||
|
||||
export const hashRuntimeParams = (params: CustomJsxRuntimeParams) => {
|
||||
|
||||
@@ -1,32 +1,87 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { buildCustomWidgetAiPrompt } from "../core/ai-prompt";
|
||||
import { buildCustomWidgetAiPrompt, buildCustomWidgetFixPrompt, buildCustomWidgetMcpPrompt } from "../core/ai-prompt";
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
|
||||
describe("buildCustomWidgetAiPrompt", () => {
|
||||
test("describes the complete v2 named-request and render-child workflow", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt({ type: "object" }, '{"serviceId":"alpha"}');
|
||||
|
||||
expect(prompt).toContain('"$schema": "homarr-custom-widget-v3"');
|
||||
expect(prompt).toContain("jsxApiVersion: 2");
|
||||
expect(prompt).toContain("SubFetch can reference query requests only");
|
||||
expect(prompt).toContain("Prefer the SubFetch function-as-children API");
|
||||
expect(prompt).toContain('<SubFetch requestId="service-detail"');
|
||||
expect(prompt).toContain("ActionButton and ToggleSwitch can reference action requests only");
|
||||
expect(prompt).toContain("## Generated component reference");
|
||||
expect(prompt).toContain("## Tested examples");
|
||||
expect(prompt).toContain('{"serviceId":"alpha"}');
|
||||
test("is concise and describes the one-widget v2 contract", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(
|
||||
undefined,
|
||||
null,
|
||||
null,
|
||||
"Create a Portainer widget",
|
||||
"https://example.com/docs",
|
||||
);
|
||||
expect(prompt).toContain("homarr-custom-widget-v2");
|
||||
expect(prompt).toContain("Return exactly two fenced blocks");
|
||||
expect(prompt).toContain("Never include credentials");
|
||||
expect(prompt).toContain("Create a Portainer widget");
|
||||
expect(prompt.length).toBeLessThanOrEqual(8_000);
|
||||
});
|
||||
|
||||
test("keeps an existing multiline template readable and outside JSON escaping", () => {
|
||||
const template = '<Stack gap="sm">\n <Text>{data.name}</Text>\n</Stack>';
|
||||
const prompt = buildCustomWidgetAiPrompt({ type: "object" }, null, {
|
||||
name: "Existing",
|
||||
displayConfig: { type: "customJsx", jsxApiVersion: 2, template, requests: [] },
|
||||
});
|
||||
test("includes an existing widget without exposing secret fields", () => {
|
||||
const secret = "TOP-SECRET-123";
|
||||
const source = CUSTOM_WIDGET_STARTER.sources[0];
|
||||
if (!source) throw new Error("Starter widget requires one source");
|
||||
const prompt = buildCustomWidgetAiPrompt(
|
||||
undefined,
|
||||
JSON.stringify({ token: secret }),
|
||||
{
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: [{ ...source, baseUrl: `https://user:${secret}@example.com?api_key=${secret}` }],
|
||||
secrets: [{ sourceId: "default", kind: "apiKey", value: secret }],
|
||||
},
|
||||
`Improve it with API key: ${secret}`,
|
||||
`https://example.com/docs?token=${secret}`,
|
||||
);
|
||||
expect(prompt).toContain('"$schema": "homarr-custom-widget-v2"');
|
||||
expect(prompt).not.toContain(secret);
|
||||
expect(prompt).not.toContain("user:");
|
||||
expect(prompt).not.toContain("api_key=");
|
||||
});
|
||||
|
||||
expect(prompt).toContain('"template": "__HOMARR_TEMPLATE__"');
|
||||
expect(prompt).toContain(`\`\`\`jsx\n${template}\n\`\`\``);
|
||||
expect(prompt).not.toContain(template.replaceAll("\n", "\\n"));
|
||||
expect(prompt).toContain("PASTE_API_RESPONSE_HERE");
|
||||
test("redacts camel-case credentials and invalid structured editor drafts", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(undefined, null, {
|
||||
sources: '[{"baseUrl":"https://user:password@example.com?accessToken=VALUE"}]',
|
||||
requests: '[{"bodyTemplate":{"clientSecret":"VALUE"}}]',
|
||||
template: "<Text>accessToken: VALUE</Text>",
|
||||
});
|
||||
expect(prompt).not.toContain("password@");
|
||||
expect(prompt).not.toContain('clientSecret": "VALUE');
|
||||
expect(prompt).not.toContain("accessToken: VALUE");
|
||||
});
|
||||
|
||||
test("redacts malformed URLs without recursing", () => {
|
||||
expect(buildCustomWidgetAiPrompt(undefined, null, null, "Inspect http://[", null)).toContain("[REDACTED_URL]");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCustomWidgetFixPrompt", () => {
|
||||
test("includes the complete current widget and redacted iteration evidence", () => {
|
||||
const secret = "literal-sensitive-value";
|
||||
const prompt = buildCustomWidgetFixPrompt({
|
||||
currentConfig: {
|
||||
name: "Large widget",
|
||||
template: `<Text>${"x".repeat(9_000)}</Text>`,
|
||||
secrets: [{ value: secret }],
|
||||
},
|
||||
request: `Fix it with password='${secret}'`,
|
||||
diagnostics: `Header apiKey='${secret}' is invalid`,
|
||||
journal: [{ requestId: "load", authorization: secret }],
|
||||
});
|
||||
expect(prompt).toContain("x".repeat(9_000));
|
||||
expect(prompt).toContain("Validation diagnostics");
|
||||
expect(prompt).not.toContain(secret);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCustomWidgetMcpPrompt", () => {
|
||||
test("describes tool-driven iteration without embedding the copy/paste output contract", () => {
|
||||
const prompt = buildCustomWidgetMcpPrompt("Create two Portainer widgets", "https://example.com/docs");
|
||||
expect(prompt).toContain("customWidget_previewCreate");
|
||||
expect(prompt).toContain("homarr://custom-widgets/schema");
|
||||
expect(prompt).toContain("Create two Portainer widgets");
|
||||
expect(prompt).not.toContain("Return exactly two fenced blocks");
|
||||
expect(prompt.length).toBeLessThan(8_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
CUSTOM_WIDGET_SKILL_MD,
|
||||
CUSTOM_WIDGET_SKILL_SHA256,
|
||||
getCustomWidgetComponent,
|
||||
getCustomWidgetSkill,
|
||||
} from "../core/authoring-resources";
|
||||
|
||||
const repositoryRoot = resolve(import.meta.dirname, "../../../..");
|
||||
|
||||
describe("custom widget Agent Skill", () => {
|
||||
test("keeps the MCP skill text synchronized with the repository source", async () => {
|
||||
const source = await readFile(resolve(repositoryRoot, ".agents/skills/homarr-custom-widget/SKILL.md"), "utf8");
|
||||
expect(CUSTOM_WIDGET_SKILL_MD).toBe(source);
|
||||
expect(getCustomWidgetSkill().skillMd).toBe(source);
|
||||
});
|
||||
|
||||
test("publishes the exact archive hash", async () => {
|
||||
const archive = await readFile(
|
||||
resolve(repositoryRoot, "apps/docs/static/downloads/homarr-custom-widget-2.0.0.zip"),
|
||||
);
|
||||
expect(createHash("sha256").update(archive).digest("hex")).toBe(CUSTOM_WIDGET_SKILL_SHA256);
|
||||
});
|
||||
|
||||
test("publishes safe icon names with the Tabler icon component", () => {
|
||||
expect(getCustomWidgetComponent("TablerIcon")?.knownValues?.name).toContain("server");
|
||||
});
|
||||
});
|
||||
@@ -183,12 +183,14 @@ describe("customJsxComponentRegistry", () => {
|
||||
});
|
||||
|
||||
test.each([
|
||||
["ChartTooltip", "allowed"],
|
||||
["ChartLegend", "allowed"],
|
||||
["VisuallyHidden", "allowed"],
|
||||
["ChartTooltip", "wrapped"],
|
||||
["ChartLegend", "wrapped"],
|
||||
["VisuallyHidden", "wrapped"],
|
||||
["SubFetch", "wrapped"],
|
||||
["Portal", "denied"],
|
||||
["TextInput", "denied"],
|
||||
["TextInput", "wrapped"],
|
||||
["ModalRoot", "denied"],
|
||||
["AppShellMain", "denied"],
|
||||
] as const)("classifies %s as %s", (name, safety) => {
|
||||
expect(customJsxComponentByName.get(name)?.safety).toBe(safety);
|
||||
});
|
||||
@@ -207,6 +209,9 @@ describe("customJsxComponentRegistry", () => {
|
||||
expect(component.supportedProps, component.name).toBeInstanceOf(Array);
|
||||
expect(component.subcomponents, component.name).toBeInstanceOf(Array);
|
||||
expect(component.accessibilityRequirements, component.name).toBeInstanceOf(Array);
|
||||
expect(component.supportedProps, component.name).not.toContain("renderOption");
|
||||
expect(component.supportedProps, component.name).not.toContain("rootRef");
|
||||
expect(component.supportedProps, component.name).not.toContain("popoverTarget");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { extractDisplayData } from "../core/display-data";
|
||||
import type { DisplayConfig } from "../core/schema";
|
||||
|
||||
const response = {
|
||||
value: 42,
|
||||
status: "online",
|
||||
total: 100,
|
||||
rows: [
|
||||
{ name: "Alpha", count: 2 },
|
||||
{ name: "Beta", count: 3 },
|
||||
],
|
||||
};
|
||||
|
||||
const extract = (config: DisplayConfig) => extractDisplayData(response, config.type, config);
|
||||
|
||||
describe("display data extraction", () => {
|
||||
test("extracts a single value", () => {
|
||||
expect(extract({ type: "singleValue", jsonPath: "$.value", label: "Value", unit: "%" })).toMatchObject({
|
||||
type: "singleValue",
|
||||
value: 42,
|
||||
valueSize: "lg",
|
||||
labelPosition: "below",
|
||||
});
|
||||
});
|
||||
|
||||
test("extracts key-value mappings", () => {
|
||||
expect(
|
||||
extract({
|
||||
type: "keyValue",
|
||||
mappings: [
|
||||
{ label: "Value", jsonPath: "$.value", unit: "%" },
|
||||
{ label: "Status", jsonPath: "$.status", unit: "" },
|
||||
],
|
||||
}),
|
||||
).toMatchObject({ entries: [{ value: 42 }, { value: "online" }], layout: "list", columns: 2 });
|
||||
});
|
||||
|
||||
test("extracts table rows", () => {
|
||||
expect(
|
||||
extract({
|
||||
type: "table",
|
||||
tablePath: "$.rows",
|
||||
columns: [
|
||||
{ header: "Name", jsonPath: "$.name" },
|
||||
{ header: "Count", jsonPath: "$.count" },
|
||||
],
|
||||
}),
|
||||
).toMatchObject({
|
||||
columns: ["Name", "Count"],
|
||||
rows: [
|
||||
["Alpha", 2],
|
||||
["Beta", 3],
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("extracts stat cards", () => {
|
||||
expect(
|
||||
extract({ type: "statGrid", items: [{ label: "Value", jsonPath: "$.value", unit: "", color: "red" }] }),
|
||||
).toMatchObject({ items: [{ value: 42, color: "red" }], columns: 2, cardStyle: "filled" });
|
||||
});
|
||||
|
||||
test("extracts progress values and maxima", () => {
|
||||
expect(
|
||||
extract({
|
||||
type: "progressBars",
|
||||
bars: [{ label: "Usage", valuePath: "$.value", maxPath: "$.total", unit: "%" }],
|
||||
}),
|
||||
).toMatchObject({ bars: [{ value: 42, max: 100, color: "blue" }], showPercentage: true, barSize: "md" });
|
||||
});
|
||||
|
||||
test("classifies status values", () => {
|
||||
expect(
|
||||
extract({
|
||||
type: "statusIndicator",
|
||||
items: [{ label: "Service", jsonPath: "$.status", goodValues: ["ONLINE"] }],
|
||||
}),
|
||||
).toMatchObject({ items: [{ value: "online", isGood: true }], layout: "list", dotSize: "md" });
|
||||
});
|
||||
|
||||
test("extracts count grids", () => {
|
||||
expect(extract({ type: "countGrid", items: [{ label: "Count", jsonPath: "$.value", unit: "" }] })).toMatchObject({
|
||||
items: [{ value: 42 }],
|
||||
columns: 2,
|
||||
valueSize: "md",
|
||||
});
|
||||
});
|
||||
|
||||
test("extracts raw paths", () => {
|
||||
expect(extract({ type: "raw", jsonPath: "$.rows", maxHeight: 200 })).toEqual({
|
||||
type: "raw",
|
||||
data: response.rows,
|
||||
maxHeight: 200,
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizes action button defaults", () => {
|
||||
expect(extract({ type: "actionButton", buttonLabel: "Run" })).toEqual({
|
||||
type: "actionButton",
|
||||
buttonLabel: "Run",
|
||||
buttonColor: "blue",
|
||||
confirmText: "",
|
||||
successMessage: "",
|
||||
});
|
||||
});
|
||||
|
||||
test("passes Custom JSX data and capabilities through", () => {
|
||||
expect(
|
||||
extract({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
template: "<Text>{data.value}</Text>",
|
||||
networkScope: "public",
|
||||
requests: [
|
||||
{
|
||||
id: "detail",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/detail",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "customJsx",
|
||||
data: response,
|
||||
jsxApiVersion: 2,
|
||||
requestCapabilities: [{ id: "detail", kind: "query", method: "GET", minimumBoardPermission: "view" }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { buildDisplayConfigFromFormValues, buildDisplayFormValues, CUSTOM_JSX_STARTER } from "../core/display-form";
|
||||
import { customWidgetDisplayTypes, displayConfigSchema } from "../core/schema";
|
||||
|
||||
const requiredFormValues = (displayType: string) => {
|
||||
const values = buildDisplayFormValues(displayType, {});
|
||||
values.label = "Value";
|
||||
values.mappings = [{ label: "CPU", jsonPath: "$.cpu", unit: "%" }];
|
||||
values.columns = [{ header: "Name", jsonPath: "$.name" }];
|
||||
values.statGridItems = [{ label: "CPU", jsonPath: "$.cpu", unit: "%", color: "blue" }];
|
||||
values.progressBars = [{ label: "Disk", valuePath: "$.used", maxPath: "$.total", unit: "GB", color: "blue" }];
|
||||
values.statusItems = [{ label: "Service", jsonPath: "$.status", goodValues: "online, true" }];
|
||||
values.countGridItems = [{ label: "Users", jsonPath: "$.users", unit: "" }];
|
||||
values.buttonLabel = "Execute";
|
||||
values.template = CUSTOM_JSX_STARTER;
|
||||
return values;
|
||||
};
|
||||
|
||||
describe("custom-widget display form contracts", () => {
|
||||
test.each(customWidgetDisplayTypes)("round-trips the %s display through one canonical transform", (displayType) => {
|
||||
const initialForm = requiredFormValues(displayType);
|
||||
const config = buildDisplayConfigFromFormValues(initialForm);
|
||||
const parsed = displayConfigSchema.parse(config);
|
||||
const hydratedForm = buildDisplayFormValues(displayType, parsed);
|
||||
const rebuilt = buildDisplayConfigFromFormValues(hydratedForm);
|
||||
|
||||
expect(rebuilt).toEqual(parsed);
|
||||
});
|
||||
|
||||
test("preserves display-only v1 Custom JSX without adding network capabilities", () => {
|
||||
const values = requiredFormValues("customJsx");
|
||||
values.jsxApiVersion = "1";
|
||||
values.requestManifest = JSON.stringify([
|
||||
{ id: "unsafe", kind: "action", method: "POST", pathTemplate: "/action" },
|
||||
]);
|
||||
|
||||
expect(buildDisplayConfigFromFormValues(values)).toEqual({
|
||||
type: "customJsx",
|
||||
template: CUSTOM_JSX_STARTER,
|
||||
});
|
||||
});
|
||||
|
||||
test("validates the v2 request manifest while serializing form state", () => {
|
||||
const values = requiredFormValues("customJsx");
|
||||
values.jsxApiVersion = "2";
|
||||
values.requestManifest = JSON.stringify([
|
||||
{
|
||||
id: "status",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/status/{id}",
|
||||
parameters: { id: "string" },
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(buildDisplayConfigFromFormValues(values)).toMatchObject({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
requests: [{ id: "status", kind: "query", method: "GET" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("does not throw on invalid request manifest JSON while serializing v2 form state", () => {
|
||||
const values = requiredFormValues("customJsx");
|
||||
values.jsxApiVersion = "2";
|
||||
|
||||
for (const invalidManifest of ["[invalid", "{not an array}", "", '{"id":1}', "null"]) {
|
||||
values.requestManifest = invalidManifest;
|
||||
expect(() => buildDisplayConfigFromFormValues(values)).not.toThrow();
|
||||
const config = buildDisplayConfigFromFormValues(values) as { requests?: unknown };
|
||||
expect(config.requests).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,68 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseCustomWidgetClipboard } from "../core/import";
|
||||
import { customWidgetImportSchema } from "../core/schema";
|
||||
|
||||
const widget = {
|
||||
$schema: "homarr-custom-widget-v3",
|
||||
name: "Example",
|
||||
url: "https://example.com/api",
|
||||
authType: "none",
|
||||
method: "GET",
|
||||
displayType: "customJsx",
|
||||
displayConfig: {
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
networkScope: "public",
|
||||
requests: [],
|
||||
template: "__HOMARR_TEMPLATE__",
|
||||
},
|
||||
};
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
import { parseCustomWidgetClipboard, parseCustomWidgetClipboardDetailed } from "../core/import";
|
||||
|
||||
describe("parseCustomWidgetClipboard", () => {
|
||||
it("keeps supporting raw JSON imports", () => {
|
||||
const result = parseCustomWidgetClipboard(JSON.stringify({ ...widget, displayType: "raw" }));
|
||||
expect(result?.name).toBe("Example");
|
||||
it("accepts the canonical raw JSON export", () => {
|
||||
expect(parseCustomWidgetClipboard(JSON.stringify(CUSTOM_WIDGET_STARTER))?.$schema).toBe("homarr-custom-widget-v2");
|
||||
});
|
||||
|
||||
it("keeps accepting the v2 import envelope", () => {
|
||||
expect(
|
||||
customWidgetImportSchema.parse({
|
||||
...widget,
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
displayType: "raw",
|
||||
displayConfig: { type: "raw", jsonPath: "$", maxHeight: 300 },
|
||||
}).$schema,
|
||||
).toBe("homarr-custom-widget-v2");
|
||||
});
|
||||
|
||||
it("combines a JSON metadata block with a readable JSX block", () => {
|
||||
const result = parseCustomWidgetClipboard(`Here is the widget:
|
||||
|
||||
\`\`\`json
|
||||
${JSON.stringify(widget, null, 2)}
|
||||
\`\`\`
|
||||
|
||||
\`\`\`jsx
|
||||
<Stack gap="sm">
|
||||
<Text>{data.name}</Text>
|
||||
</Stack>
|
||||
\`\`\``);
|
||||
|
||||
expect((result?.displayConfig as Record<string, unknown> | undefined)?.template).toBe(
|
||||
'<Stack gap="sm">\n <Text>{data.name}</Text>\n</Stack>',
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts case-insensitive fenced languages and CRLF line endings", () => {
|
||||
it("combines widget.json and widget.jsx blocks", () => {
|
||||
const manifest = { ...CUSTOM_WIDGET_STARTER, template: "__HOMARR_TEMPLATE__" };
|
||||
const result = parseCustomWidgetClipboard(
|
||||
`\`\`\`JSON\r\n${JSON.stringify(widget)}\r\n\`\`\`\r\n\`\`\`TSX\r\n<Text>{data.name}</Text>\r\n\`\`\``,
|
||||
`\`\`\`json\n${JSON.stringify(manifest)}\n\`\`\`\n\`\`\`jsx\n<Text>{options.title}</Text>\n\`\`\``,
|
||||
);
|
||||
|
||||
expect((result?.displayConfig as Record<string, unknown> | undefined)?.template).toBe("<Text>{data.name}</Text>");
|
||||
expect(result?.template).toBe("<Text>{options.title}</Text>");
|
||||
});
|
||||
|
||||
it("rejects an unterminated fence with a large whitespace payload", () => {
|
||||
expect(parseCustomWidgetClipboard(`\`\`\`json\n${" ".repeat(250_000)}`)).toBeNull();
|
||||
it("rejects removed display types and old exports", () => {
|
||||
expect(
|
||||
parseCustomWidgetClipboard(JSON.stringify({ displayType: "raw", displayConfig: { type: "raw" } })),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns an actionable validation issue for invalid AI output", () => {
|
||||
expect(parseCustomWidgetClipboardDetailed(JSON.stringify({ $schema: "homarr-custom-widget-v2" }))).toEqual({
|
||||
success: false,
|
||||
error: expect.stringMatching(/name|sources/u),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -28,4 +28,97 @@ describe("shared Custom JSX policy", () => {
|
||||
const template = `<Text>{${"!".repeat(CUSTOM_JSX_LIMITS.astDepth + 1)}data}</Text>`;
|
||||
expect(validateCustomJsxTemplate(template).some(({ message }) => message.includes("depth limit"))).toBe(true);
|
||||
});
|
||||
|
||||
test("passes unknown ordinary props through as advisories and blocks capabilities explicitly", () => {
|
||||
const diagnostics = validateCustomJsxTemplate('<Text futureMantineProp="yes">Safe</Text>');
|
||||
expect(diagnostics).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "warning", message: expect.stringContaining("UNKNOWN_MANTINE_PROP") }),
|
||||
]),
|
||||
);
|
||||
expect(sanitizeCustomJsxProps({ futureMantineProp: "yes" }, "Text")).toHaveProperty("futureMantineProp", "yes");
|
||||
expect(validateCustomJsxTemplate("<Text onClick={() => null}>Unsafe</Text>")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "error", message: expect.stringContaining("BLOCKED_CAPABILITY") }),
|
||||
]),
|
||||
);
|
||||
expect(validateCustomJsxTemplate("<Text valueFormatter={(value) => value}>Unsafe</Text>")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "error", message: expect.stringContaining("Callback prop") }),
|
||||
]),
|
||||
);
|
||||
expect(validateCustomJsxTemplate('<Anchor href="javascript:alert(1)">Unsafe</Anchor>')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "error", message: expect.stringContaining("INVALID_PROP_VALUE") }),
|
||||
]),
|
||||
);
|
||||
expect(validateCustomJsxTemplate('<Box pos="fixed" top={0}>Unsafe</Box>')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "error", message: expect.stringContaining("BLOCKED_CAPABILITY") }),
|
||||
]),
|
||||
);
|
||||
expect(sanitizeCustomJsxProps({ pos: "fixed", top: 0, unstyled: true })).toEqual({ unstyled: true });
|
||||
});
|
||||
|
||||
test("blocks refs, native popovers, and editable DOM capabilities without blocking declarative bind", () => {
|
||||
const diagnostics = validateCustomJsxTemplate(
|
||||
'<TextInput bind="search" rootRef={data.ref} popoverTarget="outside" contentEditable />',
|
||||
);
|
||||
expect(diagnostics.filter(({ severity }) => severity === "error")).toHaveLength(3);
|
||||
expect(diagnostics.some(({ message }) => message.includes("Prop 'bind'"))).toBe(false);
|
||||
});
|
||||
|
||||
test("provides closest component and binding diagnostics", () => {
|
||||
expect(validateCustomJsxTemplate("<Stak />")[0]?.message).toMatch(/UNKNOWN_COMPONENT.*Stack/u);
|
||||
expect(validateCustomJsxTemplate('<Text bind="search" />')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "warning", message: expect.stringContaining("BINDING_UNAVAILABLE") }),
|
||||
]),
|
||||
);
|
||||
expect(() => renderSafeJsx({ template: '<Text bind="search" />', components, bindings })).not.toThrow();
|
||||
});
|
||||
|
||||
test("reports denied component families as blocked capabilities", () => {
|
||||
expect(validateCustomJsxTemplate("<ModalRoot opened />")[0]?.message).toMatch(/BLOCKED_CAPABILITY/u);
|
||||
});
|
||||
|
||||
test("reports blocked capabilities introduced through spreads at runtime", () => {
|
||||
const rendered = renderSafeJsx({
|
||||
template: "<Text {...data.props}>Safe</Text>",
|
||||
components,
|
||||
bindings: { data: { props: { onClick: "unsafe", href: "javascript:alert(1)" } } },
|
||||
});
|
||||
expect(rendered.warnings).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("BLOCKED_CAPABILITY"),
|
||||
expect.stringContaining("INVALID_PROP_VALUE"),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test("sanitizes and diagnoses blocked capabilities inside nested Mantine props", () => {
|
||||
const props = sanitizeCustomJsxProps({
|
||||
tooltipProps: { label: "Safe", onClick: "unsafe", href: "javascript:alert(1)" },
|
||||
data: [{ image: "metric-name", onClick: "api-field" }],
|
||||
});
|
||||
expect(props).toEqual({
|
||||
tooltipProps: { label: "Safe" },
|
||||
data: [{ image: "metric-name", onClick: "api-field" }],
|
||||
});
|
||||
expect(validateCustomJsxTemplate("<Text tooltipProps={{ onClick: () => null }}>Unsafe</Text>")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "error", message: expect.stringContaining("Callback prop") }),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
validateCustomJsxTemplate("<BarChart data={data.items.map((item) => item)} />").some(({ message }) =>
|
||||
message.includes("Callback prop"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(validateCustomJsxTemplate("<Select data={data.items.map((item) => () => item.label)} />")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ severity: "error", message: expect.stringContaining("BLOCKED_CAPABILITY") }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -22,11 +22,23 @@ function createHarness() {
|
||||
|
||||
const input: CreatePreviewSessionInput = {
|
||||
userId: "user-1",
|
||||
baseUrl: "https://example.com/api",
|
||||
authType: "bearer",
|
||||
secrets: [{ kind: "apiKey", value: "secret" }],
|
||||
networkScope: "public",
|
||||
sources: [
|
||||
{
|
||||
id: "default",
|
||||
name: "API",
|
||||
baseUrl: "https://example.com/api",
|
||||
auth: { type: "bearer" },
|
||||
networkScope: "public",
|
||||
},
|
||||
],
|
||||
secrets: [{ sourceId: "default", kind: "apiKey", value: "secret" }],
|
||||
requests: [],
|
||||
name: "Preview",
|
||||
template: "<Text>Preview</Text>",
|
||||
optionsSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
defaultOptions: {},
|
||||
stateSchema: {},
|
||||
defaultState: {},
|
||||
};
|
||||
|
||||
describe("preview session service", () => {
|
||||
@@ -35,15 +47,15 @@ describe("preview session service", () => {
|
||||
const created = await service.create(input);
|
||||
const session = await service.get(created.id, input.userId);
|
||||
expect(session.secrets[0]?.value).toBe("encrypted:secret");
|
||||
expect(service.getSecrets(session)).toEqual([{ kind: "apiKey", value: "secret" }]);
|
||||
expect(service.getSecrets(session, "default")).toEqual([{ kind: "apiKey", value: "secret" }]);
|
||||
});
|
||||
|
||||
it("isolates sessions by user and expires them after five minutes", async () => {
|
||||
it("isolates sessions by user and expires them after ten minutes", async () => {
|
||||
const { service, advance } = createHarness();
|
||||
const created = await service.create(input);
|
||||
await expect(service.get(created.id, "other-user")).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
const second = await service.create(input);
|
||||
advance(5 * 60_000 + 1);
|
||||
advance(10 * 60_000 + 1);
|
||||
await expect(service.get(second.id, input.userId)).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { hashRuntimeParams, renderRequestBody, renderRequestTarget, validateRunt
|
||||
|
||||
const request: CustomJsxRequest = {
|
||||
id: "device",
|
||||
sourceId: "default",
|
||||
kind: "action",
|
||||
method: "PATCH",
|
||||
pathTemplate: "/devices/{device}/state",
|
||||
@@ -12,6 +13,8 @@ const request: CustomJsxRequest = {
|
||||
bodyTemplate: { enabled: { $param: "enabled" }, nested: { level: { $param: "level" } } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
queryTemplate: { verbose: true, level: { $param: "level" } },
|
||||
};
|
||||
|
||||
describe("named request manifest rendering", () => {
|
||||
@@ -28,6 +31,7 @@ describe("named request manifest rendering", () => {
|
||||
expect(renderRequestTarget("https://example.com/api", request, params).pathname).toBe(
|
||||
"/devices/living%20room%2F1/state",
|
||||
);
|
||||
expect(renderRequestTarget("https://example.com/api", request, params).searchParams.get("level")).toBe("5");
|
||||
expect(JSON.parse(renderRequestBody(request.bodyTemplate, params) ?? "null")).toEqual({
|
||||
enabled: true,
|
||||
nested: { level: 5 },
|
||||
|
||||
@@ -4,20 +4,21 @@ import { act } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { Root } from "react-dom/client";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { MantineProvider, Text } from "@mantine/core";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ActionButton, CustomWidgetRuntimeProvider, SubFetch, ToggleSwitch } from "../runtime";
|
||||
import { ActionButton, CustomJsxRenderer, CustomWidgetRuntimeProvider, SubFetch, ToggleSwitch } from "../runtime";
|
||||
import type {
|
||||
CustomJsxRequestCapability,
|
||||
CustomWidgetPublishedQueryState,
|
||||
CustomWidgetRequestResult,
|
||||
CustomWidgetRuntimeMessages,
|
||||
CustomWidgetRuntimePort,
|
||||
} from "../runtime";
|
||||
|
||||
const messages: CustomWidgetRuntimeMessages = {
|
||||
migrationRequired: "Migration required",
|
||||
requestIdRequired: "Request ID required",
|
||||
unsavedPreview: "Unsaved",
|
||||
invalidParams: "Invalid params",
|
||||
loadRequest: "Load",
|
||||
@@ -74,6 +75,7 @@ async function render(
|
||||
node: ReactNode,
|
||||
port: CustomWidgetRuntimePort,
|
||||
capabilities: readonly CustomJsxRequestCapability[] = [],
|
||||
setQueryState?: (requestId: string, value: CustomWidgetPublishedQueryState | null) => void,
|
||||
) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
await act(async () => {
|
||||
@@ -86,6 +88,7 @@ async function render(
|
||||
requestCapabilities={capabilities}
|
||||
port={port}
|
||||
messages={messages}
|
||||
setQueryState={setQueryState}
|
||||
>
|
||||
{node}
|
||||
</CustomWidgetRuntimeProvider>
|
||||
@@ -102,15 +105,48 @@ async function settle() {
|
||||
}
|
||||
|
||||
describe("Custom Widget runtime ports", () => {
|
||||
it("runs an automatic query once and exposes data to a render child", async () => {
|
||||
const port = createPort();
|
||||
await render(
|
||||
<SubFetch requestId="details" render={(data) => <span>{(data as { name: string }).name}</span>} />,
|
||||
port,
|
||||
it("does not republish local state when equivalent default objects are rendered", async () => {
|
||||
const onStateChange = vi.fn();
|
||||
const rendererMessages = {
|
||||
noTemplate: "No template",
|
||||
interactive: "Interactive",
|
||||
networkCapabilities: "Network capabilities",
|
||||
templateWarnings: (count: number) => `${count} warnings`,
|
||||
};
|
||||
const widget = () => (
|
||||
<CustomJsxRenderer
|
||||
template="<Text>{state.search}</Text>"
|
||||
data={{}}
|
||||
stateSchema={{ search: "string" }}
|
||||
defaultState={{ search: "containers" }}
|
||||
onStateChange={onStateChange}
|
||||
requestCapabilities={[]}
|
||||
components={{ Text: Text as never }}
|
||||
createBindings={() => ({})}
|
||||
messages={rendererMessages}
|
||||
/>
|
||||
);
|
||||
|
||||
await render(widget(), createPort());
|
||||
await settle();
|
||||
expect(onStateChange).toHaveBeenCalledTimes(1);
|
||||
|
||||
await render(widget(), createPort());
|
||||
await settle();
|
||||
expect(onStateChange).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("runs an automatic query once and publishes data to the declarative data root", async () => {
|
||||
const port = createPort();
|
||||
const publish = vi.fn();
|
||||
await render(<SubFetch requestId="details" />, port, [], publish);
|
||||
await settle();
|
||||
expect(port.query).toHaveBeenCalledTimes(1);
|
||||
expect(host.textContent).toContain("Bulbasaur");
|
||||
expect(publish).toHaveBeenLastCalledWith("details", {
|
||||
data: { name: "Bulbasaur" },
|
||||
status: expect.objectContaining({ loading: false, ok: true, status: 200 }),
|
||||
});
|
||||
expect(host.querySelector("button, p, code, [role='alert']")).toBeNull();
|
||||
});
|
||||
|
||||
it("passes cancellation to the port when the component unmounts", async () => {
|
||||
@@ -129,8 +165,15 @@ describe("Custom Widget runtime ports", () => {
|
||||
|
||||
it("confirms DELETE actions, reports success, and invalidates declared targets", async () => {
|
||||
const port = createPort();
|
||||
await render(<ActionButton requestId="remove" label="Remove" invalidate={["parent"]} />, port, [
|
||||
{ id: "remove", kind: "action", method: "DELETE", minimumBoardPermission: "full" },
|
||||
await render(<ActionButton requestId="remove">Remove</ActionButton>, port, [
|
||||
{
|
||||
id: "remove",
|
||||
kind: "action",
|
||||
method: "DELETE",
|
||||
trigger: "manual",
|
||||
minimumBoardPermission: "full",
|
||||
invalidates: ["parent"],
|
||||
},
|
||||
]);
|
||||
await act(async () => (host.querySelector("button") as HTMLButtonElement).click());
|
||||
await settle();
|
||||
@@ -154,4 +197,25 @@ describe("Custom Widget runtime ports", () => {
|
||||
expect(port.notify).toHaveBeenCalledWith(expect.objectContaining({ kind: "error", message: "Nope" }));
|
||||
expect(port.invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("confirms a DELETE toggle before executing it", async () => {
|
||||
const port = createPort();
|
||||
await render(
|
||||
<ToggleSwitch requestId="delete-toggle" onParams={{ enabled: true }} offParams={{ enabled: false }} />,
|
||||
port,
|
||||
[
|
||||
{
|
||||
id: "delete-toggle",
|
||||
kind: "action",
|
||||
method: "DELETE",
|
||||
trigger: "manual",
|
||||
minimumBoardPermission: "full",
|
||||
},
|
||||
],
|
||||
);
|
||||
await act(async () => (host.querySelector("input") as HTMLInputElement).click());
|
||||
await settle();
|
||||
expect(port.confirm).toHaveBeenCalledWith(expect.objectContaining({ destructive: true }));
|
||||
expect(port.executeAction).toHaveBeenCalledWith(expect.objectContaining({ confirmed: true }));
|
||||
});
|
||||
});
|
||||
@@ -1,166 +1,424 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { customJsxExamples } from "../core/examples";
|
||||
import { customJsxDisplayConfigV2Schema, customJsxRequestSchema, displayConfigSchema } from "../core/schema";
|
||||
import { validateCustomJsxTemplate } from "../jsx/analyzer";
|
||||
import { customJsxExamples, CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
import { customJsxRequestSchema, customWidgetCreateSchema, customWidgetDefinitionSchema } from "../core/schema";
|
||||
import { validateCustomWidgetOptions } from "../core/options";
|
||||
|
||||
describe("custom JSX v2 validation", () => {
|
||||
test.each(customJsxExamples)("validates the $id shared example", (example) => {
|
||||
expect(() =>
|
||||
customJsxDisplayConfigV2Schema.parse({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
template: example.template,
|
||||
networkScope: "public",
|
||||
requests: [...example.requests],
|
||||
}),
|
||||
).not.toThrow();
|
||||
describe("Custom JSX v2 validation", () => {
|
||||
test.each(customJsxExamples)("validates $id", (example) => {
|
||||
expect(() => customWidgetDefinitionSchema.parse(example.widget)).not.toThrow();
|
||||
});
|
||||
|
||||
test("retains display-only v1 compatibility", () => {
|
||||
expect(displayConfigSchema.parse({ type: "customJsx", template: "<Text>{data.value}</Text>" })).toEqual({
|
||||
type: "customJsx",
|
||||
template: "<Text>{data.value}</Text>",
|
||||
});
|
||||
});
|
||||
|
||||
test("accepts benign text containing interpreter-reserved words", () => {
|
||||
expect(() =>
|
||||
customJsxDisplayConfigV2Schema.parse({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
template: "<Text>constructor fetch prototype</Text>",
|
||||
networkScope: "public",
|
||||
requests: [],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
test("accepts supported Tabs, ScrollArea, and SubData image props without warnings", () => {
|
||||
const diagnostics = validateCustomJsxTemplate(
|
||||
'<Tabs.List grow><ScrollArea offsetScrollbars><SubData as="Image" fit="contain" alt="Artwork" /></ScrollArea></Tabs.List>',
|
||||
);
|
||||
expect(diagnostics).toEqual([]);
|
||||
});
|
||||
|
||||
test("rejects malformed JSX and direct global fetch while allowing declarative onParams", () => {
|
||||
const config = {
|
||||
type: "customJsx" as const,
|
||||
jsxApiVersion: 2 as const,
|
||||
networkScope: "public" as const,
|
||||
requests: [],
|
||||
};
|
||||
expect(customJsxDisplayConfigV2Schema.safeParse({ ...config, template: "<Text>" }).success).toBe(false);
|
||||
test("rejects every legacy schema", () => {
|
||||
expect(
|
||||
customJsxDisplayConfigV2Schema.safeParse({ ...config, template: '<Text>{fetch("/private")}</Text>' }).success,
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, $schema: "homarr-custom-widget-v3" }).success,
|
||||
).toBe(false);
|
||||
expect(customWidgetDefinitionSchema.safeParse({ displayType: "raw", displayConfig: { type: "raw" } }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("allows query POST and action GET while keeping actions manual", () => {
|
||||
const base = {
|
||||
sourceId: "default",
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "none" as const,
|
||||
trigger: "manual" as const,
|
||||
};
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "query",
|
||||
kind: "query",
|
||||
method: "POST",
|
||||
minimumBoardPermission: "view",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "action",
|
||||
kind: "action",
|
||||
method: "GET",
|
||||
minimumBoardPermission: "modify",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "action",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
trigger: "load",
|
||||
minimumBoardPermission: "modify",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxDisplayConfigV2Schema.safeParse({
|
||||
...config,
|
||||
template: '<ToggleSwitch requestId="toggle" onParams={{ enabled: true }} offParams={{ enabled: false }} />',
|
||||
requests: [
|
||||
{
|
||||
id: "toggle",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/toggle",
|
||||
parameters: { enabled: "boolean" },
|
||||
bodyTemplate: { enabled: { $param: "enabled" } },
|
||||
auth: "none",
|
||||
minimumBoardPermission: "modify",
|
||||
},
|
||||
],
|
||||
customJsxRequestSchema.safeParse({
|
||||
...base,
|
||||
id: "delete-query",
|
||||
kind: "query",
|
||||
method: "DELETE",
|
||||
minimumBoardPermission: "full",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects reserved manifest headers and mismatched request component kinds", () => {
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
id: "status",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
staticHeaders: { Authorization: "secret" },
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
customJsxDisplayConfigV2Schema.safeParse({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
networkScope: "public",
|
||||
template: '<ActionButton requestId="status" label="Run" />',
|
||||
requests: [
|
||||
{
|
||||
id: "status",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("accepts 50,000 characters and rejects 50,001", () => {
|
||||
const config = {
|
||||
type: "customJsx" as const,
|
||||
jsxApiVersion: 2 as const,
|
||||
networkScope: "public" as const,
|
||||
requests: [],
|
||||
};
|
||||
expect(customJsxDisplayConfigV2Schema.safeParse({ ...config, template: "x".repeat(50_000) }).success).toBe(true);
|
||||
expect(customJsxDisplayConfigV2Schema.safeParse({ ...config, template: "x".repeat(50_001) }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects duplicate request IDs", () => {
|
||||
test("rejects reserved headers, duplicate IDs, and unknown sources", () => {
|
||||
const request = {
|
||||
id: "status",
|
||||
sourceId: "missing",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "load" as const,
|
||||
};
|
||||
const result = customJsxDisplayConfigV2Schema.safeParse({
|
||||
type: "customJsx",
|
||||
jsxApiVersion: 2,
|
||||
template: "<Text />",
|
||||
networkScope: "public",
|
||||
requests: [request, request],
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, requests: [request] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({ ...request, sourceId: "default", staticHeaders: { Authorization: "secret" } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...request,
|
||||
sourceId: "default",
|
||||
confirmation: { title: "Ignored", message: "Ignored" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(customJsxRequestSchema.safeParse({ ...request, sourceId: "default", invalidates: ["status"] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
customWidgetCreateSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
secrets: [
|
||||
{ sourceId: "default", kind: "apiKey", value: "one" },
|
||||
{ sourceId: "default", kind: "apiKey", value: "two" },
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("accepts multi-source actions, dynamic options, conditions, and typed state", () => {
|
||||
const result = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: [
|
||||
{
|
||||
id: "sonarr",
|
||||
name: "Sonarr",
|
||||
baseUrl: "http://sonarr:8989",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Api-Key" },
|
||||
},
|
||||
{
|
||||
id: "radarr",
|
||||
name: "Radarr",
|
||||
baseUrl: "http://radarr:7878",
|
||||
networkScope: "private",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Api-Key" },
|
||||
},
|
||||
],
|
||||
requests: [
|
||||
{
|
||||
id: "list-calendars",
|
||||
sourceId: "sonarr",
|
||||
kind: "query",
|
||||
method: "POST",
|
||||
pathTemplate: "/api/v3/calendar",
|
||||
parameters: { start: "string" },
|
||||
bodyTemplate: { start: { $param: "start" } },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "manual",
|
||||
},
|
||||
{
|
||||
id: "monitor-series",
|
||||
sourceId: "sonarr",
|
||||
kind: "action",
|
||||
method: "GET",
|
||||
pathTemplate: "/api/v3/series/{seriesId}",
|
||||
parameters: { seriesId: "number" },
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
confirmation: { title: "Monitor series", message: "Monitor this series?" },
|
||||
invalidates: ["list-calendars"],
|
||||
},
|
||||
],
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
start: { type: "string", title: "Start date", "x-homarr": { control: "date", order: 1 } },
|
||||
calendarId: {
|
||||
type: "integer",
|
||||
title: "Calendar",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: {
|
||||
requestId: "list-calendars",
|
||||
itemsPath: "$.data.environments",
|
||||
valuePath: "$.Id",
|
||||
labelPath: "$.Name",
|
||||
},
|
||||
},
|
||||
},
|
||||
advancedColor: { type: "string", "x-homarr": { control: "color", advanced: true } },
|
||||
},
|
||||
required: ["start"],
|
||||
additionalProperties: false,
|
||||
if: { properties: { start: { const: "today" } } },
|
||||
// oxlint-disable-next-line unicorn/no-thenable -- JSON Schema uses the standard `then` keyword.
|
||||
then: { properties: { advancedColor: { type: "string" } } },
|
||||
},
|
||||
defaultOptions: { start: "today" },
|
||||
stateSchema: { selectedDate: "date", search: "string", opened: "boolean", selectedEntities: "string[]" },
|
||||
defaultState: { selectedDate: "2026-07-17", search: "", opened: false, selectedEntities: ["light.office"] },
|
||||
template:
|
||||
'<Stack><Calendar bind="selectedDate"/><ActionButton requestId="monitor-series" params={{ seriesId: 1 }}>Monitor</ActionButton></Stack>',
|
||||
});
|
||||
expect(result.success, result.error?.issues.map((issue) => issue.message).join("; ")).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects unsafe source URLs, auth overrides, invalid defaults, and missing dynamic requests", () => {
|
||||
const unsafeSource = { ...CUSTOM_WIDGET_STARTER.sources[0], baseUrl: "https://user:pass@example.com?token=nope" };
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, sources: [unsafeSource] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
const source = {
|
||||
...CUSTOM_WIDGET_STARTER.sources[0],
|
||||
auth: { type: "apiKeyHeader" as const, headerName: "X-Api-Key" },
|
||||
};
|
||||
const request = {
|
||||
id: "status",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "GET" as const,
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "inherit" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "load" as const,
|
||||
staticHeaders: { "x-api-key": "not-a-secret" },
|
||||
};
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, sources: [source], requests: [request] })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, defaultOptions: { apiKey: "not-exportable" } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: { accessToken: { type: "string" } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
stateSchema: { accessToken: "string" },
|
||||
defaultState: {},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
...request,
|
||||
sourceId: "default",
|
||||
auth: "none",
|
||||
staticHeaders: { "X-Custom": "Bearer not-exportable-token" },
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
...request,
|
||||
sourceId: "default",
|
||||
auth: "none",
|
||||
staticHeaders: { "X-API-Key": "not-exportable" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
stateSchema: { count: "number" },
|
||||
defaultState: { count: "wrong" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
id: "action",
|
||||
sourceId: "default",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/action",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
invalidates: ["missing"],
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
endpoint: {
|
||||
type: "string",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: { requestId: "missing", valuePath: "$.id", labelPath: "$.name" },
|
||||
},
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("requires literal bindings to reference declared camel-case state", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
stateSchema: { selectedDate: "date" },
|
||||
defaultState: { selectedDate: "2026-07-17" },
|
||||
template: '<Calendar bind="selectedDate" />',
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
stateSchema: { selectedDate: "date" },
|
||||
template: '<Calendar bind="missingDate" />',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
stateSchema: { selectedDate: "date" },
|
||||
template: "<Calendar bind={state.selectedDate} />",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("validates values declared only by the active conditional branch", () => {
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: { mode: { type: "string", enum: ["simple", "advanced"] } },
|
||||
required: ["mode"],
|
||||
additionalProperties: false,
|
||||
if: { properties: { mode: { const: "advanced" } } },
|
||||
// oxlint-disable-next-line unicorn/no-thenable -- JSON Schema uses the standard `then` keyword.
|
||||
then: {
|
||||
properties: { color: { type: "string" } },
|
||||
required: ["color"],
|
||||
},
|
||||
};
|
||||
expect(validateCustomWidgetOptions(schema, { mode: "advanced", color: "blue" })).toEqual([]);
|
||||
expect(validateCustomWidgetOptions(schema, { mode: "advanced" })).toEqual([
|
||||
{ path: "configuration.color", message: "This field is required" },
|
||||
]);
|
||||
expect(validateCustomWidgetOptions(schema, { mode: "simple", color: "blue" })).toEqual([
|
||||
{ path: "configuration.color", message: "Unknown option" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects unsafe custom authentication header names", () => {
|
||||
const result = customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: [
|
||||
{
|
||||
...CUSTOM_WIDGET_STARTER.sources[0],
|
||||
auth: { type: "apiKeyHeader", headerName: "X-Forwarded-Authorization" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects mutation-shaped queries and weak DELETE permissions", () => {
|
||||
test("rejects prototype-pollution keys in structured authored data", () => {
|
||||
const request = {
|
||||
id: "status",
|
||||
sourceId: "default",
|
||||
kind: "query" as const,
|
||||
method: "POST" as const,
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
bodyTemplate: JSON.parse('{"constructor":{"prototype":{"polluted":true}}}') as unknown,
|
||||
auth: "none" as const,
|
||||
minimumBoardPermission: "view" as const,
|
||||
trigger: "manual" as const,
|
||||
};
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, requests: [request] }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects option controls, enum values, and icon URLs that do not match their declared capability", () => {
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
id: "mutating-query",
|
||||
kind: "query",
|
||||
method: "POST",
|
||||
pathTemplate: "/status",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: "javascript:alert(1)" }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: "https://user:password@example.com/icon.png",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({
|
||||
id: "delete",
|
||||
kind: "action",
|
||||
method: "DELETE",
|
||||
pathTemplate: "/resource",
|
||||
parameters: {},
|
||||
auth: "inherit",
|
||||
minimumBoardPermission: "modify",
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: "https://example.com/icon.png?accessToken=literal-secret",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
template: '<Text>apiKey="literal-secret"</Text>',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: { enabled: { type: "boolean", "x-homarr": { control: "slider" } } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
defaultOptions: { enabled: true },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: { count: { type: "integer", enum: [1, "two"] } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
defaultOptions: { count: 1 },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
assertSafeStaticHeaders,
|
||||
classifyAddress,
|
||||
executeCustomWidgetRequest,
|
||||
invalidateCustomWidgetResponseCache,
|
||||
resolveAndValidateHost,
|
||||
resolveSameOriginTarget,
|
||||
validateCustomWidgetUrl,
|
||||
@@ -52,6 +53,66 @@ describe("custom widget network policy", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves structured bodies for GET queries", async () => {
|
||||
const server = createServer((request, response) => {
|
||||
let body = "";
|
||||
request.setEncoding("utf8");
|
||||
request.on("data", (chunk: string) => {
|
||||
body += chunk;
|
||||
});
|
||||
request.on("end", () => {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ body }));
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
try {
|
||||
await expect(
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET",
|
||||
body: '{"query":"status"}',
|
||||
networkScope: "loopback",
|
||||
kind: "query",
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true, data: { body: '{"query":"status"}' } });
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("evicts declared response-cache prefixes after an action", async () => {
|
||||
let calls = 0;
|
||||
const server = createServer((_request, response) => {
|
||||
calls += 1;
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ calls }));
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
const cacheKey = "custom-jsx:item:status:params";
|
||||
const input = {
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET" as const,
|
||||
networkScope: "loopback" as const,
|
||||
kind: "query" as const,
|
||||
cacheKey,
|
||||
cacheTtlSeconds: 60,
|
||||
};
|
||||
try {
|
||||
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 1 } });
|
||||
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 1 } });
|
||||
invalidateCustomWidgetResponseCache(["custom-jsx:item:status:"]);
|
||||
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 2 } });
|
||||
} finally {
|
||||
invalidateCustomWidgetResponseCache(["custom-jsx:item:status:"]);
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("allows only credential-free HTTP(S) URLs without fragments", () => {
|
||||
expect(validateCustomWidgetUrl("https://example.com/api").href).toBe("https://example.com/api");
|
||||
expect(() => validateCustomWidgetUrl("file:///etc/passwd")).toThrow("HTTP and HTTPS");
|
||||
|
||||
@@ -2,13 +2,16 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
analyzeJsxTemplate,
|
||||
analyzeCustomWidgetAccessibility,
|
||||
analyzeRequestManifest,
|
||||
appendDataPath,
|
||||
createResponseTreeNode,
|
||||
CUSTOM_JSX_TEMPLATE_LIMIT,
|
||||
DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
|
||||
customWidgetFormSchema,
|
||||
renameCustomWidgetRequest,
|
||||
} from "../workbench";
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
|
||||
describe("Custom Widget workbench contracts", () => {
|
||||
it("always provides a valid starter template", () => {
|
||||
@@ -39,17 +42,25 @@ describe("Custom Widget workbench contracts", () => {
|
||||
});
|
||||
|
||||
it("validates named request references and rejects inline network capabilities", () => {
|
||||
expect(analyzeJsxTemplate('<SubFetch requestId="known" />', { apiVersion: 2, requestIds: ["known"] })).toEqual([]);
|
||||
expect(
|
||||
analyzeJsxTemplate('<SubFetch requestId="missing" url="/api" />', { apiVersion: 2, requestIds: ["known"] }),
|
||||
).toEqual(
|
||||
expect(analyzeJsxTemplate('<SubFetch requestId="known" />', { requestIds: ["known"] })).toEqual([]);
|
||||
expect(analyzeJsxTemplate('<SubFetch requestId="missing" url="/api" />', { requestIds: ["known"] })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "legacyNetworkProps" }),
|
||||
expect.objectContaining({ code: "inlineRequestProps" }),
|
||||
expect.objectContaining({ code: "unknownRequest", value: "missing" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("diagnoses dynamic and unknown local-state bindings", () => {
|
||||
expect(analyzeJsxTemplate('<Calendar bind="selectedDate" />', { stateKeys: ["selectedDate"] })).toEqual([]);
|
||||
expect(analyzeJsxTemplate('<Calendar bind="missing" />', { stateKeys: ["selectedDate"] })).toEqual([
|
||||
expect.objectContaining({ code: "unknownStateBinding", value: "missing" }),
|
||||
]);
|
||||
expect(analyzeJsxTemplate("<Calendar bind={state.selectedDate} />", { stateKeys: ["selectedDate"] })).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "dynamicStateBinding" })]),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the AST security policy for computed reflective access while accepting benign fetch text", () => {
|
||||
expect(analyzeJsxTemplate("<Text>{data['con' + 'structor']}</Text>")).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ code: "ast", severity: "error" })]),
|
||||
@@ -64,4 +75,71 @@ describe("Custom Widget workbench contracts", () => {
|
||||
const tree = createResponseTreeNode({ items: [{ name: "one" }] }, "data", "data");
|
||||
expect(tree.children?.[0]?.children?.[0]?.children?.[0]?.value).toBe("data.items[0].name");
|
||||
});
|
||||
|
||||
it("renames a request and every canonical reference atomically", () => {
|
||||
const renamed = renameCustomWidgetRequest(
|
||||
{
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: [
|
||||
{
|
||||
id: "items",
|
||||
sourceId: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
pathTemplate: "/items",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "view",
|
||||
trigger: "manual",
|
||||
},
|
||||
{
|
||||
id: "refresh",
|
||||
sourceId: "default",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
pathTemplate: "/refresh",
|
||||
parameters: {},
|
||||
auth: "none",
|
||||
minimumBoardPermission: "modify",
|
||||
trigger: "manual",
|
||||
invalidates: ["items"],
|
||||
},
|
||||
],
|
||||
optionsSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
item: {
|
||||
type: "string",
|
||||
"x-homarr": {
|
||||
control: "select",
|
||||
optionsSource: { requestId: "items", valuePath: "$.id", labelPath: "$.name" },
|
||||
},
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
template: '<Stack><SubFetch requestId="items" />{data["items"]}{status.items.ok}</Stack>',
|
||||
},
|
||||
"items",
|
||||
"inventory",
|
||||
);
|
||||
|
||||
expect(renamed.requests[0]?.id).toBe("inventory");
|
||||
expect(renamed.requests[1]?.invalidates).toEqual(["inventory"]);
|
||||
expect(JSON.stringify(renamed.optionsSchema)).toContain('"requestId":"inventory"');
|
||||
expect(renamed.template).toBe(
|
||||
'<Stack><SubFetch requestId="inventory" />{data["inventory"]}{status.inventory.ok}</Stack>',
|
||||
);
|
||||
});
|
||||
|
||||
it("reports common accessibility omissions in preview", () => {
|
||||
expect(
|
||||
analyzeCustomWidgetAccessibility('<Stack><Image src="/image.png"/><ActionIcon/><TextInput /></Stack>'),
|
||||
).toEqual(["imageAlt", "actionIconLabel", "inputLabel"]);
|
||||
expect(
|
||||
analyzeCustomWidgetAccessibility(
|
||||
'<Stack><Image src="/image.png" alt="Preview"/><ActionIcon aria-label="Refresh"/><TextInput label="Search" /></Stack>',
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,13 @@ import { CUSTOM_JSX_LIMITS, validateCustomJsxTemplate } from "../jsx";
|
||||
export type EditorDiagnosticCode =
|
||||
| "ast"
|
||||
| "dynamicRequestId"
|
||||
| "dynamicStateBinding"
|
||||
| "inlineRequestProps"
|
||||
| "invalidRequestManifest"
|
||||
| "legacyNetworkProps"
|
||||
| "missingRequestId"
|
||||
| "templateEmpty"
|
||||
| "templateTooLong"
|
||||
| "unknownStateBinding"
|
||||
| "unknownRequest";
|
||||
|
||||
export interface EditorDiagnostic {
|
||||
@@ -21,16 +23,17 @@ export interface EditorDiagnostic {
|
||||
}
|
||||
|
||||
export interface AnalyzeJsxTemplateOptions {
|
||||
apiVersion?: 1 | 2;
|
||||
requestIds?: string[];
|
||||
stateKeys?: string[];
|
||||
}
|
||||
const networkComponentPattern = /<(SubFetch|ActionButton|ToggleSwitch)\b([^>]*)>/giu;
|
||||
const stateBindingPattern = /<[A-Z][A-Za-z0-9.]*(?:\s[^<>]*?)?\bbind\s*=\s*(?:"([^"]+)"|'([^']+)'|\{)/gu;
|
||||
const lineAt = (source: string, index: number) => source.slice(0, index).split("\n").length;
|
||||
export const CUSTOM_JSX_TEMPLATE_LIMIT = CUSTOM_JSX_LIMITS.templateLength;
|
||||
|
||||
export function analyzeJsxTemplate(
|
||||
template: string,
|
||||
{ apiVersion = 1, requestIds = [] }: AnalyzeJsxTemplateOptions = {},
|
||||
{ requestIds = [], stateKeys = [] }: AnalyzeJsxTemplateOptions = {},
|
||||
): EditorDiagnostic[] {
|
||||
const diagnostics: EditorDiagnostic[] = [];
|
||||
if (!template.trim()) diagnostics.push({ code: "templateEmpty", severity: "error", line: 1, column: 1, index: 0 });
|
||||
@@ -46,13 +49,12 @@ export function analyzeJsxTemplate(
|
||||
value: entry.message,
|
||||
})),
|
||||
);
|
||||
if (apiVersion !== 2) return diagnostics;
|
||||
const knownIds = new Set(requestIds);
|
||||
for (const match of template.matchAll(networkComponentPattern)) {
|
||||
const props = match[2] ?? "";
|
||||
const line = lineAt(template, match.index);
|
||||
if (/\b(?:url|method|headers|body|onBody|offBody)\s*=/iu.test(props)) {
|
||||
diagnostics.push({ code: "legacyNetworkProps", severity: "error", line, index: match.index });
|
||||
diagnostics.push({ code: "inlineRequestProps", severity: "error", line, index: match.index });
|
||||
}
|
||||
const staticRequest = props.match(/\brequestId\s*=\s*["']([^"']+)["']/iu);
|
||||
if (staticRequest?.[1] && !knownIds.has(staticRequest[1])) {
|
||||
@@ -69,6 +71,26 @@ export function analyzeJsxTemplate(
|
||||
diagnostics.push({ code: "missingRequestId", severity: "error", line, index: match.index });
|
||||
}
|
||||
}
|
||||
const knownState = new Set(stateKeys);
|
||||
for (const match of template.matchAll(stateBindingPattern)) {
|
||||
const stateName = match[1] ?? match[2];
|
||||
if (!stateName) {
|
||||
diagnostics.push({
|
||||
code: "dynamicStateBinding",
|
||||
severity: "error",
|
||||
line: lineAt(template, match.index),
|
||||
index: match.index,
|
||||
});
|
||||
} else if (!knownState.has(stateName)) {
|
||||
diagnostics.push({
|
||||
code: "unknownStateBinding",
|
||||
severity: "error",
|
||||
line: lineAt(template, match.index),
|
||||
index: match.index,
|
||||
value: stateName,
|
||||
});
|
||||
}
|
||||
}
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,105 +1,39 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { buildDisplayFormValues } from "../core";
|
||||
import { CUSTOM_WIDGET_STARTER } from "../core";
|
||||
|
||||
const requiredScalarFields: Record<string, string[]> = {
|
||||
singleValue: ["jsonPath"],
|
||||
table: ["tablePath"],
|
||||
raw: ["rawJsonPath"],
|
||||
actionButton: ["buttonLabel"],
|
||||
customJsx: ["template"],
|
||||
};
|
||||
const requiredCollectionFields: Record<string, { collection: string; fields: string[] }> = {
|
||||
keyValue: { collection: "mappings", fields: ["label", "jsonPath"] },
|
||||
table: { collection: "columns", fields: ["header", "jsonPath"] },
|
||||
statGrid: { collection: "statGridItems", fields: ["label", "jsonPath"] },
|
||||
progressBars: { collection: "progressBars", fields: ["label", "valuePath"] },
|
||||
statusIndicator: { collection: "statusItems", fields: ["label", "jsonPath", "goodValues"] },
|
||||
countGrid: { collection: "countGridItems", fields: ["label", "jsonPath"] },
|
||||
};
|
||||
const jsonObjectString = z.string().superRefine((value, ctx) => {
|
||||
try {
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
|
||||
} catch {
|
||||
ctx.addIssue({ code: "custom", message: "Must be a JSON object" });
|
||||
}
|
||||
});
|
||||
|
||||
const requiredString = z.string();
|
||||
export const customWidgetFormSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(128),
|
||||
description: requiredString,
|
||||
iconUrl: requiredString,
|
||||
url: z.string().trim().min(1),
|
||||
authType: requiredString,
|
||||
headerName: requiredString,
|
||||
method: requiredString,
|
||||
requestBody: requiredString,
|
||||
displayType: requiredString,
|
||||
jsonPath: requiredString,
|
||||
label: requiredString,
|
||||
unit: requiredString,
|
||||
valueSize: requiredString,
|
||||
labelPosition: requiredString,
|
||||
mappings: z.array(z.object({ label: requiredString, jsonPath: requiredString, unit: requiredString })),
|
||||
kvLayout: requiredString,
|
||||
kvColumns: z.number(),
|
||||
tablePath: requiredString,
|
||||
columns: z.array(z.object({ header: requiredString, jsonPath: requiredString })),
|
||||
striped: z.boolean(),
|
||||
compact: z.boolean(),
|
||||
statGridItems: z.array(
|
||||
z.object({ label: requiredString, jsonPath: requiredString, unit: requiredString, color: requiredString }),
|
||||
),
|
||||
statGridColumns: z.number(),
|
||||
cardStyle: requiredString,
|
||||
progressBars: z.array(
|
||||
z.object({
|
||||
label: requiredString,
|
||||
valuePath: requiredString,
|
||||
maxPath: requiredString,
|
||||
unit: requiredString,
|
||||
color: requiredString,
|
||||
}),
|
||||
),
|
||||
showPercentage: z.boolean(),
|
||||
barSize: requiredString,
|
||||
statusItems: z.array(z.object({ label: requiredString, jsonPath: requiredString, goodValues: requiredString })),
|
||||
statusLayout: requiredString,
|
||||
dotSize: requiredString,
|
||||
countGridItems: z.array(z.object({ label: requiredString, jsonPath: requiredString, unit: requiredString })),
|
||||
countGridColumns: z.number(),
|
||||
countValueSize: requiredString,
|
||||
rawJsonPath: requiredString,
|
||||
rawMaxHeight: z.number(),
|
||||
buttonLabel: requiredString,
|
||||
buttonColor: requiredString,
|
||||
confirmText: requiredString,
|
||||
successMessage: requiredString,
|
||||
template: requiredString,
|
||||
jsxApiVersion: requiredString,
|
||||
networkScope: requiredString,
|
||||
requestManifest: requiredString,
|
||||
secrets: z.array(z.object({ kind: requiredString, value: requiredString, hasValue: z.boolean().optional() })),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
for (const field of requiredScalarFields[data.displayType] ?? []) {
|
||||
if (!data[field as keyof typeof data]) addRequiredIssue(ctx, [field], data[field as keyof typeof data]);
|
||||
}
|
||||
const collection = requiredCollectionFields[data.displayType];
|
||||
if (collection) {
|
||||
const entries = data[collection.collection as keyof typeof data];
|
||||
if (Array.isArray(entries))
|
||||
entries.forEach((entry, index) => {
|
||||
for (const field of collection.fields) {
|
||||
const value = (entry as Record<string, unknown>)[field];
|
||||
if (!value) addRequiredIssue(ctx, [collection.collection, index, field], value);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (data.displayType === "customJsx" && data.jsxApiVersion === "2" && !isJsonArray(data.requestManifest)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: "invalidRequestManifest",
|
||||
input: data.requestManifest,
|
||||
path: ["requestManifest"],
|
||||
});
|
||||
}
|
||||
});
|
||||
const jsonArrayString = z.string().superRefine((value, ctx) => {
|
||||
try {
|
||||
if (!Array.isArray(JSON.parse(value))) throw new Error();
|
||||
} catch {
|
||||
ctx.addIssue({ code: "custom", message: "Must be a JSON array" });
|
||||
}
|
||||
});
|
||||
|
||||
export const customWidgetFormSchema = z.object({
|
||||
name: z.string().trim().min(1).max(128),
|
||||
description: z.string().max(512),
|
||||
iconUrl: z.union([z.literal(""), z.string().url()]),
|
||||
sources: jsonArrayString,
|
||||
requests: jsonArrayString,
|
||||
optionsSchema: jsonObjectString,
|
||||
defaultOptions: jsonObjectString,
|
||||
stateSchema: jsonObjectString,
|
||||
defaultState: jsonObjectString,
|
||||
template: z.string().min(1).max(50_000),
|
||||
secrets: z.array(
|
||||
z.object({ sourceId: z.string(), kind: z.string(), value: z.string(), hasValue: z.boolean().optional() }),
|
||||
),
|
||||
});
|
||||
|
||||
export type CustomWidgetFormValues = z.infer<typeof customWidgetFormSchema>;
|
||||
|
||||
@@ -116,29 +50,16 @@ export const CUSTOM_WIDGET_AUTH_SECRET_FIELDS: Record<
|
||||
apiKeyQuery: [{ kind: "apiKey", labelKey: "apiKey", isPassword: true }],
|
||||
};
|
||||
|
||||
export const CUSTOM_WIDGET_AUTH_USES_HEADER_NAME: Record<string, boolean> = { apiKeyHeader: true, apiKeyQuery: true };
|
||||
|
||||
export const DEFAULT_CUSTOM_WIDGET_FORM_VALUES: CustomWidgetFormValues = {
|
||||
name: "",
|
||||
description: "",
|
||||
iconUrl: "",
|
||||
url: "",
|
||||
authType: "none",
|
||||
headerName: "",
|
||||
method: "GET",
|
||||
requestBody: "",
|
||||
...buildDisplayFormValues("singleValue", {}),
|
||||
name: CUSTOM_WIDGET_STARTER.name,
|
||||
description: CUSTOM_WIDGET_STARTER.description ?? "",
|
||||
iconUrl: CUSTOM_WIDGET_STARTER.iconUrl ?? "",
|
||||
sources: JSON.stringify(CUSTOM_WIDGET_STARTER.sources, null, 2),
|
||||
requests: JSON.stringify(CUSTOM_WIDGET_STARTER.requests, null, 2),
|
||||
optionsSchema: JSON.stringify(CUSTOM_WIDGET_STARTER.optionsSchema, null, 2),
|
||||
defaultOptions: JSON.stringify(CUSTOM_WIDGET_STARTER.defaultOptions, null, 2),
|
||||
stateSchema: JSON.stringify(CUSTOM_WIDGET_STARTER.stateSchema ?? {}, null, 2),
|
||||
defaultState: JSON.stringify(CUSTOM_WIDGET_STARTER.defaultState ?? {}, null, 2),
|
||||
template: CUSTOM_WIDGET_STARTER.template,
|
||||
secrets: [],
|
||||
};
|
||||
|
||||
function addRequiredIssue(ctx: z.core.$RefinementCtx, path: PropertyKey[], input: unknown): void {
|
||||
ctx.addIssue({ code: "too_small", minimum: 1, origin: "string", inclusive: true, input, path });
|
||||
}
|
||||
|
||||
function isJsonArray(value: string): boolean {
|
||||
try {
|
||||
return Array.isArray(JSON.parse(value));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -49,9 +49,9 @@ export function ImportReviewDialog({ opened, review, pending, messages, onClose,
|
||||
</Text>
|
||||
<SimpleGrid cols={{ base: 1, sm: 2 }} spacing="xs">
|
||||
<ImportFact label={messages.name} value={review.name} />
|
||||
<ImportFact label={messages.origin} value={review.origin} />
|
||||
<ImportFact label={messages.authentication} value={review.authType} />
|
||||
<ImportFact label={messages.networkScope} value={review.networkScope} />
|
||||
<ImportFact label={messages.origin} value={review.origins.join(", ")} />
|
||||
<ImportFact label={messages.authentication} value={review.authTypes.join(", ")} />
|
||||
<ImportFact label={messages.networkScope} value={review.networkScopes.join(", ")} />
|
||||
</SimpleGrid>
|
||||
<div>
|
||||
<Text size="sm" fw={600} mb={6}>
|
||||
|
||||
@@ -9,9 +9,9 @@ export * from "./preview-request-panel";
|
||||
export * from "./preview-diagnostics-panel";
|
||||
export * from "./preview-header";
|
||||
export * from "./preview-utils";
|
||||
export * from "./request-references";
|
||||
export {
|
||||
CUSTOM_WIDGET_AUTH_SECRET_FIELDS,
|
||||
CUSTOM_WIDGET_AUTH_USES_HEADER_NAME,
|
||||
DEFAULT_CUSTOM_WIDGET_FORM_VALUES,
|
||||
customWidgetFormSchema,
|
||||
} from "./form-schema";
|
||||
|
||||
@@ -10,9 +10,9 @@ export const redactPreviewUrl = (value: string): string => {
|
||||
}
|
||||
};
|
||||
|
||||
export const getPreviewNamedRequests = (displayConfig: Record<string, unknown>): PreviewNamedRequest[] => {
|
||||
if (!Array.isArray(displayConfig.requests)) return [];
|
||||
return displayConfig.requests.filter(
|
||||
export const getPreviewNamedRequests = (definition: Record<string, unknown>): PreviewNamedRequest[] => {
|
||||
if (!Array.isArray(definition.requests)) return [];
|
||||
return definition.requests.filter(
|
||||
(request): request is PreviewNamedRequest =>
|
||||
request !== null &&
|
||||
typeof request === "object" &&
|
||||
@@ -27,11 +27,47 @@ export const getPreviewNamedRequests = (displayConfig: Record<string, unknown>):
|
||||
);
|
||||
};
|
||||
|
||||
export const getPreviewLegacyMethods = (template: string): string[] => {
|
||||
const methods = new Set<string>();
|
||||
for (const match of template.matchAll(/<(?:SubFetch|ActionButton|ToggleSwitch)\b([^>]*)>/giu)) {
|
||||
const method = match[1]?.match(/\bmethod\s*=\s*["'](GET|POST|PUT|PATCH|DELETE)["']/iu)?.[1];
|
||||
methods.add(method?.toUpperCase() ?? (match[0].startsWith("<SubFetch") ? "GET" : "POST"));
|
||||
export type CustomWidgetAccessibilityIssue = "imageAlt" | "actionIconLabel" | "inputLabel";
|
||||
|
||||
export function analyzeCustomWidgetAccessibility(template: string): CustomWidgetAccessibilityIssue[] {
|
||||
const issues = new Set<CustomWidgetAccessibilityIssue>();
|
||||
const elements = template.matchAll(/<([A-Z][A-Za-z0-9.]*)\b([^>]*)>/gu);
|
||||
const inputComponents = new Set([
|
||||
"Autocomplete",
|
||||
"Checkbox",
|
||||
"ColorInput",
|
||||
"DateInput",
|
||||
"FileInput",
|
||||
"JsonInput",
|
||||
"MultiSelect",
|
||||
"NumberInput",
|
||||
"PasswordInput",
|
||||
"Radio",
|
||||
"Select",
|
||||
"Slider",
|
||||
"Switch",
|
||||
"TagsInput",
|
||||
"TextInput",
|
||||
"Textarea",
|
||||
"TimeInput",
|
||||
]);
|
||||
for (const match of elements) {
|
||||
const component = match[1] ?? "";
|
||||
const props = match[2] ?? "";
|
||||
if (component === "Image" && !hasProp(props, "alt")) issues.add("imageAlt");
|
||||
if (component === "ActionIcon" && !hasAnyProp(props, ["aria-label", "title"])) issues.add("actionIconLabel");
|
||||
if (inputComponents.has(component) && !hasAnyProp(props, ["label", "aria-label", "aria-labelledby"])) {
|
||||
issues.add("inputLabel");
|
||||
}
|
||||
}
|
||||
return [...methods];
|
||||
};
|
||||
return [...issues];
|
||||
}
|
||||
|
||||
function hasAnyProp(props: string, names: string[]) {
|
||||
return names.some((name) => hasProp(props, name));
|
||||
}
|
||||
|
||||
function hasProp(props: string, name: string) {
|
||||
const escapedName = name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
||||
return new RegExp(`(?:^|\\s)${escapedName}\\s*=`, "u").test(props);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { customWidgetDefinitionSchema } from "../core/custom-jsx-schema";
|
||||
import { customWidgetIdentifierSchema } from "../core/request-schema";
|
||||
import type { HomarrCustomWidgetV2 } from "../core/custom-jsx-schema";
|
||||
|
||||
export function renameCustomWidgetRequest(
|
||||
definition: HomarrCustomWidgetV2,
|
||||
currentId: string,
|
||||
nextId: string,
|
||||
): HomarrCustomWidgetV2 {
|
||||
const parsedId = customWidgetIdentifierSchema.safeParse(nextId);
|
||||
if (!parsedId.success) throw new Error(parsedId.error.issues[0]?.message ?? "Invalid request ID");
|
||||
if (!definition.requests.some((request) => request.id === currentId))
|
||||
throw new Error(`Unknown request '${currentId}'`);
|
||||
if (currentId !== nextId && definition.requests.some((request) => request.id === nextId)) {
|
||||
throw new Error(`Request '${nextId}' already exists`);
|
||||
}
|
||||
|
||||
const candidate = {
|
||||
...definition,
|
||||
requests: definition.requests.map((request) => ({
|
||||
...request,
|
||||
id: request.id === currentId ? nextId : request.id,
|
||||
invalidates: request.invalidates?.map((id) => (id === currentId ? nextId : id)),
|
||||
})),
|
||||
optionsSchema: replaceDynamicOptionRequest(definition.optionsSchema, currentId, nextId),
|
||||
template: replaceTemplateRequestReferences(definition.template, currentId, nextId),
|
||||
};
|
||||
return customWidgetDefinitionSchema.parse(candidate);
|
||||
}
|
||||
|
||||
function replaceDynamicOptionRequest<T>(value: T, currentId: string, nextId: string): T {
|
||||
if (Array.isArray(value)) return value.map((entry) => replaceDynamicOptionRequest(entry, currentId, nextId)) as T;
|
||||
if (value === null || typeof value !== "object") return value;
|
||||
const record = value as Record<string, unknown>;
|
||||
const replaced = Object.fromEntries(
|
||||
Object.entries(record).map(([key, child]) => [key, replaceDynamicOptionRequest(child, currentId, nextId)]),
|
||||
);
|
||||
if (record.requestId === currentId && "valuePath" in record && "labelPath" in record) replaced.requestId = nextId;
|
||||
return replaced as T;
|
||||
}
|
||||
|
||||
function replaceTemplateRequestReferences(template: string, currentId: string, nextId: string) {
|
||||
const escaped = escapeRegExp(currentId);
|
||||
return template
|
||||
.replace(new RegExp(`(requestId\\s*=\\s*["'])${escaped}(["'])`, "gu"), `$1${nextId}$2`)
|
||||
.replace(new RegExp(`((?:data|status)\\s*\\[\\s*["'])${escaped}(["']\\s*\\])`, "gu"), `$1${nextId}$2`)
|
||||
.replace(new RegExp(`((?:data|status)\\.)${escaped}\\b`, "gu"), `$1${nextId}`);
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
DROP TABLE `custom_widget_secret`;--> statement-breakpoint
|
||||
DROP TABLE `custom_widget_definition`;--> statement-breakpoint
|
||||
CREATE TABLE `custom_widget_definition` (
|
||||
`id` varchar(64) NOT NULL,
|
||||
`name` varchar(256) NOT NULL,
|
||||
`description` text,
|
||||
`icon_url` text,
|
||||
`sources` text NOT NULL,
|
||||
`requests` text NOT NULL,
|
||||
`options_schema` text NOT NULL,
|
||||
`default_options` text NOT NULL,
|
||||
`state_schema` text,
|
||||
`default_state` text,
|
||||
`template` text NOT NULL,
|
||||
`enabled` boolean DEFAULT true NOT NULL,
|
||||
`created_at` timestamp DEFAULT (now()) NOT NULL,
|
||||
`updated_at` timestamp DEFAULT (now()) NOT NULL,
|
||||
`creator_id` varchar(64),
|
||||
CONSTRAINT `custom_widget_definition_id` PRIMARY KEY(`id`)
|
||||
);--> statement-breakpoint
|
||||
CREATE TABLE `custom_widget_secret` (
|
||||
`source_id` varchar(64) NOT NULL,
|
||||
`kind` varchar(64) NOT NULL,
|
||||
`encrypted_value` text NOT NULL,
|
||||
`updated_at` timestamp NOT NULL,
|
||||
`definition_id` varchar(64) NOT NULL,
|
||||
CONSTRAINT `custom_widget_secret_definition_id_source_id_kind_pk` PRIMARY KEY(`definition_id`,`source_id`,`kind`)
|
||||
);--> statement-breakpoint
|
||||
ALTER TABLE `custom_widget_definition` ADD CONSTRAINT `custom_widget_definition_creator_id_user_id_fk` FOREIGN KEY (`creator_id`) REFERENCES `user`(`id`) ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE `custom_widget_secret` ADD CONSTRAINT `cw_secret_definition_id_cw_definition_id_fk` FOREIGN KEY (`definition_id`) REFERENCES `custom_widget_definition`(`id`) ON DELETE cascade ON UPDATE no action;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -302,6 +302,13 @@
|
||||
"when": 1783176100870,
|
||||
"tag": "0042_add_widget_secret",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 43,
|
||||
"version": "5",
|
||||
"when": 1784305537309,
|
||||
"tag": "0043_custom_widget_v2_reset",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
DROP TABLE "custom_widget_secret";--> statement-breakpoint
|
||||
DROP TABLE "custom_widget_definition";--> statement-breakpoint
|
||||
CREATE TABLE "custom_widget_definition" (
|
||||
"id" varchar(64) PRIMARY KEY NOT NULL,
|
||||
"name" varchar(256) NOT NULL,
|
||||
"description" text,
|
||||
"icon_url" text,
|
||||
"sources" text NOT NULL,
|
||||
"requests" text NOT NULL,
|
||||
"options_schema" text NOT NULL,
|
||||
"default_options" text NOT NULL,
|
||||
"state_schema" text,
|
||||
"default_state" text,
|
||||
"template" text NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp DEFAULT now() NOT NULL,
|
||||
"creator_id" varchar(64)
|
||||
);--> statement-breakpoint
|
||||
CREATE TABLE "custom_widget_secret" (
|
||||
"source_id" varchar(64) NOT NULL,
|
||||
"kind" varchar(64) NOT NULL,
|
||||
"encrypted_value" text NOT NULL,
|
||||
"updated_at" timestamp NOT NULL,
|
||||
"definition_id" varchar(64) NOT NULL,
|
||||
CONSTRAINT "custom_widget_secret_definition_id_source_id_kind_pk" PRIMARY KEY("definition_id","source_id","kind")
|
||||
);--> statement-breakpoint
|
||||
ALTER TABLE "custom_widget_definition" ADD CONSTRAINT "custom_widget_definition_creator_id_user_id_fk" FOREIGN KEY ("creator_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "custom_widget_secret" ADD CONSTRAINT "custom_widget_secret_definition_id_custom_widget_definition_id_fk" FOREIGN KEY ("definition_id") REFERENCES "public"."custom_widget_definition"("id") ON DELETE cascade ON UPDATE no action;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,13 @@
|
||||
"when": 1783176100870,
|
||||
"tag": "0008_add_widget_secret",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1784305412862,
|
||||
"tag": "0009_custom_widget_v2_reset",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import SuperJSON from "superjson";
|
||||
|
||||
import { createId, objectKeys } from "@homarr/common";
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
import {
|
||||
createDocumentationLink,
|
||||
credentialsAdminGroup,
|
||||
@@ -16,7 +15,7 @@ import type { WidgetKind } from "@homarr/definitions";
|
||||
import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings";
|
||||
|
||||
import type { Database } from "..";
|
||||
import { eq, inArray } from "..";
|
||||
import { eq } from "..";
|
||||
import { getMaxGroupPositionAsync, placeAllWidgetsAsync } from "../queries";
|
||||
import {
|
||||
getServerSettingByKeyAsync,
|
||||
@@ -39,102 +38,11 @@ import {
|
||||
searchEngines,
|
||||
sections,
|
||||
users,
|
||||
customWidgetDefinitions,
|
||||
} from "../schema";
|
||||
import type { Integration } from "../schema";
|
||||
|
||||
const isTruthyEnv = (value: string | undefined) => ["1", "yes", "t", "true"].includes((value ?? "").toLowerCase());
|
||||
|
||||
const CUSTOM_WIDGET_SEEDS: Array<{ id: string; data: Record<string, unknown> }> = [
|
||||
{
|
||||
id: "seed-dog-facts",
|
||||
data: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Random Dog Fact",
|
||||
description: "Displays a random fun fact about dogs",
|
||||
url: "https://dogapi.dog/api/v2/facts",
|
||||
authType: "none",
|
||||
method: "GET",
|
||||
displayType: "singleValue",
|
||||
displayConfig: {
|
||||
type: "singleValue",
|
||||
jsonPath: "$.data[0].attributes.body",
|
||||
label: "Dog Fact",
|
||||
unit: "",
|
||||
valueSize: "sm",
|
||||
labelPosition: "above",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "seed-currency-exchange",
|
||||
data: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Currency Exchange (JPY)",
|
||||
description: "Converts 50 Japanese Yen to EUR and USD using European Central Bank rates",
|
||||
url: "https://api.frankfurter.dev/v1/latest?from=JPY&to=EUR,USD&amount=50",
|
||||
authType: "none",
|
||||
method: "GET",
|
||||
displayType: "keyValue",
|
||||
displayConfig: {
|
||||
type: "keyValue",
|
||||
mappings: [
|
||||
{ label: "50 JPY → EUR", jsonPath: "$.rates.EUR", unit: "€" },
|
||||
{ label: "50 JPY → USD", jsonPath: "$.rates.USD", unit: "$" },
|
||||
],
|
||||
layout: "list",
|
||||
columns: 2,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "seed-jellyfin",
|
||||
data: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Jellyfin library",
|
||||
description: "Counts the number of movies, series, episodes and songs in the library",
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/jellyfin.svg",
|
||||
url: "https://jellyfin.homelab.com/Items/Counts",
|
||||
authType: "apiKeyHeader",
|
||||
headerName: "X-Emby-Token",
|
||||
method: "GET",
|
||||
requestBody: null,
|
||||
displayType: "countGrid",
|
||||
displayConfig: {
|
||||
type: "countGrid",
|
||||
items: [
|
||||
{ label: "Movies", jsonPath: "$.MovieCount", unit: "" },
|
||||
{ label: "Series", jsonPath: "$.SeriesCount", unit: "" },
|
||||
{ label: "Episodes", jsonPath: "$.EpisodeCount", unit: "" },
|
||||
{ label: "Songs", jsonPath: "$.SongCount", unit: "" },
|
||||
],
|
||||
columns: 4,
|
||||
valueSize: "lg",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "seed-pokedex",
|
||||
data: {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Pokédex",
|
||||
description: "Browseable Pokémon list",
|
||||
iconUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/poke-ball.png",
|
||||
url: "https://pokeapi.co/api/v2/pokemon?limit=75",
|
||||
authType: "none",
|
||||
headerName: null,
|
||||
method: "GET",
|
||||
requestBody: null,
|
||||
displayType: "customJsx",
|
||||
displayConfig: {
|
||||
type: "customJsx",
|
||||
template:
|
||||
'<Stack gap="md" p="xs">\n <Card\n withBorder\n radius="xl"\n p="md"\n shadow="md"\n style={{\n background: "linear-gradient(135deg, rgba(250,82,82,0.22), rgba(253,126,20,0.10), rgba(255,255,255,0.03))",\n border: "1px solid rgba(250,82,82,0.35)",\n overflow: "hidden"\n }}\n >\n <Group justify="space-between" wrap="nowrap">\n <Stack gap={2}>\n <Title order={3}>Pokédex</Title>\n </Stack>\n </Group>\n </Card>\n\n <PaginatedList pageSize={12}>\n <Grid gutter="sm">\n {data.results.map((pokemon, i) =>\n <Grid.Col span={1.5}>\n <Anchor href={pokemon.url} target="_blank" underline="never">\n <Card\n withBorder\n radius="xl"\n p="xs"\n shadow="md"\n style={{\n cursor: "pointer",\n position: "relative",\n overflow: "hidden",\n minHeight: 190,\n background: "linear-gradient(160deg, rgba(255,255,255,0.12), rgba(250,82,82,0.10), rgba(0,0,0,0.04))",\n border: "1px solid rgba(250,82,82,0.28)",\n transition: "transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease, background 180ms ease"\n }}\n >\n <Stack gap="sm" align="center">\n <Group justify="space-between" wrap="nowrap" style={{ width: "100%" }}>\n <Badge size="sm" color="red" variant="filled">\n #{String(i + 1).padStart(3, "0")}\n </Badge>\n <Text fw={800} tt="capitalize" ta="right" truncate style={{ maxWidth: 120 }}>\n {pokemon.name}\n </Text>\n </Group>\n\n <Paper\n radius="xl"\n p="xs"\n withBorder\n style={{\n background: "radial-gradient(circle, rgba(255,255,255,0.95), rgba(250,82,82,0.16))",\n border: "1px solid rgba(255,255,255,0.45)",\n boxShadow: "inset 0 0 20px rgba(255,255,255,0.25)"\n }}\n >\n <Avatar\n src={"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/" + String(i + 1) + ".png"}\n alt={pokemon.name}\n size={92}\n radius="xl"\n style={{\n transition: "transform 180ms ease",\n filter: "drop-shadow(0 8px 10px rgba(0,0,0,0.25))"\n }}\n />\n </Paper>\n </Stack>\n </Card>\n </Anchor>\n </Grid.Col>\n )}\n </Grid>\n </PaginatedList>\n</Stack>',
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const seedDataAsync = async (db: Database) => {
|
||||
if (isTruthyEnv(process.env.UNSAFE_ENABLE_MOCK_INTEGRATION)) {
|
||||
console.warn(
|
||||
@@ -149,7 +57,6 @@ export const seedDataAsync = async (db: Database) => {
|
||||
await seedDefaultIntegrationsAsync(db);
|
||||
await seedDefaultAppsAsync(db);
|
||||
await seedDefaultBoardAsync(db);
|
||||
await seedDefaultCustomWidgetsAsync(db);
|
||||
await seedBoardWidgetsAsync(db);
|
||||
|
||||
if (isTruthyEnv(process.env.DEMO_MODE)) {
|
||||
@@ -645,43 +552,6 @@ const seedDemoUserAsync = async (db: Database) => {
|
||||
);
|
||||
};
|
||||
|
||||
const seedDefaultCustomWidgetsAsync = async (db: Database) => {
|
||||
const seedIds = CUSTOM_WIDGET_SEEDS.map((s) => s.id);
|
||||
const existing = await db.query.customWidgetDefinitions.findMany({
|
||||
columns: { id: true },
|
||||
where: inArray(customWidgetDefinitions.id, seedIds),
|
||||
});
|
||||
const existingIds = new Set(existing.map((row) => row.id));
|
||||
|
||||
const seedValues = CUSTOM_WIDGET_SEEDS.filter((seed) => !existingIds.has(seed.id)).map((seed) => {
|
||||
const parsed = customWidgetImportSchema.parse(seed.data);
|
||||
return {
|
||||
id: seed.id,
|
||||
name: parsed.name,
|
||||
description: parsed.description ?? null,
|
||||
iconUrl: parsed.iconUrl ?? null,
|
||||
url: parsed.url,
|
||||
authType: parsed.authType,
|
||||
headerName: parsed.headerName ?? null,
|
||||
method: parsed.method,
|
||||
requestBody: parsed.requestBody ?? null,
|
||||
displayType: parsed.displayType,
|
||||
displayConfig: SuperJSON.stringify(parsed.displayConfig),
|
||||
enabled: false,
|
||||
creatorId: null,
|
||||
};
|
||||
});
|
||||
|
||||
if (seedValues.length === 0) {
|
||||
console.log("Skipping seeding of default custom widgets as they already exist");
|
||||
return;
|
||||
}
|
||||
|
||||
await db.insert(customWidgetDefinitions).values(seedValues);
|
||||
|
||||
console.log(`Created ${seedValues.length} default custom widgets through seeding process`);
|
||||
};
|
||||
|
||||
const seedBoardWidgetsAsync = async (db: Database) => {
|
||||
const existingItems = await db.$count(items);
|
||||
if (existingItems > 0) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
PRAGMA foreign_keys=OFF;--> statement-breakpoint
|
||||
DROP TABLE `custom_widget_secret`;--> statement-breakpoint
|
||||
DROP TABLE `custom_widget_definition`;--> statement-breakpoint
|
||||
CREATE TABLE `custom_widget_definition` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text,
|
||||
`icon_url` text,
|
||||
`sources` text NOT NULL,
|
||||
`requests` text NOT NULL,
|
||||
`options_schema` text NOT NULL,
|
||||
`default_options` text NOT NULL,
|
||||
`state_schema` text,
|
||||
`default_state` text,
|
||||
`template` text NOT NULL,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
|
||||
`updated_at` integer DEFAULT (unixepoch()) NOT NULL,
|
||||
`creator_id` text,
|
||||
FOREIGN KEY (`creator_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE set null
|
||||
);--> statement-breakpoint
|
||||
CREATE TABLE `custom_widget_secret` (
|
||||
`source_id` text NOT NULL,
|
||||
`kind` text NOT NULL,
|
||||
`encrypted_value` text NOT NULL,
|
||||
`updated_at` integer NOT NULL,
|
||||
`definition_id` text NOT NULL,
|
||||
PRIMARY KEY(`definition_id`, `source_id`, `kind`),
|
||||
FOREIGN KEY (`definition_id`) REFERENCES `custom_widget_definition`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);--> statement-breakpoint
|
||||
PRAGMA foreign_keys=ON;
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 263 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user